Search in sources :

Example 1 with ANOMALY_DETECTOR_JOB_INDEX

use of org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX in project anomaly-detection by opensearch-project.

the class ADDataMigrator method migrateDetectorInternalStateToRealtimeTask.

/**
 * Migrate detector internal state to realtime task.
 */
public void migrateDetectorInternalStateToRealtimeTask() {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(new MatchAllQueryBuilder()).size(MAX_DETECTOR_UPPER_LIMIT);
    SearchRequest searchRequest = new SearchRequest(ANOMALY_DETECTOR_JOB_INDEX).source(searchSourceBuilder);
    client.search(searchRequest, ActionListener.wrap(r -> {
        if (r == null || r.getHits().getTotalHits() == null || r.getHits().getTotalHits().value == 0) {
            logger.info("No anomaly detector job found, no need to migrate");
            return;
        }
        ConcurrentLinkedQueue<AnomalyDetectorJob> detectorJobs = new ConcurrentLinkedQueue<>();
        Iterator<SearchHit> iterator = r.getHits().iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next();
            try (XContentParser parser = createXContentParserFromRegistry(xContentRegistry, searchHit.getSourceRef())) {
                ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser);
                AnomalyDetectorJob job = AnomalyDetectorJob.parse(parser);
                detectorJobs.add(job);
            } catch (IOException e) {
                logger.error("Fail to parse AD job " + searchHit.getId(), e);
            }
        }
        logger.info("Total AD jobs to backfill realtime task: {}", detectorJobs.size());
        backfillRealtimeTask(detectorJobs, true);
    }, e -> {
        if (ExceptionUtil.getErrorMessage(e).contains("all shards failed")) {
            // This error may happen when AD job index not ready for query as some nodes not in cluster yet.
            // Will recreate realtime task when AD job starts.
            logger.warn("No available shards of AD job index, reset dataMigrated as false");
            this.dataMigrated.set(false);
        } else if (!(e instanceof IndexNotFoundException)) {
            logger.error("Failed to migrate AD data", e);
        }
    }));
}
Also used : ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) ADTask(org.opensearch.ad.model.ADTask) MAX_DETECTOR_UPPER_LIMIT(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_DETECTOR_UPPER_LIMIT) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ADTaskType.taskTypeToString(org.opensearch.ad.model.ADTaskType.taskTypeToString) ADTaskState(org.opensearch.ad.model.ADTaskState) XCONTENT_WITH_TYPE(org.opensearch.ad.util.RestHandlerUtils.XCONTENT_WITH_TYPE) AnomalyDetectorFunction(org.opensearch.ad.rest.handler.AnomalyDetectorFunction) XContentParser(org.opensearch.common.xcontent.XContentParser) WriteRequest(org.opensearch.action.support.WriteRequest) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) DETECTOR_ID_FIELD(org.opensearch.ad.model.ADTask.DETECTOR_ID_FIELD) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) XContentFactory(org.opensearch.common.xcontent.XContentFactory) SearchRequest(org.opensearch.action.search.SearchRequest) ActionListener(org.opensearch.action.ActionListener) Client(org.opensearch.client.Client) CommonName(org.opensearch.ad.constant.CommonName) RestHandlerUtils.createXContentParserFromRegistry(org.opensearch.ad.util.RestHandlerUtils.createXContentParserFromRegistry) Iterator(java.util.Iterator) SearchHit(org.opensearch.search.SearchHit) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ANOMALY_DETECTORS_INDEX(org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX) GetRequest(org.opensearch.action.get.GetRequest) ExceptionsHelper(org.opensearch.ExceptionsHelper) ADTaskType(org.opensearch.ad.model.ADTaskType) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) IOException(java.io.IOException) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) IS_LATEST_FIELD(org.opensearch.ad.model.ADTask.IS_LATEST_FIELD) DETECTION_STATE_INDEX(org.opensearch.ad.constant.CommonName.DETECTION_STATE_INDEX) Instant(java.time.Instant) TASK_TYPE_FIELD(org.opensearch.ad.model.ADTask.TASK_TYPE_FIELD) Logger(org.apache.logging.log4j.Logger) ExceptionUtil(org.opensearch.ad.util.ExceptionUtil) DetectorInternalState(org.opensearch.ad.model.DetectorInternalState) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) TermsQueryBuilder(org.opensearch.index.query.TermsQueryBuilder) IndexRequest(org.opensearch.action.index.IndexRequest) MatchAllQueryBuilder(org.opensearch.index.query.MatchAllQueryBuilder) LogManager(org.apache.logging.log4j.LogManager) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) SearchRequest(org.opensearch.action.search.SearchRequest) SearchHit(org.opensearch.search.SearchHit) Iterator(java.util.Iterator) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IOException(java.io.IOException) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) XContentParser(org.opensearch.common.xcontent.XContentParser) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) MatchAllQueryBuilder(org.opensearch.index.query.MatchAllQueryBuilder)

