Search in sources :

Example 6 with TransportResponseHandler

use of org.elasticsearch.transport.TransportResponseHandler in project uavstack by uavorg.

the class TransportIT method doAsyncStart.

@SuppressWarnings({ "rawtypes", "unchecked" })
public Object doAsyncStart(Object[] args) {
    DiscoveryNode node = (DiscoveryNode) args[0];
    esAction = (String) args[1];
    TransportResponseHandler handler = (TransportResponseHandler) args[4];
    String address = node.getHostAddress();
    Integer port = node.getAddress().getPort();
    targetURL = "elasticsearch://" + address + ":" + port;
    if (logger.isDebugable()) {
        logger.debug("Elastaicsearch INVOKE START: " + targetURL + " action: " + esAction, null);
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(CaptureConstants.INFO_CLIENT_REQUEST_URL, targetURL);
    params.put(CaptureConstants.INFO_CLIENT_REQUEST_ACTION, esAction);
    params.put(CaptureConstants.INFO_CLIENT_APPID, appid);
    params.put(CaptureConstants.INFO_CLIENT_TYPE, "elasticsearch.client");
    ccMap = UAVServer.instance().runMonitorAsyncCaptureOnServerCapPoint(CaptureConstants.CAPPOINT_APP_CLIENT, Monitor.CapturePhase.PRECAP, params, null);
    // register adapter
    UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "registerAdapter", TransportAdapter.class);
    ivcContextParams = (Map<String, Object>) UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "runCap", InvokeChainConstants.CHAIN_APP_CLIENT, InvokeChainConstants.CapturePhase.PRECAP, params, TransportAdapter.class, args);
    if (handler == null) {
        return null;
    }
    handler = JDKProxyInvokeUtil.newProxyInstance(TransportResponseHandler.class.getClassLoader(), new Class<?>[] { TransportResponseHandler.class }, new JDKProxyInvokeHandler<TransportResponseHandler>(handler, new ESHandlerProxyInvokeProcessor()));
    return handler;
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) HashMap(java.util.HashMap) JDKProxyInvokeHandler(com.creditease.monitor.proxy.spi.JDKProxyInvokeHandler) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler)

Example 7 with TransportResponseHandler

use of org.elasticsearch.transport.TransportResponseHandler in project crate by crate.

the class PeerRecoveryTargetService method doRecovery.

