Search in sources :

Example 21 with AnomalyResult

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

the class AnomalyDetectorRunner method parsePreviewResult.

private List<AnomalyResult> parsePreviewResult(AnomalyDetector detector, Features features, List<ThresholdingResult> results, Entity entity) {
    // unprocessedFeatures[][], each row is for one date range.
    // For example, unprocessedFeatures[0][2] is for the first time range, the third feature
    double[][] unprocessedFeatures = features.getUnprocessedFeatures();
    List<Map.Entry<Long, Long>> timeRanges = features.getTimeRanges();
    List<Feature> featureAttributes = detector.getFeatureAttributes().stream().filter(Feature::getEnabled).collect(Collectors.toList());
    List<AnomalyResult> anomalyResults = new ArrayList<>();
    if (timeRanges != null && timeRanges.size() > 0) {
        for (int i = 0; i < timeRanges.size(); i++) {
            Map.Entry<Long, Long> timeRange = timeRanges.get(i);
            List<FeatureData> featureDatas = new ArrayList<>();
            int featureSize = featureAttributes.size();
            for (int j = 0; j < featureSize; j++) {
                double value = unprocessedFeatures[i][j];
                Feature feature = featureAttributes.get(j);
                FeatureData data = new FeatureData(feature.getId(), feature.getName(), value);
                featureDatas.add(data);
            }
            AnomalyResult result;
            if (results != null && results.size() > i) {
                ThresholdingResult thresholdingResult = results.get(i);
                result = thresholdingResult.toAnomalyResult(detector, Instant.ofEpochMilli(timeRange.getKey()), Instant.ofEpochMilli(timeRange.getValue()), null, null, featureDatas, entity, CommonValue.NO_SCHEMA_VERSION, null, null, null);
            } else {
                result = new AnomalyResult(detector.getDetectorId(), null, featureDatas, Instant.ofEpochMilli(timeRange.getKey()), Instant.ofEpochMilli(timeRange.getValue()), null, null, null, entity, detector.getUser(), CommonValue.NO_SCHEMA_VERSION, null);
            }
            anomalyResults.add(result);
        }
    }
    return anomalyResults;
}
Also used : ArrayList(java.util.ArrayList) FeatureData(org.opensearch.ad.model.FeatureData) Feature(org.opensearch.ad.model.Feature) ThresholdingResult(org.opensearch.ad.ml.ThresholdingResult) AnomalyResult(org.opensearch.ad.model.AnomalyResult) EntityAnomalyResult(org.opensearch.ad.model.EntityAnomalyResult) Map(java.util.Map)

Example 22 with AnomalyResult

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

the class AnomalyDetectorRunner method executeDetector.

/**
 * run anomaly detector and return anomaly result.
 *
 * @param detector  anomaly detector instance
 * @param startTime detection period start time
 * @param endTime   detection period end time
 * @param context   stored thread context
 * @param listener handle anomaly result
 * @throws IOException - if a user gives wrong query input when defining a detector
 */
