org.elasticsearch.action.ActionListenerResponseHandler Java Examples

The following examples show how to use org.elasticsearch.action.ActionListenerResponseHandler. 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: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public void sendFreeContext(DiscoveryNode node, final long contextId, SearchRequest request) {
    transportService.sendRequest(node, FREE_CONTEXT_ACTION_NAME, new SearchFreeContextRequest(request, contextId), new ActionListenerResponseHandler<SearchFreeContextResponse>(new ActionListener<SearchFreeContextResponse>() {
        @Override
        public void onResponse(SearchFreeContextResponse response) {
            // no need to respond if it was freed or not
        }

        @Override
        public void onFailure(Throwable e) {

        }
    }) {
        @Override
        public SearchFreeContextResponse newInstance() {
            return new SearchFreeContextResponse();
        }
    });
}
 
Example #2
Source File: TransportAnalyzeAction.java    From crate with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<AcknowledgedResponse> publishTableStats(Map<RelationName, Stats> newTableStats) {
    List<DiscoveryNode> nodesOn41OrAfter = StreamSupport.stream(clusterService.state().nodes().spliterator(), false)
        .filter(x -> x.getVersion().onOrAfter(Version.V_4_1_0))
        .collect(Collectors.toList());
    var listener = new FutureActionListener<AcknowledgedResponse, AcknowledgedResponse>(x -> x);
    var multiListener = new MultiActionListener<>(
        nodesOn41OrAfter.size(),
        Collectors.reducing(
            new AcknowledgedResponse(true),
            (resp1, resp2) -> new AcknowledgedResponse(resp1.isAcknowledged() && resp2.isAcknowledged())
        ),
        listener
    );
    var responseHandler = new ActionListenerResponseHandler<>(
        multiListener,
        AcknowledgedResponse::new,
        ThreadPool.Names.SAME
    );
    PublishTableStatsRequest request = new PublishTableStatsRequest(newTableStats);
    for (DiscoveryNode node : nodesOn41OrAfter) {
        transportService.sendRequest(node, RECEIVE_TABLE_STATS, request, responseHandler);
    }
    return listener;
}
 
Example #3
Source File: TransportNodeStatsAction.java    From crate with Apache License 2.0 6 votes vote down vote up
public void execute(final String nodeName,
                    final NodeStatsRequest request,
                    final ActionListener<NodeStatsResponse> listener,
                    final TimeValue timeout) {
    TransportRequestOptions options = TransportRequestOptions.builder()
        .withTimeout(timeout)
        .build();

    transports.sendRequest(
        ACTION_NAME,
        nodeName,
        request,
        listener,
        new ActionListenerResponseHandler<>(listener, NodeStatsResponse::new),
        options
    );
}
 
Example #4
Source File: RemoteRecoveryTargetHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public void indexTranslogOperations(List<Translog.Operation> operations,
                                    int totalTranslogOps,
                                    long maxSeenAutoIdTimestampOnPrimary,
                                    long maxSeqNoOfDeletesOrUpdatesOnPrimary,
                                    ActionListener<Long> listener) {
    final RecoveryTranslogOperationsRequest request = new RecoveryTranslogOperationsRequest(
        recoveryId,
        shardId,
        operations,
        totalTranslogOps,
        maxSeenAutoIdTimestampOnPrimary,
        maxSeqNoOfDeletesOrUpdatesOnPrimary);
    transportService.submitRequest(
        targetNode,
        PeerRecoveryTargetService.Actions.TRANSLOG_OPS,
        request,
        translogOpsRequestOptions,
        new ActionListenerResponseHandler<>(
            ActionListener.wrap(
                r -> listener.onResponse(r.localCheckpoint), listener::onFailure),
            RecoveryTranslogOperationsResponse::new,
            ThreadPool.Names.GENERIC)
    );
}
 
