Search in sources :

Example 6 with DetectorProfileName

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

the class ProfileTransportActionTests method testMultiEntityNodeOperation.

@Test
public void testMultiEntityNodeOperation() {
    setUpModelSize(100);
    DiscoveryNode nodeId = clusterService().localNode();
    profilesToRetrieve = new HashSet<DetectorProfileName>();
    profilesToRetrieve.add(DetectorProfileName.ACTIVE_ENTITIES);
    ProfileRequest profileRequest = new ProfileRequest(detectorId, profilesToRetrieve, true, nodeId);
    ProfileNodeResponse response = action.nodeOperation(new ProfileNodeRequest(profileRequest));
    assertEquals(activeEntities, response.getActiveEntities());
    assertEquals(null, response.getModelSize());
    profilesToRetrieve.add(DetectorProfileName.INIT_PROGRESS);
    profileRequest = new ProfileRequest(detectorId, profilesToRetrieve, true, nodeId);
    response = action.nodeOperation(new ProfileNodeRequest(profileRequest));
    assertEquals(activeEntities, response.getActiveEntities());
    assertEquals(null, response.getModelSize());
    assertEquals(totalUpdates, response.getTotalUpdates());
    profilesToRetrieve.add(DetectorProfileName.MODELS);
    profileRequest = new ProfileRequest(detectorId, profilesToRetrieve, true, nodeId);
    response = action.nodeOperation(new ProfileNodeRequest(profileRequest));
    assertEquals(activeEntities, response.getActiveEntities());
    assertEquals(null, response.getModelSize());
    assertEquals(2, response.getModelProfiles().size());
    assertEquals(totalUpdates, response.getTotalUpdates());
    assertEquals(2, response.getModelCount());
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) DetectorProfileName(org.opensearch.ad.model.DetectorProfileName) Test(org.junit.Test)

Example 7 with DetectorProfileName

use of org.opensearch.ad.model.DetectorProfileName 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 8 with DetectorProfileName

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

the class ProfileRequest method writeTo.

@Override
public void writeTo(StreamOutput out) throws IOException {
    super.writeTo(out);
    out.writeVInt(profilesToBeRetrieved.size());
    for (DetectorProfileName profile : profilesToBeRetrieved) {
        out.writeEnum(profile);
    }
    out.writeString(detectorId);
    out.writeBoolean(forMultiEntityDetector);
}
Also used : DetectorProfileName(org.opensearch.ad.model.DetectorProfileName)

Example 9 with DetectorProfileName

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

the class AnomalyDetectorProfileRunnerTests method testErrorStateTemplate.

