Search in sources :

Example 21 with PlainActionFuture

use of org.opensearch.action.support.PlainActionFuture in project anomaly-detection by opensearch-project.

the class RCFResultTests method testExecutionException.

@SuppressWarnings("unchecked")
public void testExecutionException() {
    TransportService transportService = new TransportService(Settings.EMPTY, mock(Transport.class), null, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null, Collections.emptySet());
    ModelManager manager = mock(ModelManager.class);
    ADCircuitBreakerService adCircuitBreakerService = mock(ADCircuitBreakerService.class);
    RCFResultTransportAction action = new RCFResultTransportAction(mock(ActionFilters.class), transportService, manager, adCircuitBreakerService, hashRing);
    doThrow(NullPointerException.class).when(manager).getTRcfResult(any(String.class), any(String.class), any(double[].class), any(ActionListener.class));
    when(adCircuitBreakerService.isOpen()).thenReturn(false);
    final PlainActionFuture<RCFResultResponse> future = new PlainActionFuture<>();
    RCFResultRequest request = new RCFResultRequest("123", "123-rcf-1", new double[] { 0 });
    action.doExecute(mock(Task.class), request, future);
    expectThrows(NullPointerException.class, () -> future.actionGet());
}
Also used : Task(org.opensearch.tasks.Task) ADCircuitBreakerService(org.opensearch.ad.breaker.ADCircuitBreakerService) ActionFilters(org.opensearch.action.support.ActionFilters) ModelManager(org.opensearch.ad.ml.ModelManager) ActionListener(org.opensearch.action.ActionListener) TransportService(org.opensearch.transport.TransportService) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Transport(org.opensearch.transport.Transport)

Example 22 with PlainActionFuture

use of org.opensearch.action.support.PlainActionFuture in project anomaly-detection by opensearch-project.

the class RCFResultTests method testCircuitBreaker.

@SuppressWarnings("unchecked")
public void testCircuitBreaker() {
    TransportService transportService = new TransportService(Settings.EMPTY, mock(Transport.class), null, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null, Collections.emptySet());
    ModelManager manager = mock(ModelManager.class);
    ADCircuitBreakerService breakerService = mock(ADCircuitBreakerService.class);
    RCFResultTransportAction action = new RCFResultTransportAction(mock(ActionFilters.class), transportService, manager, breakerService, hashRing);
    doAnswer(invocation -> {
        ActionListener<ThresholdingResult> listener = invocation.getArgument(3);
        listener.onResponse(new ThresholdingResult(grade, 0d, 0.5, totalUpdates, 0, attribution, pastValues, expectedValuesList, likelihood, threshold, 30));
        return null;
    }).when(manager).getTRcfResult(any(String.class), any(String.class), any(double[].class), any(ActionListener.class));
    when(breakerService.isOpen()).thenReturn(true);
    final PlainActionFuture<RCFResultResponse> future = new PlainActionFuture<>();
    RCFResultRequest request = new RCFResultRequest("123", "123-rcf-1", new double[] { 0 });
    action.doExecute(mock(Task.class), request, future);
    expectThrows(LimitExceededException.class, () -> future.actionGet());
}
Also used : Task(org.opensearch.tasks.Task) ADCircuitBreakerService(org.opensearch.ad.breaker.ADCircuitBreakerService) ActionFilters(org.opensearch.action.support.ActionFilters) ModelManager(org.opensearch.ad.ml.ModelManager) ThresholdingResult(org.opensearch.ad.ml.ThresholdingResult) ActionListener(org.opensearch.action.ActionListener) TransportService(org.opensearch.transport.TransportService) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Transport(org.opensearch.transport.Transport)

Example 23 with PlainActionFuture

use of org.opensearch.action.support.PlainActionFuture in project anomaly-detection by opensearch-project.

the class DeleteTests method StopDetectorResponseTemplate.

@SuppressWarnings("unchecked")
public void StopDetectorResponseTemplate(DetectorExecutionMode mode) throws Exception {
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        assertTrue(String.format("The size of args is %d.  Its content is %s", args.length, Arrays.toString(args)), args.length >= 3);
        assertTrue(args[2] instanceof ActionListener);
        ActionListener<DeleteModelResponse> listener = (ActionListener<DeleteModelResponse>) args[2];
        assertTrue(listener != null);
        if (mode == DetectorExecutionMode.DELETE_MODEL_FAILURE) {
            listener.onFailure(new OpenSearchException(""));
        } else {
            listener.onResponse(response);
        }
        return null;
    }).when(client).execute(eq(DeleteModelAction.INSTANCE), any(), any());
    BulkByScrollResponse deleteByQueryResponse = mock(BulkByScrollResponse.class);
    when(deleteByQueryResponse.getDeleted()).thenReturn(10L);
    String detectorID = "123";
    DiscoveryNodeFilterer nodeFilter = mock(DiscoveryNodeFilterer.class);
    StopDetectorTransportAction action = new StopDetectorTransportAction(transportService, nodeFilter, actionFilters, client);
    StopDetectorRequest request = new StopDetectorRequest().adID(detectorID);
    PlainActionFuture<StopDetectorResponse> listener = new PlainActionFuture<>();
    action.doExecute(task, request, listener);
    StopDetectorResponse response = listener.actionGet();
    assertTrue(!response.success());
}
Also used : DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) BulkByScrollResponse(org.opensearch.index.reindex.BulkByScrollResponse) ActionListener(org.opensearch.action.ActionListener) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) OpenSearchException(org.opensearch.OpenSearchException)

Example 24 with PlainActionFuture

use of org.opensearch.action.support.PlainActionFuture in project asynchronous-search by opensearch-project.

the class AsynchronousSearchContextPermitsTests method testAllOperationsInvoked.

