use of org.opensearch.ad.util.RestHandlerUtils.XCONTENT_WITH_TYPE in project anomaly-detection by opensearch-project.
the class AnomalyDetectorJobRunner method stopAdJob.
private void stopAdJob(String detectorId, AnomalyDetectorFunction function) {
GetRequest getRequest = new GetRequest(AnomalyDetectorJob.ANOMALY_DETECTOR_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);
AnomalyDetectorJob job = AnomalyDetectorJob.parse(parser);
if (job.isEnabled()) {
AnomalyDetectorJob newJob = new AnomalyDetectorJob(job.getName(), job.getSchedule(), job.getWindowDelay(), false, job.getEnabledTime(), Instant.now(), Instant.now(), job.getLockDurationSeconds(), job.getUser(), job.getResultIndex());
IndexRequest indexRequest = new IndexRequest(AnomalyDetectorJob.ANOMALY_DETECTOR_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("AD Job was disabled by JobRunner for " + detectorId);
// function.execute();
} else {
log.warn("Failed to disable AD job for " + detectorId);
}
}, exception -> {
log.error("JobRunner failed to update AD job as disabled for " + detectorId, exception);
}));
} else {
log.info("AD Job was disabled for " + detectorId);
// function.execute();
}
} catch (IOException e) {
log.error("JobRunner failed to stop detector job " + detectorId, e);
}
} else {
log.info("AD Job was not found for " + detectorId);
// function.execute();
}
}, exception -> log.error("JobRunner failed to get detector job " + detectorId, exception));
client.get(getRequest, ActionListener.runAfter(listener, () -> function.execute()));
}
use of org.opensearch.ad.util.RestHandlerUtils.XCONTENT_WITH_TYPE in project anomaly-detection by opensearch-project.
the class ADTaskManager method resetLatestFlagAsFalse.
/**
* Set old AD task's latest flag as false.
* @param adTasks list of AD tasks
*/
public void resetLatestFlagAsFalse(List<ADTask> adTasks) {
if (adTasks == null || adTasks.size() == 0) {
return;
}
BulkRequest bulkRequest = new BulkRequest();
adTasks.forEach(task -> {
try {
task.setLatest(false);
task.setLastUpdateTime(Instant.now());
IndexRequest indexRequest = new IndexRequest(DETECTION_STATE_INDEX).id(task.getTaskId()).source(task.toXContent(XContentBuilder.builder(XContentType.JSON.xContent()), XCONTENT_WITH_TYPE));
bulkRequest.add(indexRequest);
} catch (Exception e) {
logger.error("Fail to parse task AD task to XContent, task id " + task.getTaskId(), e);
}
});
bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
client.execute(BulkAction.INSTANCE, bulkRequest, ActionListener.wrap(res -> {
BulkItemResponse[] bulkItemResponses = res.getItems();
if (bulkItemResponses != null && bulkItemResponses.length > 0) {
for (BulkItemResponse bulkItemResponse : bulkItemResponses) {
if (!bulkItemResponse.isFailed()) {
logger.warn("Reset AD tasks latest flag as false Successfully. Task id: {}", bulkItemResponse.getId());
} else {
logger.warn("Failed to reset AD tasks latest flag as false. Task id: " + bulkItemResponse.getId());
}
}
}
}, e -> {
logger.warn("Failed to reset AD tasks latest flag as false", e);
}));
}
use of org.opensearch.ad.util.RestHandlerUtils.XCONTENT_WITH_TYPE in project anomaly-detection by opensearch-project.
the class ADDataMigrator method createRealtimeADTask.
private void createRealtimeADTask(AnomalyDetectorJob job, String error, ConcurrentLinkedQueue<AnomalyDetectorJob> detectorJobs, boolean migrateAll) {
client.get(new GetRequest(ANOMALY_DETECTORS_INDEX, job.getName()), ActionListener.wrap(r -> {
if (r != null && r.isExists()) {
try (XContentParser parser = createXContentParserFromRegistry(xContentRegistry, r.getSourceAsBytesRef())) {
ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser);
AnomalyDetector detector = AnomalyDetector.parse(parser, r.getId());
ADTaskType taskType = detector.isMultientityDetector() ? ADTaskType.REALTIME_HC_DETECTOR : ADTaskType.REALTIME_SINGLE_ENTITY;
Instant now = Instant.now();
String userName = job.getUser() != null ? job.getUser().getName() : null;
ADTask adTask = new ADTask.Builder().detectorId(detector.getDetectorId()).detector(detector).error(error).isLatest(true).taskType(taskType.name()).executionStartTime(now).taskProgress(0.0f).initProgress(0.0f).state(ADTaskState.CREATED.name()).lastUpdateTime(now).startedBy(userName).coordinatingNode(null).detectionDateRange(null).user(job.getUser()).build();
IndexRequest indexRequest = new IndexRequest(DETECTION_STATE_INDEX).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source(adTask.toXContent(XContentFactory.jsonBuilder(), XCONTENT_WITH_TYPE));
client.index(indexRequest, ActionListener.wrap(indexResponse -> {
logger.info("Backfill realtime task successfully for detector {}", job.getName());
backfillRealtimeTask(detectorJobs, migrateAll);
}, ex -> {
logger.error("Failed to backfill realtime task for detector " + job.getName(), ex);
backfillRealtimeTask(detectorJobs, migrateAll);
}));
} catch (IOException e) {
logger.error("Fail to parse detector " + job.getName(), e);
backfillRealtimeTask(detectorJobs, migrateAll);
}
} else {
logger.error("Detector doesn't exist " + job.getName());
backfillRealtimeTask(detectorJobs, migrateAll);
}
}, e -> {
logger.error("Fail to get detector " + job.getName(), e);
backfillRealtimeTask(detectorJobs, migrateAll);
}));
}
Aggregations