Example #5
Source File: TransportAnalyzeAction.java    From crate with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<Samples> fetchSamples(RelationName relationName, List<Reference> columns) {
    FutureActionListener<FetchSampleResponse, Samples> listener = new FutureActionListener<>(FetchSampleResponse::samples);
    List<DiscoveryNode> nodesOn41OrAfter = StreamSupport.stream(clusterService.state().nodes().spliterator(), false)
        .filter(x -> x.getVersion().onOrAfter(Version.V_4_1_0))
        .collect(Collectors.toList());
    MultiActionListener<FetchSampleResponse, ?, FetchSampleResponse> multiListener = new MultiActionListener<>(
        nodesOn41OrAfter.size(),
        Collectors.reducing(
            new FetchSampleResponse(Samples.EMPTY),
            (FetchSampleResponse s1, FetchSampleResponse s2) -> FetchSampleResponse.merge(TransportAnalyzeAction.NUM_SAMPLES, s1, s2)),
        listener
    );
    List<Streamer> streamers = Arrays.asList(Symbols.streamerArray(columns));
    ActionListenerResponseHandler<FetchSampleResponse> responseHandler = new ActionListenerResponseHandler<>(
        multiListener,
        in -> new FetchSampleResponse(streamers, in),
        ThreadPool.Names.SAME
    );
    for (DiscoveryNode node : nodesOn41OrAfter) {
        transportService.sendRequest(
            node,
            FETCH_SAMPLES,
            new FetchSampleRequest(relationName, columns, TransportAnalyzeAction.NUM_SAMPLES),
            responseHandler
        );
    }
    return listener;
}
 
Example #6
Source File: TransportDecommissionNodeAction.java    From crate with Apache License 2.0 5 votes vote down vote up
public void execute(final String nodeId,
                    final DecommissionNodeRequest request,
                    final ActionListener<AcknowledgedResponse> listener) {
    transports.sendRequest(
        ACTION_NAME,
        nodeId,
        request,
        listener,
        new ActionListenerResponseHandler<>(listener, AcknowledgedResponse::new)
    );
}
 
Example #7
Source File: TransportFetchNodeAction.java    From crate with Apache License 2.0 5 votes vote down vote up
public void execute(String targetNode,
                    final IntObjectMap<Streamer[]> streamers,
                    final NodeFetchRequest request,
                    RamAccounting ramAccounting,
                    ActionListener<NodeFetchResponse> listener) {
    transports.sendRequest(TRANSPORT_ACTION, targetNode, request, listener,
        new ActionListenerResponseHandler<>(listener, in -> new NodeFetchResponse(in, streamers, ramAccounting)));
}
 
Example #8
Source File: TransportReplicationAction.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the specified replica request to the specified node.
 *
 * @param replicaRequest the replica request
 * @param node           the node to send the request to
 * @param listener       callback for handling the response or failure
 */
protected void sendReplicaRequest(
        final ConcreteReplicaRequest<ReplicaRequest> replicaRequest,
        final DiscoveryNode node,
        final ActionListener<ReplicationOperation.ReplicaResponse> listener) {
    final ActionListenerResponseHandler<ReplicaResponse> handler = new ActionListenerResponseHandler<>(listener, ReplicaResponse::new);
    transportService.sendRequest(node, transportReplicaAction, replicaRequest, transportOptions, handler);
}
 
Example #9
Source File: RemoteRecoveryTargetHandler.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void writeFileChunk(StoreFileMetaData fileMetaData,
                           long position,
                           BytesReference content,
                           boolean lastChunk,
                           int totalTranslogOps,
                           ActionListener<Void> listener) {
    // Pause using the rate limiter, if desired, to throttle the recovery
    final long throttleTimeInNanos;
    // always fetch the ratelimiter - it might be updated in real-time on the recovery settings
    final RateLimiter rl = recoverySettings.rateLimiter();
    if (rl != null) {
        long bytes = bytesSinceLastPause.addAndGet(content.length());
        if (bytes > rl.getMinPauseCheckBytes()) {
            // Time to pause
            bytesSinceLastPause.addAndGet(-bytes);
            try {
                throttleTimeInNanos = rl.pause(bytes);
                onSourceThrottle.accept(throttleTimeInNanos);
            } catch (IOException e) {
                throw new ElasticsearchException("failed to pause recovery", e);
            }
        } else {
            throttleTimeInNanos = 0;
        }
    } else {
        throttleTimeInNanos = 0;
    }

    transportService.submitRequest(targetNode, PeerRecoveryTargetService.Actions.FILE_CHUNK,
        new RecoveryFileChunkRequest(recoveryId, shardId, fileMetaData, position, content, lastChunk,
            totalTranslogOps,
            /* we send estimateTotalOperations with every request since we collect stats on the target and that way we can
             * see how many translog ops we accumulate while copying files across the network. A future optimization
             * would be in to restart file copy again (new deltas) if we have too many translog ops are piling up.
             */
            throttleTimeInNanos), fileChunkRequestOptions, new ActionListenerResponseHandler<>(
            ActionListener.wrap(r -> listener.onResponse(null), listener::onFailure), in -> TransportResponse.Empty.INSTANCE));
}
 
