Search in sources :

Example 6 with ADTaskManager

use of org.opensearch.ad.task.ADTaskManager in project anomaly-detection by opensearch-project.

the class GetAnomalyDetectorTests method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    ClusterService clusterService = mock(ClusterService.class);
    ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, Collections.unmodifiableSet(new HashSet<>(Arrays.asList(AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES))));
    when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
    transportService = new TransportService(Settings.EMPTY, mock(Transport.class), null, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null, Collections.emptySet());
    nodeFilter = mock(DiscoveryNodeFilterer.class);
    actionFilters = mock(ActionFilters.class);
    client = mock(Client.class);
    when(client.threadPool()).thenReturn(threadPool);
    adTaskManager = mock(ADTaskManager.class);
    action = new GetAnomalyDetectorTransportAction(transportService, nodeFilter, actionFilters, clusterService, client, Settings.EMPTY, xContentRegistry(), adTaskManager);
    entity = Entity.createSingleAttributeEntity(categoryField, entityValue);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Arrays(java.util.Arrays) DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) BeforeClass(org.junit.BeforeClass) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) AbstractADTest(org.opensearch.ad.AbstractADTest) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) HashSet(java.util.HashSet) Transport(org.opensearch.transport.Transport) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ActionListener(org.opensearch.action.ActionListener) ClusterSettings(org.opensearch.common.settings.ClusterSettings) GetResponse(org.opensearch.action.get.GetResponse) AfterClass(org.junit.AfterClass) Client(org.opensearch.client.Client) ANOMALY_DETECTORS_INDEX(org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX) GetRequest(org.opensearch.action.get.GetRequest) IOException(java.io.IOException) ADTaskManager(org.opensearch.ad.task.ADTaskManager) Settings(org.opensearch.common.settings.Settings) Mockito.when(org.mockito.Mockito.when) TransportService(org.opensearch.transport.TransportService) ActionFilters(org.opensearch.action.support.ActionFilters) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) Entity(org.opensearch.ad.model.Entity) ClusterService(org.opensearch.cluster.service.ClusterService) Collections(java.util.Collections) Mockito.mock(org.mockito.Mockito.mock) ClusterService(org.opensearch.cluster.service.ClusterService) ClusterSettings(org.opensearch.common.settings.ClusterSettings) DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) TransportService(org.opensearch.transport.TransportService) ADTaskManager(org.opensearch.ad.task.ADTaskManager) ActionFilters(org.opensearch.action.support.ActionFilters) Client(org.opensearch.client.Client) HashSet(java.util.HashSet)

Example 7 with ADTaskManager

use of org.opensearch.ad.task.ADTaskManager in project anomaly-detection by opensearch-project.

the class GetAnomalyDetectorTransportActionTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    ClusterService clusterService = mock(ClusterService.class);
    ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, Collections.unmodifiableSet(new HashSet<>(Arrays.asList(AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES))));
    when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
    adTaskManager = mock(ADTaskManager.class);
    action = new GetAnomalyDetectorTransportAction(Mockito.mock(TransportService.class), Mockito.mock(DiscoveryNodeFilterer.class), Mockito.mock(ActionFilters.class), clusterService, client(), Settings.EMPTY, xContentRegistry(), adTaskManager);
    task = Mockito.mock(Task.class);
    response = new ActionListener<GetAnomalyDetectorResponse>() {

        @Override
        public void onResponse(GetAnomalyDetectorResponse getResponse) {
            // When no detectors exist, get response is not generated
            assertTrue(true);
        }

        @Override
        public void onFailure(Exception e) {
        }
    };
    categoryField = "catField";
    categoryValue = "app-0";
    entity = Entity.createSingleAttributeEntity(categoryField, categoryValue);
}
Also used : ADTask(org.opensearch.ad.model.ADTask) Task(org.opensearch.tasks.Task) ClusterService(org.opensearch.cluster.service.ClusterService) ClusterSettings(org.opensearch.common.settings.ClusterSettings) ADTaskManager(org.opensearch.ad.task.ADTaskManager) IOException(java.io.IOException) HashSet(java.util.HashSet) Before(org.junit.Before)

Example 8 with ADTaskManager

use of org.opensearch.ad.task.ADTaskManager in project anomaly-detection by opensearch-project.