@SuppressWarnings("unchecked")
public void testErrorStateTemplate(RCFPollingStatus initStatus, ErrorResultStatus status, DetectorState state, String error, JobStatus jobStatus, Set<DetectorProfileName> profilesToCollect) throws IOException, InterruptedException {
    ADTask adTask = TestHelpers.randomAdTask();
    adTask.setError(getError(status));
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        Consumer<Optional<ADTask>> function = (Consumer<Optional<ADTask>>) args[2];
        function.accept(Optional.of(adTask));
        return null;
    }).when(adTaskManager).getAndExecuteOnLatestDetectorLevelTask(any(), any(), any(), any(), anyBoolean(), any());
    setUpClientExecuteRCFPollingAction(initStatus);
    setUpClientGet(DetectorStatus.EXIST, jobStatus, initStatus, status);
    DetectorProfile.Builder builder = new DetectorProfile.Builder();
    if (profilesToCollect.contains(DetectorProfileName.STATE)) {
        builder.state(state);
    }
    if (profilesToCollect.contains(DetectorProfileName.ERROR)) {
        builder.error(error);
    }
    DetectorProfile expectedProfile = builder.build();
    final CountDownLatch inProgressLatch = new CountDownLatch(1);
    runner.profile(detector.getDetectorId(), ActionListener.wrap(response -> {
        assertEquals(expectedProfile, response);
        inProgressLatch.countDown();
    }, exception -> {
        logger.info(exception);
        for (StackTraceElement ste : exception.getStackTrace()) {
            logger.info(ste);
        }
        assertTrue("Should not reach here", false);
        inProgressLatch.countDown();
    }), profilesToCollect);
    assertTrue(inProgressLatch.await(100, TimeUnit.SECONDS));
}
Also used : Arrays(java.util.Arrays) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) Version(org.opensearch.Version) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ANOMALY_DETECTOR_JOB_INDEX(org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) RCFPollingAction(org.opensearch.ad.transport.RCFPollingAction) ActionListener(org.opensearch.action.ActionListener) GetResponse(org.opensearch.action.get.GetResponse) ProfileNodeResponse(org.opensearch.ad.transport.ProfileNodeResponse) DetectorProfile(org.opensearch.ad.model.DetectorProfile) RemoteTransportException(org.opensearch.transport.RemoteTransportException) Set(java.util.Set) Instant(java.time.Instant) TransportAddress(org.opensearch.common.transport.TransportAddress) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) DetectorState(org.opensearch.ad.model.DetectorState) DetectorInternalState(org.opensearch.ad.model.DetectorInternalState) Optional(java.util.Optional) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) NotSerializableExceptionWrapper(org.opensearch.common.io.stream.NotSerializableExceptionWrapper) ADTask(org.opensearch.ad.model.ADTask) HashMap(java.util.HashMap) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) ModelProfileOnNode(org.opensearch.ad.model.ModelProfileOnNode) ArrayList(java.util.ArrayList) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ProfileResponse(org.opensearch.ad.transport.ProfileResponse) Collections.emptyMap(java.util.Collections.emptyMap) CommonName(org.opensearch.ad.constant.CommonName) Collections.emptySet(java.util.Collections.emptySet) FailedNodeException(org.opensearch.action.FailedNodeException) InitProgressProfile(org.opensearch.ad.model.InitProgressProfile) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ANOMALY_DETECTORS_INDEX(org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX) GetRequest(org.opensearch.action.get.GetRequest) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) DetectorProfileName(org.opensearch.ad.model.DetectorProfileName) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) RCFPollingResponse(org.opensearch.ad.transport.RCFPollingResponse) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) ChronoUnit(java.time.temporal.ChronoUnit) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) ClusterName(org.opensearch.cluster.ClusterName) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) Collections(java.util.Collections) ProfileAction(org.opensearch.ad.transport.ProfileAction) Optional(java.util.Optional) Consumer(java.util.function.Consumer) ADTask(org.opensearch.ad.model.ADTask) DetectorProfile(org.opensearch.ad.model.DetectorProfile) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 10 with DetectorProfileName

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

the class ProfileTransportActionTests method testNodeOperation.

@Test
public void testNodeOperation() {
    setUpModelSize(100);
    DiscoveryNode nodeId = clusterService().localNode();
    ProfileRequest profileRequest = new ProfileRequest(detectorId, profilesToRetrieve, false, nodeId);
    ProfileNodeResponse response = action.nodeOperation(new ProfileNodeRequest(profileRequest));
    assertEquals(shingleSize, response.getShingleSize());
    assertEquals(null, response.getModelSize());
    profilesToRetrieve = new HashSet<DetectorProfileName>();
    profilesToRetrieve.add(DetectorProfileName.TOTAL_SIZE_IN_BYTES);
    profileRequest = new ProfileRequest(detectorId, profilesToRetrieve, false, nodeId);
    response = action.nodeOperation(new ProfileNodeRequest(profileRequest));
    assertEquals(-1, response.getShingleSize());
    assertEquals(1, response.getModelSize().size());
    assertEquals(modelSize, response.getModelSize().get(modelId).longValue());
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) DetectorProfileName(org.opensearch.ad.model.DetectorProfileName) Test(org.junit.Test)

Aggregations

DetectorProfileName (org.opensearch.ad.model.DetectorProfileName)14 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)8 ActionListener (org.opensearch.action.ActionListener)6 List (java.util.List)5 Set (java.util.Set)5 GetRequest (org.opensearch.action.get.GetRequest)5 AnomalyDetectorSettings (org.opensearch.ad.settings.AnomalyDetectorSettings)5 ADTaskManager (org.opensearch.ad.task.ADTaskManager)5 DiscoveryNodeFilterer (org.opensearch.ad.util.DiscoveryNodeFilterer)5 Client (org.opensearch.client.Client)5 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 LogManager (org.apache.logging.log4j.LogManager)4 Logger (org.apache.logging.log4j.Logger)4 ResourceNotFoundException (org.opensearch.ad.common.exception.ResourceNotFoundException)4 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)4 ANOMALY_DETECTORS_INDEX (org.opensearch.ad.model.AnomalyDetector.ANOMALY_DETECTORS_INDEX)4 AnomalyDetectorJob (org.opensearch.ad.model.AnomalyDetectorJob)4 ANOMALY_DETECTOR_JOB_INDEX (org.opensearch.ad.model.AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX)4 DetectorProfile (org.opensearch.ad.model.DetectorProfile)4