Search in sources :

Example 1 with AnomalyResult

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

the class MultiResponsesDelegateActionListenerTests method testForceResponse.

@SuppressWarnings("unchecked")
public void testForceResponse() {
    AnomalyResult anomalyResult1 = randomHCADAnomalyDetectResult(0.25, 0.25, "error");
    AnomalyResult anomalyResult2 = randomHCADAnomalyDetectResult(0.5, 0.5, "error");
    EntityAnomalyResult entityAnomalyResult1 = new EntityAnomalyResult(new ArrayList<AnomalyResult>() {

        {
            add(anomalyResult1);
        }
    });
    EntityAnomalyResult entityAnomalyResult2 = new EntityAnomalyResult(new ArrayList<AnomalyResult>() {

        {
            add(anomalyResult2);
        }
    });
    ActionListener<EntityAnomalyResult> actualListener = mock(ActionListener.class);
    MultiResponsesDelegateActionListener<EntityAnomalyResult> multiListener = new MultiResponsesDelegateActionListener<EntityAnomalyResult>(actualListener, 3, "blah", true);
    multiListener.onResponse(entityAnomalyResult1);
    multiListener.onResponse(entityAnomalyResult2);
    multiListener.onFailure(new RuntimeException());
    entityAnomalyResult1.merge(entityAnomalyResult2);
    verify(actualListener).onResponse(entityAnomalyResult1);
}
Also used : AnomalyResult(org.opensearch.ad.model.AnomalyResult) EntityAnomalyResult(org.opensearch.ad.model.EntityAnomalyResult) EntityAnomalyResult(org.opensearch.ad.model.EntityAnomalyResult)

Example 2 with AnomalyResult

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

the class AnomalyResultHandlerTests method testSavingAdResult.

@Test
public void testSavingAdResult() throws IOException {
    setUpSavingAnomalyResultIndex(false);
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        assertTrue(String.format("The size of args is %d.  Its content is %s", args.length, Arrays.toString(args)), args.length >= 2);
        IndexRequest request = invocation.getArgument(0);
        ActionListener<IndexResponse> listener = invocation.getArgument(1);
        assertTrue(request != null && listener != null);
        listener.onResponse(mock(IndexResponse.class));
        return null;
    }).when(client).index(any(IndexRequest.class), ArgumentMatchers.<ActionListener<IndexResponse>>any());
    AnomalyIndexHandler<AnomalyResult> handler = new AnomalyIndexHandler<AnomalyResult>(client, settings, threadPool, CommonName.ANOMALY_RESULT_INDEX_ALIAS, anomalyDetectionIndices, clientUtil, indexUtil, clusterService);
    handler.index(TestHelpers.randomAnomalyDetectResult(), detectorId, null);
    assertEquals(1, testAppender.countMessage(AnomalyIndexHandler.SUCCESS_SAVING_MSG, true));
}
Also used : IndexResponse(org.opensearch.action.index.IndexResponse) AnomalyResult(org.opensearch.ad.model.AnomalyResult) IndexRequest(org.opensearch.action.index.IndexRequest) Test(org.junit.Test)

Example 3 with AnomalyResult

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

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

the class AnomalyDetectorRestApiIT method testSearchAnomalyResult.