the class GetAnomalyDetectorTransportAction method getExecute.

protected void getExecute(GetAnomalyDetectorRequest request, ActionListener<GetAnomalyDetectorResponse> listener) {
    String detectorID = request.getDetectorID();
    String typesStr = request.getTypeStr();
    String rawPath = request.getRawPath();
    Entity entity = request.getEntity();
    boolean all = request.isAll();
    boolean returnJob = request.isReturnJob();
    boolean returnTask = request.isReturnTask();
    try {
        if (!Strings.isEmpty(typesStr) || rawPath.endsWith(PROFILE) || rawPath.endsWith(PROFILE + "/")) {
            if (entity != null) {
                Set<EntityProfileName> entityProfilesToCollect = getEntityProfilesToCollect(typesStr, all);
                EntityProfileRunner profileRunner = new EntityProfileRunner(client, xContentRegistry, AnomalyDetectorSettings.NUM_MIN_SAMPLES);
                profileRunner.profile(detectorID, entity, entityProfilesToCollect, ActionListener.wrap(profile -> {
                    listener.onResponse(new GetAnomalyDetectorResponse(0, null, 0, 0, null, null, false, null, null, false, null, null, profile, true));
                }, e -> listener.onFailure(e)));
            } else {
                Set<DetectorProfileName> profilesToCollect = getProfilesToCollect(typesStr, all);
                AnomalyDetectorProfileRunner profileRunner = new AnomalyDetectorProfileRunner(client, xContentRegistry, nodeFilter, AnomalyDetectorSettings.NUM_MIN_SAMPLES, transportService, adTaskManager);
                profileRunner.profile(detectorID, getProfileActionListener(listener), profilesToCollect);
            }
        } else {
            if (returnTask) {
                adTaskManager.getAndExecuteOnLatestADTasks(detectorID, null, null, ALL_DETECTOR_TASK_TYPES, (taskList) -> {
                    Optional<ADTask> realtimeAdTask = Optional.empty();
                    Optional<ADTask> historicalAdTask = Optional.empty();
                    if (taskList != null && taskList.size() > 0) {
                        Map<String, ADTask> adTasks = new HashMap<>();
                        List<ADTask> duplicateAdTasks = new ArrayList<>();
                        for (ADTask task : taskList) {
                            if (adTasks.containsKey(task.getTaskType())) {
                                LOG.info("Found duplicate latest task of detector {}, task id: {}, task type: {}", detectorID, task.getTaskType(), task.getTaskId());
                                duplicateAdTasks.add(task);
                                continue;
                            }
                            adTasks.put(task.getTaskType(), task);
                        }
                        if (duplicateAdTasks.size() > 0) {
                            adTaskManager.resetLatestFlagAsFalse(duplicateAdTasks);
                        }
                        if (adTasks.containsKey(ADTaskType.REALTIME_HC_DETECTOR.name())) {
                            realtimeAdTask = Optional.ofNullable(adTasks.get(ADTaskType.REALTIME_HC_DETECTOR.name()));
                        } else if (adTasks.containsKey(ADTaskType.REALTIME_SINGLE_ENTITY.name())) {
                            realtimeAdTask = Optional.ofNullable(adTasks.get(ADTaskType.REALTIME_SINGLE_ENTITY.name()));
                        }
                        if (adTasks.containsKey(ADTaskType.HISTORICAL_HC_DETECTOR.name())) {
                            historicalAdTask = Optional.ofNullable(adTasks.get(ADTaskType.HISTORICAL_HC_DETECTOR.name()));
                        } else if (adTasks.containsKey(ADTaskType.HISTORICAL_SINGLE_ENTITY.name())) {
                            historicalAdTask = Optional.ofNullable(adTasks.get(ADTaskType.HISTORICAL_SINGLE_ENTITY.name()));
                        } else if (adTasks.containsKey(ADTaskType.HISTORICAL.name())) {
                            historicalAdTask = Optional.ofNullable(adTasks.get(ADTaskType.HISTORICAL.name()));
                        }
                    }
                    getDetectorAndJob(detectorID, returnJob, returnTask, realtimeAdTask, historicalAdTask, listener);
                }, transportService, true, 2, listener);
            } else {
                getDetectorAndJob(detectorID, returnJob, returnTask, Optional.empty(), Optional.empty(), listener);
            }
        }
    } catch (Exception e) {
        LOG.error(e);
        listener.onFailure(e);
    }
}
Also used : Arrays(java.util.Arrays) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) AnomalyDetectorProfileRunner(org.opensearch.ad.AnomalyDetectorProfileRunner) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) Name(org.opensearch.ad.Name) FAIL_TO_FIND_DETECTOR_MSG(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG) EntityProfileName(org.opensearch.ad.model.EntityProfileName) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) ParseUtils.resolveUserAndExecute(org.opensearch.ad.util.ParseUtils.resolveUserAndExecute) Strings(org.opensearch.common.Strings) XContentParser(org.opensearch.common.xcontent.XContentParser) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) ParseUtils.getUserContext(org.opensearch.ad.util.ParseUtils.getUserContext) Map(java.util.Map) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) EnumSet(java.util.EnumSet) RestHandlerUtils.wrapRestActionListener(org.opensearch.ad.util.RestHandlerUtils.wrapRestActionListener) DetectorProfile(org.opensearch.ad.model.DetectorProfile) Client(org.opensearch.client.Client) PROFILE(org.opensearch.ad.util.RestHandlerUtils.PROFILE) Set(java.util.Set) ADTaskType(org.opensearch.ad.model.ADTaskType) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) ADTaskManager(org.opensearch.ad.task.ADTaskManager) Settings(org.opensearch.common.settings.Settings) Task(org.opensearch.tasks.Task) RestStatus(org.opensearch.rest.RestStatus) Collectors(java.util.stream.Collectors) TransportService(org.opensearch.transport.TransportService) EntityProfileRunner(org.opensearch.ad.EntityProfileRunner) Sets(com.google.common.collect.Sets) ActionFilters(org.opensearch.action.support.ActionFilters) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Optional(java.util.Optional) ALL_DETECTOR_TASK_TYPES(org.opensearch.ad.model.ADTaskType.ALL_DETECTOR_TASK_TYPES) RestHandlerUtils(org.opensearch.ad.util.RestHandlerUtils) HandledTransportAction(org.opensearch.action.support.HandledTransportAction) DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) ADTask(org.opensearch.ad.model.ADTask) CheckedConsumer(org.opensearch.common.CheckedConsumer) HashMap(java.util.HashMap) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ANOMALY_DETECTORS_INDEX(org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX) FILTER_BY_BACKEND_ROLES(org.opensearch.ad.settings.AnomalyDetectorSettings.FILTER_BY_BACKEND_ROLES) FAIL_TO_GET_DETECTOR(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_GET_DETECTOR) DetectorProfileName(org.opensearch.ad.model.DetectorProfileName) MultiGetItemResponse(org.opensearch.action.get.MultiGetItemResponse) Entity(org.opensearch.ad.model.Entity) User(org.opensearch.commons.authuser.User) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) LogManager(org.apache.logging.log4j.LogManager) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) Entity(org.opensearch.ad.model.Entity) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EntityProfileRunner(org.opensearch.ad.EntityProfileRunner) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) DetectorProfileName(org.opensearch.ad.model.DetectorProfileName) ADTask(org.opensearch.ad.model.ADTask) AnomalyDetectorProfileRunner(org.opensearch.ad.AnomalyDetectorProfileRunner) EntityProfileName(org.opensearch.ad.model.EntityProfileName)

