Search in sources :

Example 96 with ADTask

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

the class ADTaskManagerTests method testRemoveStaleRunningEntity.

@SuppressWarnings("unchecked")
public void testRemoveStaleRunningEntity() throws IOException {
    ActionListener<AnomalyDetectorJobResponse> actionListener = mock(ActionListener.class);
    ADTask adTask = randomAdTask();
    String entity = randomAlphaOfLength(5);
    ExecutorService executeService = mock(ExecutorService.class);
    when(threadPool.executor(anyString())).thenReturn(executeService);
    doAnswer(invocation -> {
        Runnable runnable = invocation.getArgument(0);
        runnable.run();
        return null;
    }).when(executeService).execute(any());
    when(adTaskCacheManager.removeRunningEntity(anyString(), anyString())).thenReturn(true);
    when(adTaskCacheManager.getPendingEntityCount(anyString())).thenReturn(randomIntBetween(1, 10));
    adTaskManager.removeStaleRunningEntity(adTask, entity, transportService, actionListener);
    verify(adTaskManager, times(1)).runNextEntityForHCADHistorical(any(), any(), any());
    when(adTaskCacheManager.removeRunningEntity(anyString(), anyString())).thenReturn(false);
    when(adTaskCacheManager.hasEntity(anyString())).thenReturn(false);
    adTaskManager.removeStaleRunningEntity(adTask, entity, transportService, actionListener);
    verify(adTaskManager, times(1)).setHCDetectorTaskDone(any(), any(), any());
    when(adTaskCacheManager.hasEntity(anyString())).thenReturn(true);
    adTaskManager.removeStaleRunningEntity(adTask, entity, transportService, actionListener);
    verify(adTaskManager, times(1)).setHCDetectorTaskDone(any(), any(), any());
}
Also used : AnomalyDetectorJobResponse(org.opensearch.ad.transport.AnomalyDetectorJobResponse) ADTask(org.opensearch.ad.model.ADTask) ExecutorService(java.util.concurrent.ExecutorService) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString)

Example 97 with ADTask

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

the class ADTaskManagerTests method testResetLatestFlagAsFalse.

public void testResetLatestFlagAsFalse() throws IOException {
    List<ADTask> adTasks = new ArrayList<>();
    adTaskManager.resetLatestFlagAsFalse(adTasks);
    verify(client, never()).execute(any(), any(), any());
    ADTask adTask = randomAdTask();
    adTasks.add(adTask);
    doAnswer(invocation -> {
        ActionListener<BulkResponse> listener = invocation.getArgument(2);
        BulkItemResponse[] responses = new BulkItemResponse[1];
        ShardId shardId = new ShardId(new Index("index_name", "uuid"), 0);
        responses[0] = new BulkItemResponse(0, randomFrom(DocWriteRequest.OpType.values()), new IndexResponse(shardId, "_doc", "id", 1, 1, 1, true));
        listener.onResponse(new BulkResponse(responses, 1));
        return null;
    }).when(client).execute(any(), any(), any());
    adTaskManager.resetLatestFlagAsFalse(adTasks);
    verify(client, times(1)).execute(any(), any(), any());
}
Also used : ShardId(org.opensearch.index.shard.ShardId) IndexResponse(org.opensearch.action.index.IndexResponse) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) ADTask(org.opensearch.ad.model.ADTask) ArrayList(java.util.ArrayList) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) BulkResponse(org.opensearch.action.bulk.BulkResponse) Index(org.opensearch.index.Index)

Example 98 with ADTask

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

the class AnomalyDetectorJobTransportActionTests method testStartHistoricalAnalysisForMultiCategoryHCWithUser.

