Search in sources :

Example 1 with IntervalTimeConfiguration

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

the class AnomalyDetectorJobRunner method indexAnomalyResult.

private void indexAnomalyResult(AnomalyDetectorJob jobParameter, LockService lockService, LockModel lock, Instant detectionStartTime, Instant executionStartTime, AnomalyResultResponse response) {
    String detectorId = jobParameter.getName();
    detectorEndRunExceptionCount.remove(detectorId);
    try {
        // We return 0 or Double.NaN rcf score if there is no error.
        if ((response.getAnomalyScore() <= 0 || Double.isNaN(response.getAnomalyScore())) && response.getError() == null) {
            updateRealtimeTask(response, detectorId);
            return;
        }
        IntervalTimeConfiguration windowDelay = (IntervalTimeConfiguration) jobParameter.getWindowDelay();
        Instant dataStartTime = detectionStartTime.minus(windowDelay.getInterval(), windowDelay.getUnit());
        Instant dataEndTime = executionStartTime.minus(windowDelay.getInterval(), windowDelay.getUnit());
        User user = jobParameter.getUser();
        if (response.getError() != null) {
            log.info("Anomaly result action run successfully for {} with error {}", detectorId, response.getError());
        }
        AnomalyResult anomalyResult = response.toAnomalyResult(detectorId, dataStartTime, dataEndTime, executionStartTime, Instant.now(), anomalyDetectionIndices.getSchemaVersion(ADIndex.RESULT), user, response.getError());
        String resultIndex = jobParameter.getResultIndex();
        anomalyResultHandler.index(anomalyResult, detectorId, resultIndex);
        updateRealtimeTask(response, detectorId);
    } catch (EndRunException e) {
        handleAdException(jobParameter, lockService, lock, detectionStartTime, executionStartTime, e);
    } catch (Exception e) {
        log.error("Failed to index anomaly result for " + detectorId, e);
    } finally {
        releaseLock(jobParameter, lockService, lock);
    }
}
Also used : User(org.opensearch.commons.authuser.User) EndRunException(org.opensearch.ad.common.exception.EndRunException) Instant(java.time.Instant) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) AnomalyResult(org.opensearch.ad.model.AnomalyResult) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) EndRunException(org.opensearch.ad.common.exception.EndRunException) IOException(java.io.IOException)

Example 2 with IntervalTimeConfiguration

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

the class AnomalyResultTransportAction method onGetDetector.