public void testAllOperationsInvoked() throws InterruptedException, TimeoutException {
    int numThreads = 10;
    class DummyException extends RuntimeException {
    }
    List<PlainActionFuture<Releasable>> futures = new ArrayList<>();
    List<Thread> operationThreads = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(numThreads / 4);
    for (int i = 0; i < numThreads; i++) {
        boolean failingListener = randomBoolean();
        PlainActionFuture<Releasable> future = new PlainActionFuture<Releasable>() {

            @Override
            public void onResponse(Releasable releasable) {
                releasable.close();
                if (failingListener) {
                    throw new DummyException();
                } else {
                    super.onResponse(releasable);
                }
            }
        };
        Thread thread = new Thread(() -> {
            latch.countDown();
            try {
                permits.asyncAcquirePermit(future, TimeValue.timeValueSeconds(1), "testAllOperationsInvoked");
            } catch (DummyException dummyException) {
                // ok, notify future
                assertTrue(failingListener);
                future.onFailure(dummyException);
            }
        });
        futures.add(future);
        operationThreads.add(thread);
    }
    CountDownLatch blockFinished = new CountDownLatch(1);
    threadPool.generic().execute(() -> {
        try {
            latch.await();
            blockFinished.countDown();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    for (Thread thread : operationThreads) {
        thread.start();
    }
    for (PlainActionFuture<Releasable> future : futures) {
        try {
            assertNotNull(future.get(1, TimeUnit.MINUTES));
        } catch (ExecutionException e) {
            assertThat(e.getCause(), either(instanceOf(DummyException.class)).or(instanceOf(OpenSearchRejectedExecutionException.class)));
        }
    }
    for (Thread thread : operationThreads) {
        thread.join();
    }
    blockFinished.await();
}
Also used : ArrayList(java.util.ArrayList) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) CountDownLatch(java.util.concurrent.CountDownLatch) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Releasable(org.opensearch.common.lease.Releasable) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) ExecutionException(java.util.concurrent.ExecutionException)

Example 25 with PlainActionFuture

use of org.opensearch.action.support.PlainActionFuture in project OpenSearch by opensearch-project.

the class TransportBroadcastByNodeActionTests method testRequestsAreNotSentToFailedMaster.

// simulate the master being removed from the cluster but before a new master is elected
// as such, the shards assigned to the master will still show up in the cluster state as assigned to a node but
// that node will not be in the local cluster state on any node that has detected the master as failing
// in this case, such a shard should be treated as unassigned
public void testRequestsAreNotSentToFailedMaster() {
    Request request = new Request(new String[] { TEST_INDEX });
    PlainActionFuture<Response> listener = new PlainActionFuture<>();
    DiscoveryNode masterNode = clusterService.state().nodes().getMasterNode();
    DiscoveryNodes.Builder builder = DiscoveryNodes.builder(clusterService.state().getNodes());
    builder.remove(masterNode.getId());
    setState(clusterService, ClusterState.builder(clusterService.state()).nodes(builder));
    action.new AsyncAction(null, request, listener).start();
    Map<String, List<CapturingTransport.CapturedRequest>> capturedRequests = transport.getCapturedRequestsByTargetNodeAndClear();
    // the master should not be in the list of nodes that requests were sent to
    ShardsIterator shardIt = clusterService.state().routingTable().allShards(new String[] { TEST_INDEX });
    Set<String> set = new HashSet<>();
    for (ShardRouting shard : shardIt) {
        if (!shard.currentNodeId().equals(masterNode.getId())) {
            set.add(shard.currentNodeId());
        }
    }
    // check a request was sent to the right number of nodes
    assertEquals(set.size(), capturedRequests.size());
    // check requests were sent to the right nodes
    assertEquals(set, capturedRequests.keySet());
    for (Map.Entry<String, List<CapturingTransport.CapturedRequest>> entry : capturedRequests.entrySet()) {
        // check one request was sent to each non-master node
        assertEquals(1, entry.getValue().size());
    }
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) CapturingTransport(org.opensearch.test.transport.CapturingTransport) BroadcastRequest(org.opensearch.action.support.broadcast.BroadcastRequest) IndicesRequest(org.opensearch.action.IndicesRequest) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) HasToString.hasToString(org.hamcrest.object.HasToString.hasToString) ShardsIterator(org.opensearch.cluster.routing.ShardsIterator) TransportResponse(org.opensearch.transport.TransportResponse) BroadcastResponse(org.opensearch.action.support.broadcast.BroadcastResponse) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) List(java.util.List) ArrayList(java.util.ArrayList) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting) Map(java.util.Map) HashMap(java.util.HashMap) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) HashSet(java.util.HashSet)

Aggregations

PlainActionFuture (org.opensearch.action.support.PlainActionFuture)191 ActionListener (org.opensearch.action.ActionListener)59 ShardId (org.opensearch.index.shard.ShardId)55 Settings (org.opensearch.common.settings.Settings)46 IOException (java.io.IOException)43 ActionFilters (org.opensearch.action.support.ActionFilters)43 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)42 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)42 CountDownLatch (java.util.concurrent.CountDownLatch)41 ClusterState (org.opensearch.cluster.ClusterState)40 ShardRouting (org.opensearch.cluster.routing.ShardRouting)39 ExecutionException (java.util.concurrent.ExecutionException)38 List (java.util.List)37 ThreadPool (org.opensearch.threadpool.ThreadPool)37 ArrayList (java.util.ArrayList)35 Matchers.containsString (org.hamcrest.Matchers.containsString)31 HashSet (java.util.HashSet)30 IndexShard (org.opensearch.index.shard.IndexShard)29 Mockito.anyString (org.mockito.Mockito.anyString)28 TransportRequest (org.opensearch.transport.TransportRequest)28