Search in sources :

Example 1 with RemotingException

use of com.alipay.sofa.jraft.error.RemotingException in project sofa-jraft by sofastack.

the class GrpcClient method invokeSync.

@Override
public Object invokeSync(final Endpoint endpoint, final Object request, final InvokeContext ctx, final long timeoutMs) throws RemotingException {
    final CompletableFuture<Object> future = new CompletableFuture<>();
    invokeAsync(endpoint, request, ctx, (result, err) -> {
        if (err == null) {
            future.complete(result);
        } else {
            future.completeExceptionally(err);
        }
    }, timeoutMs);
    try {
        return future.get(timeoutMs, TimeUnit.MILLISECONDS);
    } catch (final TimeoutException e) {
        future.cancel(true);
        throw new InvokeTimeoutException(e);
    } catch (final Throwable t) {
        future.cancel(true);
        throw new RemotingException(t);
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) InvokeTimeoutException(com.alipay.sofa.jraft.error.InvokeTimeoutException) RemotingException(com.alipay.sofa.jraft.error.RemotingException) TimeoutException(java.util.concurrent.TimeoutException) InvokeTimeoutException(com.alipay.sofa.jraft.error.InvokeTimeoutException)

Example 2 with RemotingException

use of com.alipay.sofa.jraft.error.RemotingException in project sofa-jraft by sofastack.

the class DefaultRaftClientService method onConnectionFail.

// fail-fast when no connection
private Future<Message> onConnectionFail(final Endpoint endpoint, final Message request, Closure done, final Executor executor) {
    final FutureImpl<Message> future = new FutureImpl<>();
    executor.execute(() -> {
        final String fmt = "Check connection[%s] fail and try to create new one";
        if (done != null) {
            try {
                done.run(new Status(RaftError.EINTERNAL, fmt, endpoint));
            } catch (final Throwable t) {
                LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
            }
        }
        if (!future.isDone()) {
            future.failure(new RemotingException(String.format(fmt, endpoint)));
        }
    });
    return future;
}
Also used : Status(com.alipay.sofa.jraft.Status) Message(com.google.protobuf.Message) FutureImpl(com.alipay.sofa.jraft.rpc.impl.FutureImpl) RemotingException(com.alipay.sofa.jraft.error.RemotingException)

Example 3 with RemotingException

use of com.alipay.sofa.jraft.error.RemotingException in project sofa-jraft by sofastack.

the class AbstractClientService method invokeWithDone.

public <T extends Message> Future<Message> invokeWithDone(final Endpoint endpoint, final Message request, final InvokeContext ctx, final RpcResponseClosure<T> done, final int timeoutMs, final Executor rpcExecutor) {
    final RpcClient rc = this.rpcClient;
    final FutureImpl<Message> future = new FutureImpl<>();
    final Executor currExecutor = rpcExecutor != null ? rpcExecutor : this.rpcExecutor;
    try {
        if (rc == null) {
            future.failure(new IllegalStateException("Client service is uninitialized."));
            // should be in another thread to avoid dead locking.
            RpcUtils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTERNAL, "Client service is uninitialized."));
            return future;
        }
        rc.invokeAsync(endpoint, request, ctx, new InvokeCallback() {

            @SuppressWarnings({ "unchecked", "ConstantConditions" })
            @Override
            public void complete(final Object result, final Throwable err) {
                if (future.isCancelled()) {
                    onCanceled(request, done);
                    return;
                }
                if (err == null) {
                    Status status = Status.OK();
                    Message msg;
                    if (result instanceof ErrorResponse) {
                        status = handleErrorResponse((ErrorResponse) result);
                        msg = (Message) result;
                    } else if (result instanceof Message) {
                        final Descriptors.FieldDescriptor fd = // 
                        ((Message) result).getDescriptorForType().findFieldByNumber(RpcResponseFactory.ERROR_RESPONSE_NUM);
                        if (fd != null && ((Message) result).hasField(fd)) {
                            final ErrorResponse eResp = (ErrorResponse) ((Message) result).getField(fd);
                            status = handleErrorResponse(eResp);
                            msg = eResp;
                        } else {
                            msg = (T) result;
                        }
                    } else {
                        msg = (T) result;
                    }
                    if (done != null) {
                        try {
                            if (status.isOk()) {
                                done.setResponse((T) msg);
                            }
                            done.run(status);
                        } catch (final Throwable t) {
                            LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
                        }
                    }
                    if (!future.isDone()) {
                        future.setResult(msg);
                    }
                } else {
                    if (done != null) {
                        try {
                            done.run(new Status(err instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT : RaftError.EINTERNAL, "RPC exception:" + err.getMessage()));
                        } catch (final Throwable t) {
                            LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
                        }
                    }
                    if (!future.isDone()) {
                        future.failure(err);
                    }
                }
            }

            @Override
            public Executor executor() {
                return currExecutor;
            }
        }, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs);
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
        future.failure(e);
        // should be in another thread to avoid dead locking.
        RpcUtils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTR, "Sending rpc was interrupted"));
    } catch (final RemotingException e) {
        future.failure(e);
        // should be in another thread to avoid dead locking.
        RpcUtils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage()));
    }
    return future;
}
Also used : Status(com.alipay.sofa.jraft.Status) InvokeCallback(com.alipay.sofa.jraft.rpc.InvokeCallback) InvokeTimeoutException(com.alipay.sofa.jraft.error.InvokeTimeoutException) Message(com.google.protobuf.Message) ErrorResponse(com.alipay.sofa.jraft.rpc.RpcRequests.ErrorResponse) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Executor(java.util.concurrent.Executor) RemotingException(com.alipay.sofa.jraft.error.RemotingException) Descriptors(com.google.protobuf.Descriptors) RpcClient(com.alipay.sofa.jraft.rpc.RpcClient)