private ActionListener<Optional<AnomalyDetector>> onGetDetector(ActionListener<AnomalyResultResponse> listener, String adID, AnomalyResultRequest request) {
    return ActionListener.wrap(detectorOptional -> {
        if (!detectorOptional.isPresent()) {
            listener.onFailure(new EndRunException(adID, "AnomalyDetector is not available.", true));
            return;
        }
        AnomalyDetector anomalyDetector = detectorOptional.get();
        if (anomalyDetector.isMultientityDetector()) {
            hcDetectors.add(adID);
            adStats.getStat(StatNames.AD_HC_EXECUTE_REQUEST_COUNT.getName()).increment();
        }
        long delayMillis = Optional.ofNullable((IntervalTimeConfiguration) anomalyDetector.getWindowDelay()).map(t -> t.toDuration().toMillis()).orElse(0L);
        long dataStartTime = request.getStart() - delayMillis;
        long dataEndTime = request.getEnd() - delayMillis;
        adTaskManager.initRealtimeTaskCacheAndCleanupStaleCache(adID, anomalyDetector, transportService, ActionListener.runAfter(initRealtimeTaskCacheListener(adID), () -> executeAnomalyDetection(listener, adID, request, anomalyDetector, dataStartTime, dataEndTime)));
    }, exception -> handleExecuteException(exception, listener, adID));
}
Also used : ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) ModelManager(org.opensearch.ad.ml.ModelManager) HashRing(org.opensearch.ad.cluster.HashRing) ADStats(org.opensearch.ad.stats.ADStats) ActionRequest(org.opensearch.action.ActionRequest) LimitExceededException(org.opensearch.ad.common.exception.LimitExceededException) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Map(java.util.Map) NodeClosedException(org.opensearch.node.NodeClosedException) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) NodeNotConnectedException(org.opensearch.transport.NodeNotConnectedException) Client(org.opensearch.client.Client) ActionNotFoundTransportException(org.opensearch.transport.ActionNotFoundTransportException) TransportRequestOptions(org.opensearch.transport.TransportRequestOptions) Set(java.util.Set) ExceptionsHelper(org.opensearch.ExceptionsHelper) 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) ActionFilters(org.opensearch.action.support.ActionFilters) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ExceptionUtil(org.opensearch.ad.util.ExceptionUtil) NodeStateManager(org.opensearch.ad.NodeStateManager) Entry(java.util.Map.Entry) OpenSearchTimeoutException(org.opensearch.OpenSearchTimeoutException) ActionListenerResponseHandler(org.opensearch.action.ActionListenerResponseHandler) Optional(java.util.Optional) SingleStreamModelIdMapper(org.opensearch.ad.ml.SingleStreamModelIdMapper) ConnectTransportException(org.opensearch.transport.ConnectTransportException) ReceiveTimeoutTransportException(org.opensearch.transport.ReceiveTimeoutTransportException) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) ADCircuitBreakerService(org.opensearch.ad.breaker.ADCircuitBreakerService) MAX_ENTITIES_PER_QUERY(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_ENTITIES_PER_QUERY) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) HandledTransportAction(org.opensearch.action.support.HandledTransportAction) NotSerializableExceptionWrapper(org.opensearch.common.io.stream.NotSerializableExceptionWrapper) ThreadPool(org.opensearch.threadpool.ThreadPool) FeatureData(org.opensearch.ad.model.FeatureData) EnabledSetting(org.opensearch.ad.settings.EnabledSetting) Releasable(org.opensearch.common.lease.Releasable) IndicesOptions(org.opensearch.action.support.IndicesOptions) ThreadedActionListener(org.opensearch.action.support.ThreadedActionListener) AtomicReference(java.util.concurrent.atomic.AtomicReference) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) PAGE_SIZE(org.opensearch.ad.settings.AnomalyDetectorSettings.PAGE_SIZE) ClientException(org.opensearch.ad.common.exception.ClientException) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ConnectException(java.net.ConnectException) EndRunException(org.opensearch.ad.common.exception.EndRunException) SinglePointFeatures(org.opensearch.ad.feature.SinglePointFeatures) InternalFailure(org.opensearch.ad.common.exception.InternalFailure) CommonName(org.opensearch.ad.constant.CommonName) Iterator(java.util.Iterator) FeatureManager(org.opensearch.ad.feature.FeatureManager) ClusterBlockLevel(org.opensearch.cluster.block.ClusterBlockLevel) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) NotSerializedADExceptionName(org.opensearch.ad.common.exception.NotSerializedADExceptionName) INVALID_SEARCH_QUERY_MSG(org.opensearch.ad.constant.CommonErrorMessages.INVALID_SEARCH_QUERY_MSG) CompositeRetriever(org.opensearch.ad.feature.CompositeRetriever) PageIterator(org.opensearch.ad.feature.CompositeRetriever.PageIterator) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) Entity(org.opensearch.ad.model.Entity) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) AnomalyDetectorPlugin(org.opensearch.ad.AnomalyDetectorPlugin) SearchPhaseExecutionException(org.opensearch.action.search.SearchPhaseExecutionException) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) StatNames(org.opensearch.ad.stats.StatNames) LogManager(org.apache.logging.log4j.LogManager) NetworkExceptionHelper(org.opensearch.common.transport.NetworkExceptionHelper) ParseUtils(org.opensearch.ad.util.ParseUtils) EndRunException(org.opensearch.ad.common.exception.EndRunException) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector)

Example 3 with IntervalTimeConfiguration

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

