Search in sources :

Example 6 with ActionResponse

use of org.opensearch.action.ActionResponse 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 7 with ActionResponse

use of org.opensearch.action.ActionResponse in project OpenSearch by opensearch-project.

the class RestCancellableNodeClient method doExecute.

@Override
public <Request extends ActionRequest, Response extends ActionResponse> void doExecute(ActionType<Response> action, Request request, ActionListener<Response> listener) {
    CloseListener closeListener = httpChannels.computeIfAbsent(httpChannel, channel -> new CloseListener());
    TaskHolder taskHolder = new TaskHolder();
    Task task = client.executeLocally(action, request, new ActionListener<Response>() {

        @Override
        public void onResponse(Response response) {
            try {
                closeListener.unregisterTask(taskHolder);
            } finally {
                listener.onResponse(response);
            }
        }

        @Override
        public void onFailure(Exception e) {
            try {
                closeListener.unregisterTask(taskHolder);
            } finally {
                listener.onFailure(e);
            }
        }
    });
    final TaskId taskId = new TaskId(client.getLocalNodeId(), task.getId());
    closeListener.registerTask(taskHolder, taskId);
    closeListener.maybeRegisterChannel(httpChannel);
}
Also used : ActionResponse(org.opensearch.action.ActionResponse) Task(org.opensearch.tasks.Task) TaskId(org.opensearch.tasks.TaskId)

Example 8 with ActionResponse

use of org.opensearch.action.ActionResponse in project OpenSearch by opensearch-project.

the class ParentTaskAssigningClientTests method testSetsParentId.

public void testSetsParentId() {
    TaskId[] parentTaskId = new TaskId[] { new TaskId(randomAlphaOfLength(3), randomLong()) };
    // This mock will do nothing but verify that parentTaskId is set on all requests sent to it.
    NoOpClient mock = new NoOpClient(getTestName()) {

        @Override
        protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute(ActionType<Response> action, Request request, ActionListener<Response> listener) {
            assertEquals(parentTaskId[0], request.getParentTask());
            super.doExecute(action, request, listener);
        }
    };
    try (ParentTaskAssigningClient client = new ParentTaskAssigningClient(mock, parentTaskId[0])) {
        // All of these should have the parentTaskId set
        client.bulk(new BulkRequest());
        client.search(new SearchRequest());
        client.clearScroll(new ClearScrollRequest());
        // Now lets verify that unwrapped calls don't have the parentTaskId set
        parentTaskId[0] = TaskId.EMPTY_TASK_ID;
        client.unwrap().bulk(new BulkRequest());
        client.unwrap().search(new SearchRequest());
        client.unwrap().clearScroll(new ClearScrollRequest());
    }
}
Also used : SearchRequest(org.opensearch.action.search.SearchRequest) TaskId(org.opensearch.tasks.TaskId) ActionType(org.opensearch.action.ActionType) ActionListener(org.opensearch.action.ActionListener) ActionRequest(org.opensearch.action.ActionRequest) NoOpClient(org.opensearch.test.client.NoOpClient) BulkRequest(org.opensearch.action.bulk.BulkRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) SearchRequest(org.opensearch.action.search.SearchRequest) ActionRequest(org.opensearch.action.ActionRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) ActionResponse(org.opensearch.action.ActionResponse)

Example 9 with ActionResponse

use of org.opensearch.action.ActionResponse in project OpenSearch by opensearch-project.

the class OriginSettingClientTests method testSetsParentId.

public void testSetsParentId() {
    String origin = randomAlphaOfLength(7);
    /*
         * This mock will do nothing but verify that origin is set in the
         * thread context before executing the action.
         */
    NoOpClient mock = new NoOpClient(getTestName()) {

        @Override
        protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute(ActionType<Response> action, Request request, ActionListener<Response> listener) {
            assertEquals(origin, threadPool().getThreadContext().getTransient(ThreadContext.ACTION_ORIGIN_TRANSIENT_NAME));
            super.doExecute(action, request, listener);
        }
    };
    try (OriginSettingClient client = new OriginSettingClient(mock, origin)) {
        // All of these should have the origin set
        client.bulk(new BulkRequest());
        client.search(new SearchRequest());
        client.clearScroll(new ClearScrollRequest());
        ThreadContext threadContext = client.threadPool().getThreadContext();
        client.bulk(new BulkRequest(), listenerThatAssertsOriginNotSet(threadContext));
        client.search(new SearchRequest(), listenerThatAssertsOriginNotSet(threadContext));
        client.clearScroll(new ClearScrollRequest(), listenerThatAssertsOriginNotSet(threadContext));
    }
}
Also used : SearchRequest(org.opensearch.action.search.SearchRequest) ActionType(org.opensearch.action.ActionType) ActionListener(org.opensearch.action.ActionListener) ActionRequest(org.opensearch.action.ActionRequest) NoOpClient(org.opensearch.test.client.NoOpClient) BulkRequest(org.opensearch.action.bulk.BulkRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) SearchRequest(org.opensearch.action.search.SearchRequest) ActionRequest(org.opensearch.action.ActionRequest) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) ActionResponse(org.opensearch.action.ActionResponse)