private void doRecovery(final long recoveryId) {
    final StartRecoveryRequest request;
    final RecoveryState.Timer timer;
    CancellableThreads cancellableThreads;
    try (RecoveryRef recoveryRef = onGoingRecoveries.getRecovery(recoveryId)) {
        if (recoveryRef == null) {
            LOGGER.trace("not running recovery with id [{}] - can not find it (probably finished)", recoveryId);
            return;
        }
        final RecoveryTarget recoveryTarget = recoveryRef.target();
        timer = recoveryTarget.state().getTimer();
        cancellableThreads = recoveryTarget.cancellableThreads();
        try {
            assert recoveryTarget.sourceNode() != null : "can not do a recovery without a source node";
            LOGGER.trace("{} preparing shard for peer recovery", recoveryTarget.shardId());
            recoveryTarget.indexShard().prepareForIndexRecovery();
            final long startingSeqNo = recoveryTarget.indexShard().recoverLocallyUpToGlobalCheckpoint();
            assert startingSeqNo == UNASSIGNED_SEQ_NO || recoveryTarget.state().getStage() == RecoveryState.Stage.TRANSLOG : "unexpected recovery stage [" + recoveryTarget.state().getStage() + "] starting seqno [ " + startingSeqNo + "]";
            request = getStartRecoveryRequest(LOGGER, clusterService.localNode(), recoveryTarget, startingSeqNo);
        } catch (final Exception e) {
            // this will be logged as warning later on...
            LOGGER.trace("unexpected error while preparing shard for peer recovery, failing recovery", e);
            onGoingRecoveries.failRecovery(recoveryId, new RecoveryFailedException(recoveryTarget.state(), "failed to prepare shard for recovery", e), true);
            return;
        }
    }
    Consumer<Exception> handleException = e -> {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(() -> new ParameterizedMessage("[{}][{}] Got exception on recovery", request.shardId().getIndex().getName(), request.shardId().id()), e);
        }
        Throwable cause = SQLExceptions.unwrap(e);
        if (cause instanceof CancellableThreads.ExecutionCancelledException) {
            // this can also come from the source wrapped in a RemoteTransportException
            onGoingRecoveries.failRecovery(recoveryId, new RecoveryFailedException(request, "source has canceled the recovery", cause), false);
            return;
        }
        if (cause instanceof RecoveryEngineException) {
            // unwrap an exception that was thrown as part of the recovery
            cause = cause.getCause();
        }
        // do it twice, in case we have double transport exception
        cause = SQLExceptions.unwrap(cause);
        if (cause instanceof RecoveryEngineException) {
            // unwrap an exception that was thrown as part of the recovery
            cause = cause.getCause();
        }
        if (cause instanceof IllegalIndexShardStateException || cause instanceof IndexNotFoundException || cause instanceof ShardNotFoundException) {
            // if the target is not ready yet, retry
            retryRecovery(recoveryId, "remote shard not ready", recoverySettings.retryDelayStateSync(), recoverySettings.activityTimeout());
            return;
        }
        if (cause instanceof DelayRecoveryException) {
            retryRecovery(recoveryId, cause, recoverySettings.retryDelayStateSync(), recoverySettings.activityTimeout());
            return;
        }
        if (cause instanceof ConnectTransportException) {
            LOGGER.debug("delaying recovery of {} for [{}] due to networking error [{}]", request.shardId(), recoverySettings.retryDelayNetwork(), cause.getMessage());
            retryRecovery(recoveryId, cause.getMessage(), recoverySettings.retryDelayNetwork(), recoverySettings.activityTimeout());
            return;
        }
        if (cause instanceof AlreadyClosedException) {
            onGoingRecoveries.failRecovery(recoveryId, new RecoveryFailedException(request, "source shard is closed", cause), false);
            return;
        }
        onGoingRecoveries.failRecovery(recoveryId, new RecoveryFailedException(request, e), true);
    };
    try {
        LOGGER.trace("{} starting recovery from {}", request.shardId(), request.sourceNode());
        cancellableThreads.executeIO(() -> transportService.sendRequest(request.sourceNode(), PeerRecoverySourceService.Actions.START_RECOVERY, request, new TransportResponseHandler<RecoveryResponse>() {

            @Override
            public void handleResponse(RecoveryResponse recoveryResponse) {
                final TimeValue recoveryTime = new TimeValue(timer.time());
                // do this through ongoing recoveries to remove it from the collection
                onGoingRecoveries.markRecoveryAsDone(recoveryId);
                if (LOGGER.isTraceEnabled()) {
                    StringBuilder sb = new StringBuilder();
                    sb.append('[').append(request.shardId().getIndex().getName()).append(']').append('[').append(request.shardId().id()).append("] ");
                    sb.append("recovery completed from ").append(request.sourceNode()).append(", took[").append(recoveryTime).append("]\n");
                    sb.append("   phase1: recovered_files [").append(recoveryResponse.phase1FileNames.size()).append("]").append(" with total_size of [").append(new ByteSizeValue(recoveryResponse.phase1TotalSize)).append("]").append(", took [").append(timeValueMillis(recoveryResponse.phase1Time)).append("], throttling_wait [").append(timeValueMillis(recoveryResponse.phase1ThrottlingWaitTime)).append(']').append("\n");
                    sb.append("         : reusing_files   [").append(recoveryResponse.phase1ExistingFileNames.size()).append("] with total_size of [").append(new ByteSizeValue(recoveryResponse.phase1ExistingTotalSize)).append("]\n");
                    sb.append("   phase2: start took [").append(timeValueMillis(recoveryResponse.startTime)).append("]\n");
                    sb.append("         : recovered [").append(recoveryResponse.phase2Operations).append("]").append(" transaction log operations").append(", took [").append(timeValueMillis(recoveryResponse.phase2Time)).append("]").append("\n");
                    LOGGER.trace("{}", sb);
                } else {
                    LOGGER.debug("{} recovery done from [{}], took [{}]", request.shardId(), request.sourceNode(), recoveryTime);
                }
            }

            @Override
            public void handleException(TransportException e) {
                handleException.accept(e);
            }

            @Override
            public String executor() {
                // we do some heavy work like refreshes in the response so fork off to the generic threadpool
                return ThreadPool.Names.GENERIC;
            }

            @Override
            public RecoveryResponse read(StreamInput in) throws IOException {
                return new RecoveryResponse(in);
            }
        }));
    } catch (CancellableThreads.ExecutionCancelledException e) {
        LOGGER.trace("recovery cancelled", e);
    } catch (Exception e) {
        handleException.accept(e);
    }
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) CancellableThreads(org.elasticsearch.common.util.CancellableThreads) ShardId(org.elasticsearch.index.shard.ShardId) TransportChannel(org.elasticsearch.transport.TransportChannel) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) ClusterService(org.elasticsearch.cluster.service.ClusterService) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) RecoveryEngineException(org.elasticsearch.index.engine.RecoveryEngineException) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) TranslogCorruptedException(org.elasticsearch.index.translog.TranslogCorruptedException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) Settings(org.elasticsearch.common.settings.Settings) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Store(org.elasticsearch.index.store.Store) ChannelActionListener(org.elasticsearch.action.support.ChannelActionListener) ThreadPool(org.elasticsearch.threadpool.ThreadPool) TransportResponse(org.elasticsearch.transport.TransportResponse) TransportService(org.elasticsearch.transport.TransportService) ClusterStateObserver(org.elasticsearch.cluster.ClusterStateObserver) Nullable(javax.annotation.Nullable) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) RecoveryRef(org.elasticsearch.indices.recovery.RecoveriesCollection.RecoveryRef) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) IndexShard(org.elasticsearch.index.shard.IndexShard) UNASSIGNED_SEQ_NO(org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) IOException(java.io.IOException) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) TransportRequestHandler(org.elasticsearch.transport.TransportRequestHandler) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) Logger(org.apache.logging.log4j.Logger) TimeValue.timeValueMillis(io.crate.common.unit.TimeValue.timeValueMillis) StreamInput(org.elasticsearch.common.io.stream.StreamInput) TimeValue(io.crate.common.unit.TimeValue) Translog(org.elasticsearch.index.translog.Translog) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) SQLExceptions(io.crate.exceptions.SQLExceptions) LogManager(org.apache.logging.log4j.LogManager) TransportException(org.elasticsearch.transport.TransportException) RateLimiter(org.apache.lucene.store.RateLimiter) ActionListener(org.elasticsearch.action.ActionListener) MapperException(org.elasticsearch.index.mapper.MapperException) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) RecoveryEngineException(org.elasticsearch.index.engine.RecoveryEngineException) RecoveryRef(org.elasticsearch.indices.recovery.RecoveriesCollection.RecoveryRef) TimeValue(io.crate.common.unit.TimeValue) CancellableThreads(org.elasticsearch.common.util.CancellableThreads) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) TransportException(org.elasticsearch.transport.TransportException) ElasticsearchException(org.elasticsearch.ElasticsearchException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) RecoveryEngineException(org.elasticsearch.index.engine.RecoveryEngineException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) TranslogCorruptedException(org.elasticsearch.index.translog.TranslogCorruptedException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) IOException(java.io.IOException) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) TransportException(org.elasticsearch.transport.TransportException) MapperException(org.elasticsearch.index.mapper.MapperException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) StreamInput(org.elasticsearch.common.io.stream.StreamInput) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage)