public void testStartHistoricalAnalysisForMultiCategoryHCWithUser() throws IOException, InterruptedException {
    ingestTestData(testIndex, startTime, detectionIntervalInMinutes, type + "1", DEFAULT_IP, 2000, false);
    ingestTestData(testIndex, startTime, detectionIntervalInMinutes, type + "2", DEFAULT_IP, 2000, false);
    ingestTestData(testIndex, startTime, detectionIntervalInMinutes, type + "3", "127.0.0.2", 2000, false);
    ingestTestData(testIndex, startTime, detectionIntervalInMinutes, type + "4", "127.0.0.2", 2000, false);
    AnomalyDetector detector = TestHelpers.randomDetector(ImmutableList.of(maxValueFeature()), testIndex, detectionIntervalInMinutes, MockSimpleLog.TIME_FIELD, ImmutableList.of(categoryField, ipField));
    String detectorId = createDetector(detector);
    AnomalyDetectorJobRequest request = new AnomalyDetectorJobRequest(detectorId, dateRange, true, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, START_JOB);
    Client nodeClient = getDataNodeClient();
    if (nodeClient != null) {
        AnomalyDetectorJobResponse response = nodeClient.execute(MockAnomalyDetectorJobAction.INSTANCE, request).actionGet(100_000);
        String taskId = response.getId();
        waitUntil(() -> {
            try {
                ADTask task = getADTask(taskId);
                return !TestHelpers.HISTORICAL_ANALYSIS_RUNNING_STATS.contains(task.getState());
            } catch (IOException e) {
                return false;
            }
        }, 90, TimeUnit.SECONDS);
        ADTask adTask = getADTask(taskId);
        assertEquals(ADTaskType.HISTORICAL_HC_DETECTOR.toString(), adTask.getTaskType());
        // Task may fail if memory circuit breaker triggered
        assertTrue(HISTORICAL_ANALYSIS_FINISHED_FAILED_STATS.contains(adTask.getState()));
        assertEquals(categoryField, adTask.getDetector().getCategoryField().get(0));
        assertEquals(ipField, adTask.getDetector().getCategoryField().get(1));
        if (ADTaskState.FINISHED.name().equals(adTask.getState())) {
            List<ADTask> adTasks = searchADTasks(detectorId, taskId, true, 100);
            assertEquals(5, adTasks.size());
            List<ADTask> entityTasks = adTasks.stream().filter(task -> ADTaskType.HISTORICAL_HC_ENTITY.name().equals(task.getTaskType())).collect(Collectors.toList());
            assertEquals(5, entityTasks.size());
        }
    }
}
Also used : 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) ADTask(org.opensearch.ad.model.ADTask) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) FAIL_TO_FIND_DETECTOR_MSG(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG) AtomicReference(java.util.concurrent.atomic.AtomicReference) ADTaskProfile(org.opensearch.ad.model.ADTaskProfile) ADTaskState(org.opensearch.ad.model.ADTaskState) UNASSIGNED_SEQ_NO(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) ImmutableList(com.google.common.collect.ImmutableList) MAX_OLD_AD_TASK_DOCS_PER_DETECTOR(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_OLD_AD_TASK_DOCS_PER_DETECTOR) After(org.junit.After) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) STOP_JOB(org.opensearch.ad.util.RestHandlerUtils.STOP_JOB) ActionListener(org.opensearch.action.ActionListener) DETECTOR_IS_RUNNING(org.opensearch.ad.constant.CommonErrorMessages.DETECTOR_IS_RUNNING) GetResponse(org.opensearch.action.get.GetResponse) Before(org.junit.Before) Client(org.opensearch.client.Client) Versions(org.opensearch.common.lucene.uid.Versions) CommonName(org.opensearch.ad.constant.CommonName) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) PROFILE(org.opensearch.ad.util.RestHandlerUtils.PROFILE) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) START_JOB(org.opensearch.ad.util.RestHandlerUtils.START_JOB) Set(java.util.Set) MockSimpleLog(org.opensearch.ad.mock.model.MockSimpleLog) ADTaskType(org.opensearch.ad.model.ADTaskType) IOException(java.io.IOException) Settings(org.opensearch.common.settings.Settings) UNASSIGNED_PRIMARY_TERM(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) ChronoUnit(java.time.temporal.ChronoUnit) Ignore(org.junit.Ignore) MockAnomalyDetectorJobAction(org.opensearch.ad.mock.transport.MockAnomalyDetectorJobAction) TestHelpers(org.opensearch.ad.TestHelpers) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) HISTORICAL_ANALYSIS_FINISHED_FAILED_STATS(org.opensearch.ad.TestHelpers.HISTORICAL_ANALYSIS_FINISHED_FAILED_STATS) DetectionDateRange(org.opensearch.ad.model.DetectionDateRange) HistoricalAnalysisIntegTestCase(org.opensearch.ad.HistoricalAnalysisIntegTestCase) StatNames(org.opensearch.ad.stats.StatNames) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) ADTask(org.opensearch.ad.model.ADTask) IOException(java.io.IOException) Client(org.opensearch.client.Client) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector)

