Search in sources :

Example 6 with TransportResponse

use of org.opensearch.transport.TransportResponse in project anomaly-detection by opensearch-project.

the class AnomalyResultTests method thresholdExceptionTestTemplate.

public void thresholdExceptionTestTemplate(Exception thrownException, String adID, Class<? extends Exception> expectedExceptionType, String error) {
    TransportInterceptor failureTransportInterceptor = new TransportInterceptor() {

        @Override
        public AsyncSender interceptSender(AsyncSender sender) {
            return new AsyncSender() {

                @Override
                public <T extends TransportResponse> void sendRequest(Transport.Connection connection, String action, TransportRequest request, TransportRequestOptions options, TransportResponseHandler<T> handler) {
                    if (ThresholdResultAction.NAME.equals(action)) {
                        sender.sendRequest(connection, action, request, options, rcfFailureHandler(handler, thrownException));
                    } else if (RCFResultAction.NAME.equals(action)) {
                        sender.sendRequest(connection, action, request, options, rcfResponseHandler(handler));
                    } else {
                        sender.sendRequest(connection, action, request, options, handler);
                    }
                }
            };
        }
    };
    // need to close nodes created in the setUp nodes and create new nodes
    // for the failure interceptor. Otherwise, we will get thread leak error.
    tearDownTestNodes();
    setupTestNodes(failureTransportInterceptor, Settings.EMPTY, AnomalyDetectorSettings.MAX_ENTITIES_PER_QUERY, AnomalyDetectorSettings.PAGE_SIZE);
    // mock hashing ring response. This has to happen after setting up test nodes with the failure interceptor
    Optional<DiscoveryNode> discoveryNode = Optional.of(testNodes[1].discoveryNode());
    when(hashRing.getOwningNodeWithSameLocalAdVersionForRealtimeAD(any(String.class))).thenReturn(discoveryNode);
    when(hashRing.getNodeByAddress(any(TransportAddress.class))).thenReturn(discoveryNode);
    // register handlers on testNodes[1]
    ActionFilters actionFilters = new ActionFilters(Collections.emptySet());
    new RCFResultTransportAction(actionFilters, testNodes[1].transportService, normalModelManager, adCircuitBreakerService, hashRing);
    new ThresholdResultTransportAction(actionFilters, testNodes[1].transportService, normalModelManager);
    TransportService realTransportService = testNodes[0].transportService;
    ClusterService realClusterService = testNodes[0].clusterService;
    AnomalyResultTransportAction action = new AnomalyResultTransportAction(new ActionFilters(Collections.emptySet()), realTransportService, settings, client, stateManager, featureQuery, normalModelManager, hashRing, realClusterService, indexNameResolver, adCircuitBreakerService, adStats, threadPool, NamedXContentRegistry.EMPTY, adTaskManager);
    AnomalyResultRequest request = new AnomalyResultRequest(adID, 100, 200);
    PlainActionFuture<AnomalyResultResponse> listener = new PlainActionFuture<>();
    action.doExecute(null, request, listener);
    Throwable exception = assertException(listener, expectedExceptionType);
    assertTrue("actual message: " + exception.getMessage(), exception.getMessage().contains(error));
}
Also used : TransportInterceptor(org.opensearch.transport.TransportInterceptor) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) TransportRequest(org.opensearch.transport.TransportRequest) TransportAddress(org.opensearch.common.transport.TransportAddress) TransportResponseHandler(org.opensearch.transport.TransportResponseHandler) Matchers.containsString(org.hamcrest.Matchers.containsString) Mockito.anyString(org.mockito.Mockito.anyString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ActionFilters(org.opensearch.action.support.ActionFilters) TransportResponse(org.opensearch.transport.TransportResponse) ClusterService(org.opensearch.cluster.service.ClusterService) TransportService(org.opensearch.transport.TransportService) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) TransportRequestOptions(org.opensearch.transport.TransportRequestOptions)

Example 7 with TransportResponse

use of org.opensearch.transport.TransportResponse in project anomaly-detection by opensearch-project.