Example #10
Source File: RemoteRecoveryTargetHandler.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void finalizeRecovery(final long globalCheckpoint, final ActionListener<Void> listener) {
    transportService.submitRequest(
        targetNode,
        PeerRecoveryTargetService.Actions.FINALIZE,
        new RecoveryFinalizeRecoveryRequest(recoveryId, shardId, globalCheckpoint),
        TransportRequestOptions.builder().withTimeout(recoverySettings.internalActionLongTimeout()).build(),
        new ActionListenerResponseHandler<>(
            ActionListener.wrap(r -> listener.onResponse(null), listener::onFailure),
            in -> TransportResponse.Empty.INSTANCE, ThreadPool.Names.GENERIC
        )
    );
}
 
Example #11
Source File: RemoteRecoveryTargetHandler.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void prepareForTranslogOperations(boolean fileBasedRecovery,
                                         int totalTranslogOps,
                                         ActionListener<Void> listener) {
    transportService.submitRequest(
        targetNode,
        PeerRecoveryTargetService.Actions.PREPARE_TRANSLOG,
        new RecoveryPrepareForTranslogOperationsRequest(recoveryId, shardId, totalTranslogOps, fileBasedRecovery),
        TransportRequestOptions.builder().withTimeout(recoverySettings.internalActionTimeout()).build(),
        new ActionListenerResponseHandler<>(
            ActionListener.wrap(r -> listener.onResponse(null), listener::onFailure),
            in -> TransportResponse.Empty.INSTANCE, ThreadPool.Names.GENERIC)
    );
}
 
Example #12
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendExecuteScan(DiscoveryNode node, final InternalScrollSearchRequest request, final ActionListener<ScrollQueryFetchSearchResult> listener) {
    transportService.sendRequest(node, SCAN_SCROLL_ACTION_NAME, request, new ActionListenerResponseHandler<ScrollQueryFetchSearchResult>(listener) {
        @Override
        public ScrollQueryFetchSearchResult newInstance() {
            return new ScrollQueryFetchSearchResult();
        }
    });
}
 
Example #13
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendExecuteScan(DiscoveryNode node, final ShardSearchTransportRequest request, final ActionListener<QuerySearchResult> listener) {
    transportService.sendRequest(node, SCAN_ACTION_NAME, request, new ActionListenerResponseHandler<QuerySearchResult>(listener) {
        @Override
        public QuerySearchResult newInstance() {
            return new QuerySearchResult();
        }
    });
}
 
Example #14
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void sendExecuteFetch(DiscoveryNode node, String action, final ShardFetchRequest request, final ActionListener<FetchSearchResult> listener) {
    transportService.sendRequest(node, action, request, new ActionListenerResponseHandler<FetchSearchResult>(listener) {
        @Override
        public FetchSearchResult newInstance() {
            return new FetchSearchResult();
        }
    });
}
 
Example #15
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendExecuteFetch(DiscoveryNode node, final InternalScrollSearchRequest request, final ActionListener<ScrollQueryFetchSearchResult> listener) {
    transportService.sendRequest(node, QUERY_FETCH_SCROLL_ACTION_NAME, request, new ActionListenerResponseHandler<ScrollQueryFetchSearchResult>(listener) {
        @Override
        public ScrollQueryFetchSearchResult newInstance() {
            return new ScrollQueryFetchSearchResult();
        }
    });
}
 
Example #16
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendExecuteFetch(DiscoveryNode node, final QuerySearchRequest request, final ActionListener<QueryFetchSearchResult> listener) {
    transportService.sendRequest(node, QUERY_QUERY_FETCH_ACTION_NAME, request, new ActionListenerResponseHandler<QueryFetchSearchResult>(listener) {
        @Override
        public QueryFetchSearchResult newInstance() {
            return new QueryFetchSearchResult();
        }
    });
}
 