Example 2 with ANOMALY_DETECTOR_JOB_INDEX

use of org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX in project anomaly-detection by opensearch-project.

the class EntityProfileRunnerTests method testJobIndexNotFound.

@SuppressWarnings("unchecked")
public void testJobIndexNotFound() throws InterruptedException {
    setUpExecuteEntityProfileAction(InittedEverResultStatus.INITTED);
    final CountDownLatch inProgressLatch = new CountDownLatch(1);
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        GetRequest request = (GetRequest) args[0];
        ActionListener<GetResponse> listener = (ActionListener<GetResponse>) args[1];
        String indexName = request.index();
        if (indexName.equals(ANOMALY_DETECTORS_INDEX)) {
            listener.onResponse(TestHelpers.createGetResponse(detector, detector.getDetectorId(), AnomalyDetector.ANOMALY_DETECTORS_INDEX));
        } else if (indexName.equals(ANOMALY_DETECTOR_JOB_INDEX)) {
            listener.onFailure(new IndexNotFoundException(ANOMALY_DETECTOR_JOB_INDEX));
        }
        return null;
    }).when(client).get(any(), any());
    EntityProfile expectedProfile = new EntityProfile.Builder().build();
    runner.profile(detectorId, entity, initNInfo, ActionListener.wrap(response -> {
        assertEquals(expectedProfile, response);
        inProgressLatch.countDown();
    }, exception -> {
        LOG.error("Unexpected error", exception);
        assertTrue("Should not reach here", false);
        inProgressLatch.countDown();
    }));
    assertTrue(inProgressLatch.await(100, TimeUnit.SECONDS));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Arrays(java.util.Arrays) ModelProfile(org.opensearch.ad.model.ModelProfile) DocValueFormat(org.opensearch.search.DocValueFormat) SearchHits(org.opensearch.search.SearchHits) EntityProfileName(org.opensearch.ad.model.EntityProfileName) ModelProfileOnNode(org.opensearch.ad.model.ModelProfileOnNode) HashSet(java.util.HashSet) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) EntityProfileResponse(org.opensearch.ad.transport.EntityProfileResponse) Mockito.doAnswer(org.mockito.Mockito.doAnswer) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) SearchRequest(org.opensearch.action.search.SearchRequest) ActionListener(org.opensearch.action.ActionListener) SearchResponse(org.opensearch.action.search.SearchResponse) GetResponse(org.opensearch.action.get.GetResponse) EntityProfile(org.opensearch.ad.model.EntityProfile) Collections.emptyMap(java.util.Collections.emptyMap) Client(org.opensearch.client.Client) CommonName(org.opensearch.ad.constant.CommonName) InitProgressProfile(org.opensearch.ad.model.InitProgressProfile) SearchHit(org.opensearch.search.SearchHit) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ANOMALY_DETECTORS_INDEX(org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX) GetRequest(org.opensearch.action.get.GetRequest) Set(java.util.Set) IOException(java.io.IOException) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) TimeUnit(java.util.concurrent.TimeUnit) TotalHits(org.apache.lucene.search.TotalHits) CountDownLatch(java.util.concurrent.CountDownLatch) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) ChronoUnit(java.time.temporal.ChronoUnit) Entity(org.opensearch.ad.model.Entity) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) EntityState(org.opensearch.ad.model.EntityState) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) Collections(java.util.Collections) EntityProfileAction(org.opensearch.ad.transport.EntityProfileAction) Text(org.opensearch.common.text.Text) Mockito.mock(org.mockito.Mockito.mock) ActionListener(org.opensearch.action.ActionListener) GetRequest(org.opensearch.action.get.GetRequest) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) EntityProfile(org.opensearch.ad.model.EntityProfile) CountDownLatch(java.util.concurrent.CountDownLatch) GetResponse(org.opensearch.action.get.GetResponse)