Example 8 with TransportResponseHandler

use of org.elasticsearch.transport.TransportResponseHandler in project crate by crate.

the class TransportKillNodeAction method broadcast.

public void broadcast(Request request, ActionListener<Long> listener, Collection<String> excludedNodeIds) {
    Stream<DiscoveryNode> nodes = StreamSupport.stream(clusterService.state().nodes().spliterator(), false);
    Collection<DiscoveryNode> filteredNodes = nodes.filter(node -> !excludedNodeIds.contains(node.getId())).collect(Collectors.toList());
    MultiActionListener<KillResponse, ?, Long> multiListener = new MultiActionListener<>(filteredNodes.size(), Collectors.summingLong(KillResponse::numKilled), listener);
    TransportResponseHandler<KillResponse> responseHandler = new ActionListenerResponseHandler<>(multiListener, KillResponse::new);
    for (DiscoveryNode node : filteredNodes) {
        transportService.sendRequest(node, name, request, responseHandler);
    }
}
Also used : TransportRequest(org.elasticsearch.transport.TransportRequest) Collection(java.util.Collection) NodeActionRequestHandler(io.crate.execution.support.NodeActionRequestHandler) ClusterService(org.elasticsearch.cluster.service.ClusterService) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) Collectors(java.util.stream.Collectors) MultiActionListener(io.crate.execution.support.MultiActionListener) TasksService(io.crate.execution.jobs.TasksService) NodeAction(io.crate.execution.support.NodeAction) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Stream(java.util.stream.Stream) ActionListenerResponseHandler(org.elasticsearch.action.ActionListenerResponseHandler) StreamInput(org.elasticsearch.common.io.stream.StreamInput) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) ThreadPool(org.elasticsearch.threadpool.ThreadPool) StreamSupport(java.util.stream.StreamSupport) TransportService(org.elasticsearch.transport.TransportService) Writeable(org.elasticsearch.common.io.stream.Writeable) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MultiActionListener(io.crate.execution.support.MultiActionListener) ActionListenerResponseHandler(org.elasticsearch.action.ActionListenerResponseHandler)