Example #17
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendExecuteFetch(DiscoveryNode node, final ShardSearchTransportRequest request, final ActionListener<QueryFetchSearchResult> listener) {
    transportService.sendRequest(node, QUERY_FETCH_ACTION_NAME, request, new ActionListenerResponseHandler<QueryFetchSearchResult>(listener) {
        @Override
        public QueryFetchSearchResult newInstance() {
            return new QueryFetchSearchResult();
        }
    });
}
 
Example #18
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendExecuteQuery(DiscoveryNode node, final InternalScrollSearchRequest request, final ActionListener<ScrollQuerySearchResult> listener) {
    transportService.sendRequest(node, QUERY_SCROLL_ACTION_NAME, request, new ActionListenerResponseHandler<ScrollQuerySearchResult>(listener) {
        @Override
        public ScrollQuerySearchResult newInstance() {
            return new ScrollQuerySearchResult();
        }
    });
}
 
Example #19
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendExecuteQuery(DiscoveryNode node, final QuerySearchRequest request, final ActionListener<QuerySearchResult> listener) {
    transportService.sendRequest(node, QUERY_ID_ACTION_NAME, request, new ActionListenerResponseHandler<QuerySearchResult>(listener) {
        @Override
        public QuerySearchResult newInstance() {
            return new QuerySearchResult();
        }
    });
}
 
Example #20
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendExecuteQuery(DiscoveryNode node, final ShardSearchTransportRequest request, final ActionListener<QuerySearchResultProvider> listener) {
    transportService.sendRequest(node, QUERY_ACTION_NAME, request, new ActionListenerResponseHandler<QuerySearchResultProvider>(listener) {
        @Override
        public QuerySearchResult newInstance() {
            return new QuerySearchResult();
        }
    });
}
 
Example #21
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendExecuteDfs(DiscoveryNode node, final ShardSearchTransportRequest request, final ActionListener<DfsSearchResult> listener) {
    transportService.sendRequest(node, DFS_ACTION_NAME, request, new ActionListenerResponseHandler<DfsSearchResult>(listener) {
        @Override
        public DfsSearchResult newInstance() {
            return new DfsSearchResult();
        }
    });
}
 
Example #22
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendClearAllScrollContexts(DiscoveryNode node, ClearScrollRequest request, final ActionListener<TransportResponse> listener) {
    transportService.sendRequest(node, CLEAR_SCROLL_CONTEXTS_ACTION_NAME, new ClearScrollContextsRequest(request), new ActionListenerResponseHandler<TransportResponse>(listener) {
        @Override
        public TransportResponse newInstance() {
            return TransportResponse.Empty.INSTANCE;
        }
    });
}
 
Example #23
Source File: SearchServiceTransportAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void sendFreeContext(DiscoveryNode node, long contextId, ClearScrollRequest request, final ActionListener<SearchFreeContextResponse> listener) {
    transportService.sendRequest(node, FREE_CONTEXT_SCROLL_ACTION_NAME, new ScrollFreeContextRequest(request, contextId), new ActionListenerResponseHandler<SearchFreeContextResponse>(listener) {
        @Override
        public SearchFreeContextResponse newInstance() {
            return new SearchFreeContextResponse();
        }
    });
}
 