the class EntityProfileTests method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    state = new HashSet<EntityProfileName>();
    state.add(EntityProfileName.STATE);
    all = new HashSet<EntityProfileName>();
    all.add(EntityProfileName.INIT_PROGRESS);
    all.add(EntityProfileName.ENTITY_INFO);
    all.add(EntityProfileName.MODELS);
    model = new HashSet<EntityProfileName>();
    model.add(EntityProfileName.MODELS);
    hashRing = mock(HashRing.class);
    actionFilters = mock(ActionFilters.class);
    transportService = new TransportService(Settings.EMPTY, mock(Transport.class), null, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null, Collections.emptySet());
    settings = Settings.EMPTY;
    modelId = "yecrdnUBqurvo9uKU_d8_entity_app_0";
    clusterService = mock(ClusterService.class);
    cacheProvider = mock(CacheProvider.class);
    EntityCache cache = mock(EntityCache.class);
    updates = 1L;
    when(cache.getTotalUpdates(anyString(), anyString())).thenReturn(updates);
    when(cache.isActive(anyString(), anyString())).thenReturn(isActive);
    when(cache.getLastActiveMs(anyString(), anyString())).thenReturn(lastActiveTimestamp);
    Map<String, Long> modelSizeMap = new HashMap<>();
    modelSizeMap.put(modelId, modelSize);
    when(cache.getModelSize(anyString())).thenReturn(modelSizeMap);
    when(cacheProvider.get()).thenReturn(cache);
    action = new EntityProfileTransportAction(actionFilters, transportService, settings, hashRing, clusterService, cacheProvider);
    future = new PlainActionFuture<>();
    transportAddress1 = new TransportAddress(new InetSocketAddress(InetAddress.getByName("1.2.3.4"), 9300));
    entity = Entity.createSingleAttributeEntity(categoryName, entityValue);
    request = new EntityProfileRequest(detectorId, entity, state);
    normalTransportInterceptor = new TransportInterceptor() {

        @Override
        public AsyncSender interceptSender(AsyncSender sender) {
            return new AsyncSender() {

                @Override
                public <T extends TransportResponse> void sendRequest(Transport.Connection connection, String action, TransportRequest request, TransportRequestOptions options, TransportResponseHandler<T> handler) {
                    if (EntityProfileAction.NAME.equals(action)) {
                        sender.sendRequest(connection, action, request, options, entityProfileHandler(handler));
                    } else {
                        sender.sendRequest(connection, action, request, options, handler);
                    }
                }
            };
        }
    };
    failureTransportInterceptor = new TransportInterceptor() {

        @Override
        public AsyncSender interceptSender(AsyncSender sender) {
            return new AsyncSender() {

                @Override
                public <T extends TransportResponse> void sendRequest(Transport.Connection connection, String action, TransportRequest request, TransportRequestOptions options, TransportResponseHandler<T> handler) {
                    if (EntityProfileAction.NAME.equals(action)) {
                        sender.sendRequest(connection, action, request, options, entityFailureProfileandler(handler));
                    } else {
                        sender.sendRequest(connection, action, request, options, handler);
                    }
                }
            };
        }
    };
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) CacheProvider(org.opensearch.ad.caching.CacheProvider) JsonDeserializer(test.org.opensearch.ad.util.JsonDeserializer) BeforeClass(org.junit.BeforeClass) ModelProfile(org.opensearch.ad.model.ModelProfile) HashRing(org.opensearch.ad.cluster.HashRing) ToXContent(org.opensearch.common.xcontent.ToXContent) TransportInterceptor(org.opensearch.transport.TransportInterceptor) AbstractADTest(org.opensearch.ad.AbstractADTest) HashMap(java.util.HashMap) Version(org.opensearch.Version) JsonPathNotFoundException(org.opensearch.ad.common.exception.JsonPathNotFoundException) EntityProfileName(org.opensearch.ad.model.EntityProfileName) ModelProfileOnNode(org.opensearch.ad.model.ModelProfileOnNode) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) InetAddress(java.net.InetAddress) HashSet(java.util.HashSet) Transport(org.opensearch.transport.Transport) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Map(java.util.Map) EntityCache(org.opensearch.ad.caching.EntityCache) Mockito.anyString(org.mockito.Mockito.anyString) StreamInput(org.opensearch.common.io.stream.StreamInput) AfterClass(org.junit.AfterClass) CommonName(org.opensearch.ad.constant.CommonName) TransportRequest(org.opensearch.transport.TransportRequest) TransportRequestOptions(org.opensearch.transport.TransportRequestOptions) Set(java.util.Set) TransportResponseHandler(org.opensearch.transport.TransportResponseHandler) IOException(java.io.IOException) Settings(org.opensearch.common.settings.Settings) Mockito.when(org.mockito.Mockito.when) Task(org.opensearch.tasks.Task) TransportResponse(org.opensearch.transport.TransportResponse) InetSocketAddress(java.net.InetSocketAddress) TransportService(org.opensearch.transport.TransportService) TransportAddress(org.opensearch.common.transport.TransportAddress) ActionFilters(org.opensearch.action.support.ActionFilters) Entity(org.opensearch.ad.model.Entity) TestHelpers(org.opensearch.ad.TestHelpers) FakeNode(test.org.opensearch.ad.util.FakeNode) ClusterService(org.opensearch.cluster.service.ClusterService) Optional(java.util.Optional) ConnectTransportException(org.opensearch.transport.ConnectTransportException) Collections(java.util.Collections) TransportException(org.opensearch.transport.TransportException) Mockito.mock(org.mockito.Mockito.mock) TransportInterceptor(org.opensearch.transport.TransportInterceptor) EntityCache(org.opensearch.ad.caching.EntityCache) HashMap(java.util.HashMap) TransportAddress(org.opensearch.common.transport.TransportAddress) InetSocketAddress(java.net.InetSocketAddress) Mockito.anyString(org.mockito.Mockito.anyString) HashRing(org.opensearch.ad.cluster.HashRing) TransportRequestOptions(org.opensearch.transport.TransportRequestOptions) TransportRequest(org.opensearch.transport.TransportRequest) ActionFilters(org.opensearch.action.support.ActionFilters) CacheProvider(org.opensearch.ad.caching.CacheProvider) ClusterService(org.opensearch.cluster.service.ClusterService) TransportService(org.opensearch.transport.TransportService) Transport(org.opensearch.transport.Transport) EntityProfileName(org.opensearch.ad.model.EntityProfileName)

