forked from opensearch-project/anomaly-detection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIndexManagement.java
1446 lines (1334 loc) · 66.2 KB
/
IndexManagement.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.timeseries.indices;
import static org.opensearch.ad.indices.ADIndexManagement.getFlattenedResultMappings;
import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;
import static org.opensearch.timeseries.util.RestHandlerUtils.createXContentParserFromRegistry;
import java.io.IOException;
import java.net.URL;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.opensearch.ExceptionsHelper;
import org.opensearch.ResourceAlreadyExistsException;
import org.opensearch.action.admin.cluster.state.ClusterStateRequest;
import org.opensearch.action.admin.indices.alias.Alias;
import org.opensearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.opensearch.action.admin.indices.create.CreateIndexRequest;
import org.opensearch.action.admin.indices.create.CreateIndexResponse;
import org.opensearch.action.admin.indices.delete.DeleteIndexRequest;
import org.opensearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.opensearch.action.admin.indices.rollover.RolloverRequest;
import org.opensearch.action.admin.indices.settings.get.GetSettingsAction;
import org.opensearch.action.admin.indices.settings.get.GetSettingsRequest;
import org.opensearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.opensearch.action.admin.indices.settings.put.UpdateSettingsRequest;
import org.opensearch.action.delete.DeleteRequest;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.search.SearchRequest;
import org.opensearch.action.support.GroupedActionListener;
import org.opensearch.action.support.IndicesOptions;
import org.opensearch.client.AdminClient;
import org.opensearch.client.Client;
import org.opensearch.cluster.LocalNodeClusterManagerListener;
import org.opensearch.cluster.metadata.AliasMetadata;
import org.opensearch.cluster.metadata.IndexMetadata;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.xcontent.LoggingDeprecationHandler;
import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.commons.InjectSecurity;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.common.Strings;
import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.core.xcontent.XContentParser.Token;
import org.opensearch.index.IndexNotFoundException;
import org.opensearch.index.query.BoolQueryBuilder;
import org.opensearch.index.query.QueryBuilders;
import org.opensearch.search.SearchHit;
import org.opensearch.search.builder.SearchSourceBuilder;
import org.opensearch.threadpool.Scheduler;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.timeseries.common.exception.EndRunException;
import org.opensearch.timeseries.common.exception.TimeSeriesException;
import org.opensearch.timeseries.constant.CommonMessages;
import org.opensearch.timeseries.constant.CommonName;
import org.opensearch.timeseries.constant.CommonValue;
import org.opensearch.timeseries.function.BiCheckedFunction;
import org.opensearch.timeseries.function.ExecutorFunction;
import org.opensearch.timeseries.model.Config;
import org.opensearch.timeseries.settings.TimeSeriesSettings;
import org.opensearch.timeseries.util.DiscoveryNodeFilterer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public abstract class IndexManagement<IndexType extends Enum<IndexType> & TimeSeriesIndex> implements LocalNodeClusterManagerListener {
private static final Logger logger = LogManager.getLogger(IndexManagement.class);
// minimum shards of the job index
public static int minJobIndexReplicas = 1;
// maximum shards of the job index
public static int maxJobIndexReplicas = 20;
// package private for testing
public static final String META = "_meta";
public static final String SCHEMA_VERSION = "schema_version";
public static final String customResultIndexAutoExpandReplica = "0-2";
protected ClusterService clusterService;
protected final Client client;
protected final AdminClient adminClient;
protected final ThreadPool threadPool;
protected DiscoveryNodeFilterer nodeFilter;
// index settings
protected final Settings settings;
// don't retry updating endlessly. Can be annoying if there are too many exception logs.
protected final int maxUpdateRunningTimes;
// whether all index have the correct mappings
protected boolean allMappingUpdated;
// whether all index settings are updated
protected boolean allSettingUpdated;
// we only want one update at a time
protected final AtomicBoolean updateRunning;
// the number of times updates run
protected int updateRunningTimes;
private final Class<IndexType> indexType;
// keep track of whether the mapping version is up-to-date
protected EnumMap<IndexType, IndexState> indexStates;
protected int maxPrimaryShards;
private Scheduler.Cancellable scheduledRollover = null;
protected volatile TimeValue historyRolloverPeriod;
protected volatile Long historyMaxDocs;
protected volatile TimeValue historyRetentionPeriod;
// result index mapping to valida custom index
private Map<String, Object> RESULT_FIELD_CONFIGS;
private String resultMapping;
private NamedXContentRegistry xContentRegistry;
protected BiCheckedFunction<XContentParser, String, ? extends Config, IOException> configParser;
protected String customResultIndexPrefix;
private final ObjectMapper objectMapper = new ObjectMapper();
protected class IndexState {
// keep track of whether the mapping version is up-to-date
public Boolean mappingUpToDate;
// keep track of whether the setting needs to change
public Boolean settingUpToDate;
// record schema version reading from the mapping file
public Integer schemaVersion;
public IndexState(String mappingFile) {
this.mappingUpToDate = false;
this.settingUpToDate = false;
this.schemaVersion = IndexManagement.parseSchemaVersion(mappingFile);
}
}
protected IndexManagement(
Client client,
ClusterService clusterService,
ThreadPool threadPool,
Settings settings,
DiscoveryNodeFilterer nodeFilter,
int maxUpdateRunningTimes,
Class<IndexType> indexType,
int maxPrimaryShards,
TimeValue historyRolloverPeriod,
Long historyMaxDocs,
TimeValue historyRetentionPeriod,
String resultMapping,
NamedXContentRegistry xContentRegistry,
BiCheckedFunction<XContentParser, String, ? extends Config, IOException> configParser,
String customResultIndexPrefix
)
throws IOException {
this.client = client;
this.adminClient = client.admin();
this.clusterService = clusterService;
this.threadPool = threadPool;
this.clusterService.addLocalNodeClusterManagerListener(this);
this.nodeFilter = nodeFilter;
this.settings = Settings.builder().put(IndexMetadata.SETTING_INDEX_HIDDEN, true).build();
this.maxUpdateRunningTimes = maxUpdateRunningTimes;
this.indexType = indexType;
this.maxPrimaryShards = maxPrimaryShards;
this.historyRolloverPeriod = historyRolloverPeriod;
this.historyMaxDocs = historyMaxDocs;
this.historyRetentionPeriod = historyRetentionPeriod;
this.allMappingUpdated = false;
this.allSettingUpdated = false;
this.updateRunning = new AtomicBoolean(false);
this.updateRunningTimes = 0;
this.resultMapping = resultMapping;
this.xContentRegistry = xContentRegistry;
this.configParser = configParser;
this.customResultIndexPrefix = customResultIndexPrefix;
}
/**
* Alias exists or not
* @param alias Alias name
* @return true if the alias exists
*/
public boolean doesAliasExist(String alias) {
return clusterService.state().metadata().hasAlias(alias);
}
public static Integer parseSchemaVersion(String mapping) {
try {
XContentParser xcp = XContentType.JSON
.xContent()
.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, mapping);
while (!xcp.isClosed()) {
Token token = xcp.currentToken();
if (token != null && token != XContentParser.Token.END_OBJECT && token != XContentParser.Token.START_OBJECT) {
if (xcp.currentName() != IndexManagement.META) {
xcp.nextToken();
xcp.skipChildren();
} else {
while (xcp.nextToken() != XContentParser.Token.END_OBJECT) {
if (xcp.currentName().equals(IndexManagement.SCHEMA_VERSION)) {
Integer version = xcp.intValue();
if (version < 0) {
version = CommonValue.NO_SCHEMA_VERSION;
}
return version;
} else {
xcp.nextToken();
}
}
}
}
xcp.nextToken();
}
return CommonValue.NO_SCHEMA_VERSION;
} catch (Exception e) {
// since this method is called in the constructor that is called by TimeSeriesAnalyticsPlugin.createComponents,
// we cannot throw checked exception
throw new RuntimeException(e);
}
}
protected static Integer getIntegerSetting(GetSettingsResponse settingsResponse, String settingKey) {
Integer value = null;
for (Settings settings : settingsResponse.getIndexToSettings().values()) {
value = settings.getAsInt(settingKey, null);
if (value != null) {
break;
}
}
return value;
}
protected static String getStringSetting(GetSettingsResponse settingsResponse, String settingKey) {
String value = null;
for (Settings settings : settingsResponse.getIndexToSettings().values()) {
value = settings.get(settingKey, null);
if (value != null) {
break;
}
}
return value;
}
public boolean doesIndexExist(String indexName) {
return clusterService.state().metadata().hasIndex(indexName);
}
protected static String getMappings(String mappingFileRelativePath) throws IOException {
URL url = IndexManagement.class.getClassLoader().getResource(mappingFileRelativePath);
return Resources.toString(url, Charsets.UTF_8);
}
public static String getScripts(String scriptFileRelativePath) throws IOException {
URL url = IndexManagement.class.getClassLoader().getResource(scriptFileRelativePath);
return Resources.toString(url, Charsets.UTF_8);
}
protected void choosePrimaryShards(CreateIndexRequest request, boolean hiddenIndex) {
request
.settings(
Settings
.builder()
// put 1 primary shards per hot node if possible
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, getNumberOfPrimaryShards())
// 1 replica for better search performance and fail-over
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1)
.put(IndexMetadata.SETTING_INDEX_HIDDEN, hiddenIndex)
);
}
protected void deleteOldHistoryIndices(String indexPattern, TimeValue historyRetentionPeriod) {
Set<String> candidates = new HashSet<String>();
ClusterStateRequest clusterStateRequest = new ClusterStateRequest()
.clear()
.indices(indexPattern)
.metadata(true)
.local(true)
.indicesOptions(IndicesOptions.strictExpand());
adminClient.cluster().state(clusterStateRequest, ActionListener.wrap(clusterStateResponse -> {
String latestToDelete = null;
long latest = Long.MIN_VALUE;
for (IndexMetadata indexMetaData : clusterStateResponse.getState().metadata().indices().values()) {
long creationTime = indexMetaData.getCreationDate();
long indexAgeMillis = Instant.now().toEpochMilli() - creationTime;
if (indexAgeMillis > historyRetentionPeriod.millis()) {
String indexName = indexMetaData.getIndex().getName();
candidates.add(indexName);
if (latest < creationTime) {
latest = creationTime;
latestToDelete = indexName;
}
}
}
if (candidates.size() > 1) {
// delete all indices except the last one because the last one may contain docs newer than the retention period
candidates.remove(latestToDelete);
String[] toDelete = candidates.toArray(Strings.EMPTY_ARRAY);
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(toDelete);
adminClient.indices().delete(deleteIndexRequest, ActionListener.wrap(deleteIndexResponse -> {
if (!deleteIndexResponse.isAcknowledged()) {
logger.error("Could not delete one or more result indices: {}. Retrying one by one.", Arrays.toString(toDelete));
deleteIndexIteration(toDelete);
} else {
logger.info("Succeeded in deleting expired result indices: {}.", Arrays.toString(toDelete));
}
}, exception -> {
logger.error("Failed to delete expired result indices: {}.", Arrays.toString(toDelete));
deleteIndexIteration(toDelete);
}));
}
}, exception -> { logger.error("Fail to delete result indices", exception); }));
}
protected void deleteIndexIteration(String[] toDelete) {
for (String index : toDelete) {
DeleteIndexRequest singleDeleteRequest = new DeleteIndexRequest(index);
adminClient.indices().delete(singleDeleteRequest, ActionListener.wrap(singleDeleteResponse -> {
if (!singleDeleteResponse.isAcknowledged()) {
logger.error("Retrying deleting {} does not succeed.", index);
}
}, exception -> {
if (exception instanceof IndexNotFoundException) {
logger.info("{} was already deleted.", index);
} else {
logger.error(new ParameterizedMessage("Retrying deleting {} does not succeed.", index), exception);
}
}));
}
}
@SuppressWarnings("unchecked")
protected void shouldUpdateConcreteIndex(String concreteIndex, Integer newVersion, ActionListener<Boolean> thenDo) {
IndexMetadata indexMeataData = clusterService.state().getMetadata().indices().get(concreteIndex);
if (indexMeataData == null) {
thenDo.onResponse(Boolean.FALSE);
return;
}
Integer oldVersion = CommonValue.NO_SCHEMA_VERSION;
Map<String, Object> indexMapping = indexMeataData.mapping().getSourceAsMap();
Object meta = indexMapping.get(IndexManagement.META);
if (meta != null && meta instanceof Map) {
Map<String, Object> metaMapping = (Map<String, Object>) meta;
Object schemaVersion = metaMapping.get(org.opensearch.timeseries.constant.CommonName.SCHEMA_VERSION_FIELD);
if (schemaVersion instanceof Integer) {
oldVersion = (Integer) schemaVersion;
}
}
thenDo.onResponse(newVersion > oldVersion);
}
protected void updateJobIndexSettingIfNecessary(String indexName, IndexState jobIndexState, ActionListener<Void> listener) {
GetSettingsRequest getSettingsRequest = new GetSettingsRequest()
.indices(indexName)
.names(
new String[] {
IndexMetadata.SETTING_NUMBER_OF_SHARDS,
IndexMetadata.SETTING_NUMBER_OF_REPLICAS,
IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS }
);
client.execute(GetSettingsAction.INSTANCE, getSettingsRequest, ActionListener.wrap(settingResponse -> {
// auto expand setting is a range string like "1-all"
String autoExpandReplica = getStringSetting(settingResponse, IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS);
// if the auto expand setting is already there, return immediately
if (autoExpandReplica != null) {
jobIndexState.settingUpToDate = true;
logger.info(new ParameterizedMessage("Mark [{}]'s setting up-to-date", indexName));
listener.onResponse(null);
return;
}
Integer primaryShardsNumber = getIntegerSetting(settingResponse, IndexMetadata.SETTING_NUMBER_OF_SHARDS);
Integer replicaNumber = getIntegerSetting(settingResponse, IndexMetadata.SETTING_NUMBER_OF_REPLICAS);
if (primaryShardsNumber == null || replicaNumber == null) {
logger
.error(
new ParameterizedMessage(
"Fail to find job index's primary or replica shard number: primary [{}], replica [{}]",
primaryShardsNumber,
replicaNumber
)
);
// don't throw exception as we don't know how to handle it and retry next time
listener.onResponse(null);
return;
}
// at least minJobIndexReplicas
// at most maxJobIndexReplicas / primaryShardsNumber replicas.
// For example, if we have 2 primary shards, since the max number of shards are maxJobIndexReplicas (20),
// we will use 20 / 2 = 10 replicas as the upper bound of replica.
int maxExpectedReplicas = Math
.max(IndexManagement.maxJobIndexReplicas / primaryShardsNumber, IndexManagement.minJobIndexReplicas);
Settings updatedSettings = Settings
.builder()
.put(IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS, IndexManagement.minJobIndexReplicas + "-" + maxExpectedReplicas)
.build();
final UpdateSettingsRequest updateSettingsRequest = new UpdateSettingsRequest(indexName).settings(updatedSettings);
client.admin().indices().updateSettings(updateSettingsRequest, ActionListener.wrap(response -> {
jobIndexState.settingUpToDate = true;
logger.info(new ParameterizedMessage("Mark [{}]'s setting up-to-date", indexName));
listener.onResponse(null);
}, listener::onFailure));
}, e -> {
if (e instanceof IndexNotFoundException) {
// new index will be created with auto expand replica setting
jobIndexState.settingUpToDate = true;
logger.info(new ParameterizedMessage("Mark [{}]'s setting up-to-date", indexName));
listener.onResponse(null);
} else {
listener.onFailure(e);
}
}));
}
/**
* Create config index if not exist.
*
* @param actionListener action called after create index
* @throws IOException IOException from {@link IndexManagement#getConfigMappings}
*/
public void initConfigIndexIfAbsent(ActionListener<CreateIndexResponse> actionListener) throws IOException {
if (!doesConfigIndexExist()) {
initConfigIndex(actionListener);
}
}
/**
* Create config index directly.
*
* @param actionListener action called after create index
* @throws IOException IOException from {@link IndexManagement#getConfigMappings}
*/
public void initConfigIndex(ActionListener<CreateIndexResponse> actionListener) throws IOException {
CreateIndexRequest request = new CreateIndexRequest(CommonName.CONFIG_INDEX)
.mapping(getConfigMappings(), XContentType.JSON)
.settings(settings);
adminClient.indices().create(request, actionListener);
}
/**
* Config index exist or not.
*
* @return true if config index exists
*/
public boolean doesConfigIndexExist() {
return doesIndexExist(CommonName.CONFIG_INDEX);
}
/**
* Job index exist or not.
*
* @return true if anomaly detector job index exists
*/
public boolean doesJobIndexExist() {
return doesIndexExist(CommonName.JOB_INDEX);
}
/**
* Get config index mapping in json format.
*
* @return config index mapping
* @throws IOException IOException if mapping file can't be read correctly
*/
public static String getConfigMappings() throws IOException {
return getMappings(TimeSeriesSettings.CONFIG_INDEX_MAPPING_FILE);
}
/**
* Get job index mapping in json format.
*
* @return job index mapping
* @throws IOException IOException if mapping file can't be read correctly
*/
public static String getJobMappings() throws IOException {
return getMappings(TimeSeriesSettings.JOBS_INDEX_MAPPING_FILE);
}
/**
* Createjob index.
*
* @param actionListener action called after create index
*/
public void initJobIndex(ActionListener<CreateIndexResponse> actionListener) {
try {
CreateIndexRequest request = new CreateIndexRequest(CommonName.JOB_INDEX).mapping(getJobMappings(), XContentType.JSON);
request
.settings(
Settings
.builder()
// AD job index is small. 1 primary shard is enough
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
// Job scheduler puts both primary and replica shards in the
// hash ring. Auto-expand the number of replicas based on the
// number of data nodes (up to 20) in the cluster so that each node can
// become a coordinating node. This is useful when customers
// scale out their cluster so that we can do adaptive scaling
// accordingly.
// At least 1 replica for fail-over.
.put(IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS, minJobIndexReplicas + "-" + maxJobIndexReplicas)
.put(IndexMetadata.SETTING_INDEX_HIDDEN, true)
);
adminClient.indices().create(request, actionListener);
} catch (IOException e) {
logger.error("Fail to init AD job index", e);
actionListener.onFailure(e);
}
}
/**
* Validates the result index and executes the provided function.
*
* <p>
* This method first checks if the mapping for the given result index is valid. If the mapping is not validated
* and is found to be invalid, the method logs a warning and notifies the listener of the failure.
* </p>
*
* <p>
* If the mapping is valid or has been previously validated, the method attempts to write and then immediately
* delete a dummy forecast result to the index. This is a workaround to verify the user's write permission on
* the custom result index, as there is currently no straightforward method to check for write permissions directly.
* </p>
*
* <p>
* If both write and delete operations are successful, the provided function is executed. If any step fails,
* the method logs an error and notifies the listener of the failure.
* </p>
*
* @param <T> The type of the action listener's response.
* @param resultIndexOrAlias The custom result index to validate.
* @param function The function to be executed if validation is successful.
* @param mappingValidated Indicates whether the mapping for the result index has been previously validated.
* @param listener The listener to be notified of the success or failure of the operation.
*
* @throws IllegalArgumentException If the result index mapping is found to be invalid.
*/
public <T> void validateResultIndexAndExecute(
String resultIndexOrAlias,
ExecutorFunction function,
boolean mappingValidated,
ActionListener<T> listener
) {
if (!mappingValidated) {
validateResultIndexMapping(resultIndexOrAlias, ActionListener.wrap(validMapping -> {
if (validMapping) {
executeAfterValidateResultIndexMapping(resultIndexOrAlias, function, listener);
} else {
logger.warn("Can't create analysis with custom result index {} as its mapping is invalid", resultIndexOrAlias);
listener.onFailure(new IllegalArgumentException(CommonMessages.INVALID_RESULT_INDEX_MAPPING + resultIndexOrAlias));
}
}, listener::onFailure));
} else {
try {
executeAfterValidateResultIndexMapping(resultIndexOrAlias, function, listener);
} catch (Exception e) {
logger.error("Failed to validate custom result index " + resultIndexOrAlias, e);
listener.onFailure(e);
}
}
}
private <T> void executeAfterValidateResultIndexMapping(
String resultIndexOrAlias,
ExecutorFunction function,
ActionListener<T> listener
) throws IOException {
IndexRequest indexRequest = createDummyIndexRequest(resultIndexOrAlias);
// User may have no write permission on custom result index. Talked with security plugin team, seems no easy way to verify
// if user has write permission. So just tried to write and delete a dummy result to verify.
client.index(indexRequest, ActionListener.wrap(response -> {
logger.debug("Successfully wrote dummy result to result index {}", resultIndexOrAlias);
client.delete(createDummyDeleteRequest(resultIndexOrAlias), ActionListener.wrap(deleteResponse -> {
logger.debug("Successfully deleted dummy result from result index {}", resultIndexOrAlias);
function.execute();
}, ex -> {
logger.error("Failed to delete dummy result from result index " + resultIndexOrAlias, ex);
listener.onFailure(ex);
}));
}, exception -> {
logger.error("Failed to write dummy result to result index " + resultIndexOrAlias, exception);
listener.onFailure(exception);
}));
}
public void update() {
if ((allMappingUpdated && allSettingUpdated) || updateRunningTimes >= maxUpdateRunningTimes || updateRunning.get()) {
return;
}
updateRunning.set(true);
updateRunningTimes++;
// set updateRunning to false when both updateMappingIfNecessary and updateSettingIfNecessary
// stop running
final GroupedActionListener<Void> groupListeneer = new GroupedActionListener<>(
ActionListener.wrap(r -> updateRunning.set(false), exception -> {
updateRunning.set(false);
logger.error("Fail to update time series indices", exception);
}),
// 2 since we need both updateMappingIfNecessary and updateSettingIfNecessary to return
// before setting updateRunning to false
2
);
updateMappingIfNecessary(groupListeneer);
updateSettingIfNecessary(groupListeneer);
}
private void updateSettingIfNecessary(GroupedActionListener<Void> delegateListeneer) {
if (allSettingUpdated) {
delegateListeneer.onResponse(null);
return;
}
List<IndexType> updates = new ArrayList<>();
for (IndexType index : indexType.getEnumConstants()) {
Boolean updated = indexStates.computeIfAbsent(index, k -> new IndexState(k.getMapping())).settingUpToDate;
if (Boolean.FALSE.equals(updated)) {
updates.add(index);
}
}
if (updates.size() == 0) {
allSettingUpdated = true;
delegateListeneer.onResponse(null);
return;
}
final GroupedActionListener<Void> conglomerateListeneer = new GroupedActionListener<>(
ActionListener.wrap(r -> delegateListeneer.onResponse(null), exception -> {
delegateListeneer.onResponse(null);
logger.error("Fail to update time series indices' settings", exception);
}),
updates.size()
);
for (IndexType timeseriesIndex : updates) {
logger.info(new ParameterizedMessage("Check [{}]'s setting", timeseriesIndex.getIndexName()));
if (timeseriesIndex.isJobIndex() && doesIndexExist(timeseriesIndex.getIndexName())) {
updateJobIndexSettingIfNecessary(
timeseriesIndex.getIndexName(),
indexStates.computeIfAbsent(timeseriesIndex, k -> new IndexState(k.getMapping())),
conglomerateListeneer
);
} else {
// we don't have settings to update for other cases
IndexState indexState = indexStates.computeIfAbsent(timeseriesIndex, k -> new IndexState(k.getMapping()));
indexState.settingUpToDate = true;
logger.info(new ParameterizedMessage("Mark [{}]'s setting up-to-date", timeseriesIndex.getIndexName()));
conglomerateListeneer.onResponse(null);
}
}
}
/**
* Update mapping if schema version changes.
*/
private void updateMappingIfNecessary(GroupedActionListener<Void> delegateListeneer) {
if (allMappingUpdated) {
delegateListeneer.onResponse(null);
return;
}
List<IndexType> updates = new ArrayList<>();
for (IndexType index : indexType.getEnumConstants()) {
Boolean updated = indexStates.computeIfAbsent(index, k -> new IndexState(k.getMapping())).mappingUpToDate;
if (Boolean.FALSE.equals(updated)) {
updates.add(index);
}
}
if (updates.size() == 0) {
allMappingUpdated = true;
delegateListeneer.onResponse(null);
return;
}
final GroupedActionListener<Void> conglomerateListeneer = new GroupedActionListener<>(
ActionListener.wrap(r -> delegateListeneer.onResponse(null), exception -> {
delegateListeneer.onResponse(null);
logger.error("Fail to update time series indices' mappings", exception);
}),
updates.size()
);
for (IndexType index : updates) {
if (index.isCustomResultIndex()) {
updateCustomResultIndexMapping(index, conglomerateListeneer);
} else {
logger.info(new ParameterizedMessage("Check [{}]'s mapping", index.getIndexName()));
shouldUpdateIndex(index, ActionListener.wrap(shouldUpdate -> {
if (shouldUpdate) {
adminClient
.indices()
.putMapping(
new PutMappingRequest().indices(index.getIndexName()).source(index.getMapping(), XContentType.JSON),
ActionListener.wrap(putMappingResponse -> {
if (putMappingResponse.isAcknowledged()) {
logger.info(new ParameterizedMessage("Succeeded in updating [{}]'s mapping", index.getIndexName()));
markMappingUpdated(index);
} else {
logger.error(new ParameterizedMessage("Fail to update [{}]'s mapping", index.getIndexName()));
}
conglomerateListeneer.onResponse(null);
}, exception -> {
logger
.error(
new ParameterizedMessage(
"Fail to update [{}]'s mapping due to [{}]",
index.getIndexName(),
exception.getMessage()
)
);
conglomerateListeneer.onFailure(exception);
})
);
} else {
// index does not exist or the version is already up-to-date.
// When creating index, new mappings will be used.
// We don't need to update it.
logger.info(new ParameterizedMessage("We don't need to update [{}]'s mapping", index.getIndexName()));
markMappingUpdated(index);
conglomerateListeneer.onResponse(null);
}
}, exception -> {
logger
.error(
new ParameterizedMessage("Fail to check whether we should update [{}]'s mapping", index.getIndexName()),
exception
);
conglomerateListeneer.onFailure(exception);
}));
}
}
}
private void updateCustomResultIndexMapping(IndexType customIndex, GroupedActionListener<Void> delegateListeneer) {
getConfigsWithCustomResultIndexAlias(ActionListener.wrap(candidateResultAliases -> {
if (candidateResultAliases == null || candidateResultAliases.size() == 0) {
logger.info("candidate custom result indices are empty.");
markMappingUpdated(customIndex);
delegateListeneer.onResponse(null);
return;
}
final GroupedActionListener<Void> customIndexMappingUpdateListener = new GroupedActionListener<>(
ActionListener.wrap(mappingUpdateResponse -> {
markMappingUpdated(customIndex);
delegateListeneer.onResponse(null);
}, exception -> {
delegateListeneer.onResponse(null);
logger.error("Fail to update result indices' mappings", exception);
}),
candidateResultAliases.size()
);
processResultIndexMappingIteration(
0,
getSchemaVersion(customIndex),
customIndex.getMapping(),
candidateResultAliases,
customIndexMappingUpdateListener
);
}, e -> delegateListeneer.onFailure(new TimeSeriesException("Fail to update custom result indices' mapping.", e))));
}
private void getConfigsWithCustomResultIndexAlias(ActionListener<List<Config>> listener) {
IndexType configIndex = null;
for (IndexType timeseriesIndex : indexType.getEnumConstants()) {
if (timeseriesIndex.isConfigIndex() && doesIndexExist(timeseriesIndex.getIndexName())) {
configIndex = timeseriesIndex;
break;
}
}
if (configIndex == null || configIndex.getIndexName() == null) {
listener.onResponse(new ArrayList<Config>());
return;
}
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
BoolQueryBuilder shouldQueries = new BoolQueryBuilder();
shouldQueries.should(QueryBuilders.wildcardQuery(Config.RESULT_INDEX_FIELD, customResultIndexPrefix + "*"));
if (shouldQueries.should().isEmpty() == false) {
boolQuery.filter(shouldQueries);
}
SearchRequest searchRequest = new SearchRequest()
.indices(new String[] { configIndex.getIndexName() })
.source(new SearchSourceBuilder().size(10000).query(boolQuery));
client.search(searchRequest, ActionListener.wrap(r -> {
if (r == null || r.getHits().getTotalHits() == null || r.getHits().getTotalHits().value == 0) {
logger.info("no config available.");
listener.onResponse(new ArrayList<Config>());
return;
}
Iterator<SearchHit> iterator = r.getHits().iterator();
List<Config> candidateConfigs = new ArrayList<>();
while (iterator.hasNext()) {
SearchHit searchHit = iterator.next();
try (XContentParser parser = createXContentParserFromRegistry(xContentRegistry, searchHit.getSourceRef())) {
ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser);
Config config = configParser.apply(parser, searchHit.getId());
String indexOrAlias = config.getCustomResultIndexOrAlias();
// old custom index is an index, new custom index is an alias. We will only deal with new result index for simplicity.
if (doesAliasExist(indexOrAlias)) {
candidateConfigs.add(config);
}
} catch (Exception e) {
logger.error("failed to parse config " + searchHit.getId(), e);
}
}
listener.onResponse(candidateConfigs);
}, e -> listener.onFailure(new TimeSeriesException("Fail to update custom result indices' mapping.", e))));
}
private void processResultIndexMappingIteration(
int indexPos,
Integer newestSchemaVersion,
String mappingSource,
List<Config> candidateResultIndices,
GroupedActionListener<Void> conglomerateListeneer
) {
if (indexPos >= candidateResultIndices.size()) {
return;
}
String index = candidateResultIndices.get(indexPos).getCustomResultIndexOrAlias();
logger.info(new ParameterizedMessage("Check [{}]'s mapping", index));
shouldUpdateIndex(index, true, newestSchemaVersion, ActionListener.wrap(shouldUpdate -> {
if (shouldUpdate) {
adminClient
.indices()
.putMapping(
new PutMappingRequest().indices(index).source(mappingSource, XContentType.JSON),
ActionListener.wrap(putMappingResponse -> {
if (putMappingResponse.isAcknowledged()) {
logger.info(new ParameterizedMessage("Succeeded in updating [{}]'s mapping", index));
} else {
logger.error(new ParameterizedMessage("Fail to update [{}]'s mapping", index));
}
conglomerateListeneer.onResponse(null);
processResultIndexMappingIteration(
indexPos + 1,
newestSchemaVersion,
mappingSource,
candidateResultIndices,
conglomerateListeneer
);
}, exception -> {
logger
.error(
new ParameterizedMessage("Fail to update [{}]'s mapping due to [{}]", index, exception.getMessage())
);
conglomerateListeneer.onFailure(exception);
processResultIndexMappingIteration(
indexPos + 1,
newestSchemaVersion,
mappingSource,
candidateResultIndices,
conglomerateListeneer
);
})
);
} else {
// index does not exist or the version is already up-to-date.
// When creating index, new mappings will be used.
// We don't need to update it.
logger.info(new ParameterizedMessage("We don't need to update [{}]'s mapping", index));
conglomerateListeneer.onResponse(null);
processResultIndexMappingIteration(
indexPos + 1,
newestSchemaVersion,
mappingSource,
candidateResultIndices,
conglomerateListeneer
);
}
}, exception -> {
logger.error(new ParameterizedMessage("Fail to check whether we should update [{}]'s mapping", index), exception);
conglomerateListeneer.onFailure(exception);
processResultIndexMappingIteration(
indexPos + 1,
newestSchemaVersion,
mappingSource,
candidateResultIndices,
conglomerateListeneer
);
}));
}
private void markMappingUpdated(IndexType adIndex) {
IndexState indexState = indexStates.computeIfAbsent(adIndex, k -> new IndexState(k.getMapping()));
if (Boolean.FALSE.equals(indexState.mappingUpToDate)) {
indexState.mappingUpToDate = Boolean.TRUE;
logger.info(new ParameterizedMessage("Mark [{}]'s mapping up-to-date", adIndex.getIndexName()));
}
}
private void shouldUpdateIndex(IndexType index, ActionListener<Boolean> thenDo) {
Integer newVersion = indexStates.computeIfAbsent(index, k -> new IndexState(k.getMapping())).schemaVersion;
shouldUpdateIndex(index.getIndexName(), index.isAlias(), newVersion, thenDo);
}
private void shouldUpdateIndex(String indexOrAliasName, boolean isAlias, Integer newVersion, ActionListener<Boolean> thenDo) {
boolean exists = false;
if (isAlias) {
exists = doesAliasExist(indexOrAliasName);
} else {
exists = doesIndexExist(indexOrAliasName);
}
if (false == exists) {
thenDo.onResponse(Boolean.FALSE);
return;
}
if (isAlias) {
GetAliasesRequest getAliasRequest = new GetAliasesRequest()
.aliases(indexOrAliasName)
.indicesOptions(IndicesOptions.lenientExpandOpenHidden());
adminClient.indices().getAliases(getAliasRequest, ActionListener.wrap(getAliasResponse -> {
String concreteIndex = null;
for (Map.Entry<String, List<AliasMetadata>> entry : getAliasResponse.getAliases().entrySet()) {
if (false == entry.getValue().isEmpty()) {
// we assume the alias map to one concrete index, thus we can return after finding one
concreteIndex = entry.getKey();
break;
}
}
if (concreteIndex == null) {
thenDo.onResponse(Boolean.FALSE);
return;
}
shouldUpdateConcreteIndex(concreteIndex, newVersion, thenDo);
}, exception -> logger.error(new ParameterizedMessage("Fail to get [{}]'s alias", indexOrAliasName), exception)));
} else {
shouldUpdateConcreteIndex(indexOrAliasName, newVersion, thenDo);
}
}
protected void getConcreteIndex(String indexOrAliasName, ActionListener<String> thenDo) {
if (doesAliasExist(indexOrAliasName)) {
GetAliasesRequest getAliasRequest = new GetAliasesRequest()
.aliases(indexOrAliasName)
.indicesOptions(IndicesOptions.lenientExpandOpenHidden());
adminClient.indices().getAliases(getAliasRequest, ActionListener.wrap(getAliasResponse -> {
String concreteIndex = null;
for (Map.Entry<String, List<AliasMetadata>> entry : getAliasResponse.getAliases().entrySet()) {
if (false == entry.getValue().isEmpty()) {
// we assume the alias map to one concrete index, thus we can return after finding one
concreteIndex = entry.getKey();
break;
}
}
thenDo.onResponse(concreteIndex);
}, exception -> logger.error(new ParameterizedMessage("Fail to get [{}]'s alias", indexOrAliasName), exception)));
} else {
// if this is not an alias or the index does not exist yet, return indexOrAliasName
thenDo.onResponse(indexOrAliasName);
}
}
/**
*
* @param index Index metadata
* @return The schema version of the given Index
*/
public int getSchemaVersion(IndexType index) {
IndexState indexState = this.indexStates.computeIfAbsent(index, k -> new IndexState(k.getMapping()));
return indexState.schemaVersion;
}
public <T> void initCustomResultIndexAndExecute(String resultIndexOrAlias, ExecutorFunction function, ActionListener<T> listener) {
if (!doesIndexExist(resultIndexOrAlias) && !doesAliasExist(resultIndexOrAlias)) {
initCustomResultIndexDirectly(resultIndexOrAlias, ActionListener.wrap(response -> {
if (response.isAcknowledged()) {
logger.info("Successfully created result index {}", resultIndexOrAlias);
validateResultIndexAndExecute(resultIndexOrAlias, function, false, listener);
} else {