Example 4 with RemotingException

use of com.alipay.sofa.jraft.error.RemotingException in project sofa-jraft by sofastack.

the class AbstractClientService method connect.

@Override
public boolean connect(final Endpoint endpoint) {
    final RpcClient rc = this.rpcClient;
    if (rc == null) {
        throw new IllegalStateException("Client service is uninitialized.");
    }
    if (isConnected(rc, endpoint)) {
        return true;
    }
    try {
        final PingRequest req = // 
        PingRequest.newBuilder().setSendTimestamp(// 
        System.currentTimeMillis()).build();
        final ErrorResponse resp = (ErrorResponse) rc.invokeSync(endpoint, req, this.rpcOptions.getRpcConnectTimeoutMs());
        return resp.getErrorCode() == 0;
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    } catch (final RemotingException e) {
        LOG.error("Fail to connect {}, remoting exception: {}.", endpoint, e.getMessage());
        return false;
    }
}
Also used : PingRequest(com.alipay.sofa.jraft.rpc.RpcRequests.PingRequest) RemotingException(com.alipay.sofa.jraft.error.RemotingException) RpcClient(com.alipay.sofa.jraft.rpc.RpcClient) ErrorResponse(com.alipay.sofa.jraft.rpc.RpcRequests.ErrorResponse)

Example 5 with RemotingException

use of com.alipay.sofa.jraft.error.RemotingException in project sofa-jraft by sofastack.

the class GrpcClient method invokeAsync.

@Override
public void invokeAsync(final Endpoint endpoint, final Object request, final InvokeContext ctx, final InvokeCallback callback, final long timeoutMs) {
    Requires.requireNonNull(endpoint, "endpoint");
    Requires.requireNonNull(request, "request");
    final Executor executor = callback.executor() != null ? callback.executor() : DirectExecutor.INSTANCE;
    final Channel ch = getCheckedChannel(endpoint);
    if (ch == null) {
        executor.execute(() -> callback.complete(null, new RemotingException("Fail to connect: " + endpoint)));
        return;
    }
    final MethodDescriptor<Message, Message> method = getCallMethod(request);
    final CallOptions callOpts = CallOptions.DEFAULT.withDeadlineAfter(timeoutMs, TimeUnit.MILLISECONDS);
    ClientCalls.asyncUnaryCall(ch.newCall(method, callOpts), (Message) request, new StreamObserver<Message>() {

        @Override
        public void onNext(final Message value) {
            executor.execute(() -> callback.complete(value, null));
        }

        @Override
        public void onError(final Throwable throwable) {
            executor.execute(() -> callback.complete(null, throwable));
        }

        @Override
        public void onCompleted() {
        // NO-OP
        }
    });
}
Also used : Executor(java.util.concurrent.Executor) DirectExecutor(com.alipay.sofa.jraft.util.DirectExecutor) Message(com.google.protobuf.Message) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) RemotingException(com.alipay.sofa.jraft.error.RemotingException) CallOptions(io.grpc.CallOptions)

Aggregations

RemotingException (com.alipay.sofa.jraft.error.RemotingException)8 Message (com.google.protobuf.Message)4 ErrorResponse (com.alipay.sofa.jraft.rpc.RpcRequests.ErrorResponse)3 Status (com.alipay.sofa.jraft.Status)2 InvokeTimeoutException (com.alipay.sofa.jraft.error.InvokeTimeoutException)2 RpcClient (com.alipay.sofa.jraft.rpc.RpcClient)2 PingRequest (com.alipay.sofa.jraft.rpc.RpcRequests.PingRequest)2 Executor (java.util.concurrent.Executor)2 Test (org.junit.Test)2 InvokeCallback (com.alipay.sofa.jraft.rpc.InvokeCallback)1 FutureImpl (com.alipay.sofa.jraft.rpc.impl.FutureImpl)1 DirectExecutor (com.alipay.sofa.jraft.util.DirectExecutor)1 Descriptors (com.google.protobuf.Descriptors)1 RpcResponse (com.jd.blockchain.consensus.raft.rpc.RpcResponse)1 CallOptions (io.grpc.CallOptions)1 Channel (io.grpc.Channel)1 ManagedChannel (io.grpc.ManagedChannel)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ExecutionException (java.util.concurrent.ExecutionException)1 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)1