forked from opensearch-project/anomaly-detection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ADTaskManager.java
3132 lines (2980 loc) · 147 KB
/
ADTaskManager.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.ad.task;
import static org.opensearch.action.DocWriteResponse.Result.CREATED;
import static org.opensearch.ad.AnomalyDetectorPlugin.AD_BATCH_TASK_THREAD_POOL_NAME;
import static org.opensearch.ad.constant.CommonErrorMessages.CAN_NOT_FIND_LATEST_TASK;
import static org.opensearch.ad.constant.CommonErrorMessages.CREATE_INDEX_NOT_ACKNOWLEDGED;
import static org.opensearch.ad.constant.CommonErrorMessages.DETECTOR_IS_RUNNING;
import static org.opensearch.ad.constant.CommonErrorMessages.EXCEED_HISTORICAL_ANALYSIS_LIMIT;
import static org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG;
import static org.opensearch.ad.constant.CommonErrorMessages.HC_DETECTOR_TASK_IS_UPDATING;
import static org.opensearch.ad.constant.CommonErrorMessages.NO_ELIGIBLE_NODE_TO_RUN_DETECTOR;
import static org.opensearch.ad.constant.CommonName.DETECTION_STATE_INDEX;
import static org.opensearch.ad.indices.AnomalyDetectionIndices.ALL_AD_RESULTS_INDEX_PATTERN;
import static org.opensearch.ad.model.ADTask.COORDINATING_NODE_FIELD;
import static org.opensearch.ad.model.ADTask.DETECTOR_ID_FIELD;
import static org.opensearch.ad.model.ADTask.ERROR_FIELD;
import static org.opensearch.ad.model.ADTask.ESTIMATED_MINUTES_LEFT_FIELD;
import static org.opensearch.ad.model.ADTask.EXECUTION_END_TIME_FIELD;
import static org.opensearch.ad.model.ADTask.EXECUTION_START_TIME_FIELD;
import static org.opensearch.ad.model.ADTask.INIT_PROGRESS_FIELD;
import static org.opensearch.ad.model.ADTask.IS_LATEST_FIELD;
import static org.opensearch.ad.model.ADTask.LAST_UPDATE_TIME_FIELD;
import static org.opensearch.ad.model.ADTask.PARENT_TASK_ID_FIELD;
import static org.opensearch.ad.model.ADTask.STATE_FIELD;
import static org.opensearch.ad.model.ADTask.STOPPED_BY_FIELD;
import static org.opensearch.ad.model.ADTask.TASK_PROGRESS_FIELD;
import static org.opensearch.ad.model.ADTask.TASK_TYPE_FIELD;
import static org.opensearch.ad.model.ADTaskState.NOT_ENDED_STATES;
import static org.opensearch.ad.model.ADTaskType.ALL_HISTORICAL_TASK_TYPES;
import static org.opensearch.ad.model.ADTaskType.HISTORICAL_DETECTOR_TASK_TYPES;
import static org.opensearch.ad.model.ADTaskType.REALTIME_TASK_TYPES;
import static org.opensearch.ad.model.ADTaskType.taskTypeToString;
import static org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX;
import static org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX;
import static org.opensearch.ad.model.AnomalyResult.TASK_ID_FIELD;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.BATCH_TASK_PIECE_INTERVAL_SECONDS;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.DELETE_AD_RESULT_WHEN_DELETE_DETECTOR;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_BATCH_TASK_PER_NODE;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_OLD_AD_TASK_DOCS;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_OLD_AD_TASK_DOCS_PER_DETECTOR;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_RUNNING_ENTITIES_PER_DETECTOR_FOR_HISTORICAL_ANALYSIS;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.NUM_MIN_SAMPLES;
import static org.opensearch.ad.settings.AnomalyDetectorSettings.REQUEST_TIMEOUT;
import static org.opensearch.ad.stats.InternalStatNames.AD_DETECTOR_ASSIGNED_BATCH_TASK_SLOT_COUNT;
import static org.opensearch.ad.stats.InternalStatNames.AD_USED_BATCH_TASK_SLOT_COUNT;
import static org.opensearch.ad.util.ExceptionUtil.getErrorMessage;
import static org.opensearch.ad.util.ExceptionUtil.getShardsFailure;
import static org.opensearch.ad.util.ParseUtils.isNullOrEmpty;
import static org.opensearch.ad.util.RestHandlerUtils.XCONTENT_WITH_TYPE;
import static org.opensearch.ad.util.RestHandlerUtils.createXContentParserFromRegistry;
import static org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.opensearch.ExceptionsHelper;
import org.opensearch.OpenSearchStatusException;
import org.opensearch.ResourceAlreadyExistsException;
import org.opensearch.Version;
import org.opensearch.action.ActionListener;
import org.opensearch.action.ActionListenerResponseHandler;
import org.opensearch.action.bulk.BulkAction;
import org.opensearch.action.bulk.BulkItemResponse;
import org.opensearch.action.bulk.BulkRequest;
import org.opensearch.action.delete.DeleteRequest;
import org.opensearch.action.delete.DeleteResponse;
import org.opensearch.action.get.GetRequest;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.index.IndexResponse;
import org.opensearch.action.search.SearchRequest;
import org.opensearch.action.search.SearchResponse;
import org.opensearch.action.support.WriteRequest;
import org.opensearch.action.update.UpdateRequest;
import org.opensearch.action.update.UpdateResponse;
import org.opensearch.ad.auth.UserIdentity;
import org.opensearch.ad.cluster.HashRing;
import org.opensearch.ad.common.exception.ADTaskCancelledException;
import org.opensearch.ad.common.exception.AnomalyDetectionException;
import org.opensearch.ad.common.exception.DuplicateTaskException;
import org.opensearch.ad.common.exception.EndRunException;
import org.opensearch.ad.common.exception.LimitExceededException;
import org.opensearch.ad.common.exception.ResourceNotFoundException;
import org.opensearch.ad.indices.AnomalyDetectionIndices;
import org.opensearch.ad.model.ADEntityTaskProfile;
import org.opensearch.ad.model.ADTask;
import org.opensearch.ad.model.ADTaskAction;
import org.opensearch.ad.model.ADTaskProfile;
import org.opensearch.ad.model.ADTaskState;
import org.opensearch.ad.model.ADTaskType;
import org.opensearch.ad.model.AnomalyDetector;
import org.opensearch.ad.model.AnomalyDetectorJob;
import org.opensearch.ad.model.DetectionDateRange;
import org.opensearch.ad.model.DetectorProfile;
import org.opensearch.ad.model.Entity;
import org.opensearch.ad.rest.handler.AnomalyDetectorFunction;
import org.opensearch.ad.rest.handler.IndexAnomalyDetectorJobActionHandler;
import org.opensearch.ad.transport.ADBatchAnomalyResultAction;
import org.opensearch.ad.transport.ADBatchAnomalyResultRequest;
import org.opensearch.ad.transport.ADCancelTaskAction;
import org.opensearch.ad.transport.ADCancelTaskRequest;
import org.opensearch.ad.transport.ADStatsNodeResponse;
import org.opensearch.ad.transport.ADStatsNodesAction;
import org.opensearch.ad.transport.ADStatsRequest;
import org.opensearch.ad.transport.ADTaskProfileAction;
import org.opensearch.ad.transport.ADTaskProfileNodeResponse;
import org.opensearch.ad.transport.ADTaskProfileRequest;
import org.opensearch.ad.transport.AnomalyDetectorJobResponse;
import org.opensearch.ad.transport.ForwardADTaskAction;
import org.opensearch.ad.transport.ForwardADTaskRequest;
import org.opensearch.ad.util.DiscoveryNodeFilterer;
import org.opensearch.ad.util.RestHandlerUtils;
import org.opensearch.client.Request;
import org.opensearch.client.Response;
import org.opensearch.cluster.node.DiscoveryNode;
import org.opensearch.common.Strings;
import org.opensearch.common.bytes.BytesReference;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.xcontent.LoggingDeprecationHandler;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.common.xcontent.json.JsonXContent;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.index.IndexNotFoundException;
import org.opensearch.index.query.BoolQueryBuilder;
import org.opensearch.index.query.NestedQueryBuilder;
import org.opensearch.index.query.QueryBuilders;
import org.opensearch.index.query.TermQueryBuilder;
import org.opensearch.index.query.TermsQueryBuilder;
import org.opensearch.index.reindex.BulkByScrollResponse;
import org.opensearch.index.reindex.DeleteByQueryAction;
import org.opensearch.index.reindex.DeleteByQueryRequest;
import org.opensearch.index.reindex.UpdateByQueryAction;
import org.opensearch.index.reindex.UpdateByQueryRequest;
import org.opensearch.rest.RestStatus;
import org.opensearch.script.Script;
import org.opensearch.sdk.SDKClient.SDKRestClient;
import org.opensearch.sdk.SDKClusterService;
import org.opensearch.sdk.SDKNamedXContentRegistry;
import org.opensearch.search.SearchHit;
import org.opensearch.search.builder.SearchSourceBuilder;
import org.opensearch.search.sort.SortOrder;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.transport.TransportRequestOptions;
import org.opensearch.transport.TransportService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/**
* Manage AD task.
*/
public class ADTaskManager {
public static final String AD_TASK_LEAD_NODE_MODEL_ID = "ad_task_lead_node_model_id";
public static final String AD_TASK_MAINTAINENCE_NODE_MODEL_ID = "ad_task_maintainence_node_model_id";
// HC batch task timeout after 10 minutes if no update after last known run time.
public static final int HC_BATCH_TASK_CACHE_TIMEOUT_IN_MILLIS = 600_000;
private final Logger logger = LogManager.getLogger(this.getClass());
static final String STATE_INDEX_NOT_EXIST_MSG = "State index does not exist.";
private final Set<String> retryableErrors = ImmutableSet.of(EXCEED_HISTORICAL_ANALYSIS_LIMIT, NO_ELIGIBLE_NODE_TO_RUN_DETECTOR);
private final SDKRestClient client;
private final SDKClusterService clusterService;
private final SDKNamedXContentRegistry xContentRegistry;
private final AnomalyDetectionIndices detectionIndices;
private final DiscoveryNodeFilterer nodeFilter;
private final ADTaskCacheManager adTaskCacheManager;
private final HashRing hashRing;
private volatile Integer maxOldAdTaskDocsPerDetector;
private volatile Integer pieceIntervalSeconds;
private volatile boolean deleteADResultWhenDeleteDetector;
private volatile TransportRequestOptions transportRequestOptions;
private final ThreadPool threadPool;
private static int DEFAULT_MAINTAIN_INTERVAL_IN_SECONDS = 5;
private final Semaphore checkingTaskSlot;
private volatile Integer maxAdBatchTaskPerNode;
private volatile Integer maxRunningEntitiesPerDetector;
private final Semaphore scaleEntityTaskLane;
private static final int SCALE_ENTITY_TASK_LANE_INTERVAL_IN_MILLIS = 10_000; // 10 seconds
public ADTaskManager(
Settings settings,
SDKClusterService clusterService,
SDKRestClient client,
SDKNamedXContentRegistry xContentRegistry,
AnomalyDetectionIndices detectionIndices,
DiscoveryNodeFilterer nodeFilter,
HashRing hashRing,
ADTaskCacheManager adTaskCacheManager,
ThreadPool threadPool
) {
this.client = client;
this.xContentRegistry = xContentRegistry;
this.detectionIndices = detectionIndices;
this.nodeFilter = nodeFilter;
this.clusterService = clusterService;
this.adTaskCacheManager = adTaskCacheManager;
this.hashRing = hashRing;
this.maxOldAdTaskDocsPerDetector = MAX_OLD_AD_TASK_DOCS_PER_DETECTOR.get(settings);
clusterService
.getClusterSettings()
.addSettingsUpdateConsumer(MAX_OLD_AD_TASK_DOCS_PER_DETECTOR, it -> maxOldAdTaskDocsPerDetector = it);
this.pieceIntervalSeconds = BATCH_TASK_PIECE_INTERVAL_SECONDS.get(settings);
clusterService.getClusterSettings().addSettingsUpdateConsumer(BATCH_TASK_PIECE_INTERVAL_SECONDS, it -> pieceIntervalSeconds = it);
this.deleteADResultWhenDeleteDetector = DELETE_AD_RESULT_WHEN_DELETE_DETECTOR.get(settings);
clusterService
.getClusterSettings()
.addSettingsUpdateConsumer(DELETE_AD_RESULT_WHEN_DELETE_DETECTOR, it -> deleteADResultWhenDeleteDetector = it);
this.maxAdBatchTaskPerNode = MAX_BATCH_TASK_PER_NODE.get(settings);
clusterService.getClusterSettings().addSettingsUpdateConsumer(MAX_BATCH_TASK_PER_NODE, it -> maxAdBatchTaskPerNode = it);
this.maxRunningEntitiesPerDetector = MAX_RUNNING_ENTITIES_PER_DETECTOR_FOR_HISTORICAL_ANALYSIS.get(settings);
clusterService
.getClusterSettings()
.addSettingsUpdateConsumer(MAX_RUNNING_ENTITIES_PER_DETECTOR_FOR_HISTORICAL_ANALYSIS, it -> maxRunningEntitiesPerDetector = it);
transportRequestOptions = TransportRequestOptions
.builder()
.withType(TransportRequestOptions.Type.REG)
.withTimeout(REQUEST_TIMEOUT.get(settings))
.build();
clusterService
.getClusterSettings()
.addSettingsUpdateConsumer(
REQUEST_TIMEOUT,
it -> {
transportRequestOptions = TransportRequestOptions
.builder()
.withType(TransportRequestOptions.Type.REG)
.withTimeout(it)
.build();
}
);
this.threadPool = threadPool;
this.checkingTaskSlot = new Semaphore(1);
this.scaleEntityTaskLane = new Semaphore(1);
}
/**
* Start detector. Will create schedule job for realtime detector,
* and start AD task for historical detector.
*
* @param detectorId detector id
* @param detectionDateRange historical analysis date range
* @param handler anomaly detector job action handler
* @param user user
* @param transportService transport service
* @param listener action listener
*/
public void startDetector(
String detectorId,
DetectionDateRange detectionDateRange,
IndexAnomalyDetectorJobActionHandler handler,
UserIdentity user,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener
) {
// upgrade index mapping of AD default indices
// FIXME @anomaly.detection - startdetector : uncomment after AnomalyDetectionIndices.updateJobIndexSettingIfNecessary() client execution has been replaced with the java client
// detectionIndices.update();
getDetector(detectorId, (detector) -> {
if (!detector.isPresent()) {
listener.onFailure(new OpenSearchStatusException(FAIL_TO_FIND_DETECTOR_MSG + detectorId, RestStatus.NOT_FOUND));
return;
}
// Validate if detector is ready to start. Will return null if ready to start.
String errorMessage = validateDetector(detector.get());
if (errorMessage != null) {
listener.onFailure(new OpenSearchStatusException(errorMessage, RestStatus.BAD_REQUEST));
return;
}
String resultIndex = detector.get().getResultIndex();
if (resultIndex == null) {
startRealtimeOrHistoricalDetection(detectionDateRange, handler, user, transportService, listener, detector);
return;
}
detectionIndices
.initCustomResultIndexAndExecute(
resultIndex,
() -> startRealtimeOrHistoricalDetection(detectionDateRange, handler, user, transportService, listener, detector),
listener
);
}, listener);
}
private void startRealtimeOrHistoricalDetection(
DetectionDateRange detectionDateRange,
IndexAnomalyDetectorJobActionHandler handler,
UserIdentity user,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener,
Optional<AnomalyDetector> detector
) {
try {
if (detectionDateRange == null) {
// start realtime job
handler.startAnomalyDetectorJob(detector.get());
} else {
// start historical analysis task
forwardApplyForTaskSlotsRequestToLeadNode(detector.get(), detectionDateRange, user, transportService, listener);
}
} catch (Exception e) {
logger.error("Failed to stash context", e);
listener.onFailure(e);
}
}
/**
* When AD receives start historical analysis request for a detector, will
* 1. Forward to lead node to check available task slots first.
* 2. If available task slots exit, will forward request to coordinating node
* to gather information like top entities.
* 3. Then coordinating node will choose one data node with least load as work
* node and dispatch historical analysis to it.
*
* @param detector detector
* @param detectionDateRange detection date range
* @param user user
* @param transportService transport service
* @param listener action listener
*/
protected void forwardApplyForTaskSlotsRequestToLeadNode(
AnomalyDetector detector,
DetectionDateRange detectionDateRange,
UserIdentity user,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener
) {
ForwardADTaskRequest forwardADTaskRequest = new ForwardADTaskRequest(
detector,
detectionDateRange,
user,
ADTaskAction.APPLY_FOR_TASK_SLOTS
);
forwardRequestToLeadNode(forwardADTaskRequest, transportService, listener);
}
public void forwardScaleTaskSlotRequestToLeadNode(
ADTask adTask,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener
) {
forwardRequestToLeadNode(new ForwardADTaskRequest(adTask, ADTaskAction.CHECK_AVAILABLE_TASK_SLOTS), transportService, listener);
}
public void forwardRequestToLeadNode(
ForwardADTaskRequest forwardADTaskRequest,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener
) {
hashRing.buildAndGetOwningNodeWithSameLocalAdVersion(AD_TASK_LEAD_NODE_MODEL_ID, node -> {
if (!node.isPresent()) {
listener.onFailure(new ResourceNotFoundException("Can't find AD task lead node"));
return;
}
transportService
.sendRequest(
node.get(),
ForwardADTaskAction.NAME,
forwardADTaskRequest,
transportRequestOptions,
new ActionListenerResponseHandler<>(listener, AnomalyDetectorJobResponse::new)
);
}, listener);
}
/**
* Forward historical analysis task to coordinating node.
*
* @param detector anomaly detector
* @param detectionDateRange historical analysis date range
* @param user user
* @param availableTaskSlots available task slots
* @param transportService transport service
* @param listener action listener
*/
public void startHistoricalAnalysis(
AnomalyDetector detector,
DetectionDateRange detectionDateRange,
UserIdentity user,
int availableTaskSlots,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener
) {
String detectorId = detector.getDetectorId();
hashRing.buildAndGetOwningNodeWithSameLocalAdVersion(detectorId, owningNode -> {
if (!owningNode.isPresent()) {
logger.debug("Can't find eligible node to run as AD task's coordinating node");
listener.onFailure(new OpenSearchStatusException("No eligible node to run detector", RestStatus.INTERNAL_SERVER_ERROR));
return;
}
logger.debug("coordinating node is : {} for detector: {}", owningNode.get().getId(), detectorId);
forwardDetectRequestToCoordinatingNode(
detector,
detectionDateRange,
user,
availableTaskSlots,
ADTaskAction.START,
transportService,
owningNode.get(),
listener
);
}, listener);
}
/**
* We have three types of nodes in AD task process.
*
* 1.Forwarding node which receives external request. The request will \
* be sent to coordinating node first.
* 2.Coordinating node which maintains running historical detector set.\
* We use hash ring to find coordinating node with detector id. \
* Coordinating node will find a worker node with least load and \
* dispatch AD task to that worker node.
* 3.Worker node which will run AD task.
*
* This function is to forward the request to coordinating node.
*
* @param detector anomaly detector
* @param detectionDateRange historical analysis date range
* @param user user
* @param availableTaskSlots available task slots
* @param adTaskAction AD task action
* @param transportService transport service
* @param node ES node
* @param listener action listener
*/
protected void forwardDetectRequestToCoordinatingNode(
AnomalyDetector detector,
DetectionDateRange detectionDateRange,
UserIdentity user,
Integer availableTaskSlots,
ADTaskAction adTaskAction,
TransportService transportService,
DiscoveryNode node,
ActionListener<AnomalyDetectorJobResponse> listener
) {
Version adVersion = hashRing.getAdVersion(node.getId());
transportService
.sendRequest(
node,
ForwardADTaskAction.NAME,
// We need to check AD version of remote node as we may send clean detector cache request to old
// node, check ADTaskManager#cleanDetectorCache.
new ForwardADTaskRequest(detector, detectionDateRange, user, adTaskAction, availableTaskSlots, adVersion),
transportRequestOptions,
new ActionListenerResponseHandler<>(listener, AnomalyDetectorJobResponse::new)
);
}
/**
* Forward AD task to coordinating node
*
* @param adTask AD task
* @param adTaskAction AD task action
* @param transportService transport service
* @param listener action listener
*/
protected void forwardADTaskToCoordinatingNode(
ADTask adTask,
ADTaskAction adTaskAction,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener
) {
logger.debug("Forward AD task to coordinating node, task id: {}, action: {}", adTask.getTaskId(), adTaskAction.name());
transportService
.sendRequest(
getCoordinatingNode(adTask),
ForwardADTaskAction.NAME,
new ForwardADTaskRequest(adTask, adTaskAction),
transportRequestOptions,
new ActionListenerResponseHandler<>(listener, AnomalyDetectorJobResponse::new)
);
}
/**
* Forward stale running entities to coordinating node to clean up.
*
* @param adTask AD task
* @param adTaskAction AD task action
* @param transportService transport service
* @param staleRunningEntity stale running entities
* @param listener action listener
*/
protected void forwardStaleRunningEntitiesToCoordinatingNode(
ADTask adTask,
ADTaskAction adTaskAction,
TransportService transportService,
List<String> staleRunningEntity,
ActionListener<AnomalyDetectorJobResponse> listener
) {
transportService
.sendRequest(
getCoordinatingNode(adTask),
ForwardADTaskAction.NAME,
new ForwardADTaskRequest(adTask, adTaskAction, staleRunningEntity),
transportRequestOptions,
new ActionListenerResponseHandler<>(listener, AnomalyDetectorJobResponse::new)
);
}
/**
* Check available task slots before start historical analysis and scale task lane.
* This check will be done on lead node which will gather detector task slots of all
* data nodes and calculate how many task slots available.
*
* @param adTask AD task
* @param detector detector
* @param detectionDateRange detection date range
* @param user user
* @param afterCheckAction target task action to run after task slot checking
* @param transportService transport service
* @param listener action listener
*/
public void checkTaskSlots(
ADTask adTask,
AnomalyDetector detector,
DetectionDateRange detectionDateRange,
UserIdentity user,
ADTaskAction afterCheckAction,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener
) {
String detectorId = detector.getDetectorId();
logger.debug("Start checking task slots for detector: {}, task action: {}", detectorId, afterCheckAction);
if (!checkingTaskSlot.tryAcquire()) {
logger.info("Can't acquire checking task slot semaphore for detector {}", detectorId);
listener
.onFailure(
new OpenSearchStatusException(
"Too many historical analysis requests in short time. Please retry later.",
RestStatus.FORBIDDEN
)
);
return;
}
ActionListener<AnomalyDetectorJobResponse> wrappedActionListener = ActionListener.runAfter(listener, () -> {
checkingTaskSlot.release(1);
logger.debug("Release checking task slot semaphore on lead node for detector {}", detectorId);
});
hashRing.getNodesWithSameLocalAdVersion(nodes -> {
int maxAdTaskSlots = nodes.length * maxAdBatchTaskPerNode;
ADStatsRequest adStatsRequest = new ADStatsRequest(nodes);
adStatsRequest
.addAll(ImmutableSet.of(AD_USED_BATCH_TASK_SLOT_COUNT.getName(), AD_DETECTOR_ASSIGNED_BATCH_TASK_SLOT_COUNT.getName()));
client.execute(ADStatsNodesAction.INSTANCE, adStatsRequest, ActionListener.wrap(adStatsResponse -> {
int totalUsedTaskSlots = 0; // Total entity tasks running on worker nodes
int totalAssignedTaskSlots = 0; // Total assigned task slots on coordinating nodes
for (ADStatsNodeResponse response : adStatsResponse.getNodes()) {
totalUsedTaskSlots += (int) response.getStatsMap().get(AD_USED_BATCH_TASK_SLOT_COUNT.getName());
totalAssignedTaskSlots += (int) response.getStatsMap().get(AD_DETECTOR_ASSIGNED_BATCH_TASK_SLOT_COUNT.getName());
}
logger
.info(
"Current total used task slots is {}, total detector assigned task slots is {} when start historical "
+ "analysis for detector {}",
totalUsedTaskSlots,
totalAssignedTaskSlots,
detectorId
);
// In happy case, totalAssignedTaskSlots >= totalUsedTaskSlots. If some coordinating node left, then we can't
// get detector task slots cached on it, so it's possible that totalAssignedTaskSlots < totalUsedTaskSlots.
int currentUsedTaskSlots = Math.max(totalUsedTaskSlots, totalAssignedTaskSlots);
if (currentUsedTaskSlots >= maxAdTaskSlots) {
wrappedActionListener.onFailure(new OpenSearchStatusException("No available task slot", RestStatus.BAD_REQUEST));
return;
}
int availableAdTaskSlots = maxAdTaskSlots - currentUsedTaskSlots;
logger.info("Current available task slots is {} for historical analysis of detector {}", availableAdTaskSlots, detectorId);
if (ADTaskAction.SCALE_ENTITY_TASK_SLOTS == afterCheckAction) {
forwardToCoordinatingNode(
adTask,
detector,
detectionDateRange,
user,
afterCheckAction,
transportService,
wrappedActionListener,
availableAdTaskSlots
);
return;
}
// It takes long time to check top entities especially for multi-category HC. Tested with
// 1.8 billion docs for multi-category HC, it took more than 20 seconds and caused timeout.
// By removing top entity check, it took about 200ms to return. So just remove it to make
// sure REST API can return quickly.
// We may assign more task slots. For example, cluster has 4 data nodes, each node can run 2
// batch tasks, so the available task slot number is 8. If max running entities per HC is 4,
// then we will assign 4 tasks slots to this HC detector (4 is less than 8). The data index
// only has 2 entities. So we assign 2 more task slots than actual need. But it's ok as we
// will auto tune task slot when historical analysis task starts.
int approvedTaskSlots = detector.isMultientityDetector()
? Math.min(maxRunningEntitiesPerDetector, availableAdTaskSlots)
: 1;
forwardToCoordinatingNode(
adTask,
detector,
detectionDateRange,
user,
afterCheckAction,
transportService,
wrappedActionListener,
approvedTaskSlots
);
}, exception -> {
logger.error("Failed to get node's task stats for detector " + detectorId, exception);
wrappedActionListener.onFailure(exception);
}));
}, wrappedActionListener);
}
private void forwardToCoordinatingNode(
ADTask adTask,
AnomalyDetector detector,
DetectionDateRange detectionDateRange,
UserIdentity user,
ADTaskAction targetActionOfTaskSlotChecking,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> wrappedActionListener,
int approvedTaskSlots
) {
switch (targetActionOfTaskSlotChecking) {
case START:
logger
.info(
"Will assign {} task slots to run historical analysis for detector {}",
approvedTaskSlots,
detector.getDetectorId()
);
startHistoricalAnalysis(detector, detectionDateRange, user, approvedTaskSlots, transportService, wrappedActionListener);
break;
case SCALE_ENTITY_TASK_SLOTS:
logger
.info(
"There are {} task slots available now to scale historical analysis task lane for detector {}",
approvedTaskSlots,
adTask.getDetectorId()
);
scaleTaskLaneOnCoordinatingNode(adTask, approvedTaskSlots, transportService, wrappedActionListener);
break;
default:
wrappedActionListener.onFailure(new AnomalyDetectionException("Unknown task action " + targetActionOfTaskSlotChecking));
break;
}
}
protected void scaleTaskLaneOnCoordinatingNode(
ADTask adTask,
int approvedTaskSlot,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener
) {
DiscoveryNode coordinatingNode = getCoordinatingNode(adTask);
transportService
.sendRequest(
coordinatingNode,
ForwardADTaskAction.NAME,
new ForwardADTaskRequest(adTask, approvedTaskSlot, ADTaskAction.SCALE_ENTITY_TASK_SLOTS),
transportRequestOptions,
new ActionListenerResponseHandler<>(listener, AnomalyDetectorJobResponse::new)
);
}
private DiscoveryNode getCoordinatingNode(ADTask adTask) {
String coordinatingNode = adTask.getCoordinatingNode();
DiscoveryNode[] eligibleDataNodes = nodeFilter.getEligibleDataNodes();
DiscoveryNode targetNode = null;
for (DiscoveryNode node : eligibleDataNodes) {
if (node.getId().equals(coordinatingNode)) {
targetNode = node;
break;
}
}
if (targetNode == null) {
throw new ResourceNotFoundException(adTask.getDetectorId(), "AD task coordinating node not found");
}
return targetNode;
}
/**
* Start anomaly detector.
* For historical analysis, this method will be called on coordinating node.
* For realtime task, we won't know AD job coordinating node until AD job starts. So
* this method will be called on vanilla node.
*
* Will init task index if not exist and write new AD task to index. If task index
* exists, will check if there is task running. If no running task, reset old task
* as not latest and clean old tasks which exceeds max old task doc limitation.
* Then find out node with least load and dispatch task to that node(worker node).
*
* @param detector anomaly detector
* @param detectionDateRange detection date range
* @param user user
* @param transportService transport service
* @param listener action listener
*/
public void startDetector(
AnomalyDetector detector,
DetectionDateRange detectionDateRange,
UserIdentity user,
TransportService transportService,
ActionListener<AnomalyDetectorJobResponse> listener
) {
try {
if (detectionIndices.doesDetectorStateIndexExist()) {
// If detection index exist, check if latest AD task is running
getAndExecuteOnLatestDetectorLevelTask(detector.getDetectorId(), getADTaskTypes(detectionDateRange), (adTask) -> {
if (!adTask.isPresent() || adTask.get().isDone()) {
updateLatestFlagOfOldTasksAndCreateNewTask(detector, detectionDateRange, user, listener);
} else {
listener.onFailure(new OpenSearchStatusException(DETECTOR_IS_RUNNING, RestStatus.BAD_REQUEST));
}
}, transportService, true, listener);
} else {
// If detection index doesn't exist, create index and execute detector.
detectionIndices.initDetectionStateIndex(ActionListener.wrap(r -> {
if (r.isAcknowledged()) {
logger.info("Created {} with mappings.", DETECTION_STATE_INDEX);
updateLatestFlagOfOldTasksAndCreateNewTask(detector, detectionDateRange, user, listener);
} else {
String error = String.format(Locale.ROOT, CREATE_INDEX_NOT_ACKNOWLEDGED, DETECTION_STATE_INDEX);
logger.warn(error);
listener.onFailure(new OpenSearchStatusException(error, RestStatus.INTERNAL_SERVER_ERROR));
}
}, e -> {
if (ExceptionsHelper.unwrapCause(e) instanceof ResourceAlreadyExistsException) {
updateLatestFlagOfOldTasksAndCreateNewTask(detector, detectionDateRange, user, listener);
} else {
logger.error("Failed to init anomaly detection state index", e);
listener.onFailure(e);
}
}));
}
} catch (Exception e) {
logger.error("Failed to start detector " + detector.getDetectorId(), e);
listener.onFailure(e);
}
}
private ADTaskType getADTaskType(AnomalyDetector detector, DetectionDateRange detectionDateRange) {
if (detectionDateRange == null) {
return detector.isMultientityDetector() ? ADTaskType.REALTIME_HC_DETECTOR : ADTaskType.REALTIME_SINGLE_ENTITY;
} else {
return detector.isMultientityDetector() ? ADTaskType.HISTORICAL_HC_DETECTOR : ADTaskType.HISTORICAL_SINGLE_ENTITY;
}
}
private List<ADTaskType> getADTaskTypes(DetectionDateRange detectionDateRange) {
return getADTaskTypes(detectionDateRange, false);
}
/**
* Get list of task types.
* 1. If detection date range is null, will return all realtime task types
* 2. If detection date range is not null, will return all historical detector level tasks types
* if resetLatestTaskStateFlag is true; otherwise return all historical tasks types include
* HC entity level task type.
* @param detectionDateRange detection date range
* @param resetLatestTaskStateFlag reset latest task state or not
* @return list of AD task types
*/
private List<ADTaskType> getADTaskTypes(DetectionDateRange detectionDateRange, boolean resetLatestTaskStateFlag) {
if (detectionDateRange == null) {
return REALTIME_TASK_TYPES;
} else {
if (resetLatestTaskStateFlag) {
// return all task types include HC entity task to make sure we can reset all tasks latest flag
return ALL_HISTORICAL_TASK_TYPES;
} else {
return HISTORICAL_DETECTOR_TASK_TYPES;
}
}
}
/**
* Stop detector.
* For realtime detector, will set detector job as disabled.
* For historical detector, will set its AD task as cancelled.
*
* @param detectorId detector id
* @param historical stop historical analysis or not
* @param handler AD job action handler
* @param user user
* @param transportService transport service
* @param listener action listener
*/
// @anomaly-detection.create-detector Commented this code until we have support of Job Scheduler for extensibility
// public void stopDetector(
// String detectorId,
// boolean historical,
// IndexAnomalyDetectorJobActionHandler handler,
// UserIdentity user,
// TransportService transportService,
// ActionListener<AnomalyDetectorJobResponse> listener
// ) {
// getDetector(detectorId, (detector) -> {
// if (!detector.isPresent()) {
// listener.onFailure(new OpenSearchStatusException(FAIL_TO_FIND_DETECTOR_MSG + detectorId, RestStatus.NOT_FOUND));
// return;
// }
// if (historical) {
// // stop historical analyis
// getAndExecuteOnLatestDetectorLevelTask(
// detectorId,
// HISTORICAL_DETECTOR_TASK_TYPES,
// (task) -> stopHistoricalAnalysis(detectorId, task, user, listener),
// transportService,
// false,// don't need to reset task state when stop detector
// listener
// );
// } else {
// // stop realtime detector job
// handler.stopAnomalyDetectorJob(detectorId);
// }
// }, listener);
// }
/**
* Get anomaly detector and execute consumer function.
* [Important!] Make sure listener returns in function
*
* @param detectorId detector id
* @param function consumer function
* @param listener action listener
* @param <T> action listener response type
*/
public <T> void getDetector(String detectorId, Consumer<Optional<AnomalyDetector>> function, ActionListener<T> listener) {
GetRequest getRequest = new GetRequest(ANOMALY_DETECTORS_INDEX, detectorId);
client.get(getRequest, ActionListener.wrap(response -> {
if (!response.isExists()) {
function.accept(Optional.empty());
return;
}
try (XContentParser parser = createXContentParserFromRegistry(xContentRegistry.getRegistry(), response.getSourceAsBytesRef())) {
ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser);
AnomalyDetector detector = AnomalyDetector.parse(parser, response.getId(), response.getVersion());
function.accept(Optional.of(detector));
} catch (Exception e) {
String message = "Failed to parse anomaly detector " + detectorId;
logger.error(message, e);
listener.onFailure(new OpenSearchStatusException(message, RestStatus.INTERNAL_SERVER_ERROR));
}
}, exception -> {
logger.error("Failed to get detector " + detectorId, exception);
listener.onFailure(exception);
}));
}
/**
* Get latest AD task and execute consumer function.
* [Important!] Make sure listener returns in function
*
* @param detectorId detector id
* @param adTaskTypes AD task types
* @param function consumer function
* @param transportService transport service
* @param resetTaskState reset task state or not
* @param listener action listener
* @param <T> action listener response type
*/
public <T> void getAndExecuteOnLatestDetectorLevelTask(
String detectorId,
List<ADTaskType> adTaskTypes,
Consumer<Optional<ADTask>> function,
TransportService transportService,
boolean resetTaskState,
ActionListener<T> listener
) {
getAndExecuteOnLatestADTask(detectorId, null, null, adTaskTypes, function, transportService, resetTaskState, listener);
}
/**
* Get one latest AD task and execute consumer function.
* [Important!] Make sure listener returns in function
*
* @param detectorId detector id
* @param parentTaskId parent task id
* @param entity entity value
* @param adTaskTypes AD task types
* @param function consumer function
* @param transportService transport service
* @param resetTaskState reset task state or not
* @param listener action listener
* @param <T> action listener response type
*/
public <T> void getAndExecuteOnLatestADTask(
String detectorId,
String parentTaskId,
Entity entity,
List<ADTaskType> adTaskTypes,
Consumer<Optional<ADTask>> function,
TransportService transportService,
boolean resetTaskState,
ActionListener<T> listener
) {
getAndExecuteOnLatestADTasks(detectorId, parentTaskId, entity, adTaskTypes, (taskList) -> {
if (taskList != null && taskList.size() > 0) {
function.accept(Optional.ofNullable(taskList.get(0)));
} else {
function.accept(Optional.empty());
}
}, transportService, resetTaskState, 1, listener);
}
/**
* Get latest AD tasks and execute consumer function.
* If resetTaskState is true, will collect latest task's profile data from all data nodes. If no data
* node running the latest task, will reset the task state as STOPPED; otherwise, check if there is
* any stale running entities(entity exists in coordinating node cache but no task running on worker
* node) and clean up.
* [Important!] Make sure listener returns in function
*
* @param detectorId detector id
* @param parentTaskId parent task id
* @param entity entity value
* @param adTaskTypes AD task types
* @param function consumer function
* @param transportService transport service
* @param resetTaskState reset task state or not
* @param size return how many AD tasks
* @param listener action listener
* @param <T> response type of action listener
*/
public <T> void getAndExecuteOnLatestADTasks(
String detectorId,
String parentTaskId,
Entity entity,
List<ADTaskType> adTaskTypes,
Consumer<List<ADTask>> function,
TransportService transportService,
boolean resetTaskState,
int size,
ActionListener<T> listener
) {
BoolQueryBuilder query = new BoolQueryBuilder();
query.filter(new TermQueryBuilder(DETECTOR_ID_FIELD, detectorId));
query.filter(new TermQueryBuilder(IS_LATEST_FIELD, true));
if (parentTaskId != null) {
query.filter(new TermQueryBuilder(PARENT_TASK_ID_FIELD, parentTaskId));
}
if (adTaskTypes != null && adTaskTypes.size() > 0) {
query.filter(new TermsQueryBuilder(TASK_TYPE_FIELD, taskTypeToString(adTaskTypes)));
}
if (entity != null && !isNullOrEmpty(entity.getAttributes())) {
String path = "entity";
String entityKeyFieldName = path + ".name";
String entityValueFieldName = path + ".value";
for (Map.Entry<String, String> attribute : entity.getAttributes().entrySet()) {
BoolQueryBuilder entityBoolQuery = new BoolQueryBuilder();
TermQueryBuilder entityKeyFilterQuery = QueryBuilders.termQuery(entityKeyFieldName, attribute.getKey());
TermQueryBuilder entityValueFilterQuery = QueryBuilders.termQuery(entityValueFieldName, attribute.getValue());
entityBoolQuery.filter(entityKeyFilterQuery).filter(entityValueFilterQuery);