public void executeDetector(AnomalyDetector detector, Instant startTime, Instant endTime, ThreadContext.StoredContext context, ActionListener<List<AnomalyResult>> listener) throws IOException {
    context.restore();
    List<String> categoryField = detector.getCategoryField();
    if (categoryField != null && !categoryField.isEmpty()) {
        featureManager.getPreviewEntities(detector, startTime.toEpochMilli(), endTime.toEpochMilli(), ActionListener.wrap(entities -> {
            if (entities == null || entities.isEmpty()) {
                // TODO return exception like IllegalArgumentException to explain data is not enough for preview
                // This also requires front-end change to handle error message correspondingly
                // We return empty list for now to avoid breaking front-end
                listener.onResponse(Collections.emptyList());
                return;
            }
            ActionListener<EntityAnomalyResult> entityAnomalyResultListener = ActionListener.wrap(entityAnomalyResult -> {
                listener.onResponse(entityAnomalyResult.getAnomalyResults());
            }, e -> onFailure(e, listener, detector.getDetectorId()));
            MultiResponsesDelegateActionListener<EntityAnomalyResult> multiEntitiesResponseListener = new MultiResponsesDelegateActionListener<EntityAnomalyResult>(entityAnomalyResultListener, entities.size(), String.format(Locale.ROOT, "Fail to get preview result for multi entity detector %s", detector.getDetectorId()), true);
            for (Entity entity : entities) {
                featureManager.getPreviewFeaturesForEntity(detector, entity, startTime.toEpochMilli(), endTime.toEpochMilli(), ActionListener.wrap(features -> {
                    List<ThresholdingResult> entityResults = modelManager.getPreviewResults(features.getProcessedFeatures(), detector.getShingleSize());
                    List<AnomalyResult> sampledEntityResults = sample(parsePreviewResult(detector, features, entityResults, entity), maxPreviewResults);
                    multiEntitiesResponseListener.onResponse(new EntityAnomalyResult(sampledEntityResults));
                }, e -> multiEntitiesResponseListener.onFailure(e)));
            }
        }, e -> onFailure(e, listener, detector.getDetectorId())));
    } else {
        featureManager.getPreviewFeatures(detector, startTime.toEpochMilli(), endTime.toEpochMilli(), ActionListener.wrap(features -> {
            try {
                List<ThresholdingResult> results = modelManager.getPreviewResults(features.getProcessedFeatures(), detector.getShingleSize());
                listener.onResponse(sample(parsePreviewResult(detector, features, results, null), maxPreviewResults));
            } catch (Exception e) {
                onFailure(e, listener, detector.getDetectorId());
            }
        }, e -> onFailure(e, listener, detector.getDetectorId())));
    }
}
Also used : ModelManager(org.opensearch.ad.ml.ModelManager) ThresholdingResult(org.opensearch.ad.ml.ThresholdingResult) FeatureData(org.opensearch.ad.model.FeatureData) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) ArrayList(java.util.ArrayList) Locale(java.util.Locale) Map(java.util.Map) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ActionListener(org.opensearch.action.ActionListener) CommonValue(org.opensearch.ad.constant.CommonValue) FeatureManager(org.opensearch.ad.feature.FeatureManager) Feature(org.opensearch.ad.model.Feature) IOException(java.io.IOException) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) OpenSearchSecurityException(org.opensearch.OpenSearchSecurityException) Features(org.opensearch.ad.feature.Features) MultiResponsesDelegateActionListener(org.opensearch.ad.util.MultiResponsesDelegateActionListener) List(java.util.List) Logger(org.apache.logging.log4j.Logger) AnomalyResult(org.opensearch.ad.model.AnomalyResult) Entity(org.opensearch.ad.model.Entity) EntityAnomalyResult(org.opensearch.ad.model.EntityAnomalyResult) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) Entity(org.opensearch.ad.model.Entity) MultiResponsesDelegateActionListener(org.opensearch.ad.util.MultiResponsesDelegateActionListener) IOException(java.io.IOException) OpenSearchSecurityException(org.opensearch.OpenSearchSecurityException) ThresholdingResult(org.opensearch.ad.ml.ThresholdingResult) ActionListener(org.opensearch.action.ActionListener) MultiResponsesDelegateActionListener(org.opensearch.ad.util.MultiResponsesDelegateActionListener) AnomalyResult(org.opensearch.ad.model.AnomalyResult) EntityAnomalyResult(org.opensearch.ad.model.EntityAnomalyResult) ArrayList(java.util.ArrayList) List(java.util.List) EntityAnomalyResult(org.opensearch.ad.model.EntityAnomalyResult)

Example 23 with AnomalyResult

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

the class ResultWriteWorker method enqueueRetryRequestIteration.

private void enqueueRetryRequestIteration(List<IndexRequest> requestToRetry, int index) {
    if (index >= requestToRetry.size()) {
        return;
    }
    DocWriteRequest<?> currentRequest = requestToRetry.get(index);
    Optional<AnomalyResult> resultToRetry = getAnomalyResult(currentRequest);
    if (false == resultToRetry.isPresent()) {
        enqueueRetryRequestIteration(requestToRetry, index + 1);
        return;
    }
    AnomalyResult result = resultToRetry.get();
    String detectorId = result.getDetectorId();
    nodeStateManager.getAnomalyDetector(detectorId, onGetDetector(requestToRetry, index, detectorId, result));
}
Also used : AnomalyResult(org.opensearch.ad.model.AnomalyResult)

Example 24 with AnomalyResult

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

the class AnomalyDetectionIndices method validateCustomResultIndexAndExecute.

