Search in sources :

Example 1 with IndexAnomalyDetectorActionHandler

use of org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler in project anomaly-detection by opensearch-project.

the class IndexAnomalyDetectorTransportAction method adExecute.

protected void adExecute(IndexAnomalyDetectorRequest request, User user, AnomalyDetector currentDetector, ThreadContext.StoredContext storedContext, ActionListener<IndexAnomalyDetectorResponse> listener) {
    anomalyDetectionIndices.update();
    String detectorId = request.getDetectorID();
    long seqNo = request.getSeqNo();
    long primaryTerm = request.getPrimaryTerm();
    WriteRequest.RefreshPolicy refreshPolicy = request.getRefreshPolicy();
    AnomalyDetector detector = request.getDetector();
    RestRequest.Method method = request.getMethod();
    TimeValue requestTimeout = request.getRequestTimeout();
    Integer maxSingleEntityAnomalyDetectors = request.getMaxSingleEntityAnomalyDetectors();
    Integer maxMultiEntityAnomalyDetectors = request.getMaxMultiEntityAnomalyDetectors();
    Integer maxAnomalyFeatures = request.getMaxAnomalyFeatures();
    storedContext.restore();
    checkIndicesAndExecute(detector.getIndices(), () -> {
        // Don't replace detector's user when update detector
        // Github issue: https://github.com/opensearch-project/anomaly-detection/issues/124
        User detectorUser = currentDetector == null ? user : currentDetector.getUser();
        IndexAnomalyDetectorActionHandler indexAnomalyDetectorActionHandler = new IndexAnomalyDetectorActionHandler(clusterService, client, transportService, listener, anomalyDetectionIndices, detectorId, seqNo, primaryTerm, refreshPolicy, detector, requestTimeout, maxSingleEntityAnomalyDetectors, maxMultiEntityAnomalyDetectors, maxAnomalyFeatures, method, xContentRegistry, detectorUser, adTaskManager, searchFeatureDao);
        indexAnomalyDetectorActionHandler.start();
    }, listener);
}
Also used : RestRequest(org.opensearch.rest.RestRequest) User(org.opensearch.commons.authuser.User) WriteRequest(org.opensearch.action.support.WriteRequest) IndexAnomalyDetectorActionHandler(org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) TimeValue(org.opensearch.common.unit.TimeValue)

Example 2 with IndexAnomalyDetectorActionHandler

use of org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler 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 3 with IndexAnomalyDetectorActionHandler

use of org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler 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 4 with IndexAnomalyDetectorActionHandler

use of org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler in project anomaly-detection by opensearch-project.

the class IndexAnomalyDetectorActionHandlerTests method setUp.

@SuppressWarnings("unchecked")
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    settings = Settings.EMPTY;
    clusterService = mock(ClusterService.class);
    clientMock = spy(new NodeClient(settings, threadPool));
    transportService = mock(TransportService.class);
    channel = mock(ActionListener.class);
    anomalyDetectionIndices = mock(AnomalyDetectionIndices.class);
    when(anomalyDetectionIndices.doesAnomalyDetectorIndexExist()).thenReturn(true);
    detectorId = "123";
    seqNo = 0L;
    primaryTerm = 0L;
    WriteRequest.RefreshPolicy refreshPolicy = WriteRequest.RefreshPolicy.IMMEDIATE;
    String field = "a";
    detector = TestHelpers.randomAnomalyDetectorUsingCategoryFields(detectorId, Arrays.asList(field));
    requestTimeout = new TimeValue(1000L);
    maxSingleEntityAnomalyDetectors = 1000;
    maxMultiEntityAnomalyDetectors = 10;
    maxAnomalyFeatures = 5;
    method = RestRequest.Method.POST;
    adTaskManager = mock(ADTaskManager.class);
    searchFeatureDao = mock(SearchFeatureDao.class);
    handler = new IndexAnomalyDetectorActionHandler(clusterService, clientMock, transportService, channel, anomalyDetectionIndices, detectorId, seqNo, primaryTerm, refreshPolicy, detector, requestTimeout, maxSingleEntityAnomalyDetectors, maxMultiEntityAnomalyDetectors, maxAnomalyFeatures, method, xContentRegistry(), null, adTaskManager, searchFeatureDao);
}
Also used : NodeClient(org.opensearch.client.node.NodeClient) ClusterService(org.opensearch.cluster.service.ClusterService) ActionListener(org.opensearch.action.ActionListener) TransportService(org.opensearch.transport.TransportService) ADTaskManager(org.opensearch.ad.task.ADTaskManager) WriteRequest(org.opensearch.action.support.WriteRequest) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) IndexAnomalyDetectorActionHandler(org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler) SearchFeatureDao(org.opensearch.ad.feature.SearchFeatureDao) TimeValue(org.opensearch.common.unit.TimeValue) Before(org.junit.Before)

Example 5 with IndexAnomalyDetectorActionHandler

use of org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler 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)

Aggregations

IndexAnomalyDetectorActionHandler (org.opensearch.ad.rest.handler.IndexAnomalyDetectorActionHandler)9 IOException (java.io.IOException)7 SearchResponse (org.opensearch.action.search.SearchResponse)7 ADValidationException (org.opensearch.ad.common.exception.ADValidationException)7 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)7 ActionListener (org.opensearch.action.ActionListener)6 SearchRequest (org.opensearch.action.search.SearchRequest)6 NodeClient (org.opensearch.client.node.NodeClient)6 GetRequest (org.opensearch.action.get.GetRequest)5 WriteRequest (org.opensearch.action.support.WriteRequest)5 GetResponse (org.opensearch.action.get.GetResponse)4 RestRequest (org.opensearch.rest.RestRequest)4 ActionRequest (org.opensearch.action.ActionRequest)3 ActionResponse (org.opensearch.action.ActionResponse)3 ActionType (org.opensearch.action.ActionType)3 ClusterName (org.opensearch.cluster.ClusterName)3 ClusterState (org.opensearch.cluster.ClusterState)3 Ignore (org.junit.Ignore)2 IndexAnomalyDetectorResponse (org.opensearch.ad.transport.IndexAnomalyDetectorResponse)2 TimeValue (org.opensearch.common.unit.TimeValue)2