Example 3 with ANOMALY_DETECTOR_JOB_INDEX

use of org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX in project anomaly-detection by opensearch-project.

the class ADTaskManager method resetRealtimeDetectorTaskState.

private <T> void resetRealtimeDetectorTaskState(List<ADTask> runningRealtimeTasks, AnomalyDetectorFunction function, TransportService transportService, ActionListener<T> listener) {
    if (isNullOrEmpty(runningRealtimeTasks)) {
        function.execute();
        return;
    }
    ADTask adTask = runningRealtimeTasks.get(0);
    String detectorId = adTask.getDetectorId();
    GetRequest getJobRequest = new GetRequest(ANOMALY_DETECTOR_JOB_INDEX).id(detectorId);
    client.get(getJobRequest, ActionListener.wrap(r -> {
        if (r.isExists()) {
            try (XContentParser parser = createXContentParserFromRegistry(xContentRegistry, r.getSourceAsBytesRef())) {
                ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser);
                AnomalyDetectorJob job = AnomalyDetectorJob.parse(parser);
                if (!job.isEnabled()) {
                    logger.debug("AD job is disabled, reset realtime task as stopped for detector {}", detectorId);
                    resetTaskStateAsStopped(adTask, function, transportService, listener);
                } else {
                    function.execute();
                }
            } catch (IOException e) {
                logger.error(" Failed to parse AD job " + detectorId, e);
                listener.onFailure(e);
            }
        } else {
            logger.debug("AD job is not found, reset realtime task as stopped for detector {}", detectorId);
            resetTaskStateAsStopped(adTask, function, transportService, listener);
        }
    }, e -> {
        logger.error("Fail to get AD realtime job for detector " + detectorId, e);
        listener.onFailure(e);
    }));
}
Also used : PARENT_TASK_ID_FIELD(org.opensearch.ad.model.ADTask.PARENT_TASK_ID_FIELD) IndexResponse(org.opensearch.action.index.IndexResponse) HashRing(org.opensearch.ad.cluster.HashRing) Version(org.opensearch.Version) FAIL_TO_FIND_DETECTOR_MSG(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG) BulkAction(org.opensearch.action.bulk.BulkAction) LimitExceededException(org.opensearch.ad.common.exception.LimitExceededException) ExceptionUtil.getShardsFailure(org.opensearch.ad.util.ExceptionUtil.getShardsFailure) ADTaskState(org.opensearch.ad.model.ADTaskState) AnomalyDetectorFunction(org.opensearch.ad.rest.handler.AnomalyDetectorFunction) STOPPED_BY_FIELD(org.opensearch.ad.model.ADTask.STOPPED_BY_FIELD) WriteRequest(org.opensearch.action.support.WriteRequest) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) MAX_OLD_AD_TASK_DOCS_PER_DETECTOR(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_OLD_AD_TASK_DOCS_PER_DETECTOR) Map(java.util.Map) ForwardADTaskAction(org.opensearch.ad.transport.ForwardADTaskAction) ActionListener(org.opensearch.action.ActionListener) DETECTOR_IS_RUNNING(org.opensearch.ad.constant.CommonErrorMessages.DETECTOR_IS_RUNNING) ADStatsNodeResponse(org.opensearch.ad.transport.ADStatsNodeResponse) DeleteRequest(org.opensearch.action.delete.DeleteRequest) MAX_RUNNING_ENTITIES_PER_DETECTOR_FOR_HISTORICAL_ANALYSIS(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_RUNNING_ENTITIES_PER_DETECTOR_FOR_HISTORICAL_ANALYSIS) Client(org.opensearch.client.Client) UpdateByQueryAction(org.opensearch.index.reindex.UpdateByQueryAction) AD_BATCH_TASK_THREAD_POOL_NAME(org.opensearch.ad.AnomalyDetectorPlugin.AD_BATCH_TASK_THREAD_POOL_NAME) ADTaskProfileRequest(org.opensearch.ad.transport.ADTaskProfileRequest) TimeValue(org.opensearch.common.unit.TimeValue) RestHandlerUtils.createXContentParserFromRegistry(org.opensearch.ad.util.RestHandlerUtils.createXContentParserFromRegistry) SearchHit(org.opensearch.search.SearchHit) TransportRequestOptions(org.opensearch.transport.TransportRequestOptions) Set(java.util.Set) ExceptionsHelper(org.opensearch.ExceptionsHelper) Settings(org.opensearch.common.settings.Settings) NO_ELIGIBLE_NODE_TO_RUN_DETECTOR(org.opensearch.ad.constant.CommonErrorMessages.NO_ELIGIBLE_NODE_TO_RUN_DETECTOR) IS_LATEST_FIELD(org.opensearch.ad.model.ADTask.IS_LATEST_FIELD) DETECTION_STATE_INDEX(org.opensearch.ad.constant.CommonName.DETECTION_STATE_INDEX) ScoreMode(org.apache.lucene.search.join.ScoreMode) TransportService(org.opensearch.transport.TransportService) Logger(org.apache.logging.log4j.Logger) CAN_NOT_FIND_LATEST_TASK(org.opensearch.ad.constant.CommonErrorMessages.CAN_NOT_FIND_LATEST_TASK) ADEntityTaskProfile(org.opensearch.ad.model.ADEntityTaskProfile) ActionListenerResponseHandler(org.opensearch.action.ActionListenerResponseHandler) TermsQueryBuilder(org.opensearch.index.query.TermsQueryBuilder) EXECUTION_END_TIME_FIELD(org.opensearch.ad.model.ADTask.EXECUTION_END_TIME_FIELD) UpdateRequest(org.opensearch.action.update.UpdateRequest) XContentType(org.opensearch.common.xcontent.XContentType) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) BATCH_TASK_PIECE_INTERVAL_SECONDS(org.opensearch.ad.settings.AnomalyDetectorSettings.BATCH_TASK_PIECE_INTERVAL_SECONDS) MAX_BATCH_TASK_PER_NODE(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_BATCH_TASK_PER_NODE) UpdateResponse(org.opensearch.action.update.UpdateResponse) ThreadPool(org.opensearch.threadpool.ThreadPool) ADTaskType.taskTypeToString(org.opensearch.ad.model.ADTaskType.taskTypeToString) ADTaskProfile(org.opensearch.ad.model.ADTaskProfile) ArrayList(java.util.ArrayList) XCONTENT_WITH_TYPE(org.opensearch.ad.util.RestHandlerUtils.XCONTENT_WITH_TYPE) HC_DETECTOR_TASK_IS_UPDATING(org.opensearch.ad.constant.CommonErrorMessages.HC_DETECTOR_TASK_IS_UPDATING) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ADCancelTaskAction(org.opensearch.ad.transport.ADCancelTaskAction) BiConsumer(java.util.function.BiConsumer) DeleteResponse(org.opensearch.action.delete.DeleteResponse) SearchRequest(org.opensearch.action.search.SearchRequest) INIT_PROGRESS_FIELD(org.opensearch.ad.model.ADTask.INIT_PROGRESS_FIELD) QueryBuilders(org.opensearch.index.query.QueryBuilders) ADStatsNodesAction(org.opensearch.ad.transport.ADStatsNodesAction) IOException(java.io.IOException) TotalHits(org.apache.lucene.search.TotalHits) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) ChronoUnit(java.time.temporal.ChronoUnit) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) ExceptionUtil.getErrorMessage(org.opensearch.ad.util.ExceptionUtil.getErrorMessage) ADTaskAction(org.opensearch.ad.model.ADTaskAction) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) AD_DETECTOR_ASSIGNED_BATCH_TASK_SLOT_COUNT(org.opensearch.ad.stats.InternalStatNames.AD_DETECTOR_ASSIGNED_BATCH_TASK_SLOT_COUNT) DeleteByQueryAction(org.opensearch.index.reindex.DeleteByQueryAction) COORDINATING_NODE_FIELD(org.opensearch.ad.model.ADTask.COORDINATING_NODE_FIELD) DELETE_AD_RESULT_WHEN_DELETE_DETECTOR(org.opensearch.ad.settings.AnomalyDetectorSettings.DELETE_AD_RESULT_WHEN_DELETE_DETECTOR) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) MAX_OLD_AD_TASK_DOCS(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_OLD_AD_TASK_DOCS) ADBatchAnomalyResultAction(org.opensearch.ad.transport.ADBatchAnomalyResultAction) ToXContent(org.opensearch.common.xcontent.ToXContent) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) BulkRequest(org.opensearch.action.bulk.BulkRequest) ERROR_FIELD(org.opensearch.ad.model.ADTask.ERROR_FIELD) EXECUTION_START_TIME_FIELD(org.opensearch.ad.model.ADTask.EXECUTION_START_TIME_FIELD) ParseUtils.isNullOrEmpty(org.opensearch.ad.util.ParseUtils.isNullOrEmpty) ADTaskCancelledException(org.opensearch.ad.common.exception.ADTaskCancelledException) ADStatsRequest(org.opensearch.ad.transport.ADStatsRequest) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) XContentParser(org.opensearch.common.xcontent.XContentParser) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) IndexAnomalyDetectorJobActionHandler(org.opensearch.ad.rest.handler.IndexAnomalyDetectorJobActionHandler) DETECTOR_ID_FIELD(org.opensearch.ad.model.ADTask.DETECTOR_ID_FIELD) Locale(java.util.Locale) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) XContentFactory(org.opensearch.common.xcontent.XContentFactory) REALTIME_TASK_TYPES(org.opensearch.ad.model.ADTaskType.REALTIME_TASK_TYPES) NestedQueryBuilder(org.opensearch.index.query.NestedQueryBuilder) TASK_PROGRESS_FIELD(org.opensearch.ad.model.ADTask.TASK_PROGRESS_FIELD) DetectorProfile(org.opensearch.ad.model.DetectorProfile) ImmutableSet(com.google.common.collect.ImmutableSet) ESTIMATED_MINUTES_LEFT_FIELD(org.opensearch.ad.model.ADTask.ESTIMATED_MINUTES_LEFT_FIELD) NOT_ENDED_STATES(org.opensearch.ad.model.ADTaskState.NOT_ENDED_STATES) ImmutableMap(com.google.common.collect.ImmutableMap) Script(org.opensearch.script.Script) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) ADTaskType(org.opensearch.ad.model.ADTaskType) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) ADTaskProfileNodeResponse(org.opensearch.ad.transport.ADTaskProfileNodeResponse) LAST_UPDATE_TIME_FIELD(org.opensearch.ad.model.ADTask.LAST_UPDATE_TIME_FIELD) Instant(java.time.Instant) RestStatus(org.opensearch.rest.RestStatus) Collectors(java.util.stream.Collectors) TASK_TYPE_FIELD(org.opensearch.ad.model.ADTask.TASK_TYPE_FIELD) Objects(java.util.Objects) AnomalyDetectorJobResponse(org.opensearch.ad.transport.AnomalyDetectorJobResponse) List(java.util.List) ForwardADTaskRequest(org.opensearch.ad.transport.ForwardADTaskRequest) DuplicateTaskException(org.opensearch.ad.common.exception.DuplicateTaskException) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) CREATED(org.opensearch.action.DocWriteResponse.Result.CREATED) DetectionDateRange(org.opensearch.ad.model.DetectionDateRange) NUM_MIN_SAMPLES(org.opensearch.ad.settings.AnomalyDetectorSettings.NUM_MIN_SAMPLES) Optional(java.util.Optional) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) ALL_HISTORICAL_TASK_TYPES(org.opensearch.ad.model.ADTaskType.ALL_HISTORICAL_TASK_TYPES) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) RestHandlerUtils(org.opensearch.ad.util.RestHandlerUtils) TASK_ID_FIELD(org.opensearch.ad.model.AnomalyResult.TASK_ID_FIELD) REQUEST_TIMEOUT(org.opensearch.ad.settings.AnomalyDetectorSettings.REQUEST_TIMEOUT) DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) BytesReference(org.opensearch.common.bytes.BytesReference) ADTask(org.opensearch.ad.model.ADTask) HashMap(java.util.HashMap) SortOrder(org.opensearch.search.sort.SortOrder) ImmutableList(com.google.common.collect.ImmutableList) EXCEED_HISTORICAL_ANALYSIS_LIMIT(org.opensearch.ad.constant.CommonErrorMessages.EXCEED_HISTORICAL_ANALYSIS_LIMIT) ADCancelTaskRequest(org.opensearch.ad.transport.ADCancelTaskRequest) SearchResponse(org.opensearch.action.search.SearchResponse) EndRunException(org.opensearch.ad.common.exception.EndRunException) ADBatchAnomalyResultRequest(org.opensearch.ad.transport.ADBatchAnomalyResultRequest) HISTORICAL_DETECTOR_TASK_TYPES(org.opensearch.ad.model.ADTaskType.HISTORICAL_DETECTOR_TASK_TYPES) Iterator(java.util.Iterator) ALL_AD_RESULTS_INDEX_PATTERN(org.opensearch.ad.indices.AnomalyDetectionIndices.ALL_AD_RESULTS_INDEX_PATTERN) Semaphore(java.util.concurrent.Semaphore) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ANOMALY_DETECTORS_INDEX(org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX) GetRequest(org.opensearch.action.get.GetRequest) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) STATE_FIELD(org.opensearch.ad.model.ADTask.STATE_FIELD) CREATE_INDEX_NOT_ACKNOWLEDGED(org.opensearch.ad.constant.CommonErrorMessages.CREATE_INDEX_NOT_ACKNOWLEDGED) Consumer(java.util.function.Consumer) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) AD_USED_BATCH_TASK_SLOT_COUNT(org.opensearch.ad.stats.InternalStatNames.AD_USED_BATCH_TASK_SLOT_COUNT) Entity(org.opensearch.ad.model.Entity) User(org.opensearch.commons.authuser.User) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) IndexRequest(org.opensearch.action.index.IndexRequest) LogManager(org.apache.logging.log4j.LogManager) ADTaskProfileAction(org.opensearch.ad.transport.ADTaskProfileAction) GetRequest(org.opensearch.action.get.GetRequest) ADTask(org.opensearch.ad.model.ADTask) ADTaskType.taskTypeToString(org.opensearch.ad.model.ADTaskType.taskTypeToString) IOException(java.io.IOException) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 4 with ANOMALY_DETECTOR_JOB_INDEX