Example 9 with TransportResponseHandler

use of org.elasticsearch.transport.TransportResponseHandler in project crate by crate.

the class PublicationTransportHandler method sendClusterStateToNode.

private void sendClusterStateToNode(ClusterState clusterState, BytesReference bytes, DiscoveryNode node, ActionListener<PublishWithJoinResponse> responseActionListener, boolean sendDiffs, Map<Version, BytesReference> serializedStates) {
    try {
        final BytesTransportRequest request = new BytesTransportRequest(bytes, node.getVersion());
        final Consumer<TransportException> transportExceptionHandler = exp -> {
            if (sendDiffs && exp.unwrapCause() instanceof IncompatibleClusterStateVersionException) {
                LOGGER.debug("resending full cluster state to node {} reason {}", node, exp.getDetailedMessage());
                sendFullClusterState(clusterState, serializedStates, node, responseActionListener);
            } else {
                LOGGER.debug(() -> new ParameterizedMessage("failed to send cluster state to {}", node), exp);
                responseActionListener.onFailure(exp);
            }
        };
        final TransportResponseHandler<PublishWithJoinResponse> publishWithJoinResponseHandler = new TransportResponseHandler<PublishWithJoinResponse>() {

            @Override
            public PublishWithJoinResponse read(StreamInput in) throws IOException {
                return new PublishWithJoinResponse(in);
            }

            @Override
            public void handleResponse(PublishWithJoinResponse response) {
                responseActionListener.onResponse(response);
            }

            @Override
            public void handleException(TransportException exp) {
                transportExceptionHandler.accept(exp);
            }

            @Override
            public String executor() {
                return ThreadPool.Names.GENERIC;
            }
        };
        transportService.sendRequest(node, PUBLISH_STATE_ACTION_NAME, request, stateRequestOptions, publishWithJoinResponseHandler);
    } catch (Exception e) {
        LOGGER.warn(() -> new ParameterizedMessage("error sending cluster state to {}", node), e);
        responseActionListener.onFailure(e);
    }
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) StreamOutput(org.elasticsearch.common.io.stream.StreamOutput) TransportChannel(org.elasticsearch.transport.TransportChannel) IncompatibleClusterStateVersionException(org.elasticsearch.cluster.IncompatibleClusterStateVersionException) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) HashMap(java.util.HashMap) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Diff(org.elasticsearch.cluster.Diff) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) ThreadPool(org.elasticsearch.threadpool.ThreadPool) TransportResponse(org.elasticsearch.transport.TransportResponse) TransportService(org.elasticsearch.transport.TransportService) BytesTransportRequest(org.elasticsearch.transport.BytesTransportRequest) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) Compressor(org.elasticsearch.common.compress.Compressor) IOUtils(io.crate.common.io.IOUtils) IOException(java.io.IOException) BytesReference(org.elasticsearch.common.bytes.BytesReference) ClusterChangedEvent(org.elasticsearch.cluster.ClusterChangedEvent) CompressorFactory(org.elasticsearch.common.compress.CompressorFactory) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) Logger(org.apache.logging.log4j.Logger) Version(org.elasticsearch.Version) StreamInput(org.elasticsearch.common.io.stream.StreamInput) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) TransportRequestOptions(org.elasticsearch.transport.TransportRequestOptions) LogManager(org.apache.logging.log4j.LogManager) TransportException(org.elasticsearch.transport.TransportException) ActionListener(org.elasticsearch.action.ActionListener) BytesTransportRequest(org.elasticsearch.transport.BytesTransportRequest) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.elasticsearch.common.io.stream.StreamInput) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) IncompatibleClusterStateVersionException(org.elasticsearch.cluster.IncompatibleClusterStateVersionException) TransportException(org.elasticsearch.transport.TransportException) ElasticsearchException(org.elasticsearch.ElasticsearchException) IncompatibleClusterStateVersionException(org.elasticsearch.cluster.IncompatibleClusterStateVersionException) IOException(java.io.IOException) TransportException(org.elasticsearch.transport.TransportException)