Example 8 with TransportResponse

use of org.opensearch.transport.TransportResponse in project OpenSearch by opensearch-project.

the class ClearScrollController method cleanAllScrolls.

void cleanAllScrolls() {
    for (final DiscoveryNode node : nodes) {
        try {
            Transport.Connection connection = searchTransportService.getConnection(null, node);
            searchTransportService.sendClearAllScrollContexts(connection, new ActionListener<TransportResponse>() {

                @Override
                public void onResponse(TransportResponse response) {
                    onFreedContext(true);
                }

                @Override
                public void onFailure(Exception e) {
                    onFailedFreedContext(e, node);
                }
            });
        } catch (Exception e) {
            onFailedFreedContext(e, node);
        }
    }
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) Transport(org.opensearch.transport.Transport) TransportResponse(org.opensearch.transport.TransportResponse)

Example 9 with TransportResponse

use of org.opensearch.transport.TransportResponse in project OpenSearch by opensearch-project.

the class TransportReplicationActionTests method testRetryOnReplicaWithRealTransport.

public void testRetryOnReplicaWithRealTransport() throws Exception {
    final ShardId shardId = new ShardId("test", "_na_", 0);
    final ClusterState initialState = state(shardId.getIndexName(), true, ShardRoutingState.STARTED, ShardRoutingState.STARTED);
    final ShardRouting replica = initialState.getRoutingTable().shardRoutingTable(shardId).replicaShards().get(0);
    final long primaryTerm = initialState.metadata().index(shardId.getIndexName()).primaryTerm(shardId.id());
    // simulate execution of the node holding the replica
    final ClusterState stateWithNodes = ClusterState.builder(initialState).nodes(DiscoveryNodes.builder(initialState.nodes()).localNodeId(replica.currentNodeId())).build();
    setState(clusterService, stateWithNodes);
    AtomicBoolean throwException = new AtomicBoolean(true);
    final ReplicationTask task = maybeTask();
    NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(Collections.emptyList());
    final Transport transport = new MockNioTransport(Settings.EMPTY, Version.CURRENT, threadPool, new NetworkService(Collections.emptyList()), PageCacheRecycler.NON_RECYCLING_INSTANCE, namedWriteableRegistry, new NoneCircuitBreakerService());
    transportService = new MockTransportService(Settings.EMPTY, transport, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null, Collections.emptySet());
    transportService.start();
    transportService.acceptIncomingRequests();
    AtomicBoolean calledSuccessfully = new AtomicBoolean(false);
    TestAction action = new TestAction(Settings.EMPTY, "internal:testActionWithExceptions", transportService, clusterService, shardStateAction, threadPool) {

        @Override
        protected void shardOperationOnReplica(Request shardRequest, IndexShard replica, ActionListener<ReplicaResult> listener) {
            ActionListener.completeWith(listener, () -> {
                assertPhase(task, "replica");
                if (throwException.get()) {
                    throw new RetryOnReplicaException(shardId, "simulation");
                }
                calledSuccessfully.set(true);
                return new ReplicaResult();
            });
        }
    };
    final PlainActionFuture<TransportResponse> listener = new PlainActionFuture<>();
    final Request request = new Request(shardId);
    final long checkpoint = randomNonNegativeLong();
    final long maxSeqNoOfUpdates = randomNonNegativeLong();
    action.handleReplicaRequest(new TransportReplicationAction.ConcreteReplicaRequest<>(request, replica.allocationId().getId(), primaryTerm, checkpoint, maxSeqNoOfUpdates), createTransportChannel(listener), task);
    if (listener.isDone()) {
        // fail with the exception if there
        listener.get();
        fail("listener shouldn't be done");
    }
    // release the waiting
    throwException.set(false);
    // publish a new state (same as the old state with the version incremented)
    setState(clusterService, stateWithNodes);
    // Assert that the request was retried, this time successful
    assertTrue("action should have been successfully called on retry but was not", calledSuccessfully.get());
    transportService.stop();
}
Also used : NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) Matchers.hasToString(org.hamcrest.Matchers.hasToString) Metadata(org.opensearch.cluster.metadata.Metadata) AllocationService(org.opensearch.cluster.routing.allocation.AllocationService) TestThreadPool(org.opensearch.threadpool.TestThreadPool) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ClusterStateChanges(org.opensearch.indices.cluster.ClusterStateChanges) Version(org.opensearch.Version) ClusterServiceUtils.setState(org.opensearch.test.ClusterServiceUtils.setState) NoNodeAvailableException(org.opensearch.client.transport.NoNodeAvailableException) Transport(org.opensearch.transport.Transport) Mockito.doThrow(org.mockito.Mockito.doThrow) ClusterBlock(org.opensearch.cluster.block.ClusterBlock) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) OpenSearchAllocationTestCase(org.opensearch.cluster.OpenSearchAllocationTestCase) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Is.is(org.hamcrest.core.Is.is) ActionListener(org.opensearch.action.ActionListener) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) EnumSet(java.util.EnumSet) AfterClass(org.junit.AfterClass) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Index(org.opensearch.index.Index) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) TransportService(org.opensearch.transport.TransportService) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ActionFilters(org.opensearch.action.support.ActionFilters) ActionTestUtils(org.opensearch.action.support.ActionTestUtils) RoutingNode(org.opensearch.cluster.routing.RoutingNode) TransportException(org.opensearch.transport.TransportException) Mockito.eq(org.mockito.Mockito.eq) Mockito.mock(org.mockito.Mockito.mock) Matchers.arrayWithSize(org.hamcrest.Matchers.arrayWithSize) IndexShardState(org.opensearch.index.shard.IndexShardState) ThreadPool(org.opensearch.threadpool.ThreadPool) Releasable(org.opensearch.common.lease.Releasable) MockTransportService(org.opensearch.test.transport.MockTransportService) ClusterState(org.opensearch.cluster.ClusterState) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) Mockito.anyLong(org.mockito.Mockito.anyLong) ClusterBlocks(org.opensearch.cluster.block.ClusterBlocks) Mockito.anyString(org.mockito.Mockito.anyString) Before(org.junit.Before) MockNioTransport(org.opensearch.transport.nio.MockNioTransport) IOException(java.io.IOException) ShardNotFoundException(org.opensearch.index.shard.ShardNotFoundException) IndexService(org.opensearch.index.IndexService) SETTING_WAIT_FOR_ACTIVE_SHARDS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_WAIT_FOR_ACTIVE_SHARDS) ExecutionException(java.util.concurrent.ExecutionException) Matcher(org.hamcrest.Matcher) ClusterService(org.opensearch.cluster.service.ClusterService) NetworkService(org.opensearch.common.network.NetworkService) Mockito.anyInt(org.mockito.Mockito.anyInt) ReplicationGroup(org.opensearch.index.shard.ReplicationGroup) Assert(org.junit.Assert) PageCacheRecycler(org.opensearch.common.util.PageCacheRecycler) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) OpenSearchException(org.opensearch.OpenSearchException) TestTransportChannel(org.opensearch.transport.TestTransportChannel) ReplicaResponse(org.opensearch.action.support.replication.ReplicationOperation.ReplicaResponse) Collections.singleton(java.util.Collections.singleton) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) After(org.junit.After) UnavailableShardsException(org.opensearch.action.UnavailableShardsException) CloseIndexRequest(org.opensearch.action.admin.indices.close.CloseIndexRequest) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) TransportChannel(org.opensearch.transport.TransportChannel) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) IndicesService(org.opensearch.indices.IndicesService) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) IndexShardClosedException(org.opensearch.index.shard.IndexShardClosedException) TransportResponse(org.opensearch.transport.TransportResponse) RestStatus(org.opensearch.rest.RestStatus) ClusterStateCreationUtils.state(org.opensearch.action.support.replication.ClusterStateCreationUtils.state) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Mockito.any(org.mockito.Mockito.any) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) BeforeClass(org.junit.BeforeClass) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ShardNotInPrimaryModeException(org.opensearch.index.shard.ShardNotInPrimaryModeException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StreamOutput(org.opensearch.common.io.stream.StreamOutput) AtomicReference(java.util.concurrent.atomic.AtomicReference) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) HashSet(java.util.HashSet) IndexShard(org.opensearch.index.shard.IndexShard) IndexClosedException(org.opensearch.indices.IndexClosedException) StreamInput(org.opensearch.common.io.stream.StreamInput) ClusterServiceUtils.createClusterService(org.opensearch.test.ClusterServiceUtils.createClusterService) TransportRequest(org.opensearch.transport.TransportRequest) AllocationId(org.opensearch.cluster.routing.AllocationId) ClusterBlockLevel(org.opensearch.cluster.block.ClusterBlockLevel) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ClusterStateCreationUtils.stateWithActivePrimary(org.opensearch.action.support.replication.ClusterStateCreationUtils.stateWithActivePrimary) Mockito.when(org.mockito.Mockito.when) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) Mockito.verify(org.mockito.Mockito.verify) ShardRouting(org.opensearch.cluster.routing.ShardRouting) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting) CapturingTransport(org.opensearch.test.transport.CapturingTransport) Collections(java.util.Collections) ClusterState(org.opensearch.cluster.ClusterState) MockTransportService(org.opensearch.test.transport.MockTransportService) IndexShard(org.opensearch.index.shard.IndexShard) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) CloseIndexRequest(org.opensearch.action.admin.indices.close.CloseIndexRequest) TransportRequest(org.opensearch.transport.TransportRequest) TransportResponse(org.opensearch.transport.TransportResponse) ShardId(org.opensearch.index.shard.ShardId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ActionListener(org.opensearch.action.ActionListener) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) MockNioTransport(org.opensearch.transport.nio.MockNioTransport) NetworkService(org.opensearch.common.network.NetworkService) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting) Transport(org.opensearch.transport.Transport) MockNioTransport(org.opensearch.transport.nio.MockNioTransport) CapturingTransport(org.opensearch.test.transport.CapturingTransport) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService)