Example 99 with ADTask

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

the class AnomalyDetectorJobTransportActionTests method testStopHistoricalDetector.

public void testStopHistoricalDetector() throws IOException, InterruptedException {
    updateTransientSettings(ImmutableMap.of(BATCH_TASK_PIECE_INTERVAL_SECONDS.getKey(), 5));
    ADTask adTask = startHistoricalAnalysis(startTime, endTime);
    assertEquals(ADTaskState.INIT.name(), adTask.getState());
    assertNull(adTask.getStartedBy());
    assertNull(adTask.getUser());
    waitUntil(() -> {
        try {
            ADTask task = getADTask(adTask.getTaskId());
            boolean taskRunning = TestHelpers.HISTORICAL_ANALYSIS_RUNNING_STATS.contains(task.getState());
            if (taskRunning) {
                // It's possible that the task not started on worker node yet. Recancel it to make sure
                // task cancelled.
                AnomalyDetectorJobRequest request = stopDetectorJobRequest(adTask.getDetectorId(), true);
                client().execute(AnomalyDetectorJobAction.INSTANCE, request).actionGet(10000);
            }
            return !taskRunning;
        } catch (Exception e) {
            return false;
        }
    }, 20, TimeUnit.SECONDS);
    ADTask stoppedTask = getADTask(adTask.getTaskId());
    assertEquals(ADTaskState.STOPPED.name(), stoppedTask.getState());
    assertEquals(0, getExecutingADTask());
}
Also used : ADTask(org.opensearch.ad.model.ADTask) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IOException(java.io.IOException)

Example 100 with ADTask

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

the class AnomalyDetectorJobTransportActionTests method testStartHistoricalAnalysisForSingleCategoryHCWithUser.