the class FeatureManagerTests method setup.

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    maxTrainSamples = 24;
    maxSampleStride = 100;
    trainSampleTimeRangeInHours = 1;
    minTrainSamples = 4;
    shingleSize = 3;
    maxMissingPointsRate = 0.67;
    maxNeighborDistance = 2;
    previewSampleRate = 0.5;
    maxPreviewSamples = 2;
    featureBufferTtl = Duration.ofMillis(1_000L);
    detectorId = "id";
    when(detector.getDetectorId()).thenReturn(detectorId);
    when(detector.getShingleSize()).thenReturn(shingleSize);
    IntervalTimeConfiguration detectorIntervalTimeConfig = new IntervalTimeConfiguration(1, ChronoUnit.MINUTES);
    intervalInMilliseconds = detectorIntervalTimeConfig.toDuration().toMillis();
    when(detector.getDetectorIntervalInMilliseconds()).thenReturn(intervalInMilliseconds);
    Interpolator interpolator = new LinearUniformInterpolator(new SingleFeatureLinearUniformInterpolator());
    ExecutorService executorService = mock(ExecutorService.class);
    when(threadPool.executor(AnomalyDetectorPlugin.AD_THREAD_POOL_NAME)).thenReturn(executorService);
    doAnswer(invocation -> {
        Runnable runnable = invocation.getArgument(0);
        runnable.run();
        return null;
    }).when(executorService).execute(any(Runnable.class));
    this.featureManager = spy(new FeatureManager(searchFeatureDao, interpolator, clock, maxTrainSamples, maxSampleStride, trainSampleTimeRangeInHours, minTrainSamples, maxMissingPointsRate, maxNeighborDistance, previewSampleRate, maxPreviewSamples, featureBufferTtl, threadPool, AnomalyDetectorPlugin.AD_THREAD_POOL_NAME));
}
Also used : SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) ExecutorService(java.util.concurrent.ExecutorService) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) Interpolator(org.opensearch.ad.dataprocessor.Interpolator) LinearUniformInterpolator(org.opensearch.ad.dataprocessor.LinearUniformInterpolator) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) LinearUniformInterpolator(org.opensearch.ad.dataprocessor.LinearUniformInterpolator) Before(org.junit.Before)

Example 4 with IntervalTimeConfiguration

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

the class FeatureManagerTests method getColdStartData_returnExpectedToListener.

@Test
@SuppressWarnings("unchecked")
@Parameters(method = "getTrainDataTestData")
public void getColdStartData_returnExpectedToListener(Long latestTime, List<Entry<Long, Long>> sampleRanges, List<Optional<double[]>> samples, double[][] expected) throws Exception {
    long detectionInterval = (new IntervalTimeConfiguration(15, ChronoUnit.MINUTES)).toDuration().toMillis();
    when(detector.getDetectorIntervalInMilliseconds()).thenReturn(detectionInterval);
    when(detector.getShingleSize()).thenReturn(4);
    doAnswer(invocation -> {
        ActionListener<Optional<Long>> listener = invocation.getArgument(1);
        listener.onResponse(Optional.ofNullable(latestTime));
        return null;
    }).when(searchFeatureDao).getLatestDataTime(eq(detector), any(ActionListener.class));
    if (latestTime != null) {
        doAnswer(invocation -> {
            ActionListener<List<Optional<double[]>>> listener = invocation.getArgument(2);
            listener.onResponse(samples);
            return null;
        }).when(searchFeatureDao).getFeatureSamplesForPeriods(eq(detector), eq(sampleRanges), any(ActionListener.class));
    }
    ActionListener<Optional<double[][]>> listener = mock(ActionListener.class);
    featureManager = spy(new FeatureManager(searchFeatureDao, interpolator, clock, maxTrainSamples, maxSampleStride, trainSampleTimeRangeInHours, minTrainSamples, 0.5, /*maxMissingPointsRate*/
    1, /*maxNeighborDistance*/
    previewSampleRate, maxPreviewSamples, featureBufferTtl, threadPool, AnomalyDetectorPlugin.AD_THREAD_POOL_NAME));
    featureManager.getColdStartData(detector, listener);
    ArgumentCaptor<Optional<double[][]>> captor = ArgumentCaptor.forClass(Optional.class);
    verify(listener).onResponse(captor.capture());
    Optional<double[][]> result = captor.getValue();
    assertTrue(Arrays.deepEquals(expected, result.orElse(null)));
}
Also used : Optional(java.util.Optional) ActionListener(org.opensearch.action.ActionListener) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ArrayList(java.util.ArrayList) Parameters(junitparams.Parameters) Test(org.junit.Test)

