forked from opensearch-project/anomaly-detection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JobProcessor.java
653 lines (609 loc) · 27.2 KB
/
JobProcessor.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
/*
* 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;
import static org.opensearch.action.DocWriteResponse.Result.CREATED;
import static org.opensearch.action.DocWriteResponse.Result.UPDATED;
import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;
import static org.opensearch.timeseries.util.RestHandlerUtils.XCONTENT_WITH_TYPE;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.opensearch.action.ActionListener;
import org.opensearch.action.ActionType;
import org.opensearch.action.get.GetRequest;
import org.opensearch.action.get.GetResponse;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.support.WriteRequest;
import org.opensearch.ad.transport.AnomalyResultTransportAction;
import org.opensearch.client.Client;
import org.opensearch.common.settings.Setting;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.xcontent.LoggingDeprecationHandler;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.commons.InjectSecurity;
import org.opensearch.commons.authuser.User;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.jobscheduler.spi.JobExecutionContext;
import org.opensearch.jobscheduler.spi.LockModel;
import org.opensearch.jobscheduler.spi.schedule.IntervalSchedule;
import org.opensearch.jobscheduler.spi.utils.LockService;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.timeseries.common.exception.EndRunException;
import org.opensearch.timeseries.common.exception.InternalFailure;
import org.opensearch.timeseries.common.exception.TimeSeriesException;
import org.opensearch.timeseries.constant.CommonName;
import org.opensearch.timeseries.function.ExecutorFunction;
import org.opensearch.timeseries.indices.IndexManagement;
import org.opensearch.timeseries.indices.TimeSeriesIndex;
import org.opensearch.timeseries.model.Config;
import org.opensearch.timeseries.model.IndexableResult;
import org.opensearch.timeseries.model.Job;
import org.opensearch.timeseries.model.TaskState;
import org.opensearch.timeseries.model.TaskType;
import org.opensearch.timeseries.model.TimeSeriesTask;
import org.opensearch.timeseries.task.TaskCacheManager;
import org.opensearch.timeseries.task.TaskManager;
import org.opensearch.timeseries.transport.ResultRequest;
import org.opensearch.timeseries.transport.ResultResponse;
import org.opensearch.timeseries.util.SecurityUtil;
import com.google.common.base.Throwables;
/**
* JobScheduler will call job runner to get time series analysis result periodically
*/
public abstract class JobProcessor<IndexType extends Enum<IndexType> & TimeSeriesIndex, IndexManagementType extends IndexManagement<IndexType>, TaskCacheManagerType extends TaskCacheManager, TaskTypeEnum extends TaskType, TaskClass extends TimeSeriesTask, TaskManagerType extends TaskManager<TaskCacheManagerType, TaskTypeEnum, TaskClass, IndexType, IndexManagementType>, IndexableResultType extends IndexableResult, ExecuteResultResponseRecorderType extends ExecuteResultResponseRecorder<IndexType, IndexManagementType, TaskCacheManagerType, TaskTypeEnum, TaskClass, TaskManagerType, IndexableResultType>> {
private static final Logger log = LogManager.getLogger(JobProcessor.class);
private Settings settings;
private int maxRetryForEndRunException;
private Client client;
private ThreadPool threadPool;
private ConcurrentHashMap<String, Integer> endRunExceptionCount;
private IndexManagementType indexManagement;
private TaskManagerType taskManager;
private NodeStateManager nodeStateManager;
private ExecuteResultResponseRecorderType recorder;
private AnalysisType analysisType;
private String threadPoolName;
private ActionType<? extends ResultResponse<IndexableResultType>> resultAction;
protected JobProcessor(
AnalysisType analysisType,
String threadPoolName,
ActionType<? extends ResultResponse<IndexableResultType>> resultAction
) {
// Singleton class, use getJobRunnerInstance method instead of constructor
this.endRunExceptionCount = new ConcurrentHashMap<>();
this.analysisType = analysisType;
this.threadPoolName = threadPoolName;
this.resultAction = resultAction;
}
public void setClient(Client client) {
this.client = client;
}
public void setThreadPool(ThreadPool threadPool) {
this.threadPool = threadPool;
}
protected void registerSettings(Settings settings, Setting<Integer> maxRetryForEndRunExceptionSetting) {
this.settings = settings;
this.maxRetryForEndRunException = maxRetryForEndRunExceptionSetting.get(settings);
}
public void setTaskManager(TaskManagerType adTaskManager) {
this.taskManager = adTaskManager;
}
public void setIndexManagement(IndexManagementType anomalyDetectionIndices) {
this.indexManagement = anomalyDetectionIndices;
}
public void setNodeStateManager(NodeStateManager nodeStateManager) {
this.nodeStateManager = nodeStateManager;
}
public void setExecuteResultResponseRecorder(ExecuteResultResponseRecorderType recorder) {
this.recorder = recorder;
}
public void process(Job jobParameter, JobExecutionContext context) {
String configId = jobParameter.getName();
log.info("Start to run {} job {}", analysisType, configId);
taskManager.refreshRealtimeJobRunTime(configId);
Instant executionStartTime = Instant.now();
IntervalSchedule schedule = (IntervalSchedule) jobParameter.getSchedule();
Instant analysisStartTime = executionStartTime.minus(schedule.getInterval(), schedule.getUnit());
final LockService lockService = context.getLockService();
Runnable runnable = () -> {
try {
nodeStateManager.getConfig(configId, analysisType, ActionListener.wrap(configOptional -> {
if (!configOptional.isPresent()) {
log.error(new ParameterizedMessage("fail to get config [{}]", configId));
return;
}
Config config = configOptional.get();
if (jobParameter.getLockDurationSeconds() != null) {
lockService
.acquireLock(
jobParameter,
context,
ActionListener
.wrap(
lock -> runJob(
jobParameter,
lockService,
lock,
analysisStartTime,
executionStartTime,
recorder,
config
),
exception -> {
indexResultException(
jobParameter,
lockService,
null,
analysisStartTime,
executionStartTime,
exception,
false,
recorder,
config
);
throw new IllegalStateException("Failed to acquire lock for job: " + configId);
}
)
);
} else {
log.warn("Can't get lock for job: " + configId);
}
}, e -> log.error(new ParameterizedMessage("fail to get config [{}]", configId), e)));
} catch (Exception e) {
// os log won't show anything if there is an exception happens (maybe due to running on a ExecutorService)
// we at least log the error.
log.error("Can't start job: " + configId, e);
throw e;
}
};
ExecutorService executor = threadPool.executor(threadPoolName);
executor.submit(runnable);
}
/**
* Get analysis result, index result or handle exception if failed.
*
* @param jobParameter scheduled job parameter
* @param lockService lock service
* @param lock lock to run job
* @param analysisStartTime analysis start time
* @param analysisEndTime detection end time
* @param recorder utility to record job execution result
* @param detector associated detector accessor
*/
protected void runJob(
Job jobParameter,
LockService lockService,
LockModel lock,
Instant analysisStartTime,
Instant analysisEndTime,
ExecuteResultResponseRecorderType recorder,
Config detector
) {
String configId = jobParameter.getName();
if (lock == null) {
indexResultException(
jobParameter,
lockService,
lock,
analysisStartTime,
analysisEndTime,
"Can't run job due to null lock",
false,
recorder,
detector
);
return;
}
indexManagement.update();
User userInfo = SecurityUtil.getUserFromJob(jobParameter, settings);
String user = userInfo.getName();
List<String> roles = userInfo.getRoles();
String resultIndex = jobParameter.getCustomResultIndex();
if (resultIndex == null) {
runJob(jobParameter, lockService, lock, analysisStartTime, analysisEndTime, configId, user, roles, recorder, detector);
return;
}
ActionListener<Boolean> listener = ActionListener.wrap(r -> { log.debug("Custom index is valid"); }, e -> {
Exception exception = new EndRunException(configId, e.getMessage(), true);
handleException(jobParameter, lockService, lock, analysisStartTime, analysisEndTime, exception, recorder, detector);
});
indexManagement.validateCustomIndexForBackendJob(resultIndex, configId, user, roles, () -> {
listener.onResponse(true);
runJob(jobParameter, lockService, lock, analysisStartTime, analysisEndTime, configId, user, roles, recorder, detector);
}, listener);
}
private void runJob(
Job jobParameter,
LockService lockService,
LockModel lock,
Instant detectionStartTime,
Instant executionStartTime,
String configId,
String user,
List<String> roles,
ExecuteResultResponseRecorderType recorder,
Config detector
) {
// using one thread in the write threadpool
try (InjectSecurity injectSecurity = new InjectSecurity(configId, settings, client.threadPool().getThreadContext())) {
// Injecting user role to verify if the user has permissions for our API.
injectSecurity.inject(user, roles);
ResultRequest request = createResultRequest(configId, detectionStartTime.toEpochMilli(), executionStartTime.toEpochMilli());
client
.execute(
resultAction,
request,
ActionListener
.wrap(
response -> {
indexResult(
jobParameter,
lockService,
lock,
detectionStartTime,
executionStartTime,
response,
recorder,
detector
);
},
exception -> {
handleException(
jobParameter,
lockService,
lock,
detectionStartTime,
executionStartTime,
exception,
recorder,
detector
);
}
)
);
} catch (Exception e) {
indexResultException(jobParameter, lockService, lock, detectionStartTime, executionStartTime, e, true, recorder, detector);
log.error("Failed to execute AD job " + configId, e);
}
}
/**
* Handle exception from anomaly result action.
*
* 1. If exception is {@link EndRunException}
* a). if isEndNow == true, stop AD job and store exception in anomaly result
* b). if isEndNow == false, record count of {@link EndRunException} for this
* detector. If count of {@link EndRunException} exceeds upper limit, will
* stop AD job and store exception in anomaly result; otherwise, just
* store exception in anomaly result, not stop AD job for the detector.
*
* 2. If exception is not {@link EndRunException}, decrease count of
* {@link EndRunException} for the detector and index eception in Anomaly
* result. If exception is {@link InternalFailure}, will not log exception
* stack trace as already logged in {@link AnomalyResultTransportAction}.
*
* TODO: Handle finer granularity exception such as some exception may be
* transient and retry in current job may succeed. Currently, we don't
* know which exception is transient and retryable in
* {@link AnomalyResultTransportAction}. So we don't add backoff retry
* now to avoid bring extra load to cluster, expecially the code start
* process is relatively heavy by sending out 24 queries, initializing
* models, and saving checkpoints.
* Sometimes missing anomaly and notification is not acceptable. For example,
* current detection interval is 1hour, and there should be anomaly in
* current interval, some transient exception may fail current AD job,
* so no anomaly found and user never know it. Then we start next AD job,
* maybe there is no anomaly in next 1hour, user will never know something
* wrong happened. In one word, this is some tradeoff between protecting
* our performance, user experience and what we can do currently.
*
* @param jobParameter scheduled job parameter
* @param lockService lock service
* @param lock lock to run job
* @param detectionStartTime detection start time
* @param executionStartTime detection end time
* @param exception exception
* @param recorder utility to record job execution result
* @param config associated config accessor
*/
protected void handleException(
Job jobParameter,
LockService lockService,
LockModel lock,
Instant detectionStartTime,
Instant executionStartTime,
Exception exception,
ExecuteResultResponseRecorderType recorder,
Config config
) {
String detectorId = jobParameter.getName();
if (exception instanceof EndRunException) {
log.error("EndRunException happened when executing anomaly result action for " + detectorId, exception);
if (((EndRunException) exception).isEndNow()) {
// Stop AD job if EndRunException shows we should end job now.
log.info("JobRunner will stop AD job due to EndRunException for {}", detectorId);
stopJobForEndRunException(
jobParameter,
lockService,
lock,
detectionStartTime,
executionStartTime,
(EndRunException) exception,
recorder,
config
);
} else {
endRunExceptionCount.compute(detectorId, (k, v) -> {
if (v == null) {
return 1;
} else {
return v + 1;
}
});
log.info("EndRunException happened for {}", detectorId);
// if AD job failed consecutively due to EndRunException and failed times exceeds upper limit, will stop AD job
if (endRunExceptionCount.get(detectorId) > maxRetryForEndRunException) {
log
.info(
"JobRunner will stop AD job due to EndRunException retry exceeds upper limit {} for {}",
maxRetryForEndRunException,
detectorId
);
stopJobForEndRunException(
jobParameter,
lockService,
lock,
detectionStartTime,
executionStartTime,
(EndRunException) exception,
recorder,
config
);
return;
}
indexResultException(
jobParameter,
lockService,
lock,
detectionStartTime,
executionStartTime,
exception.getMessage(),
true,
recorder,
config
);
}
} else {
endRunExceptionCount.remove(detectorId);
if (exception instanceof InternalFailure) {
log.error("InternalFailure happened when executing anomaly result action for " + detectorId, exception);
} else {
log.error("Failed to execute anomaly result action for " + detectorId, exception);
}
indexResultException(
jobParameter,
lockService,
lock,
detectionStartTime,
executionStartTime,
exception,
true,
recorder,
config
);
}
}
private void stopJobForEndRunException(
Job jobParameter,
LockService lockService,
LockModel lock,
Instant detectionStartTime,
Instant executionStartTime,
EndRunException exception,
ExecuteResultResponseRecorderType recorder,
Config config
) {
String configId = jobParameter.getName();
endRunExceptionCount.remove(configId);
String errorPrefix = exception.isEndNow()
? "Stopped analysis: "
: "Stopped analysis as job failed consecutively for more than " + this.maxRetryForEndRunException + " times: ";
String error = errorPrefix + exception.getMessage();
stopJob(
configId,
() -> indexResultException(
jobParameter,
lockService,
lock,
detectionStartTime,
executionStartTime,
error,
true,
TaskState.STOPPED.name(),
recorder,
config
)
);
}
private void stopJob(String detectorId, ExecutorFunction function) {
GetRequest getRequest = new GetRequest(CommonName.JOB_INDEX).id(detectorId);
ActionListener<GetResponse> listener = ActionListener.wrap(response -> {
if (response.isExists()) {
try (
XContentParser parser = XContentType.JSON
.xContent()
.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, response.getSourceAsString())
) {
ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser);
Job job = Job.parse(parser);
if (job.isEnabled()) {
Job newJob = new Job(
job.getName(),
job.getSchedule(),
job.getWindowDelay(),
false,
job.getEnabledTime(),
Instant.now(),
Instant.now(),
job.getLockDurationSeconds(),
job.getUser(),
job.getCustomResultIndex(),
job.getAnalysisType()
);
IndexRequest indexRequest = new IndexRequest(CommonName.JOB_INDEX)
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.source(newJob.toXContent(XContentBuilder.builder(XContentType.JSON.xContent()), XCONTENT_WITH_TYPE))
.id(detectorId);
client.index(indexRequest, ActionListener.wrap(indexResponse -> {
if (indexResponse != null && (indexResponse.getResult() == CREATED || indexResponse.getResult() == UPDATED)) {
log.info("Job was disabled by JobRunner for " + detectorId);
// function.execute();
} else {
log.warn("Failed to disable job for " + detectorId);
}
}, exception -> { log.error("JobRunner failed to update job as disabled for " + detectorId, exception); }));
} else {
log.info("Job was disabled for " + detectorId);
}
} catch (IOException e) {
log.error("JobRunner failed to stop detector job " + detectorId, e);
}
} else {
log.info("AD Job was not found for " + detectorId);
}
}, exception -> log.error("JobRunner failed to get detector job " + detectorId, exception));
client.get(getRequest, ActionListener.runAfter(listener, () -> function.execute()));
}
private void indexResult(
Job jobParameter,
LockService lockService,
LockModel lock,
Instant detectionStartTime,
Instant executionStartTime,
ResultResponse<IndexableResultType> response,
ExecuteResultResponseRecorderType recorder,
Config detector
) {
String detectorId = jobParameter.getName();
endRunExceptionCount.remove(detectorId);
try {
recorder.indexResult(detectionStartTime, executionStartTime, response, detector);
} catch (EndRunException e) {
handleException(jobParameter, lockService, lock, detectionStartTime, executionStartTime, e, recorder, detector);
} catch (Exception e) {
log.error("Failed to index anomaly result for " + detectorId, e);
} finally {
releaseLock(jobParameter, lockService, lock);
}
}
private void indexResultException(
Job jobParameter,
LockService lockService,
LockModel lock,
Instant detectionStartTime,
Instant executionStartTime,
Exception exception,
boolean releaseLock,
ExecuteResultResponseRecorderType recorder,
Config detector
) {
try {
String errorMessage = exception instanceof TimeSeriesException
? exception.getMessage()
: Throwables.getStackTraceAsString(exception);
indexResultException(
jobParameter,
lockService,
lock,
detectionStartTime,
executionStartTime,
errorMessage,
releaseLock,
recorder,
detector
);
} catch (Exception e) {
log.error("Failed to index result for " + jobParameter.getName(), e);
}
}
private void indexResultException(
Job jobParameter,
LockService lockService,
LockModel lock,
Instant detectionStartTime,
Instant executionStartTime,
String errorMessage,
boolean releaseLock,
ExecuteResultResponseRecorderType recorder,
Config detector
) {
indexResultException(
jobParameter,
lockService,
lock,
detectionStartTime,
executionStartTime,
errorMessage,
releaseLock,
null,
recorder,
detector
);
}
private void indexResultException(
Job jobParameter,
LockService lockService,
LockModel lock,
Instant detectionStartTime,
Instant executionStartTime,
String errorMessage,
boolean releaseLock,
String taskState,
ExecuteResultResponseRecorderType recorder,
Config detector
) {
try {
recorder.indexResultException(detectionStartTime, executionStartTime, errorMessage, taskState, detector);
} finally {
if (releaseLock) {
releaseLock(jobParameter, lockService, lock);
}
}
}
private void releaseLock(Job jobParameter, LockService lockService, LockModel lock) {
lockService
.release(
lock,
ActionListener
.wrap(
released -> { log.info("Released lock for {} job {}", analysisType, jobParameter.getName()); },
exception -> {
log
.error(
new ParameterizedMessage(
"Failed to release lock for [{}] job [{}]",
analysisType,
jobParameter.getName()
),
exception
);
}
)
);
}
protected abstract ResultRequest createResultRequest(String configID, long start, long end);
}