Example 9 with ADTaskManager

use of org.opensearch.ad.task.ADTaskManager in project anomaly-detection by opensearch-project.

the class AbstractProfileRunnerTests method setUp.

@SuppressWarnings("unchecked")
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    client = mock(Client.class);
    nodeFilter = mock(DiscoveryNodeFilterer.class);
    clusterService = mock(ClusterService.class);
    adTaskManager = mock(ADTaskManager.class);
    when(clusterService.state()).thenReturn(ClusterState.builder(new ClusterName("test cluster")).build());
    requiredSamples = 128;
    neededSamples = 5;
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        Consumer<Optional<ADTask>> function = (Consumer<Optional<ADTask>>) args[2];
        function.accept(Optional.of(TestHelpers.randomAdTask()));
        return null;
    }).when(adTaskManager).getAndExecuteOnLatestDetectorLevelTask(any(), any(), any(), any(), anyBoolean(), any());
    runner = new AnomalyDetectorProfileRunner(client, xContentRegistry(), nodeFilter, requiredSamples, transportService, adTaskManager);
    detectorIntervalMin = 3;
    detectorGetReponse = mock(GetResponse.class);
}
Also used : DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) Optional(java.util.Optional) GetResponse(org.opensearch.action.get.GetResponse) ClusterService(org.opensearch.cluster.service.ClusterService) Consumer(java.util.function.Consumer) ADTaskManager(org.opensearch.ad.task.ADTaskManager) ADTask(org.opensearch.ad.model.ADTask) ClusterName(org.opensearch.cluster.ClusterName) Client(org.opensearch.client.Client) Before(org.junit.Before)