public void testStartHistoricalAnalysisForSingleCategoryHCWithUser() throws IOException, InterruptedException {
    ingestTestData(testIndex, startTime, detectionIntervalInMinutes, type + "1", DEFAULT_IP, 2000, false);
    ingestTestData(testIndex, startTime, detectionIntervalInMinutes, type + "2", DEFAULT_IP, 2000, false);
    AnomalyDetector detector = TestHelpers.randomDetector(ImmutableList.of(maxValueFeature()), testIndex, detectionIntervalInMinutes, MockSimpleLog.TIME_FIELD, ImmutableList.of(categoryField));
    String detectorId = createDetector(detector);
    AnomalyDetectorJobRequest request = new AnomalyDetectorJobRequest(detectorId, dateRange, true, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, START_JOB);
    Client nodeClient = getDataNodeClient();
    if (nodeClient != null) {
        AnomalyDetectorJobResponse response = nodeClient.execute(MockAnomalyDetectorJobAction.INSTANCE, request).actionGet(100000);
        waitUntil(() -> {
            try {
                ADTask task = getADTask(response.getId());
                return !TestHelpers.HISTORICAL_ANALYSIS_RUNNING_STATS.contains(task.getState());
            } catch (IOException e) {
                return false;
            }
        }, 20, TimeUnit.SECONDS);
        ADTask adTask = getADTask(response.getId());
        assertEquals(ADTaskType.HISTORICAL_HC_DETECTOR.toString(), adTask.getTaskType());
        assertTrue(HISTORICAL_ANALYSIS_FINISHED_FAILED_STATS.contains(adTask.getState()));
        assertEquals(categoryField, adTask.getDetector().getCategoryField().get(0));
        if (ADTaskState.FINISHED.name().equals(adTask.getState())) {
            List<ADTask> adTasks = searchADTasks(detectorId, true, 100);
            assertEquals(4, adTasks.size());
            List<ADTask> entityTasks = adTasks.stream().filter(task -> ADTaskType.HISTORICAL_HC_ENTITY.name().equals(task.getTaskType())).collect(Collectors.toList());
            assertEquals(3, entityTasks.size());
        }
    }
}
Also used : 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) ADTask(org.opensearch.ad.model.ADTask) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) FAIL_TO_FIND_DETECTOR_MSG(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG) AtomicReference(java.util.concurrent.atomic.AtomicReference) ADTaskProfile(org.opensearch.ad.model.ADTaskProfile) ADTaskState(org.opensearch.ad.model.ADTaskState) UNASSIGNED_SEQ_NO(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) ImmutableList(com.google.common.collect.ImmutableList) MAX_OLD_AD_TASK_DOCS_PER_DETECTOR(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_OLD_AD_TASK_DOCS_PER_DETECTOR) After(org.junit.After) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) STOP_JOB(org.opensearch.ad.util.RestHandlerUtils.STOP_JOB) ActionListener(org.opensearch.action.ActionListener) DETECTOR_IS_RUNNING(org.opensearch.ad.constant.CommonErrorMessages.DETECTOR_IS_RUNNING) GetResponse(org.opensearch.action.get.GetResponse) Before(org.junit.Before) Client(org.opensearch.client.Client) Versions(org.opensearch.common.lucene.uid.Versions) CommonName(org.opensearch.ad.constant.CommonName) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) PROFILE(org.opensearch.ad.util.RestHandlerUtils.PROFILE) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) START_JOB(org.opensearch.ad.util.RestHandlerUtils.START_JOB) Set(java.util.Set) MockSimpleLog(org.opensearch.ad.mock.model.MockSimpleLog) ADTaskType(org.opensearch.ad.model.ADTaskType) IOException(java.io.IOException) Settings(org.opensearch.common.settings.Settings) UNASSIGNED_PRIMARY_TERM(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) ChronoUnit(java.time.temporal.ChronoUnit) Ignore(org.junit.Ignore) MockAnomalyDetectorJobAction(org.opensearch.ad.mock.transport.MockAnomalyDetectorJobAction) TestHelpers(org.opensearch.ad.TestHelpers) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) HISTORICAL_ANALYSIS_FINISHED_FAILED_STATS(org.opensearch.ad.TestHelpers.HISTORICAL_ANALYSIS_FINISHED_FAILED_STATS) DetectionDateRange(org.opensearch.ad.model.DetectionDateRange) HistoricalAnalysisIntegTestCase(org.opensearch.ad.HistoricalAnalysisIntegTestCase) StatNames(org.opensearch.ad.stats.StatNames) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) ADTask(org.opensearch.ad.model.ADTask) IOException(java.io.IOException) Client(org.opensearch.client.Client) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector)

Aggregations

ADTask (org.opensearch.ad.model.ADTask)108 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)44 List (java.util.List)36 ArrayList (java.util.ArrayList)35 ActionListener (org.opensearch.action.ActionListener)35 Client (org.opensearch.client.Client)35 ImmutableMap (com.google.common.collect.ImmutableMap)34 AnomalyDetectorJob (org.opensearch.ad.model.AnomalyDetectorJob)34 ImmutableList (com.google.common.collect.ImmutableList)32 Map (java.util.Map)32 Optional (java.util.Optional)32 Entity (org.opensearch.ad.model.Entity)32 Instant (java.time.Instant)31 ADTaskState (org.opensearch.ad.model.ADTaskState)31 ADTaskType (org.opensearch.ad.model.ADTaskType)31 HashMap (java.util.HashMap)30 Collectors (java.util.stream.Collectors)30 DetectionDateRange (org.opensearch.ad.model.DetectionDateRange)30 TransportService (org.opensearch.transport.TransportService)30 LogManager (org.apache.logging.log4j.LogManager)29