public void testSearchAnomalyResult() throws Exception {
    AnomalyResult anomalyResult = TestHelpers.randomAnomalyDetectResult();
    Response response = TestHelpers.makeRequest(adminClient(), "POST", "/.opendistro-anomaly-results/_doc/" + UUIDs.base64UUID(), ImmutableMap.of(), TestHelpers.toHttpEntity(anomalyResult), null, false);
    assertEquals("Post anomaly result failed", RestStatus.CREATED, TestHelpers.restStatus(response));
    SearchSourceBuilder search = (new SearchSourceBuilder()).query(QueryBuilders.termQuery("detector_id", anomalyResult.getDetectorId()));
    updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, false);
    Exception ex = expectThrows(ResponseException.class, () -> TestHelpers.makeRequest(client(), "POST", TestHelpers.AD_BASE_RESULT_URI + "/_search", ImmutableMap.of(), new NStringEntity(search.toString(), ContentType.APPLICATION_JSON), null));
    assertThat(ex.getMessage(), containsString(CommonErrorMessages.DISABLED_ERR_MSG));
    updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, true);
    Response searchResponse = TestHelpers.makeRequest(client(), "POST", TestHelpers.AD_BASE_RESULT_URI + "/_search", ImmutableMap.of(), new NStringEntity(search.toString(), ContentType.APPLICATION_JSON), null);
    assertEquals("Search anomaly result failed", RestStatus.OK, TestHelpers.restStatus(searchResponse));
    SearchSourceBuilder searchAll = SearchSourceBuilder.fromXContent(TestHelpers.parser("{\"query\":{\"match_all\":{}}}"));
    Response searchAllResponse = TestHelpers.makeRequest(client(), "POST", TestHelpers.AD_BASE_RESULT_URI + "/_search", ImmutableMap.of(), new NStringEntity(searchAll.toString(), ContentType.APPLICATION_JSON), null);
    assertEquals("Search anomaly result failed", RestStatus.OK, TestHelpers.restStatus(searchAllResponse));
}
Also used : Response(org.opensearch.client.Response) NStringEntity(org.apache.http.nio.entity.NStringEntity) AnomalyResult(org.opensearch.ad.model.AnomalyResult) IOException(java.io.IOException) ResponseException(org.opensearch.client.ResponseException) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder)

Example 5 with AnomalyResult

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

the class PreviewAnomalyDetectorTransportAction method getPreviewDetectorActionListener.

private ActionListener<List<AnomalyResult>> getPreviewDetectorActionListener(ActionListener<PreviewAnomalyDetectorResponse> listener, AnomalyDetector detector) {
    return ActionListener.wrap(new CheckedConsumer<List<AnomalyResult>, Exception>() {

        @Override
        public void accept(List<AnomalyResult> anomalyResult) throws Exception {
            PreviewAnomalyDetectorResponse response = new PreviewAnomalyDetectorResponse(anomalyResult, detector);
            listener.onResponse(response);
        }
    }, exception -> {
        logger.error("Unexpected error running anomaly detector " + detector.getDetectorId(), exception);
        listener.onFailure(new OpenSearchStatusException("Unexpected error running anomaly detector " + detector.getDetectorId() + ". " + exception.getMessage(), RestStatus.INTERNAL_SERVER_ERROR));
    });
}
Also used : List(java.util.List) AnomalyResult(org.opensearch.ad.model.AnomalyResult) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) LimitExceededException(org.opensearch.ad.common.exception.LimitExceededException) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) ClientException(org.opensearch.ad.common.exception.ClientException) IOException(java.io.IOException) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Aggregations

AnomalyResult (org.opensearch.ad.model.AnomalyResult)26 ArrayList (java.util.ArrayList)10 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)10 IOException (java.io.IOException)9 List (java.util.List)9 ActionListener (org.opensearch.action.ActionListener)8 EndRunException (org.opensearch.ad.common.exception.EndRunException)7 Instant (java.time.Instant)6 IndexRequest (org.opensearch.action.index.IndexRequest)6 Map (java.util.Map)5 LogManager (org.apache.logging.log4j.LogManager)5 Logger (org.apache.logging.log4j.Logger)5 AnomalyDetectionException (org.opensearch.ad.common.exception.AnomalyDetectionException)5 FeatureData (org.opensearch.ad.model.FeatureData)5 Settings (org.opensearch.common.settings.Settings)5 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)5 Test (org.junit.Test)4 Client (org.opensearch.client.Client)4 ClusterService (org.opensearch.cluster.service.ClusterService)4 ThreadPool (org.opensearch.threadpool.ThreadPool)4