Example 5 with IntervalTimeConfiguration

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

the class NoPowermockSearchFeatureDaoTests method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    serviceField = "service";
    hostField = "host";
    detector = mock(AnomalyDetector.class);
    when(detector.isMultientityDetector()).thenReturn(true);
    when(detector.getCategoryField()).thenReturn(Arrays.asList(new String[] { serviceField, hostField }));
    detectorId = "123";
    when(detector.getDetectorId()).thenReturn(detectorId);
    when(detector.getTimeField()).thenReturn("testTimeField");
    when(detector.getIndices()).thenReturn(Arrays.asList("testIndices"));
    IntervalTimeConfiguration detectionInterval = new IntervalTimeConfiguration(1, ChronoUnit.MINUTES);
    when(detector.getDetectionInterval()).thenReturn(detectionInterval);
    when(detector.getFilterQuery()).thenReturn(QueryBuilders.matchAllQuery());
    client = mock(Client.class);
    interpolator = new LinearUniformInterpolator(new SingleFeatureLinearUniformInterpolator());
    clientUtil = mock(ClientUtil.class);
    settings = Settings.EMPTY;
    ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, Collections.unmodifiableSet(new HashSet<>(Arrays.asList(AnomalyDetectorSettings.MAX_ENTITIES_FOR_PREVIEW, AnomalyDetectorSettings.PAGE_SIZE))));
    clusterService = mock(ClusterService.class);
    when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
    clock = mock(Clock.class);
    searchFeatureDao = new SearchFeatureDao(client, // Important. Without this, ParseUtils cannot parse anything
    xContentRegistry(), interpolator, clientUtil, settings, clusterService, AnomalyDetectorSettings.NUM_SAMPLES_PER_TREE, clock, 1, 1, 60_000L);
    String app0 = "app_0";
    String server1 = "server_1";
    attrs1 = new HashMap<>();
    attrs1.put(serviceField, app0);
    attrs1.put(hostField, server1);
    String server2 = "server_2";
    attrs1 = new HashMap<>();
    attrs1.put(serviceField, app0);
    attrs1.put(hostField, server2);
}
Also used : ClusterSettings(org.opensearch.common.settings.ClusterSettings) ClientUtil(org.opensearch.ad.util.ClientUtil) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) Clock(java.time.Clock) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) ClusterService(org.opensearch.cluster.service.ClusterService) SingleFeatureLinearUniformInterpolator(org.opensearch.ad.dataprocessor.SingleFeatureLinearUniformInterpolator) LinearUniformInterpolator(org.opensearch.ad.dataprocessor.LinearUniformInterpolator) Client(org.opensearch.client.Client) HashSet(java.util.HashSet)

Aggregations

IntervalTimeConfiguration (org.opensearch.ad.model.IntervalTimeConfiguration)27 ActionListener (org.opensearch.action.ActionListener)17 ArrayList (java.util.ArrayList)12 List (java.util.List)11 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)11 IOException (java.io.IOException)10 Optional (java.util.Optional)10 EndRunException (org.opensearch.ad.common.exception.EndRunException)10 Instant (java.time.Instant)9 SearchRequest (org.opensearch.action.search.SearchRequest)9 Clock (java.time.Clock)8 Map (java.util.Map)8 CommonErrorMessages (org.opensearch.ad.constant.CommonErrorMessages)8 HashMap (java.util.HashMap)7 Collectors (java.util.stream.Collectors)7 LogManager (org.apache.logging.log4j.LogManager)7 Logger (org.apache.logging.log4j.Logger)7 GetRequest (org.opensearch.action.get.GetRequest)7 GetResponse (org.opensearch.action.get.GetResponse)7 SearchFeatureDao (org.opensearch.ad.feature.SearchFeatureDao)7