use of org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX in project anomaly-detection by opensearch-project.

the class DeleteAnomalyDetectorTransportAction method getDetectorJob.

private void getDetectorJob(String detectorId, ActionListener<DeleteResponse> listener, AnomalyDetectorFunction function) {
    if (clusterService.state().metadata().indices().containsKey(ANOMALY_DETECTOR_JOB_INDEX)) {
        GetRequest request = new GetRequest(ANOMALY_DETECTOR_JOB_INDEX).id(detectorId);
        client.get(request, ActionListener.wrap(response -> onGetAdJobResponseForWrite(response, listener, function), exception -> {
            LOG.error("Fail to get anomaly detector job: " + detectorId, exception);
            listener.onFailure(exception);
        }));
    } else {
        function.execute();
    }
}
Also used : HandledTransportAction(org.opensearch.action.support.HandledTransportAction) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) ParseUtils.resolveUserAndExecute(org.opensearch.ad.util.ParseUtils.resolveUserAndExecute) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) AnomalyDetectorFunction(org.opensearch.ad.rest.handler.AnomalyDetectorFunction) XContentParser(org.opensearch.common.xcontent.XContentParser) WriteRequest(org.opensearch.action.support.WriteRequest) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) ParseUtils.getUserContext(org.opensearch.ad.util.ParseUtils.getUserContext) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) DeleteResponse(org.opensearch.action.delete.DeleteResponse) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) GetResponse(org.opensearch.action.get.GetResponse) RestHandlerUtils.wrapRestActionListener(org.opensearch.ad.util.RestHandlerUtils.wrapRestActionListener) DeleteRequest(org.opensearch.action.delete.DeleteRequest) HISTORICAL_DETECTOR_TASK_TYPES(org.opensearch.ad.model.ADTaskType.HISTORICAL_DETECTOR_TASK_TYPES) Client(org.opensearch.client.Client) CommonName(org.opensearch.ad.constant.CommonName) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) FILTER_BY_BACKEND_ROLES(org.opensearch.ad.settings.AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES) GetRequest(org.opensearch.action.get.GetRequest) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) IOException(java.io.IOException) ADTaskManager(org.opensearch.ad.task.ADTaskManager) Settings(org.opensearch.common.settings.Settings) Task(org.opensearch.tasks.Task) RestStatus(org.opensearch.rest.RestStatus) TransportService(org.opensearch.transport.TransportService) ActionFilters(org.opensearch.action.support.ActionFilters) Logger(org.apache.logging.log4j.Logger) FAIL_TO_DELETE_DETECTOR(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_DELETE_DETECTOR) User(org.opensearch.commons.authuser.User) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) DocWriteResponse(org.opensearch.action.DocWriteResponse) LogManager(org.apache.logging.log4j.LogManager) RestHandlerUtils(org.opensearch.ad.util.RestHandlerUtils) GetRequest(org.opensearch.action.get.GetRequest)