Example 10 with TransportResponse

use of org.opensearch.transport.TransportResponse in project OpenSearch by opensearch-project.

the class TransportReplicationActionTests method testRetryOnReplica.

/**
 * test throwing a {@link org.opensearch.action.support.replication.TransportReplicationAction.RetryOnReplicaException}
 * causes a retry
 */
public void testRetryOnReplica() throws Exception {
    final ShardId shardId = new ShardId("test", "_na_", 0);
    ClusterState state = state(shardId.getIndexName(), true, ShardRoutingState.STARTED, ShardRoutingState.STARTED);
    final ShardRouting replica = state.getRoutingTable().shardRoutingTable(shardId).replicaShards().get(0);
    final long primaryTerm = state.metadata().index(shardId.getIndexName()).primaryTerm(shardId.id());
    // simulate execution of the node holding the replica
    state = ClusterState.builder(state).nodes(DiscoveryNodes.builder(state.nodes()).localNodeId(replica.currentNodeId())).build();
    setState(clusterService, state);
    AtomicBoolean throwException = new AtomicBoolean(true);
    final ReplicationTask task = maybeTask();
    TestAction action = new TestAction(Settings.EMPTY, "internal:testActionWithExceptions", transportService, clusterService, shardStateAction, threadPool) {

        @Override
        protected void shardOperationOnReplica(Request shardRequest, IndexShard replica, ActionListener<ReplicaResult> listener) {
            ActionListener.completeWith(listener, () -> {
                assertPhase(task, "replica");
                if (throwException.get()) {
                    throw new RetryOnReplicaException(shardId, "simulation");
                }
                return new ReplicaResult();
            });
        }
    };
    final PlainActionFuture<TransportResponse> listener = new PlainActionFuture<>();
    final Request request = new Request(shardId);
    final long checkpoint = randomNonNegativeLong();
    final long maxSeqNoOfUpdatesOrDeletes = randomNonNegativeLong();
    action.handleReplicaRequest(new TransportReplicationAction.ConcreteReplicaRequest<>(request, replica.allocationId().getId(), primaryTerm, checkpoint, maxSeqNoOfUpdatesOrDeletes), createTransportChannel(listener), task);
    if (listener.isDone()) {
        // fail with the exception if there
        listener.get();
        fail("listener shouldn't be done");
    }
    // no retry yet
    List<CapturingTransport.CapturedRequest> capturedRequests = transport.getCapturedRequestsByTargetNodeAndClear().get(replica.currentNodeId());
    assertThat(capturedRequests, nullValue());
    // release the waiting
    throwException.set(false);
    setState(clusterService, state);
    capturedRequests = transport.getCapturedRequestsByTargetNodeAndClear().get(replica.currentNodeId());
    assertThat(capturedRequests, notNullValue());
    assertThat(capturedRequests.size(), equalTo(1));
    final CapturingTransport.CapturedRequest capturedRequest = capturedRequests.get(0);
    assertThat(capturedRequest.action, equalTo("internal:testActionWithExceptions[r]"));
    assertThat(capturedRequest.request, instanceOf(TransportReplicationAction.ConcreteReplicaRequest.class));
    assertThat(((TransportReplicationAction.ConcreteReplicaRequest) capturedRequest.request).getGlobalCheckpoint(), equalTo(checkpoint));
    assertThat(((TransportReplicationAction.ConcreteReplicaRequest) capturedRequest.request).getMaxSeqNoOfUpdatesOrDeletes(), equalTo(maxSeqNoOfUpdatesOrDeletes));
    assertConcreteShardRequest(capturedRequest.request, request, replica.allocationId());
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) IndexShard(org.opensearch.index.shard.IndexShard) CapturingTransport(org.opensearch.test.transport.CapturingTransport) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) CloseIndexRequest(org.opensearch.action.admin.indices.close.CloseIndexRequest) TransportRequest(org.opensearch.transport.TransportRequest) TransportResponse(org.opensearch.transport.TransportResponse) ShardId(org.opensearch.index.shard.ShardId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ActionListener(org.opensearch.action.ActionListener) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting)

