Search in sources :

Example 56 with AnomalyDetector

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

the class ParseUtils method getDetector.

/**
 * If filterByEnabled is true, get detector and check if the user has permissions to access the detector,
 * then execute function; otherwise, get detector and execute function
 * @param requestUser user from request
 * @param detectorId detector id
 * @param listener action listener
 * @param function consumer function
 * @param client client
 * @param clusterService cluster service
 * @param xContentRegistry XContent registry
 * @param filterByBackendRole filter by backend role or not
 */
public static void getDetector(User requestUser, String detectorId, ActionListener listener, Consumer<AnomalyDetector> function, Client client, ClusterService clusterService, NamedXContentRegistry xContentRegistry, boolean filterByBackendRole) {
    if (clusterService.state().metadata().indices().containsKey(AnomalyDetector.ANOMALY_DETECTORS_INDEX)) {
        GetRequest request = new GetRequest(AnomalyDetector.ANOMALY_DETECTORS_INDEX).id(detectorId);
        client.get(request, ActionListener.wrap(response -> onGetAdResponse(response, requestUser, detectorId, listener, function, xContentRegistry, filterByBackendRole), exception -> {
            logger.error("Failed to get anomaly detector: " + detectorId, exception);
            listener.onFailure(exception);
        }));
    } else {
        listener.onFailure(new IndexNotFoundException(AnomalyDetector.ANOMALY_DETECTORS_INDEX));
    }
}
Also used : Max(org.opensearch.search.aggregations.metrics.Max) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) BaseAggregationBuilder(org.opensearch.search.aggregations.BaseAggregationBuilder) FAIL_TO_GET_USER_INFO(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_GET_USER_INFO) FAIL_TO_FIND_DETECTOR_MSG(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG) PipelineAggregationBuilder(org.opensearch.search.aggregations.PipelineAggregationBuilder) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) XContentParser(org.opensearch.common.xcontent.XContentParser) AggregationBuilder(org.opensearch.search.aggregations.AggregationBuilder) Matcher(java.util.regex.Matcher) DateHistogramValuesSourceBuilder(org.opensearch.search.aggregations.bucket.composite.DateHistogramValuesSourceBuilder) Map(java.util.Map) ActionListener(org.opensearch.action.ActionListener) DateRangeAggregationBuilder(org.opensearch.search.aggregations.bucket.range.DateRangeAggregationBuilder) GetResponse(org.opensearch.action.get.GetResponse) ParsingException(org.opensearch.common.ParsingException) NestedQueryBuilder(org.opensearch.index.query.NestedQueryBuilder) Client(org.opensearch.client.Client) Collection(java.util.Collection) Feature(org.opensearch.ad.model.Feature) QUERY_PARAM_PERIOD_END(org.opensearch.ad.model.AnomalyDetector.QUERY_PARAM_PERIOD_END) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Set(java.util.Set) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) Instant(java.time.Instant) ScoreMode(org.apache.lucene.search.join.ScoreMode) Objects(java.util.Objects) NO_PERMISSION_TO_ACCESS_DETECTOR(org.opensearch.ad.constant.CommonErrorMessages.NO_PERMISSION_TO_ACCESS_DETECTOR) List(java.util.List) Logger(org.apache.logging.log4j.Logger) QueryBuilder(org.opensearch.index.query.QueryBuilder) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) Entry(java.util.Map.Entry) DATE_HISTOGRAM(org.opensearch.ad.constant.CommonName.DATE_HISTOGRAM) Optional(java.util.Optional) TermsQueryBuilder(org.opensearch.index.query.TermsQueryBuilder) FEATURE_AGGS(org.opensearch.ad.constant.CommonName.FEATURE_AGGS) XContentType(org.opensearch.common.xcontent.XContentType) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) ConfigConstants(org.opensearch.commons.ConfigConstants) AggregatorFactories(org.opensearch.search.aggregations.AggregatorFactories) FeatureData(org.opensearch.ad.model.FeatureData) DoubleArrayList(com.carrotsearch.hppc.DoubleArrayList) DateHistogramInterval(org.opensearch.search.aggregations.bucket.histogram.DateHistogramInterval) ArrayList(java.util.ArrayList) CompositeAggregationBuilder(org.opensearch.search.aggregations.bucket.composite.CompositeAggregationBuilder) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) EPOCH_MILLIS_FORMAT(org.opensearch.ad.constant.CommonName.EPOCH_MILLIS_FORMAT) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SearchResponse(org.opensearch.action.search.SearchResponse) MAX_BATCH_TASK_PIECE_SIZE(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_BATCH_TASK_PIECE_SIZE) GetAnomalyDetectorResponse(org.opensearch.ad.transport.GetAnomalyDetectorResponse) QueryBuilders(org.opensearch.index.query.QueryBuilders) CommonName(org.opensearch.ad.constant.CommonName) RangeQueryBuilder(org.opensearch.index.query.RangeQueryBuilder) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) GetRequest(org.opensearch.action.get.GetRequest) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) IOException(java.io.IOException) Consumer(java.util.function.Consumer) CompositeValuesSourceBuilder(org.opensearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder) VALID_AGG_NAME(org.opensearch.search.aggregations.AggregatorFactories.VALID_AGG_NAME) Entity(org.opensearch.ad.model.Entity) AggregationBuilders.dateRange(org.opensearch.search.aggregations.AggregationBuilders.dateRange) User(org.opensearch.commons.authuser.User) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) LogManager(org.apache.logging.log4j.LogManager) QUERY_PARAM_PERIOD_START(org.opensearch.ad.model.AnomalyDetector.QUERY_PARAM_PERIOD_START) GetRequest(org.opensearch.action.get.GetRequest) IndexNotFoundException(org.opensearch.index.IndexNotFoundException)