Example 5 with ANOMALY_DETECTOR_JOB_INDEX

use of org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX in project anomaly-detection by opensearch-project.

the class AnomalyDetectorActionHandler method getDetectorJob.

/**
 * Get detector job for update/delete AD job.
 * If AD job exist, will return error message; otherwise, execute function.
 *
 * @param clusterService ES cluster service
 * @param client ES node client
 * @param detectorId detector identifier
 * @param listener Listener to send response
 * @param function AD function
 * @param xContentRegistry Registry which is used for XContentParser
 */
public void getDetectorJob(ClusterService clusterService, Client client, String detectorId, ActionListener listener, AnomalyDetectorFunction function, NamedXContentRegistry xContentRegistry) {
    if (clusterService.state().metadata().indices().containsKey(ANOMALY_DETECTOR_JOB_INDEX)) {
        GetRequest request = new GetRequest(ANOMALY_DETECTOR_JOB_INDEX).id(detectorId);
        client.get(request, ActionListener.wrap(response -> onGetAdJobResponseForWrite(response, listener, function, xContentRegistry), exception -> {
            logger.error("Fail to get anomaly detector job: " + detectorId, exception);
            listener.onFailure(exception);
        }));
    } else {
        function.execute();
    }
}
Also used : Client(org.opensearch.client.Client) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) GetRequest(org.opensearch.action.get.GetRequest) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) IOException(java.io.IOException) RestStatus(org.opensearch.rest.RestStatus) XContentParser(org.opensearch.common.xcontent.XContentParser) Logger(org.apache.logging.log4j.Logger) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) ActionListener(org.opensearch.action.ActionListener) LogManager(org.apache.logging.log4j.LogManager) GetResponse(org.opensearch.action.get.GetResponse) RestHandlerUtils(org.opensearch.ad.util.RestHandlerUtils) GetRequest(org.opensearch.action.get.GetRequest)

Aggregations

ActionListener (org.opensearch.action.ActionListener)7 GetRequest (org.opensearch.action.get.GetRequest)7 AnomalyDetectorJob (org.opensearch.ad.model.AnomalyDetectorJob)7 ANOMALY_DETECTOR_JOB_INDEX (org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX)7 Client (org.opensearch.client.Client)7 LogManager (org.apache.logging.log4j.LogManager)6 Logger (org.apache.logging.log4j.Logger)6 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)6 IOException (java.io.IOException)5 SearchRequest (org.opensearch.action.search.SearchRequest)5 CommonName (org.opensearch.ad.constant.CommonName)5 ANOMALY_DETECTORS_INDEX (org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX)5 NamedXContentRegistry (org.opensearch.common.xcontent.NamedXContentRegistry)5 XContentParser (org.opensearch.common.xcontent.XContentParser)5 XContentParserUtils.ensureExpectedToken (org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken)5 IndexNotFoundException (org.opensearch.index.IndexNotFoundException)5 Set (java.util.Set)4 OpenSearchStatusException (org.opensearch.OpenSearchStatusException)4 List (java.util.List)3 Map (java.util.Map)3