Aggregations

TransportResponse (org.opensearch.transport.TransportResponse)17 TransportRequest (org.opensearch.transport.TransportRequest)11 PlainActionFuture (org.opensearch.action.support.PlainActionFuture)8 Mockito.anyString (org.mockito.Mockito.anyString)7 IOException (java.io.IOException)6 ActionListener (org.opensearch.action.ActionListener)6 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)6 ShardRouting (org.opensearch.cluster.routing.ShardRouting)6 TestShardRouting (org.opensearch.cluster.routing.TestShardRouting)6 ClusterService (org.opensearch.cluster.service.ClusterService)6 TransportResponseHandler (org.opensearch.transport.TransportResponseHandler)6 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)5 CloseIndexRequest (org.opensearch.action.admin.indices.close.CloseIndexRequest)5 CreateIndexRequest (org.opensearch.action.admin.indices.create.CreateIndexRequest)5 TransportAddress (org.opensearch.common.transport.TransportAddress)5 ShardId (org.opensearch.index.shard.ShardId)5 TransportRequestOptions (org.opensearch.transport.TransportRequestOptions)5 Matchers.hasToString (org.hamcrest.Matchers.hasToString)4 ActionFilters (org.opensearch.action.support.ActionFilters)4 TestTransportChannel (org.opensearch.transport.TestTransportChannel)4