Example 57 with AnomalyDetector

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

the class IndexAnomalyDetectorActionHandlerTests method testMoreThanTenMultiEntityDetectors.

@SuppressWarnings("unchecked")
public void testMoreThanTenMultiEntityDetectors() throws IOException {
    String field = "a";
    AnomalyDetector detector = TestHelpers.randomAnomalyDetectorUsingCategoryFields(detectorId, Arrays.asList(field));
    SearchResponse detectorResponse = mock(SearchResponse.class);
    int totalHits = 11;
    when(detectorResponse.getHits()).thenReturn(TestHelpers.createSearchHits(totalHits));
    SearchResponse userIndexResponse = mock(SearchResponse.class);
    int userIndexHits = 0;
    when(userIndexResponse.getHits()).thenReturn(TestHelpers.createSearchHits(userIndexHits));
    // extend NodeClient since its execute method is final and mockito does not allow to mock final methods
    // we can also use spy to overstep the final methods
    NodeClient client = getCustomNodeClient(detectorResponse, userIndexResponse, detector, threadPool);
    NodeClient clientSpy = spy(client);
    handler = new IndexAnomalyDetectorActionHandler(clusterService, clientSpy, transportService, channel, anomalyDetectionIndices, detectorId, seqNo, primaryTerm, refreshPolicy, detector, requestTimeout, maxSingleEntityAnomalyDetectors, maxMultiEntityAnomalyDetectors, maxAnomalyFeatures, method, xContentRegistry(), null, adTaskManager, searchFeatureDao);
    handler.start();
    ArgumentCaptor<Exception> response = ArgumentCaptor.forClass(Exception.class);
    verify(clientSpy, times(1)).search(any(SearchRequest.class), any());
    verify(channel).onFailure(response.capture());
    Exception value = response.getValue();
    assertTrue(value instanceof IllegalArgumentException);
    String errorMsg = String.format(Locale.ROOT, IndexAnomalyDetectorActionHandler.EXCEEDED_MAX_MULTI_ENTITY_DETECTORS_PREFIX_MSG, maxMultiEntityAnomalyDetectors);
    assertTrue(value.getMessage().contains(errorMsg));
}
Also used : SearchRequest(org.opensearch.action.search.SearchRequest) NodeClient(org.opensearch.client.node.NodeClient) IndexAnomalyDetectorActionHandler(org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) IOException(java.io.IOException) SearchResponse(org.opensearch.action.search.SearchResponse)

Example 58 with AnomalyDetector

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

the class IndexAnomalyDetectorActionHandlerTests method testTextField.