Example 10 with ActionResponse

use of org.opensearch.action.ActionResponse in project OpenSearch by opensearch-project.

the class TransportActionFilterChainTests method testTooManyContinueProcessingRequest.

public void testTooManyContinueProcessingRequest() throws InterruptedException {
    final int additionalContinueCount = randomInt(10);
    RequestTestFilter testFilter = new RequestTestFilter(randomInt(), new RequestCallback() {

        @Override
        public <Request extends ActionRequest, Response extends ActionResponse> void execute(Task task, String action, Request request, ActionListener<Response> listener, ActionFilterChain<Request, Response> actionFilterChain) {
            for (int i = 0; i <= additionalContinueCount; i++) {
                actionFilterChain.proceed(task, action, request, listener);
            }
        }
    });
    Set<ActionFilter> filters = new HashSet<>();
    filters.add(testFilter);
    String actionName = randomAlphaOfLength(randomInt(30));
    ActionFilters actionFilters = new ActionFilters(filters);
    TransportAction<TestRequest, TestResponse> transportAction = new TransportAction<TestRequest, TestResponse>(actionName, actionFilters, new TaskManager(Settings.EMPTY, threadPool, Collections.emptySet())) {

        @Override
        protected void doExecute(Task task, TestRequest request, ActionListener<TestResponse> listener) {
            listener.onResponse(new TestResponse());
        }
    };
    final CountDownLatch latch = new CountDownLatch(additionalContinueCount + 1);
    final AtomicInteger responses = new AtomicInteger();
    final List<Throwable> failures = new CopyOnWriteArrayList<>();
    transportAction.execute(new TestRequest(), new LatchedActionListener<>(new ActionListener<TestResponse>() {

        @Override
        public void onResponse(TestResponse testResponse) {
            responses.incrementAndGet();
        }

        @Override
        public void onFailure(Exception e) {
            failures.add(e);
        }
    }, latch));
    if (!latch.await(10, TimeUnit.SECONDS)) {
        fail("timeout waiting for the filter to notify the listener as many times as expected");
    }
    assertThat(testFilter.runs.get(), equalTo(1));
    assertThat(testFilter.lastActionName, equalTo(actionName));
    assertThat(responses.get(), equalTo(1));
    assertThat(failures.size(), equalTo(additionalContinueCount));
    for (Throwable failure : failures) {
        assertThat(failure, instanceOf(IllegalStateException.class));
    }
}
Also used : Task(org.opensearch.tasks.Task) HashSet(java.util.HashSet) ActionRequest(org.opensearch.action.ActionRequest) CountDownLatch(java.util.concurrent.CountDownLatch) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) OpenSearchTimeoutException(org.opensearch.OpenSearchTimeoutException) ActionResponse(org.opensearch.action.ActionResponse) TaskManager(org.opensearch.tasks.TaskManager) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Aggregations

ActionResponse (org.opensearch.action.ActionResponse)18 ActionListener (org.opensearch.action.ActionListener)10 ActionRequest (org.opensearch.action.ActionRequest)9 IOException (java.io.IOException)7 ActionType (org.opensearch.action.ActionType)7 SearchRequest (org.opensearch.action.search.SearchRequest)7 NodeClient (org.opensearch.client.node.NodeClient)6 Test (org.junit.Test)5 GetRequest (org.opensearch.action.get.GetRequest)5 RestRequest (org.opensearch.rest.RestRequest)5 BytesStreamOutput (org.opensearch.common.io.stream.BytesStreamOutput)4 StreamOutput (org.opensearch.common.io.stream.StreamOutput)4 Task (org.opensearch.tasks.Task)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 OpenSearchTimeoutException (org.opensearch.OpenSearchTimeoutException)3 BulkRequest (org.opensearch.action.bulk.BulkRequest)3 WriteRequest (org.opensearch.action.support.WriteRequest)3 ThreadContext (org.opensearch.common.util.concurrent.ThreadContext)3 UncheckedIOException (java.io.UncheckedIOException)2 Collections (java.util.Collections)2