Example #24
Source File: TransportMasterNodeAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
protected void doStart() {
    final ClusterState clusterState = observer.observedState();
    final DiscoveryNodes nodes = clusterState.nodes();
    if (nodes.localNodeMaster() || localExecute(request)) {
        // check for block, if blocked, retry, else, execute locally
        final ClusterBlockException blockException = checkBlock(request, clusterState);
        if (blockException != null) {
            if (!blockException.retryable()) {
                listener.onFailure(blockException);
            } else {
                logger.trace("can't execute due to a cluster block, retrying", blockException);
                retry(blockException, retryableOrNoBlockPredicate);
            }
        } else {
            final ActionListener<Response> delegate = new ActionListener<Response>() {
                @Override
                public void onResponse(Response response) {
                    listener.onResponse(response);
                }

                @Override
                public void onFailure(Throwable t) {
                    if (t instanceof NotMasterException) {
                        logger.debug("master could not publish cluster state or stepped down before publishing action [{}], scheduling a retry", t, actionName);
                        retry(t, masterNodeChangedPredicate);
                    } else {
                        listener.onFailure(t);
                    }
                }
            };
            taskManager.registerChildTask(task, nodes.getLocalNodeId());
            threadPool.executor(executor).execute(new ActionRunnable(delegate) {
                @Override
                protected void doRun() throws Exception {
                    masterOperation(task, request, clusterService.state(), delegate);
                }
            });
        }
    } else {
        if (nodes.masterNode() == null) {
            logger.debug("no known master node, scheduling a retry");
            retry(null, masterNodeChangedPredicate);
        } else {
            taskManager.registerChildTask(task, nodes.masterNode().getId());
            transportService.sendRequest(nodes.masterNode(), actionName, request, new ActionListenerResponseHandler<Response>(listener) {
                @Override
                public Response newInstance() {
                    return newResponse();
                }

                @Override
                public void handleException(final TransportException exp) {
                    Throwable cause = exp.unwrapCause();
                    if (cause instanceof ConnectTransportException) {
                        // we want to retry here a bit to see if a new master is elected
                        logger.debug("connection exception while trying to forward request with action name [{}] to master node [{}], scheduling a retry. Error: [{}]",
                                actionName, nodes.masterNode(), exp.getDetailedMessage());
                        retry(cause, masterNodeChangedPredicate);
                    } else {
                        listener.onFailure(exp);
                    }
                }
            });
        }
    }
}
 
Example #25
Source File: TransportDistributedResultAction.java    From crate with Apache License 2.0 4 votes vote down vote up
void pushResult(String node, DistributedResultRequest request, ActionListener<DistributedResultResponse> listener) {
    transports.sendRequest(DISTRIBUTED_RESULT_ACTION, node, request, listener,
        new ActionListenerResponseHandler<>(listener, DistributedResultResponse::new));
}
 
Example #26
Source File: TransportCollectProfileNodeAction.java    From crate with Apache License 2.0 4 votes vote down vote up
public void execute(String nodeId,
                    NodeCollectProfileRequest request,
                    FutureActionListener<NodeCollectProfileResponse, Map<String, Object>> listener) {
    transports.sendRequest(TRANSPORT_ACTION, nodeId, request, listener,
        new ActionListenerResponseHandler<>(listener, NodeCollectProfileResponse::new));
}
 
Example #27
Source File: TransportJobAction.java    From crate with Apache License 2.0 4 votes vote down vote up
public void execute(String node, final JobRequest request, final ActionListener<JobResponse> listener) {
    transports.sendRequest(
        ACTION_NAME, node, request, listener, new ActionListenerResponseHandler<>(listener, JobResponse::new));
}
 
Example #28
Source File: AnomalyResultTransportAction.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
private void handleRCFResults() {
    try {
        if (coldStartIfNoModel(failure, detector)) {
            // fetch previous cold start exception
            Optional<? extends AnomalyDetectionException> previousException = globalRunner.fetchException(adID);

            if (previousException.isPresent()) {
                LOG.error("Previous exception of {}: {}", () -> adID, () -> previousException.get());
                listener.onFailure(previousException.get());
            } else {
                listener.onFailure(new InternalFailure(adID, NO_MODEL_ERR_MSG));
            }
            return;
        }

        if (rcfResults.isEmpty()) {
            listener.onFailure(new InternalFailure(adID, NO_MODEL_ERR_MSG));
            return;
        }

        CombinedRcfResult combinedResult = getCombinedResult(rcfResults);
        double combinedScore = combinedResult.getScore();

        final AtomicReference<AnomalyResultResponse> anomalyResultResponse = new AtomicReference<>();

        String thresholdNodeId = thresholdNode.getId();
        LOG.info("Sending threshold request to {} for model {}", thresholdNodeId, thresholdModelID);
        ThresholdActionListener thresholdListener = new ThresholdActionListener(
            anomalyResultResponse,
            featureInResponse,
            thresholdNodeId,
            detector,
            combinedResult,
            listener,
            adID
        );
        transportService
            .sendRequest(
                thresholdNode,
                ThresholdResultAction.NAME,
                new ThresholdResultRequest(adID, thresholdModelID, combinedScore),
                option,
                new ActionListenerResponseHandler<>(thresholdListener, ThresholdResultResponse::new)
            );
    } catch (Exception ex) {
        handleExecuteException(ex, listener, adID);
    }
}