org.elasticsearch.transport.TransportResponseHandler Java Examples
The following examples show how to use
org.elasticsearch.transport.TransportResponseHandler.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransportClearVotingConfigExclusionsActionTests.java From crate with Apache License 2.0 | 6 votes |
private TransportResponseHandler<ClearVotingConfigExclusionsResponse> responseHandler( Consumer<ClearVotingConfigExclusionsResponse> onResponse, Consumer<TransportException> onException) { return new TransportResponseHandler<ClearVotingConfigExclusionsResponse>() { @Override public void handleResponse(ClearVotingConfigExclusionsResponse response) { onResponse.accept(response); } @Override public void handleException(TransportException exp) { onException.accept(exp); } @Override public String executor() { return Names.SAME; } @Override public ClearVotingConfigExclusionsResponse read(StreamInput in) throws IOException { return new ClearVotingConfigExclusionsResponse(in); } }; }
Example #2
Source File: TransportAddVotingConfigExclusionsActionTests.java From crate with Apache License 2.0 | 6 votes |
private TransportResponseHandler<AddVotingConfigExclusionsResponse> responseHandler( Consumer<AddVotingConfigExclusionsResponse> onResponse, Consumer<TransportException> onException) { return new TransportResponseHandler<AddVotingConfigExclusionsResponse>() { @Override public void handleResponse(AddVotingConfigExclusionsResponse response) { onResponse.accept(response); } @Override public void handleException(TransportException exp) { onException.accept(exp); } @Override public String executor() { return Names.SAME; } @Override public AddVotingConfigExclusionsResponse read(StreamInput in) throws IOException { return new AddVotingConfigExclusionsResponse(in); } }; }
Example #3
Source File: MockTransport.java From crate with Apache License 2.0 | 6 votes |
/** * simulate a response for the given requestId */ @SuppressWarnings("unchecked") public <Response extends TransportResponse> void handleResponse(final long requestId, final Response response) { final TransportResponseHandler<Response> transportResponseHandler = (TransportResponseHandler<Response>) responseHandlers.onResponseReceived(requestId, listener); if (transportResponseHandler != null) { final Response deliveredResponse; try (BytesStreamOutput output = new BytesStreamOutput()) { response.writeTo(output); deliveredResponse = transportResponseHandler.read( new NamedWriteableAwareStreamInput(output.bytes().streamInput(), writeableRegistry())); } catch (IOException | UnsupportedOperationException e) { throw new AssertionError("failed to serialize/deserialize response " + response, e); } transportResponseHandler.handleResponse(deliveredResponse); } }
Example #4
Source File: Transports.java From crate with Apache License 2.0 | 6 votes |
public <TRequest extends TransportRequest, TResponse extends TransportResponse> void sendRequest( String action, String node, TRequest request, ActionListener<TResponse> listener, TransportResponseHandler<TResponse> handler, TransportRequestOptions options) { DiscoveryNode discoveryNode = clusterService.state().nodes().get(node); if (discoveryNode == null) { listener.onFailure(new NodeNotConnectedException(null, String.format(Locale.ENGLISH, "node \"%s\" not found in cluster state!", node))); return; } transportService.sendRequest(discoveryNode, action, request, options, handler); }
Example #5
Source File: TransportBroadcastByNodeAction.java From crate with Apache License 2.0 | 5 votes |
private void sendNodeRequest(final DiscoveryNode node, List<ShardRouting> shards, final int nodeIndex) { try { NodeRequest nodeRequest = new NodeRequest(node.getId(), request, shards); if (task != null) { nodeRequest.setParentTask(clusterService.localNode().getId(), task.getId()); } transportService.sendRequest(node, transportNodeBroadcastAction, nodeRequest, new TransportResponseHandler<NodeResponse>() { @Override public NodeResponse read(StreamInput in) throws IOException { return new NodeResponse(in); } @Override public void handleResponse(NodeResponse response) { onNodeResponse(node, nodeIndex, response); } @Override public void handleException(TransportException exp) { onNodeFailure(node, nodeIndex, exp); } @Override public String executor() { return ThreadPool.Names.SAME; } }); } catch (Exception e) { onNodeFailure(node, nodeIndex, e); } }
Example #6
Source File: TransportsTest.java From crate with Apache License 2.0 | 5 votes |
@Test public void testOnFailureOnListenerIsCalledIfNodeIsNotInClusterState() throws Exception { Transports transports = new Transports(clusterService, mock(TransportService.class)); ActionListener actionListener = mock(ActionListener.class); transports.sendRequest("actionName", "invalid", mock(TransportRequest.class), actionListener, mock(TransportResponseHandler.class)); verify(actionListener, times(1)).onFailure(any(ConnectTransportException.class)); }
Example #7
Source File: Transports.java From crate with Apache License 2.0 | 5 votes |
public <TRequest extends TransportRequest, TResponse extends TransportResponse> void sendRequest( String action, String node, TRequest request, ActionListener<TResponse> listener, TransportResponseHandler<TResponse> handler) { sendRequest(action, node, request, listener, handler, TransportRequestOptions.EMPTY); }
Example #8
Source File: TransportReplicationAction.java From crate with Apache License 2.0 | 5 votes |
private void performAction(final DiscoveryNode node, final String action, final boolean isPrimaryAction, final TransportRequest requestToPerform) { transportService.sendRequest(node, action, requestToPerform, transportOptions, new TransportResponseHandler<Response>() { @Override public Response read(StreamInput in) throws IOException { return TransportReplicationAction.this.read(in); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(Response response) { finishOnSuccess(response); } @Override public void handleException(TransportException exp) { try { // if we got disconnected from the node, or the node / shard is not in the right state (being closed) final Throwable cause = exp.unwrapCause(); if (cause instanceof ConnectTransportException || cause instanceof NodeClosedException || (isPrimaryAction && retryPrimaryException(cause))) { logger.trace(() -> new ParameterizedMessage( "received an error from node [{}] for request [{}], scheduling a retry", node.getId(), requestToPerform), exp); retry(exp); } else { finishAsFailed(exp); } } catch (Exception e) { e.addSuppressed(exp); finishWithUnexpectedFailure(e); } } }); }
Example #9
Source File: SnapshotShardsService.java From crate with Apache License 2.0 | 5 votes |
/** Updates the shard snapshot status by sending a {@link UpdateIndexShardSnapshotStatusRequest} to the master node */ private void sendSnapshotShardUpdate(final Snapshot snapshot, final ShardId shardId, final ShardSnapshotStatus status) { remoteFailedRequestDeduplicator.executeOnce( new UpdateIndexShardSnapshotStatusRequest(snapshot, shardId, status), new ActionListener<>() { @Override public void onResponse(Void aVoid) { LOGGER.trace("[{}] [{}] updated snapshot state", snapshot, status); } @Override public void onFailure(Exception e) { LOGGER.warn( () -> new ParameterizedMessage("[{}] [{}] failed to update snapshot state", snapshot, status), e); } }, (req, reqListener) -> transportService.sendRequest(transportService.getLocalNode(), UPDATE_SNAPSHOT_STATUS_ACTION_NAME, req, new TransportResponseHandler<UpdateIndexShardSnapshotStatusResponse>() { @Override public UpdateIndexShardSnapshotStatusResponse read(StreamInput in) throws IOException { return new UpdateIndexShardSnapshotStatusResponse(); } @Override public void handleResponse(UpdateIndexShardSnapshotStatusResponse response) { reqListener.onResponse(null); } @Override public void handleException(TransportException exp) { reqListener.onFailure(exp); } @Override public String executor() { return ThreadPool.Names.SAME; } }) ); }
Example #10
Source File: TransportIT.java From uavstack with Apache License 2.0 | 5 votes |
@Override public Object postProcess(Object res, TransportResponseHandler t, Object proxy, Method method, Object[] args) { if (method.getName().equals("handleResponse")) { doEnd(method, args, 1, null); } else if (method.getName().equals("handleException")){ doEnd(method, args, -1, (Throwable)args[0]); } return res; }
Example #11
Source File: Transports.java From Elasticsearch with Apache License 2.0 | 5 votes |
public <TRequest extends TransportRequest, TResponse extends TransportResponse> void sendRequest( String actionName, String node, TRequest request, ActionListener<TResponse> listener, TransportResponseHandler<TResponse> transportResponseHandler) { DiscoveryNode discoveryNode = clusterService.state().nodes().get(node); if (discoveryNode == null) { listener.onFailure(new IllegalArgumentException( String.format(Locale.ENGLISH, "node \"%s\" not found in cluster state!", node))); return; } transportService.sendRequest(discoveryNode, actionName, request, transportResponseHandler); }
Example #12
Source File: SyncedFlushService.java From crate with Apache License 2.0 | 5 votes |
/** * returns the number of in flight operations on primary. -1 upon error. */ protected void getInflightOpsCount(final ShardId shardId, ClusterState state, IndexShardRoutingTable shardRoutingTable, final ActionListener<InFlightOpsResponse> listener) { try { final ShardRouting primaryShard = shardRoutingTable.primaryShard(); final DiscoveryNode primaryNode = state.nodes().get(primaryShard.currentNodeId()); if (primaryNode == null) { LOGGER.trace("{} failed to resolve node for primary shard {}, skipping sync", shardId, primaryShard); listener.onResponse(new InFlightOpsResponse(-1)); return; } LOGGER.trace("{} retrieving in flight operation count", shardId); transportService.sendRequest(primaryNode, IN_FLIGHT_OPS_ACTION_NAME, new InFlightOpsRequest(shardId), new TransportResponseHandler<InFlightOpsResponse>() { @Override public InFlightOpsResponse read(StreamInput in) throws IOException { return new InFlightOpsResponse(in); } @Override public void handleResponse(InFlightOpsResponse response) { listener.onResponse(response); } @Override public void handleException(TransportException exp) { LOGGER.debug("{} unexpected error while retrieving in flight op count", shardId); listener.onFailure(exp); } @Override public String executor() { return ThreadPool.Names.SAME; } }); } catch (Exception e) { listener.onFailure(e); } }
Example #13
Source File: LocalAllocateDangledIndices.java From crate with Apache License 2.0 | 5 votes |
public void allocateDangled(Collection<IndexMetaData> indices, final Listener listener) { ClusterState clusterState = clusterService.state(); DiscoveryNode masterNode = clusterState.nodes().getMasterNode(); if (masterNode == null) { listener.onFailure(new MasterNotDiscoveredException("no master to send allocate dangled request")); return; } AllocateDangledRequest request = new AllocateDangledRequest(clusterService.localNode(), indices.toArray(new IndexMetaData[indices.size()])); transportService.sendRequest(masterNode, ACTION_NAME, request, new TransportResponseHandler<AllocateDangledResponse>() { @Override public AllocateDangledResponse read(StreamInput in) throws IOException { return new AllocateDangledResponse(in); } @Override public void handleResponse(AllocateDangledResponse response) { listener.onResponse(response); } @Override public void handleException(TransportException exp) { listener.onFailure(exp); } @Override public String executor() { return ThreadPool.Names.SAME; } }); }
Example #14
Source File: PreVoteCollector.java From crate with Apache License 2.0 | 5 votes |
void start(final Iterable<DiscoveryNode> broadcastNodes) { LOGGER.debug("{} requesting pre-votes from {}", this, broadcastNodes); broadcastNodes.forEach(n -> transportService.sendRequest(n, REQUEST_PRE_VOTE_ACTION_NAME, preVoteRequest, new TransportResponseHandler<PreVoteResponse>() { @Override public PreVoteResponse read(StreamInput in) throws IOException { return new PreVoteResponse(in); } @Override public void handleResponse(PreVoteResponse response) { handlePreVoteResponse(response, n); } @Override public void handleException(TransportException exp) { LOGGER.debug(new ParameterizedMessage("{} failed", this), exp); } @Override public String executor() { return Names.GENERIC; } @Override public String toString() { return "TransportResponseHandler{" + PreVoteCollector.this + ", node=" + n + '}'; } })); }
Example #15
Source File: AnomalyResultTests.java From anomaly-detection with Apache License 2.0 | 4 votes |
public void alertingRequestTemplate(boolean anomalyResultIndexExists) throws IOException { // These constructors register handler in transport service new RCFResultTransportAction( new ActionFilters(Collections.emptySet()), transportService, normalModelManager, adCircuitBreakerService ); new ThresholdResultTransportAction(new ActionFilters(Collections.emptySet()), transportService, normalModelManager); new AnomalyResultTransportAction( new ActionFilters(Collections.emptySet()), transportService, settings, stateManager, runner, featureQuery, normalModelManager, hashRing, clusterService, indexNameResolver, adCircuitBreakerService, adStats ); TransportRequestOptions option = TransportRequestOptions .builder() .withType(TransportRequestOptions.Type.STATE) .withTimeout(6000) .build(); transportService .sendRequest( clusterService.state().nodes().getLocalNode(), AnomalyResultAction.NAME, new AnomalyResultRequest(adID, 100, 200), option, new TransportResponseHandler<AnomalyResultResponse>() { @Override public AnomalyResultResponse read(StreamInput in) throws IOException { return new AnomalyResultResponse(in); } @Override public void handleResponse(AnomalyResultResponse response) { assertAnomalyResultResponse(response, 0, 1, 0d); } @Override public void handleException(TransportException exp) { assertThat(exp, is(nullValue())); } @Override public String executor() { return ThreadPool.Names.GENERIC; } } ); }
Example #16
Source File: TransportResyncReplicationAction.java From crate with Apache License 2.0 | 4 votes |
@Override public void sync(ResyncReplicationRequest request, Task parentTask, String primaryAllocationId, long primaryTerm, ActionListener<ReplicationResponse> listener) { // skip reroute phase transportService.sendChildRequest( clusterService.localNode(), transportPrimaryAction, new ConcreteShardRequest<>(request, primaryAllocationId, primaryTerm), parentTask, transportOptions, new TransportResponseHandler<ReplicationResponse>() { @Override public ReplicationResponse read(StreamInput in) throws IOException { return TransportResyncReplicationAction.this.read(in); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(ReplicationResponse response) { final ReplicationResponse.ShardInfo.Failure[] failures = response.getShardInfo().getFailures(); // noinspection ForLoopReplaceableByForEach for (int i = 0; i < failures.length; i++) { final ReplicationResponse.ShardInfo.Failure f = failures[i]; logger.info( new ParameterizedMessage( "{} primary-replica resync to replica on node [{}] failed", f.fullShardId(), f.nodeId()), f.getCause()); } listener.onResponse(response); } @Override public void handleException(TransportException exp) { listener.onFailure(exp); } }); }
Example #17
Source File: TransportNodesAction.java From crate with Apache License 2.0 | 4 votes |
void start() { final DiscoveryNode[] nodes = request.concreteNodes(); if (nodes.length == 0) { // nothing to notify threadPool.generic().execute(() -> listener.onResponse(newResponse(request, responses))); return; } TransportRequestOptions.Builder builder = TransportRequestOptions.builder(); if (request.timeout() != null) { builder.withTimeout(request.timeout()); } builder.withCompress(transportCompress()); for (int i = 0; i < nodes.length; i++) { final int idx = i; final DiscoveryNode node = nodes[i]; final String nodeId = node.getId(); try { TransportRequest nodeRequest = newNodeRequest(nodeId, request); if (task != null) { nodeRequest.setParentTask(clusterService.localNode().getId(), task.getId()); } transportService.sendRequest( node, transportNodeAction, nodeRequest, builder.build(), new TransportResponseHandler<NodeResponse>() { @Override public NodeResponse read(StreamInput in) throws IOException { return TransportNodesAction.this.read(in); } @Override public void handleResponse(NodeResponse response) { onOperation(idx, response); } @Override public void handleException(TransportException exp) { onFailure(idx, node.getId(), exp); } @Override public String executor() { return ThreadPool.Names.SAME; } } ); } catch (Exception e) { onFailure(idx, nodeId, e); } } }
Example #18
Source File: TransportIT.java From uavstack with Apache License 2.0 | 4 votes |
@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; }
Example #19
Source File: FollowersChecker.java From crate with Apache License 2.0 | 4 votes |
private void handleWakeUp() { if (running() == false) { LOGGER.trace("handleWakeUp: not running"); return; } final FollowerCheckRequest request = new FollowerCheckRequest(fastResponseState.term, transportService.getLocalNode()); LOGGER.trace("handleWakeUp: checking {} with {}", discoveryNode, request); transportService.sendRequest(discoveryNode, FOLLOWER_CHECK_ACTION_NAME, request, TransportRequestOptions.builder().withTimeout(followerCheckTimeout).withType(Type.PING).build(), new TransportResponseHandler<Empty>() { @Override public Empty read(StreamInput in) { return Empty.INSTANCE; } @Override public void handleResponse(Empty response) { if (running() == false) { LOGGER.trace("{} no longer running", FollowerChecker.this); return; } failureCountSinceLastSuccess = 0; LOGGER.trace("{} check successful", FollowerChecker.this); scheduleNextWakeUp(); } @Override public void handleException(TransportException exp) { if (running() == false) { LOGGER.debug(new ParameterizedMessage("{} no longer running", FollowerChecker.this), exp); return; } failureCountSinceLastSuccess++; final String reason; if (failureCountSinceLastSuccess >= followerCheckRetryCount) { LOGGER.debug(() -> new ParameterizedMessage("{} failed too many times", FollowerChecker.this), exp); reason = "followers check retry count exceeded"; } else if (exp instanceof ConnectTransportException || exp.getCause() instanceof ConnectTransportException) { LOGGER.debug(() -> new ParameterizedMessage("{} disconnected", FollowerChecker.this), exp); reason = "disconnected"; } else { LOGGER.debug(() -> new ParameterizedMessage("{} failed, retrying", FollowerChecker.this), exp); scheduleNextWakeUp(); return; } failNode(reason); } @Override public String executor() { return Names.SAME; } }); }
Example #20
Source File: TransportAddVotingConfigExclusionsActionTests.java From crate with Apache License 2.0 | 4 votes |
private TransportResponseHandler<AddVotingConfigExclusionsResponse> expectSuccess( Consumer<AddVotingConfigExclusionsResponse> onResponse) { return responseHandler(onResponse, e -> { throw new AssertionError("unexpected", e); }); }
Example #21
Source File: TransportAddVotingConfigExclusionsActionTests.java From crate with Apache License 2.0 | 4 votes |
private TransportResponseHandler<AddVotingConfigExclusionsResponse> expectError(Consumer<TransportException> onException) { return responseHandler(r -> { assert false : r; }, onException); }
Example #22
Source File: TransportIT.java From uavstack with Apache License 2.0 | 4 votes |
@Override public void catchInvokeException(TransportResponseHandler t, Object proxy, Method method, Object[] args, Throwable e) { doEnd(method, args, -1, e); }
Example #23
Source File: TransportClearVotingConfigExclusionsActionTests.java From crate with Apache License 2.0 | 4 votes |
private TransportResponseHandler<ClearVotingConfigExclusionsResponse> expectSuccess( Consumer<ClearVotingConfigExclusionsResponse> onResponse) { return responseHandler(onResponse, e -> { throw new AssertionError("unexpected", e); }); }
Example #24
Source File: TransportClearVotingConfigExclusionsActionTests.java From crate with Apache License 2.0 | 4 votes |
private TransportResponseHandler<ClearVotingConfigExclusionsResponse> expectError(Consumer<TransportException> onException) { return responseHandler(r -> { assert false : r; }, onException); }
Example #25
Source File: LeaderChecker.java From crate with Apache License 2.0 | 4 votes |
void handleWakeUp() { if (isClosed.get()) { LOGGER.trace("closed check scheduler woken up, doing nothing"); return; } LOGGER.trace("checking {} with [{}] = {}", leader, LEADER_CHECK_TIMEOUT_SETTING.getKey(), leaderCheckTimeout); transportService.sendRequest(leader, LEADER_CHECK_ACTION_NAME, new LeaderCheckRequest(transportService.getLocalNode()), TransportRequestOptions.builder().withTimeout(leaderCheckTimeout).withType(Type.PING).build(), new TransportResponseHandler<TransportResponse.Empty>() { @Override public Empty read(StreamInput in) { return Empty.INSTANCE; } @Override public void handleResponse(Empty response) { if (isClosed.get()) { LOGGER.debug("closed check scheduler received a response, doing nothing"); return; } failureCountSinceLastSuccess.set(0); scheduleNextWakeUp(); // logs trace message indicating success } @Override public void handleException(TransportException exp) { if (isClosed.get()) { LOGGER.debug("closed check scheduler received a response, doing nothing"); return; } if (exp instanceof ConnectTransportException || exp.getCause() instanceof ConnectTransportException) { LOGGER.debug(new ParameterizedMessage("leader [{}] disconnected, failing immediately", leader), exp); leaderFailed(); return; } long failureCount = failureCountSinceLastSuccess.incrementAndGet(); if (failureCount >= leaderCheckRetryCount) { LOGGER.debug(new ParameterizedMessage("{} consecutive failures (limit [{}] is {}) so leader [{}] has failed", failureCount, LEADER_CHECK_RETRY_COUNT_SETTING.getKey(), leaderCheckRetryCount, leader), exp); leaderFailed(); return; } LOGGER.debug(new ParameterizedMessage("{} consecutive failures (limit [{}] is {}) with leader [{}]", failureCount, LEADER_CHECK_RETRY_COUNT_SETTING.getKey(), leaderCheckRetryCount, leader), exp); scheduleNextWakeUp(); } @Override public String executor() { return Names.SAME; } }); }
Example #26
Source File: MockTransport.java From crate with Apache License 2.0 | 3 votes |
/** * simulate an error for the given requestId, unlike * {@link #handleLocalError(long, Throwable)} and * {@link #handleRemoteError(long, Throwable)}, the provided * exception will not be wrapped but will be delivered to the * transport layer as is * * @param requestId the id corresponding to the captured send * request * @param e the failure */ public void handleError(final long requestId, final TransportException e) { final TransportResponseHandler transportResponseHandler = responseHandlers.onResponseReceived(requestId, listener); if (transportResponseHandler != null) { transportResponseHandler.handleException(e); } }
Example #27
Source File: TransportIT.java From uavstack with Apache License 2.0 | 2 votes |
@Override public void preProcess(TransportResponseHandler t, Object proxy, Method method, Object[] args) { }