forked from opensearch-project/anomaly-detection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathADIndexManagement.java
300 lines (268 loc) · 11.5 KB
/
ADIndexManagement.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.ad.indices;
import static org.opensearch.ad.constant.ADCommonName.DUMMY_AD_RESULT_ID;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.AD_MAX_PRIMARY_SHARDS;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.AD_RESULT_HISTORY_MAX_DOCS_PER_SHARD;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.AD_RESULT_HISTORY_RETENTION_PERIOD;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.AD_RESULT_HISTORY_ROLLOVER_PERIOD;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.ANOMALY_DETECTION_STATE_INDEX_MAPPING_FILE;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.ANOMALY_RESULTS_INDEX_MAPPING_FILE;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.CHECKPOINT_INDEX_MAPPING_FILE;
import java.io.IOException;
import java.util.EnumMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opensearch.action.admin.indices.create.CreateIndexRequest;
import org.opensearch.action.admin.indices.create.CreateIndexResponse;
import org.opensearch.action.delete.DeleteRequest;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.ad.constant.ADCommonName;
import org.opensearch.ad.model.AnomalyDetector;
import org.opensearch.ad.model.AnomalyResult;
import org.opensearch.client.Client;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.timeseries.common.exception.EndRunException;
import org.opensearch.timeseries.indices.IndexManagement;
import org.opensearch.timeseries.util.DiscoveryNodeFilterer;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* This class provides utility methods for various anomaly detection indices.
*/
public class ADIndexManagement extends IndexManagement<ADIndex> {
private static final Logger logger = LogManager.getLogger(ADIndexManagement.class);
// The index name pattern to query all the AD result history indices
public static final String AD_RESULT_HISTORY_INDEX_PATTERN = "<.opendistro-anomaly-results-history-{now/d}-1>";
// The index name pattern to query all AD result, history and current AD result
public static final String ALL_AD_RESULTS_INDEX_PATTERN = ".opendistro-anomaly-results*";
/**
* Constructor function
*
* @param client OS client supports administrative actions
* @param clusterService OS cluster service
* @param threadPool OS thread pool
* @param settings OS cluster setting
* @param nodeFilter Used to filter eligible nodes to host AD indices
* @param maxUpdateRunningTimes max number of retries to update index mapping and setting
* @param xContentRegistry registry for json parser
* @throws IOException
*/
public ADIndexManagement(
Client client,
ClusterService clusterService,
ThreadPool threadPool,
Settings settings,
DiscoveryNodeFilterer nodeFilter,
int maxUpdateRunningTimes,
NamedXContentRegistry xContentRegistry
)
throws IOException {
super(
client,
clusterService,
threadPool,
settings,
nodeFilter,
maxUpdateRunningTimes,
ADIndex.class,
AD_MAX_PRIMARY_SHARDS.get(settings),
AD_RESULT_HISTORY_ROLLOVER_PERIOD.get(settings),
AD_RESULT_HISTORY_MAX_DOCS_PER_SHARD.get(settings),
AD_RESULT_HISTORY_RETENTION_PERIOD.get(settings),
ADIndex.RESULT.getMapping(),
xContentRegistry,
AnomalyDetector::parse,
ADCommonName.CUSTOM_RESULT_INDEX_PREFIX
);
this.indexStates = new EnumMap<ADIndex, IndexState>(ADIndex.class);
this.clusterService.getClusterSettings().addSettingsUpdateConsumer(AD_RESULT_HISTORY_MAX_DOCS_PER_SHARD, it -> historyMaxDocs = it);
this.clusterService.getClusterSettings().addSettingsUpdateConsumer(AD_RESULT_HISTORY_ROLLOVER_PERIOD, it -> {
historyRolloverPeriod = it;
rescheduleRollover();
});
this.clusterService.getClusterSettings().addSettingsUpdateConsumer(AD_RESULT_HISTORY_RETENTION_PERIOD, it -> {
historyRetentionPeriod = it;
});
this.clusterService.getClusterSettings().addSettingsUpdateConsumer(AD_MAX_PRIMARY_SHARDS, it -> maxPrimaryShards = it);
}
/**
* Get anomaly result index mapping json content.
*
* @return anomaly result index mapping
* @throws IOException IOException if mapping file can't be read correctly
*/
public static String getResultMappings() throws IOException {
return getMappings(ANOMALY_RESULTS_INDEX_MAPPING_FILE);
}
/**
* Retrieves the JSON mapping for the flattened result index with the "dynamic" field set to true
* @return JSON mapping for the flattened result index.
* @throws IOException if the mapping file cannot be read.
*/
public static String getFlattenedResultMappings() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> mapping = objectMapper
.readValue(ADIndexManagement.class.getClassLoader().getResourceAsStream(ANOMALY_RESULTS_INDEX_MAPPING_FILE), Map.class);
mapping.put("dynamic", true);
return objectMapper.writeValueAsString(mapping);
}
/**
* Get anomaly detector state index mapping json content.
*
* @return anomaly detector state index mapping
* @throws IOException IOException if mapping file can't be read correctly
*/
public static String getStateMappings() throws IOException {
String detectionStateMappings = getMappings(ANOMALY_DETECTION_STATE_INDEX_MAPPING_FILE);
String detectorIndexMappings = getConfigMappings();
detectorIndexMappings = detectorIndexMappings
.substring(detectorIndexMappings.indexOf("\"properties\""), detectorIndexMappings.lastIndexOf("}"));
return detectionStateMappings.replace("DETECTOR_INDEX_MAPPING_PLACE_HOLDER", detectorIndexMappings);
}
/**
* Get checkpoint index mapping json content.
*
* @return checkpoint index mapping
* @throws IOException IOException if mapping file can't be read correctly
*/
public static String getCheckpointMappings() throws IOException {
return getMappings(CHECKPOINT_INDEX_MAPPING_FILE);
}
/**
* anomaly result index exist or not.
*
* @return true if anomaly result index exists
*/
@Override
public boolean doesDefaultResultIndexExist() {
return doesAliasExist(ADCommonName.ANOMALY_RESULT_INDEX_ALIAS);
}
/**
* Anomaly state index exist or not.
*
* @return true if anomaly state index exists
*/
@Override
public boolean doesStateIndexExist() {
return doesIndexExist(ADCommonName.DETECTION_STATE_INDEX);
}
/**
* Checkpoint index exist or not.
*
* @return true if checkpoint index exists
*/
@Override
public boolean doesCheckpointIndexExist() {
return doesIndexExist(ADCommonName.CHECKPOINT_INDEX_NAME);
}
/**
* Create anomaly result index without checking exist or not.
*
* @param actionListener action called after create index
*/
@Override
public void initDefaultResultIndexDirectly(ActionListener<CreateIndexResponse> actionListener) {
initResultIndexDirectly(
AD_RESULT_HISTORY_INDEX_PATTERN,
ADCommonName.ANOMALY_RESULT_INDEX_ALIAS,
true,
true,
ADIndex.RESULT,
actionListener
);
}
/**
* Create the state index.
*
* @param actionListener action called after create index
*/
@Override
public void initStateIndex(ActionListener<CreateIndexResponse> actionListener) {
try {
CreateIndexRequest request = new CreateIndexRequest(ADCommonName.DETECTION_STATE_INDEX)
.mapping(getStateMappings(), XContentType.JSON)
.settings(settings);
adminClient.indices().create(request, markMappingUpToDate(ADIndex.STATE, actionListener));
} catch (IOException e) {
logger.error("Fail to init AD detection state index", e);
actionListener.onFailure(e);
}
}
/**
* Create the checkpoint index.
*
* @param actionListener action called after create index
* @throws EndRunException EndRunException due to failure to get mapping
*/
@Override
public void initCheckpointIndex(ActionListener<CreateIndexResponse> actionListener) {
String mapping;
try {
mapping = getCheckpointMappings();
} catch (IOException e) {
throw new EndRunException("", "Cannot find checkpoint mapping file", true);
}
CreateIndexRequest request = new CreateIndexRequest(ADCommonName.CHECKPOINT_INDEX_NAME).mapping(mapping, XContentType.JSON);
choosePrimaryShards(request, true);
adminClient.indices().create(request, markMappingUpToDate(ADIndex.CHECKPOINT, actionListener));
}
@Override
protected void rolloverAndDeleteHistoryIndex() {
rolloverAndDeleteHistoryIndex(
ADCommonName.ANOMALY_RESULT_INDEX_ALIAS,
ALL_AD_RESULTS_INDEX_PATTERN,
AD_RESULT_HISTORY_INDEX_PATTERN,
ADIndex.RESULT
);
}
/**
* Create config index directly.
*
* @param actionListener action called after create index
* @throws IOException IOException from {@link IndexManagement#getConfigMappings}
*/
@Override
public void initConfigIndex(ActionListener<CreateIndexResponse> actionListener) throws IOException {
super.initConfigIndex(markMappingUpToDate(ADIndex.CONFIG, actionListener));
}
/**
* Create job index.
*
* @param actionListener action called after create index
*/
@Override
public void initJobIndex(ActionListener<CreateIndexResponse> actionListener) {
super.initJobIndex(markMappingUpToDate(ADIndex.JOB, actionListener));
}
@Override
protected IndexRequest createDummyIndexRequest(String resultIndex) throws IOException {
AnomalyResult dummyResult = AnomalyResult.getDummyResult();
return new IndexRequest(resultIndex)
.id(DUMMY_AD_RESULT_ID)
.source(dummyResult.toXContent(XContentBuilder.builder(XContentType.JSON.xContent()), ToXContent.EMPTY_PARAMS));
}
@Override
protected DeleteRequest createDummyDeleteRequest(String resultIndex) throws IOException {
return new DeleteRequest(resultIndex).id(DUMMY_AD_RESULT_ID);
}
@Override
public void initCustomResultIndexDirectly(String resultIndex, ActionListener<CreateIndexResponse> actionListener) {
initResultIndexDirectly(getCustomResultIndexPattern(resultIndex), resultIndex, false, false, ADIndex.RESULT, actionListener);
}
}