Example 10 with ADTaskManager

use of org.opensearch.ad.task.ADTaskManager in project anomaly-detection by opensearch-project.

the class ValidateAnomalyDetectorActionHandlerTests method setUp.

@SuppressWarnings("unchecked")
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    MockitoAnnotations.initMocks(this);
    settings = Settings.EMPTY;
    clusterService = mock(ClusterService.class);
    channel = mock(ActionListener.class);
    transportService = mock(TransportService.class);
    anomalyDetectionIndices = mock(AnomalyDetectionIndices.class);
    when(anomalyDetectionIndices.doesAnomalyDetectorIndexExist()).thenReturn(true);
    detectorId = "123";
    seqNo = 0L;
    primaryTerm = 0L;
    clock = mock(Clock.class);
    refreshPolicy = WriteRequest.RefreshPolicy.IMMEDIATE;
    String field = "a";
    detector = TestHelpers.randomAnomalyDetectorUsingCategoryFields(detectorId, "timestamp", ImmutableList.of("test-index"), Arrays.asList(field));
    requestTimeout = new TimeValue(1000L);
    maxSingleEntityAnomalyDetectors = 1000;
    maxMultiEntityAnomalyDetectors = 10;
    maxAnomalyFeatures = 5;
    method = RestRequest.Method.POST;
    adTaskManager = mock(ADTaskManager.class);
    searchFeatureDao = mock(SearchFeatureDao.class);
    threadContext = new ThreadContext(settings);
    Mockito.doReturn(threadPool).when(clientMock).threadPool();
    Mockito.doReturn(threadContext).when(threadPool).getThreadContext();
}
Also used : ClusterService(org.opensearch.cluster.service.ClusterService) ActionListener(org.opensearch.action.ActionListener) TransportService(org.opensearch.transport.TransportService) ADTaskManager(org.opensearch.ad.task.ADTaskManager) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) SearchFeatureDao(org.opensearch.ad.feature.SearchFeatureDao) Clock(java.time.Clock) TimeValue(org.opensearch.common.unit.TimeValue) Before(org.junit.Before)

Aggregations

ADTaskManager (org.opensearch.ad.task.ADTaskManager)15 Before (org.junit.Before)11 ClusterService (org.opensearch.cluster.service.ClusterService)10 ActionListener (org.opensearch.action.ActionListener)9 TransportService (org.opensearch.transport.TransportService)9 Client (org.opensearch.client.Client)8 HashSet (java.util.HashSet)6 GetResponse (org.opensearch.action.get.GetResponse)6 Optional (java.util.Optional)5 GetRequest (org.opensearch.action.get.GetRequest)5 DiscoveryNodeFilterer (org.opensearch.ad.util.DiscoveryNodeFilterer)5 ClusterSettings (org.opensearch.common.settings.ClusterSettings)5 ActionFilters (org.opensearch.action.support.ActionFilters)4 CacheProvider (org.opensearch.ad.caching.CacheProvider)4 EntityCache (org.opensearch.ad.caching.EntityCache)4 FeatureManager (org.opensearch.ad.feature.FeatureManager)4 SearchFeatureDao (org.opensearch.ad.feature.SearchFeatureDao)4 AnomalyDetectionIndices (org.opensearch.ad.indices.AnomalyDetectionIndices)4 ModelManager (org.opensearch.ad.ml.ModelManager)4 ADTask (org.opensearch.ad.model.ADTask)4