Example 10 with TransportResponseHandler

use of org.elasticsearch.transport.TransportResponseHandler in project crate by crate.

the class TransportReplicationAllPermitsAcquisitionTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    globalBlock = randomBoolean();
    RestStatus restStatus = randomFrom(RestStatus.values());
    block = new ClusterBlock(randomIntBetween(1, 10), randomAlphaOfLength(5), false, true, false, restStatus, ClusterBlockLevel.ALL);
    clusterService = createClusterService(threadPool);
    final ClusterState.Builder state = ClusterState.builder(clusterService.state());
    Set<DiscoveryNodeRole> roles = new HashSet<>(DiscoveryNodeRole.BUILT_IN_ROLES);
    DiscoveryNode node1 = new DiscoveryNode("_name1", "_node1", buildNewFakeTransportAddress(), emptyMap(), roles, Version.CURRENT);
    DiscoveryNode node2 = new DiscoveryNode("_name2", "_node2", buildNewFakeTransportAddress(), emptyMap(), roles, Version.CURRENT);
    state.nodes(DiscoveryNodes.builder().add(node1).add(node2).localNodeId(node1.getId()).masterNodeId(node1.getId()));
    shardId = new ShardId("index", UUID.randomUUID().toString(), 0);
    ShardRouting shardRouting = newShardRouting(shardId, node1.getId(), true, ShardRoutingState.INITIALIZING, RecoverySource.EmptyStoreRecoverySource.INSTANCE);
    Settings indexSettings = Settings.builder().put(SETTING_VERSION_CREATED, Version.CURRENT).put(SETTING_INDEX_UUID, shardId.getIndex().getUUID()).put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 1).put(SETTING_CREATION_DATE, System.currentTimeMillis()).build();
    primary = newStartedShard(p -> newShard(shardRouting, indexSettings, new InternalEngineFactory()), true);
    for (int i = 0; i < 10; i++) {
        final String id = Integer.toString(i);
        indexDoc(primary, id, "{\"value\":" + id + "}");
    }
    IndexMetadata indexMetadata = IndexMetadata.builder(shardId.getIndexName()).settings(indexSettings).primaryTerm(shardId.id(), primary.getOperationPrimaryTerm()).putMapping("default", "{ \"properties\": { \"value\":  { \"type\": \"short\"}}}").build();
    state.metadata(Metadata.builder().put(indexMetadata, false).generateClusterUuidIfNeeded());
    replica = newShard(primary.shardId(), false, node2.getId(), indexMetadata, null);
    recoverReplica(replica, primary, true);
    IndexRoutingTable.Builder routing = IndexRoutingTable.builder(indexMetadata.getIndex());
    routing.addIndexShard(new IndexShardRoutingTable.Builder(shardId).addShard(primary.routingEntry()).build());
    state.routingTable(RoutingTable.builder().add(routing.build()).build());
    setState(clusterService, state.build());
    final Settings transportSettings = Settings.builder().put("node.name", node1.getId()).build();
    MockTransport transport = new MockTransport() {

        @Override
        protected void onSendRequest(long requestId, String action, TransportRequest request, DiscoveryNode node) {
            assertThat(action, allOf(startsWith("cluster:admin/test/"), endsWith("[r]")));
            assertThat(node, equalTo(node2));
            // node2 doesn't really exist, but we are performing some trickery in mockIndicesService() to pretend that node1 holds both
            // the primary and the replica, so redirect the request back to node1.
            transportService.sendRequest(transportService.getLocalNode(), action, request, new TransportResponseHandler<TransportReplicationAction.ReplicaResponse>() {

                @Override
                public ReplicaResponse read(StreamInput in) throws IOException {
                    return new ReplicaResponse(in);
                }

                @SuppressWarnings("unchecked")
                private TransportResponseHandler<TransportReplicationAction.ReplicaResponse> getResponseHandler() {
                    return (TransportResponseHandler<TransportReplicationAction.ReplicaResponse>) getResponseHandlers().onResponseReceived(requestId, TransportMessageListener.NOOP_LISTENER);
                }

                @Override
                public void handleResponse(TransportReplicationAction.ReplicaResponse response) {
                    getResponseHandler().handleResponse(response);
                }

                @Override
                public void handleException(TransportException exp) {
                    getResponseHandler().handleException(exp);
                }

                @Override
                public String executor() {
                    return ThreadPool.Names.SAME;
                }
            });
        }
    };
    transportService = transport.createTransportService(transportSettings, threadPool, bta -> node1, null);
    transportService.start();
    transportService.acceptIncomingRequests();
    shardStateAction = new ShardStateAction(clusterService, transportService, null, null);
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) TransportRequest(org.elasticsearch.transport.TransportRequest) SETTING_VERSION_CREATED(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_VERSION_CREATED) ClusterServiceUtils.createClusterService(org.elasticsearch.test.ClusterServiceUtils.createClusterService) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) ClusterState(org.elasticsearch.cluster.ClusterState) TransportMessageListener(org.elasticsearch.transport.TransportMessageListener) Settings(org.elasticsearch.common.settings.Settings) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) After(org.junit.After) Matchers.nullValue(org.hamcrest.Matchers.nullValue) ThreadPool(org.elasticsearch.threadpool.ThreadPool) InternalEngineFactory(org.elasticsearch.index.engine.InternalEngineFactory) Releasable(org.elasticsearch.common.lease.Releasable) CyclicBarrier(java.util.concurrent.CyclicBarrier) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Matchers.allOf(org.hamcrest.Matchers.allOf) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) Set(java.util.Set) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) UUID(java.util.UUID) Matchers.startsWith(org.hamcrest.Matchers.startsWith) Objects(java.util.Objects) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) List(java.util.List) Version(org.elasticsearch.Version) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) RestStatus(org.elasticsearch.rest.RestStatus) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TimeValue(io.crate.common.unit.TimeValue) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) DiscoveryNodeRole(org.elasticsearch.cluster.node.DiscoveryNodeRole) SETTING_INDEX_UUID(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_INDEX_UUID) TransportException(org.elasticsearch.transport.TransportException) Matchers.endsWith(org.hamcrest.Matchers.endsWith) Mockito.mock(org.mockito.Mockito.mock) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) SETTING_NUMBER_OF_SHARDS(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS) TransportChannel(org.elasticsearch.transport.TransportChannel) ClusterService(org.elasticsearch.cluster.service.ClusterService) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) ArrayList(java.util.ArrayList) TestShardRouting.newShardRouting(org.elasticsearch.cluster.routing.TestShardRouting.newShardRouting) HashSet(java.util.HashSet) Metadata(org.elasticsearch.cluster.metadata.Metadata) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) SETTING_NUMBER_OF_REPLICAS(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS) ReplicaResponse(org.elasticsearch.action.support.replication.TransportReplicationAction.ReplicaResponse) TransportResponse(org.elasticsearch.transport.TransportResponse) IndicesService(org.elasticsearch.indices.IndicesService) TransportService(org.elasticsearch.transport.TransportService) ClusterBlockLevel(org.elasticsearch.cluster.block.ClusterBlockLevel) Before(org.junit.Before) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) SetOnce(org.apache.lucene.util.SetOnce) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) MockTransport(org.elasticsearch.test.transport.MockTransport) Test(org.junit.Test) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) SETTING_CREATION_DATE(org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_CREATION_DATE) Mockito.when(org.mockito.Mockito.when) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) IndexShardTestCase(org.elasticsearch.index.shard.IndexShardTestCase) Matchers.hasItem(org.hamcrest.Matchers.hasItem) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) StreamInput(org.elasticsearch.common.io.stream.StreamInput) ClusterServiceUtils.setState(org.elasticsearch.test.ClusterServiceUtils.setState) ActionListener(org.elasticsearch.action.ActionListener) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) DiscoveryNodeRole(org.elasticsearch.cluster.node.DiscoveryNodeRole) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) ShardId(org.elasticsearch.index.shard.ShardId) InternalEngineFactory(org.elasticsearch.index.engine.InternalEngineFactory) MockTransport(org.elasticsearch.test.transport.MockTransport) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Settings(org.elasticsearch.common.settings.Settings) HashSet(java.util.HashSet) ClusterState(org.elasticsearch.cluster.ClusterState) TransportRequest(org.elasticsearch.transport.TransportRequest) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) IOException(java.io.IOException) TransportException(org.elasticsearch.transport.TransportException) RestStatus(org.elasticsearch.rest.RestStatus) StreamInput(org.elasticsearch.common.io.stream.StreamInput) ReplicaResponse(org.elasticsearch.action.support.replication.TransportReplicationAction.ReplicaResponse) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) TestShardRouting.newShardRouting(org.elasticsearch.cluster.routing.TestShardRouting.newShardRouting) ReplicaResponse(org.elasticsearch.action.support.replication.TransportReplicationAction.ReplicaResponse) Before(org.junit.Before)

Aggregations

TransportResponseHandler (org.elasticsearch.transport.TransportResponseHandler)10 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)8 IOException (java.io.IOException)7 TransportException (org.elasticsearch.transport.TransportException)7 ThreadPool (org.elasticsearch.threadpool.ThreadPool)6 TransportResponse (org.elasticsearch.transport.TransportResponse)6 TransportService (org.elasticsearch.transport.TransportService)6 ActionListener (org.elasticsearch.action.ActionListener)5 StreamInput (org.elasticsearch.common.io.stream.StreamInput)5 Settings (org.elasticsearch.common.settings.Settings)5 TransportRequest (org.elasticsearch.transport.TransportRequest)5 ElasticsearchException (org.elasticsearch.ElasticsearchException)4 ClusterState (org.elasticsearch.cluster.ClusterState)4 ClusterService (org.elasticsearch.cluster.service.ClusterService)4 TransportChannel (org.elasticsearch.transport.TransportChannel)4 ConnectTransportException (org.elasticsearch.transport.ConnectTransportException)3 TransportRequestOptions (org.elasticsearch.transport.TransportRequestOptions)3 TimeValue (io.crate.common.unit.TimeValue)2 HashMap (java.util.HashMap)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2