@SuppressWarnings("unchecked")
public void testTextField() throws IOException {
    String field = "a";
    AnomalyDetector detector = TestHelpers.randomAnomalyDetectorUsingCategoryFields(detectorId, Arrays.asList(field));
    SearchResponse detectorResponse = mock(SearchResponse.class);
    int totalHits = 9;
    when(detectorResponse.getHits()).thenReturn(TestHelpers.createSearchHits(totalHits));
    // extend NodeClient since its execute method is final and mockito does not allow to mock final methods
    // we can also use spy to overstep the final methods
    NodeClient client = new NodeClient(Settings.EMPTY, threadPool) {

        @Override
        public <Request extends ActionRequest, Response extends ActionResponse> void doExecute(ActionType<Response> action, Request request, ActionListener<Response> listener) {
            try {
                if (action.equals(SearchAction.INSTANCE)) {
                    listener.onResponse((Response) detectorResponse);
                } else {
                    // passes first get field mapping call where timestamp has to be of type date
                    // fails on second call where categorical field is checked to be type keyword or IP
                    // we need to put the test in the same package of GetFieldMappingsResponse since its constructor is package private
                    GetFieldMappingsResponse response = new GetFieldMappingsResponse(TestHelpers.createFieldMappings(detector.getIndices().get(0), field, "date"));
                    listener.onResponse((Response) response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    handler = new IndexAnomalyDetectorActionHandler(clusterService, client, transportService, channel, anomalyDetectionIndices, detectorId, seqNo, primaryTerm, refreshPolicy, detector, requestTimeout, maxSingleEntityAnomalyDetectors, maxMultiEntityAnomalyDetectors, maxAnomalyFeatures, method, xContentRegistry(), null, adTaskManager, searchFeatureDao);
    ArgumentCaptor<Exception> response = ArgumentCaptor.forClass(Exception.class);
    handler.start();
    verify(channel).onFailure(response.capture());
    Exception value = response.getValue();
    assertTrue(value instanceof Exception);
    assertTrue(value.getMessage().contains(IndexAnomalyDetectorActionHandler.CATEGORICAL_FIELD_TYPE_ERR_MSG));
}
Also used : NodeClient(org.opensearch.client.node.NodeClient) ActionType(org.opensearch.action.ActionType) ActionRequest(org.opensearch.action.ActionRequest) WriteRequest(org.opensearch.action.support.WriteRequest) SearchRequest(org.opensearch.action.search.SearchRequest) RestRequest(org.opensearch.rest.RestRequest) GetRequest(org.opensearch.action.get.GetRequest) IOException(java.io.IOException) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ActionResponse(org.opensearch.action.ActionResponse) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) IOException(java.io.IOException) SearchResponse(org.opensearch.action.search.SearchResponse) ActionListener(org.opensearch.action.ActionListener) ActionRequest(org.opensearch.action.ActionRequest) IndexAnomalyDetectorActionHandler(org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler)

Example 59 with AnomalyDetector

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

the class IndexAnomalyDetectorActionHandlerTests method testUpdateTemplate.

@SuppressWarnings("unchecked")
private void testUpdateTemplate(String fieldTypeName) throws IOException {
    String field = "a";
    AnomalyDetector detector = TestHelpers.randomAnomalyDetectorUsingCategoryFields(detectorId, Arrays.asList(field));
    SearchResponse detectorResponse = mock(SearchResponse.class);
    int totalHits = 9;
    when(detectorResponse.getHits()).thenReturn(TestHelpers.createSearchHits(totalHits));
    GetResponse getDetectorResponse = TestHelpers.createGetResponse(detector, detector.getDetectorId(), AnomalyDetector.ANOMALY_DETECTORS_INDEX);
    SearchResponse userIndexResponse = mock(SearchResponse.class);
    int userIndexHits = 0;
    when(userIndexResponse.getHits()).thenReturn(TestHelpers.createSearchHits(userIndexHits));
    // extend NodeClient since its execute method is final and mockito does not allow to mock final methods
    // we can also use spy to overstep the final methods
    NodeClient client = new NodeClient(Settings.EMPTY, threadPool) {

        @Override
        public <Request extends ActionRequest, Response extends ActionResponse> void doExecute(ActionType<Response> action, Request request, ActionListener<Response> listener) {
            try {
                if (action.equals(SearchAction.INSTANCE)) {
                    assertTrue(request instanceof SearchRequest);
                    SearchRequest searchRequest = (SearchRequest) request;
                    if (searchRequest.indices()[0].equals(ANOMALY_DETECTORS_INDEX)) {
                        listener.onResponse((Response) detectorResponse);
                    } else {
                        listener.onResponse((Response) userIndexResponse);
                    }
                } else if (action.equals(GetAction.INSTANCE)) {
                    assertTrue(request instanceof GetRequest);
                    listener.onResponse((Response) getDetectorResponse);
                } else {
                    GetFieldMappingsResponse response = new GetFieldMappingsResponse(TestHelpers.createFieldMappings(detector.getIndices().get(0), field, fieldTypeName));
                    listener.onResponse((Response) response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    NodeClient clientSpy = spy(client);
    ClusterName clusterName = new ClusterName("test");
    ClusterState clusterState = ClusterState.builder(clusterName).metadata(Metadata.builder().build()).build();
    when(clusterService.state()).thenReturn(clusterState);
    handler = new IndexAnomalyDetectorActionHandler(clusterService, clientSpy, transportService, channel, anomalyDetectionIndices, detectorId, seqNo, primaryTerm, refreshPolicy, detector, requestTimeout, maxSingleEntityAnomalyDetectors, maxMultiEntityAnomalyDetectors, maxAnomalyFeatures, RestRequest.Method.PUT, xContentRegistry(), null, adTaskManager, searchFeatureDao);
    ArgumentCaptor<Exception> response = ArgumentCaptor.forClass(Exception.class);
    handler.start();
    verify(clientSpy, times(1)).execute(eq(GetFieldMappingsAction.INSTANCE), any(), any());
    verify(channel).onFailure(response.capture());
    Exception value = response.getValue();
    if (fieldTypeName.equals(CommonName.IP_TYPE) || fieldTypeName.equals(CommonName.KEYWORD_TYPE)) {
        assertTrue(value.getMessage().contains(IndexAnomalyDetectorActionHandler.NO_DOCS_IN_USER_INDEX_MSG));
    } else {
        assertTrue(value.getMessage().contains(IndexAnomalyDetectorActionHandler.CATEGORICAL_FIELD_TYPE_ERR_MSG));
    }
}
Also used : SearchRequest(org.opensearch.action.search.SearchRequest) ClusterState(org.opensearch.cluster.ClusterState) NodeClient(org.opensearch.client.node.NodeClient) ActionType(org.opensearch.action.ActionType) ActionRequest(org.opensearch.action.ActionRequest) WriteRequest(org.opensearch.action.support.WriteRequest) SearchRequest(org.opensearch.action.search.SearchRequest) RestRequest(org.opensearch.rest.RestRequest) GetRequest(org.opensearch.action.get.GetRequest) IOException(java.io.IOException) GetResponse(org.opensearch.action.get.GetResponse) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) ActionResponse(org.opensearch.action.ActionResponse) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) IOException(java.io.IOException) SearchResponse(org.opensearch.action.search.SearchResponse) ActionResponse(org.opensearch.action.ActionResponse) GetResponse(org.opensearch.action.get.GetResponse) IndexAnomalyDetectorResponse(org.opensearch.ad.transport.IndexAnomalyDetectorResponse) SearchResponse(org.opensearch.action.search.SearchResponse) ActionListener(org.opensearch.action.ActionListener) ActionRequest(org.opensearch.action.ActionRequest) GetRequest(org.opensearch.action.get.GetRequest) ClusterName(org.opensearch.cluster.ClusterName) IndexAnomalyDetectorActionHandler(org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler)

Example 60 with AnomalyDetector

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

the class AnomalyDetectorRestApiIT method testCreateAnomalyDetectorWithNotExistingIndices.

public void testCreateAnomalyDetectorWithNotExistingIndices() throws Exception {
    AnomalyDetector detector = TestHelpers.randomAnomalyDetector(TestHelpers.randomUiMetadata(), null);
    TestHelpers.assertFailWith(ResponseException.class, "index_not_found_exception", () -> TestHelpers.makeRequest(client(), "POST", TestHelpers.AD_BASE_DETECTORS_URI, ImmutableMap.of(), TestHelpers.toHttpEntity(detector), null));
}
Also used : AnomalyDetector(org.opensearch.ad.model.AnomalyDetector)

Aggregations

AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)226 IOException (java.io.IOException)71 ActionListener (org.opensearch.action.ActionListener)54 Response (org.opensearch.client.Response)45 Map (java.util.Map)43 List (java.util.List)41 Client (org.opensearch.client.Client)38 SearchRequest (org.opensearch.action.search.SearchRequest)37 LogManager (org.apache.logging.log4j.LogManager)35 Logger (org.apache.logging.log4j.Logger)35 ArrayList (java.util.ArrayList)33 Optional (java.util.Optional)33 Test (org.junit.Test)32 SearchResponse (org.opensearch.action.search.SearchResponse)32 Instant (java.time.Instant)30 TimeValue (org.opensearch.common.unit.TimeValue)30 HashMap (java.util.HashMap)29 Entity (org.opensearch.ad.model.Entity)29 NamedXContentRegistry (org.opensearch.common.xcontent.NamedXContentRegistry)29 SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)29