Search in sources :

Example 6 with ADValidationException

use of org.opensearch.ad.common.exception.ADValidationException in project anomaly-detection by opensearch-project.

the class AbstractAnomalyDetectorActionHandler method onSearchADNameResponse.

protected void onSearchADNameResponse(SearchResponse response, String detectorId, String name, boolean indexingDryRun) throws IOException {
    if (response.getHits().getTotalHits().value > 0) {
        String errorMsg = String.format(Locale.ROOT, DUPLICATE_DETECTOR_MSG, name, Arrays.stream(response.getHits().getHits()).map(hit -> hit.getId()).collect(Collectors.toList()));
        logger.warn(errorMsg);
        listener.onFailure(new ADValidationException(errorMsg, DetectorValidationIssueType.NAME, ValidationAspect.DETECTOR));
    } else {
        tryIndexingAnomalyDetector(indexingDryRun);
    }
}
Also used : ADValidationException(org.opensearch.ad.common.exception.ADValidationException)

Example 7 with ADValidationException

use of org.opensearch.ad.common.exception.ADValidationException in project anomaly-detection by opensearch-project.

the class AbstractAnomalyDetectorActionHandler method validateTimeField.

protected void validateTimeField(boolean indexingDryRun) {
    String givenTimeField = anomalyDetector.getTimeField();
    GetFieldMappingsRequest getMappingsRequest = new GetFieldMappingsRequest();
    getMappingsRequest.indices(anomalyDetector.getIndices().toArray(new String[0])).fields(givenTimeField);
    getMappingsRequest.indicesOptions(IndicesOptions.strictExpand());
    // comments explaining fieldMappingResponse parsing can be found inside following method:
    // AbstractAnomalyDetectorActionHandler.validateCategoricalField(String, boolean)
    ActionListener<GetFieldMappingsResponse> mappingsListener = ActionListener.wrap(getMappingsResponse -> {
        boolean foundField = false;
        Map<String, Map<String, Map<String, GetFieldMappingsResponse.FieldMappingMetadata>>> mappingsByIndex = getMappingsResponse.mappings();
        for (Map<String, Map<String, GetFieldMappingsResponse.FieldMappingMetadata>> mappingsByType : mappingsByIndex.values()) {
            for (Map<String, GetFieldMappingsResponse.FieldMappingMetadata> mappingsByField : mappingsByType.values()) {
                for (Map.Entry<String, GetFieldMappingsResponse.FieldMappingMetadata> field2Metadata : mappingsByField.entrySet()) {
                    GetFieldMappingsResponse.FieldMappingMetadata fieldMetadata = field2Metadata.getValue();
                    if (fieldMetadata != null) {
                        // sourceAsMap returns sth like {host2={type=keyword}} with host2 being a nested field
                        Map<String, Object> fieldMap = fieldMetadata.sourceAsMap();
                        if (fieldMap != null) {
                            for (Object type : fieldMap.values()) {
                                if (type instanceof Map) {
                                    foundField = true;
                                    Map<String, Object> metadataMap = (Map<String, Object>) type;
                                    String typeName = (String) metadataMap.get(CommonName.TYPE);
                                    if (!typeName.equals(CommonName.DATE_TYPE)) {
                                        listener.onFailure(new ADValidationException(String.format(Locale.ROOT, CommonErrorMessages.INVALID_TIMESTAMP, givenTimeField), DetectorValidationIssueType.TIMEFIELD_FIELD, ValidationAspect.DETECTOR));
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!foundField) {
            listener.onFailure(new ADValidationException(String.format(Locale.ROOT, CommonErrorMessages.NON_EXISTENT_TIMESTAMP, givenTimeField), DetectorValidationIssueType.TIMEFIELD_FIELD, ValidationAspect.DETECTOR));
            return;
        }
        prepareAnomalyDetectorIndexing(indexingDryRun);
    }, error -> {
        String message = String.format(Locale.ROOT, "Fail to get the index mapping of %s", anomalyDetector.getIndices());
        logger.error(message, error);
        listener.onFailure(new IllegalArgumentException(message));
    });
    client.execute(GetFieldMappingsAction.INSTANCE, getMappingsRequest, mappingsListener);
}
Also used : GetFieldMappingsRequest(org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsRequest) GetFieldMappingsResponse(org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) Map(java.util.Map)

Example 8 with ADValidationException

use of org.opensearch.ad.common.exception.ADValidationException in project anomaly-detection by opensearch-project.

the class ModelValidationActionHandler method processDataFilterResults.

private void processDataFilterResults(SearchResponse response, long latestTime) {
    Histogram aggregate = checkBucketResultErrors(response);
    if (aggregate == null) {
        return;
    }
    double fullBucketRate = processBucketAggregationResults(aggregate);
    if (fullBucketRate < CONFIG_BUCKET_MINIMUM_SUCCESS_RATE) {
        listener.onFailure(new ADValidationException(CommonErrorMessages.FILTER_QUERY_TOO_SPARSE, DetectorValidationIssueType.FILTER_QUERY, ValidationAspect.MODEL));
    // blocks below are executed if data is dense enough with filter query applied.
    // If HCAD then category fields will be added to bucket aggregation to see if they
    // are the root cause of the issues and if not the feature queries will be checked for sparsity
    } else if (anomalyDetector.isMultientityDetector()) {
        getTopEntityForCategoryField(latestTime);
    } else {
        try {
            checkFeatureQueryDelegate(latestTime);
        } catch (Exception ex) {
            logger.error(ex);
            listener.onFailure(ex);
        }
    }
}
Also used : Histogram(org.opensearch.search.aggregations.bucket.histogram.Histogram) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) EndRunException(org.opensearch.ad.common.exception.EndRunException) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) IOException(java.io.IOException)

Example 9 with ADValidationException

use of org.opensearch.ad.common.exception.ADValidationException in project anomaly-detection by opensearch-project.

the class ModelValidationActionHandler method processRawDataResults.

private void processRawDataResults(SearchResponse response, long latestTime) {
    Histogram aggregate = checkBucketResultErrors(response);
    if (aggregate == null) {
        return;
    }
    double fullBucketRate = processBucketAggregationResults(aggregate);
    if (fullBucketRate < INTERVAL_BUCKET_MINIMUM_SUCCESS_RATE) {
        listener.onFailure(new ADValidationException(CommonErrorMessages.RAW_DATA_TOO_SPARSE, DetectorValidationIssueType.INDICES, ValidationAspect.MODEL));
    } else {
        checkDataFilterSparsity(latestTime);
    }
}
Also used : Histogram(org.opensearch.search.aggregations.bucket.histogram.Histogram) ADValidationException(org.opensearch.ad.common.exception.ADValidationException)

Example 10 with ADValidationException

use of org.opensearch.ad.common.exception.ADValidationException in project anomaly-detection by opensearch-project.

the class ModelValidationActionHandler method checkFeatureQueryDelegate.

private void checkFeatureQueryDelegate(long latestTime) throws IOException {
    ActionListener<MergeableList<double[]>> validateFeatureQueriesListener = ActionListener.wrap(response -> {
        windowDelayRecommendation(latestTime);
    }, exception -> {
        listener.onFailure(new ADValidationException(exception.getMessage(), DetectorValidationIssueType.FEATURE_ATTRIBUTES, ValidationAspect.MODEL));
    });
    MultiResponsesDelegateActionListener<MergeableList<double[]>> multiFeatureQueriesResponseListener = new MultiResponsesDelegateActionListener<>(validateFeatureQueriesListener, anomalyDetector.getFeatureAttributes().size(), CommonErrorMessages.FEATURE_QUERY_TOO_SPARSE, false);
    for (Feature feature : anomalyDetector.getFeatureAttributes()) {
        AggregationBuilder aggregation = getBucketAggregation(latestTime, (IntervalTimeConfiguration) anomalyDetector.getDetectionInterval());
        BoolQueryBuilder query = QueryBuilders.boolQuery().filter(anomalyDetector.getFilterQuery());
        List<String> featureFields = ParseUtils.getFieldNamesForFeature(feature, xContentRegistry);
        for (String featureField : featureFields) {
            query.filter(QueryBuilders.existsQuery(featureField));
        }
        SearchSourceBuilder searchSourceBuilder = getSearchSourceBuilder(query, aggregation);
        SearchRequest searchRequest = new SearchRequest(anomalyDetector.getIndices().toArray(new String[0])).source(searchSourceBuilder);
        client.search(searchRequest, ActionListener.wrap(response -> {
            Histogram aggregate = checkBucketResultErrors(response);
            if (aggregate == null) {
                return;
            }
            double fullBucketRate = processBucketAggregationResults(aggregate);
            if (fullBucketRate < CONFIG_BUCKET_MINIMUM_SUCCESS_RATE) {
                multiFeatureQueriesResponseListener.onFailure(new ADValidationException(CommonErrorMessages.FEATURE_QUERY_TOO_SPARSE, DetectorValidationIssueType.FEATURE_ATTRIBUTES, ValidationAspect.MODEL));
            } else {
                multiFeatureQueriesResponseListener.onResponse(new MergeableList<>(new ArrayList<>(Collections.singletonList(new double[] { fullBucketRate }))));
            }
        }, e -> {
            logger.error(e);
            multiFeatureQueriesResponseListener.onFailure(new OpenSearchStatusException(CommonErrorMessages.FEATURE_QUERY_TOO_SPARSE, RestStatus.BAD_REQUEST, e));
        }));
    }
}
Also used : TOP_VALIDATE_TIMEOUT_IN_MILLIS(org.opensearch.ad.settings.AnomalyDetectorSettings.TOP_VALIDATE_TIMEOUT_IN_MILLIS) INTERVAL_RECOMMENDATION_DECREASING_MULTIPLIER(org.opensearch.ad.settings.AnomalyDetectorSettings.INTERVAL_RECOMMENDATION_DECREASING_MULTIPLIER) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) TimeConfiguration(org.opensearch.ad.model.TimeConfiguration) MAX_INTERVAL_REC_LENGTH_IN_MINUTES(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_INTERVAL_REC_LENGTH_IN_MINUTES) AggregationBuilder(org.opensearch.search.aggregations.AggregationBuilder) FieldSortBuilder(org.opensearch.search.sort.FieldSortBuilder) Locale(java.util.Locale) Duration(java.time.Duration) Map(java.util.Map) ActionListener(org.opensearch.action.ActionListener) Client(org.opensearch.client.Client) TimeValue(org.opensearch.common.unit.TimeValue) Feature(org.opensearch.ad.model.Feature) MultiBucketsAggregation(org.opensearch.search.aggregations.bucket.MultiBucketsAggregation) CONFIG_BUCKET_MINIMUM_SUCCESS_RATE(org.opensearch.ad.settings.AnomalyDetectorSettings.CONFIG_BUCKET_MINIMUM_SUCCESS_RATE) Instant(java.time.Instant) RestStatus(org.opensearch.rest.RestStatus) Terms(org.opensearch.search.aggregations.bucket.terms.Terms) Collectors(java.util.stream.Collectors) MultiResponsesDelegateActionListener(org.opensearch.ad.util.MultiResponsesDelegateActionListener) List(java.util.List) Logger(org.apache.logging.log4j.Logger) QueryBuilder(org.opensearch.index.query.QueryBuilder) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) SearchFeatureDao(org.opensearch.ad.feature.SearchFeatureDao) Optional(java.util.Optional) TermsValuesSourceBuilder(org.opensearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) MAX_TIMES_DECREASING_INTERVAL(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_TIMES_DECREASING_INTERVAL) BucketOrder(org.opensearch.search.aggregations.BucketOrder) HashMap(java.util.HashMap) Aggregations(org.opensearch.search.aggregations.Aggregations) DateHistogramInterval(org.opensearch.search.aggregations.bucket.histogram.DateHistogramInterval) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) INTERVAL_RECOMMENDATION_INCREASING_MULTIPLIER(org.opensearch.ad.settings.AnomalyDetectorSettings.INTERVAL_RECOMMENDATION_INCREASING_MULTIPLIER) INTERVAL_BUCKET_MINIMUM_SUCCESS_RATE(org.opensearch.ad.settings.AnomalyDetectorSettings.INTERVAL_BUCKET_MINIMUM_SUCCESS_RATE) ArrayList(java.util.ArrayList) LongBounds(org.opensearch.search.aggregations.bucket.histogram.LongBounds) SortOrder(org.opensearch.search.sort.SortOrder) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SearchRequest(org.opensearch.action.search.SearchRequest) SearchResponse(org.opensearch.action.search.SearchResponse) MergeableList(org.opensearch.ad.model.MergeableList) EndRunException(org.opensearch.ad.common.exception.EndRunException) ValidationAspect(org.opensearch.ad.model.ValidationAspect) ValidateAnomalyDetectorResponse(org.opensearch.ad.transport.ValidateAnomalyDetectorResponse) QueryBuilders(org.opensearch.index.query.QueryBuilders) RangeQueryBuilder(org.opensearch.index.query.RangeQueryBuilder) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) IOException(java.io.IOException) PipelineAggregatorBuilders(org.opensearch.search.aggregations.PipelineAggregatorBuilders) CompositeAggregation(org.opensearch.search.aggregations.bucket.composite.CompositeAggregation) AggregationBuilders(org.opensearch.search.aggregations.AggregationBuilders) CommonErrorMessages(org.opensearch.ad.constant.CommonErrorMessages) ChronoUnit(java.time.temporal.ChronoUnit) DetectorValidationIssueType(org.opensearch.ad.model.DetectorValidationIssueType) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) Clock(java.time.Clock) Comparator(java.util.Comparator) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) Histogram(org.opensearch.search.aggregations.bucket.histogram.Histogram) ParseUtils(org.opensearch.ad.util.ParseUtils) SearchRequest(org.opensearch.action.search.SearchRequest) Histogram(org.opensearch.search.aggregations.bucket.histogram.Histogram) AggregationBuilder(org.opensearch.search.aggregations.AggregationBuilder) MergeableList(org.opensearch.ad.model.MergeableList) MultiResponsesDelegateActionListener(org.opensearch.ad.util.MultiResponsesDelegateActionListener) Feature(org.opensearch.ad.model.Feature) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Aggregations

ADValidationException (org.opensearch.ad.common.exception.ADValidationException)22 IOException (java.io.IOException)8 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)7 Map (java.util.Map)6 List (java.util.List)4 Locale (java.util.Locale)4 OpenSearchStatusException (org.opensearch.OpenSearchStatusException)4 SearchRequest (org.opensearch.action.search.SearchRequest)4 SearchResponse (org.opensearch.action.search.SearchResponse)4 CommonErrorMessages (org.opensearch.ad.constant.CommonErrorMessages)4 ValidationAspect (org.opensearch.ad.model.ValidationAspect)4 ValidateAnomalyDetectorActionHandler (org.opensearch.ad.rest.handler.ValidateAnomalyDetectorActionHandler)4 ClusterService (org.opensearch.cluster.service.ClusterService)4 Histogram (org.opensearch.search.aggregations.bucket.histogram.Histogram)4 SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)4 Clock (java.time.Clock)3 Instant (java.time.Instant)3 ArrayList (java.util.ArrayList)3 Collectors (java.util.stream.Collectors)3 LogManager (org.apache.logging.log4j.LogManager)3