-
Notifications
You must be signed in to change notification settings - Fork 1k
/
EsIndexRangeService.java
281 lines (247 loc) · 10.9 KB
/
EsIndexRangeService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/**
* This file is part of Graylog.
*
* Graylog is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Graylog is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Graylog. If not, see <http://www.gnu.org/licenses/>.
*/
package org.graylog2.indexer.ranges;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.joschi.jadconfig.util.Duration;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.primitives.Ints;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.NoShardAvailableActionException;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.indices.IndexMissingException;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.filter.Filter;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.Stats;
import org.graylog2.database.NotFoundException;
import org.graylog2.indexer.Deflector;
import org.graylog2.indexer.IndexMapping;
import org.graylog2.indexer.indices.Indices;
import org.graylog2.indexer.searches.TimestampStats;
import org.graylog2.plugin.Tools;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Map;
import java.util.SortedSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class EsIndexRangeService implements IndexRangeService {
private static final Logger LOG = LoggerFactory.getLogger(EsIndexRangeService.class);
private final LoadingCache<String, IndexRange> cache;
private final Client client;
private final ObjectMapper objectMapper;
private final Indices indices;
private final Deflector deflector;
@Inject
public EsIndexRangeService(Client client,
ObjectMapper objectMapper,
Indices indices,
Deflector deflector,
@Named("elasticsearch_index_range_expiration") Duration indexRangeExpiration) {
this.client = client;
this.objectMapper = objectMapper;
this.indices = indices;
this.deflector = deflector;
final CacheLoader<String, IndexRange> cacheLoader = new CacheLoader<String, IndexRange>() {
@Override
public IndexRange load(String indexName) throws Exception {
final IndexRange indexRange = loadIndexRange(indexName);
if (indexRange == null) {
throw new NotFoundException("Couldn't load index range for index " + indexName);
}
return indexRange;
}
};
this.cache = CacheBuilder.<String, IndexRange>newBuilder()
.expireAfterWrite(indexRangeExpiration.getQuantity(), indexRangeExpiration.getUnit())
.build(cacheLoader);
}
@Override
public IndexRange get(String index) throws NotFoundException {
try {
return cache.get(index);
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
if (cause instanceof NotFoundException) {
throw (NotFoundException) cause;
} else {
throw new NotFoundException(e.getCause());
}
}
}
private IndexRange loadIndexRange(String index) throws NotFoundException {
final GetRequest request = new GetRequestBuilder(client, index)
.setType(IndexMapping.TYPE_INDEX_RANGE)
.setId(index)
.request();
final GetResponse r;
try {
r = client.get(request).actionGet();
} catch (IndexMissingException | NoShardAvailableActionException e) {
throw new NotFoundException(e);
}
if (!r.isExists()) {
throw new NotFoundException("Index [" + index + "] not found.");
}
final IndexRange indexRange = parseSource(r.getIndex(), r.getSource());
if (indexRange == null) {
throw new NotFoundException("Index [" + index + "] not found.");
}
return indexRange;
}
@Nullable
private IndexRange parseSource(String index, Map<String, Object> fields) {
try {
return IndexRange.create(
index,
parseFromDateString((String) fields.get(IndexRange.FIELD_BEGIN)),
parseFromDateString((String) fields.get(IndexRange.FIELD_END)),
parseFromDateString((String) fields.get(IndexRange.FIELD_CALCULATED_AT)),
(int) fields.get(IndexRange.FIELD_TOOK_MS)
);
} catch (Exception e) {
LOG.debug("Couldn't create index range from fields: " + fields);
return null;
}
}
private DateTime parseFromDateString(String s) {
return DateTime.parse(s);
}
@Override
public SortedSet<IndexRange> find(DateTime begin, DateTime end) {
final ImmutableSortedSet.Builder<IndexRange> indexRanges = ImmutableSortedSet.orderedBy(IndexRange.COMPARATOR);
for (IndexRange indexRange : findAll()) {
if (indexRange.begin().getMillis() >= begin.getMillis() && indexRange.end().getMillis() <= end.getMillis()) {
indexRanges.add(indexRange);
}
}
return indexRanges.build();
}
@Override
public SortedSet<IndexRange> findAll() {
final ImmutableSortedSet.Builder<IndexRange> indexRanges = ImmutableSortedSet.orderedBy(IndexRange.COMPARATOR);
for (String index : deflector.getAllDeflectorIndexNames()) {
try {
indexRanges.add(cache.get(index));
} catch (ExecutionException e) {
LOG.warn("Couldn't load index range for index " + index, e.getCause());
}
}
return indexRanges.build();
}
@Override
public IndexRange calculateRange(String index) {
final Stopwatch sw = Stopwatch.createStarted();
final DateTime now = DateTime.now(DateTimeZone.UTC);
final TimestampStats stats = timestampStatsOfIndex(index);
final int duration = Ints.saturatedCast(sw.stop().elapsed(TimeUnit.MILLISECONDS));
LOG.info("Calculated range of [{}] in [{}ms].", index, duration);
return IndexRange.create(index, stats.min(), stats.max(), now, duration);
}
/**
* Calculate stats (min, max, avg) about the message timestamps in the given index.
*
* @param index Name of the index to query.
* @return the timestamp stats in the given index, or {@code null} if they couldn't be calculated.
* @see org.elasticsearch.search.aggregations.metrics.stats.Stats
*/
@VisibleForTesting
protected TimestampStats timestampStatsOfIndex(String index) {
final FilterAggregationBuilder builder = AggregationBuilders.filter("agg")
.filter(FilterBuilders.existsFilter("timestamp"))
.subAggregation(AggregationBuilders.stats("ts_stats").field("timestamp"));
final SearchRequestBuilder srb = client.prepareSearch()
.setIndices(index)
.setSearchType(SearchType.COUNT)
.addAggregation(builder);
final SearchResponse response;
try {
response = client.search(srb.request()).actionGet();
} catch (IndexMissingException e) {
throw e;
} catch (ElasticsearchException e) {
LOG.error("Error while calculating timestamp stats in index <" + index + ">", e);
throw new IndexMissingException(new Index(index));
}
final Filter f = response.getAggregations().get("agg");
if (f.getDocCount() == 0L) {
LOG.debug("No documents with attribute \"timestamp\" found in index <{}>", index);
return TimestampStats.EMPTY;
}
final Stats stats = f.getAggregations().get("ts_stats");
final DateTimeFormatter formatter = DateTimeFormat.forPattern(Tools.ES_DATE_FORMAT).withZoneUTC();
final DateTime min = formatter.parseDateTime(stats.getMinAsString());
final DateTime max = formatter.parseDateTime(stats.getMaxAsString());
final DateTime avg = formatter.parseDateTime(stats.getAvgAsString());
return TimestampStats.create(min, max, avg);
}
@Override
public void save(IndexRange indexRange) {
final byte[] source;
try {
source = objectMapper.writeValueAsBytes(indexRange);
} catch (JsonProcessingException e) {
throw Throwables.propagate(e);
}
final String indexName = indexRange.indexName();
final boolean readOnly = indices.isReadOnly(indexName);
if (readOnly) {
indices.setReadWrite(indexName);
}
final IndexRequest request = client.prepareIndex()
.setIndex(indexName)
.setType(IndexMapping.TYPE_INDEX_RANGE)
.setId(indexName)
.setRefresh(true)
.setSource(source)
.request();
final IndexResponse response = client.index(request).actionGet();
if (readOnly) {
indices.setReadOnly(indexName);
}
if (response.isCreated()) {
LOG.debug("Successfully saved index range: {}", indexRange);
} else {
LOG.debug("Successfully updated index range: {}", indexRange);
}
cache.put(indexName, indexRange);
}
}