public <T> void validateCustomResultIndexAndExecute(String resultIndex, AnomalyDetectorFunction function, ActionListener<T> listener) {
    try {
        if (!isValidResultIndexMapping(resultIndex)) {
            logger.warn("Can't create detector with custom result index {} as its mapping is invalid", resultIndex);
            listener.onFailure(new IllegalArgumentException(CommonErrorMessages.INVALID_RESULT_INDEX_MAPPING + resultIndex));
            return;
        }
        AnomalyResult dummyResult = AnomalyResult.getDummyResult();
        IndexRequest indexRequest = new IndexRequest(resultIndex).id(DUMMY_AD_RESULT_ID).source(dummyResult.toXContent(XContentBuilder.builder(XContentType.JSON.xContent()), ToXContent.EMPTY_PARAMS));
        // User may have no write permission on custom result index. Talked with security plugin team, seems no easy way to verify
        // if user has write permission. So just tried to write and delete a dummy anomaly result to verify.
        client.index(indexRequest, ActionListener.wrap(response -> {
            logger.debug("Successfully wrote dummy AD result to result index {}", resultIndex);
            client.delete(new DeleteRequest(resultIndex).id(DUMMY_AD_RESULT_ID), ActionListener.wrap(deleteResponse -> {
                logger.debug("Successfully deleted dummy AD result from result index {}", resultIndex);
                function.execute();
            }, ex -> {
                logger.error("Failed to delete dummy AD result from result index " + resultIndex, ex);
                listener.onFailure(ex);
            }));
        }, exception -> {
            logger.error("Failed to write dummy AD result to result index " + resultIndex, exception);
            listener.onFailure(exception);
        }));
    } catch (Exception e) {
        logger.error("Failed to create detector with custom result index " + resultIndex, e);
        listener.onFailure(e);
    }
}
Also used : DUMMY_AD_RESULT_ID(org.opensearch.ad.constant.CommonName.DUMMY_AD_RESULT_ID) Arrays(java.util.Arrays) UpdateSettingsRequest(org.opensearch.action.admin.indices.settings.put.UpdateSettingsRequest) URL(java.net.URL) ToXContent(org.opensearch.common.xcontent.ToXContent) Strings(org.opensearch.common.Strings) ANOMALY_RESULTS_INDEX_MAPPING_FILE(org.opensearch.ad.settings.AnomalyDetectorSettings.ANOMALY_RESULTS_INDEX_MAPPING_FILE) CHECKPOINT_INDEX_MAPPING_FILE(org.opensearch.ad.settings.AnomalyDetectorSettings.CHECKPOINT_INDEX_MAPPING_FILE) AnomalyDetectorFunction(org.opensearch.ad.rest.handler.AnomalyDetectorFunction) XContentParser(org.opensearch.common.xcontent.XContentParser) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) Alias(org.opensearch.action.admin.indices.alias.Alias) Token(org.opensearch.common.xcontent.XContentParser.Token) Map(java.util.Map) ANOMALY_DETECTION_STATE_INDEX_MAPPING_FILE(org.opensearch.ad.settings.AnomalyDetectorSettings.ANOMALY_DETECTION_STATE_INDEX_MAPPING_FILE) ActionListener(org.opensearch.action.ActionListener) MAX_PRIMARY_SHARDS(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_PRIMARY_SHARDS) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) RolloverRequest(org.opensearch.action.admin.indices.rollover.RolloverRequest) ANOMALY_DETECTORS_INDEX_MAPPING_FILE(org.opensearch.ad.settings.AnomalyDetectorSettings.ANOMALY_DETECTORS_INDEX_MAPPING_FILE) Client(org.opensearch.client.Client) TimeValue(org.opensearch.common.unit.TimeValue) AD_RESULT_HISTORY_MAX_DOCS_PER_SHARD(org.opensearch.ad.settings.AnomalyDetectorSettings.AD_RESULT_HISTORY_MAX_DOCS_PER_SHARD) EnumMap(java.util.EnumMap) AdminClient(org.opensearch.client.AdminClient) PutMappingRequest(org.opensearch.action.admin.indices.mapping.put.PutMappingRequest) LocalNodeMasterListener(org.opensearch.cluster.LocalNodeMasterListener) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Set(java.util.Set) ExceptionsHelper(org.opensearch.ExceptionsHelper) Settings(org.opensearch.common.settings.Settings) Instant(java.time.Instant) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) List(java.util.List) Logger(org.apache.logging.log4j.Logger) AnomalyResult(org.opensearch.ad.model.AnomalyResult) BytesArray(org.opensearch.common.bytes.BytesArray) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) XContentType(org.opensearch.common.xcontent.XContentType) InjectSecurity(org.opensearch.commons.InjectSecurity) Scheduler(org.opensearch.threadpool.Scheduler) GetSettingsAction(org.opensearch.action.admin.indices.settings.get.GetSettingsAction) DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ThreadPool(org.opensearch.threadpool.ThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AliasMetadata(org.opensearch.cluster.metadata.AliasMetadata) IndicesOptions(org.opensearch.action.support.IndicesOptions) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ArrayList(java.util.ArrayList) GetSettingsRequest(org.opensearch.action.admin.indices.settings.get.GetSettingsRequest) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) DeleteIndexRequest(org.opensearch.action.admin.indices.delete.DeleteIndexRequest) ANOMALY_DETECTOR_JOBS_INDEX_MAPPING_FILE(org.opensearch.ad.settings.AnomalyDetectorSettings.ANOMALY_DETECTOR_JOBS_INDEX_MAPPING_FILE) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) EndRunException(org.opensearch.ad.common.exception.EndRunException) Charsets(com.google.common.base.Charsets) CommonName(org.opensearch.ad.constant.CommonName) Iterator(java.util.Iterator) CommonValue(org.opensearch.ad.constant.CommonValue) Resources(com.google.common.io.Resources) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IOException(java.io.IOException) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) GetAliasesRequest(org.opensearch.action.admin.indices.alias.get.GetAliasesRequest) GetSettingsResponse(org.opensearch.action.admin.indices.settings.get.GetSettingsResponse) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentHelper(org.opensearch.common.xcontent.XContentHelper) ClusterStateRequest(org.opensearch.action.admin.cluster.state.ClusterStateRequest) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) AD_RESULT_HISTORY_ROLLOVER_PERIOD(org.opensearch.ad.settings.AnomalyDetectorSettings.AD_RESULT_HISTORY_ROLLOVER_PERIOD) AD_RESULT_HISTORY_RETENTION_PERIOD(org.opensearch.ad.settings.AnomalyDetectorSettings.AD_RESULT_HISTORY_RETENTION_PERIOD) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) IndexRequest(org.opensearch.action.index.IndexRequest) LogManager(org.apache.logging.log4j.LogManager) CAN_NOT_FIND_RESULT_INDEX(org.opensearch.ad.constant.CommonErrorMessages.CAN_NOT_FIND_RESULT_INDEX) AnomalyResult(org.opensearch.ad.model.AnomalyResult) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) DeleteIndexRequest(org.opensearch.action.admin.indices.delete.DeleteIndexRequest) IndexRequest(org.opensearch.action.index.IndexRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) EndRunException(org.opensearch.ad.common.exception.EndRunException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IOException(java.io.IOException)

Example 25 with AnomalyResult

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

the class AnomalyDetectorRestApiIT method testSearchTopAnomalyResultsWithCustomResultIndex.

public void testSearchTopAnomalyResultsWithCustomResultIndex() throws IOException {
    String indexName = randomAlphaOfLength(10).toLowerCase(Locale.ROOT);
    String customResultIndexName = CommonName.CUSTOM_RESULT_INDEX_PREFIX + randomAlphaOfLength(5).toLowerCase(Locale.ROOT);
    Map<String, String> categoryFieldsAndTypes = new HashMap<String, String>() {

        {
            put("keyword-field", "keyword");
            put("ip-field", "ip");
        }
    };
    String testIndexData = "{\"keyword-field\": \"field-1\", \"ip-field\": \"1.2.3.4\", \"timestamp\": 1}";
    TestHelpers.createIndexWithHCADFields(client(), indexName, categoryFieldsAndTypes);
    TestHelpers.ingestDataToIndex(client(), indexName, TestHelpers.toHttpEntity(testIndexData));
    AnomalyDetector detector = createAnomalyDetector(TestHelpers.randomAnomalyDetectorUsingCategoryFields(randomAlphaOfLength(10), TIME_FIELD, ImmutableList.of(indexName), categoryFieldsAndTypes.keySet().stream().collect(Collectors.toList()), customResultIndexName), true, client());
    Map<String, Object> entityAttrs = new HashMap<String, Object>() {

        {
            put("keyword-field", "field-1");
            put("ip-field", "1.2.3.4");
        }
    };
    AnomalyResult anomalyResult = TestHelpers.randomHCADAnomalyDetectResult(detector.getDetectorId(), null, entityAttrs, 0.5, 0.8, null, 5L, 5L);
    TestHelpers.ingestDataToIndex(client(), customResultIndexName, TestHelpers.toHttpEntity(anomalyResult));
    Response response = searchTopAnomalyResults(detector.getDetectorId(), false, "{\"start_time_ms\":0, \"end_time_ms\":10}", client());
    Map<String, Object> responseMap = entityAsMap(response);
    @SuppressWarnings("unchecked") List<Map<String, Object>> buckets = (ArrayList<Map<String, Object>>) XContentMapValues.extractValue("buckets", responseMap);
    assertEquals(1, buckets.size());
    @SuppressWarnings("unchecked") Map<String, String> bucketKey1 = (Map<String, String>) buckets.get(0).get("key");
    assertEquals("field-1", bucketKey1.get("keyword-field"));
    assertEquals("1.2.3.4", bucketKey1.get("ip-field"));
}
Also used : Response(org.opensearch.client.Response) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ToXContentObject(org.opensearch.common.xcontent.ToXContentObject) AnomalyResult(org.opensearch.ad.model.AnomalyResult) Matchers.containsString(org.hamcrest.Matchers.containsString) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector)

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