Search in sources :

Example 16 with Response

use of com.alibaba.nacos.api.remote.response.Response in project nacos by alibaba.

the class GrpcConnection method asyncRequest.

@Override
public void asyncRequest(Request request, final RequestCallBack requestCallBack) throws NacosException {
    Payload grpcRequest = GrpcUtils.convert(request);
    ListenableFuture<Payload> requestFuture = grpcFutureServiceStub.request(grpcRequest);
    // set callback .
    Futures.addCallback(requestFuture, new FutureCallback<Payload>() {

        @Override
        public void onSuccess(@Nullable Payload grpcResponse) {
            Response response = (Response) GrpcUtils.parse(grpcResponse);
            if (response != null) {
                if (response instanceof ErrorResponse) {
                    requestCallBack.onException(new NacosException(response.getErrorCode(), response.getMessage()));
                } else {
                    requestCallBack.onResponse(response);
                }
            } else {
                requestCallBack.onException(new NacosException(ResponseCode.FAIL.getCode(), "response is null"));
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            if (throwable instanceof CancellationException) {
                requestCallBack.onException(new TimeoutException("Timeout after " + requestCallBack.getTimeout() + " milliseconds."));
            } else {
                requestCallBack.onException(throwable);
            }
        }
    }, requestCallBack.getExecutor() != null ? requestCallBack.getExecutor() : this.executor);
    // set timeout future.
    ListenableFuture<Payload> payloadListenableFuture = Futures.withTimeout(requestFuture, requestCallBack.getTimeout(), TimeUnit.MILLISECONDS, RpcScheduledExecutor.TIMEOUT_SCHEDULER);
}
Also used : Response(com.alibaba.nacos.api.remote.response.Response) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse) CancellationException(java.util.concurrent.CancellationException) Payload(com.alibaba.nacos.api.grpc.auto.Payload) NacosException(com.alibaba.nacos.api.exception.NacosException) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse) TimeoutException(java.util.concurrent.TimeoutException)

Example 17 with Response

use of com.alibaba.nacos.api.remote.response.Response in project nacos by alibaba.

the class RpcClient method request.

/**
 * send request.
 *
 * @param request request.
 * @return response from server.
 */
public Response request(Request request, long timeoutMills) throws NacosException {
    int retryTimes = 0;
    Response response;
    Exception exceptionThrow = null;
    long start = System.currentTimeMillis();
    while (retryTimes < RETRY_TIMES && System.currentTimeMillis() < timeoutMills + start) {
        boolean waitReconnect = false;
        try {
            if (this.currentConnection == null || !isRunning()) {
                waitReconnect = true;
                throw new NacosException(NacosException.CLIENT_DISCONNECT, "Client not connected, current status:" + rpcClientStatus.get());
            }
            response = this.currentConnection.request(request, timeoutMills);
            if (response == null) {
                throw new NacosException(SERVER_ERROR, "Unknown Exception.");
            }
            if (response instanceof ErrorResponse) {
                if (response.getErrorCode() == NacosException.UN_REGISTER) {
                    synchronized (this) {
                        waitReconnect = true;
                        if (rpcClientStatus.compareAndSet(RpcClientStatus.RUNNING, RpcClientStatus.UNHEALTHY)) {
                            LoggerUtils.printIfErrorEnabled(LOGGER, "Connection is unregistered, switch server, connectionId = {}, request = {}", currentConnection.getConnectionId(), request.getClass().getSimpleName());
                            switchServerAsync();
                        }
                    }
                }
                throw new NacosException(response.getErrorCode(), response.getMessage());
            }
            // return response.
            lastActiveTimeStamp = System.currentTimeMillis();
            return response;
        } catch (Exception e) {
            if (waitReconnect) {
                try {
                    // wait client to reconnect.
                    Thread.sleep(Math.min(100, timeoutMills / 3));
                } catch (Exception exception) {
                // Do nothing.
                }
            }
            LoggerUtils.printIfErrorEnabled(LOGGER, "Send request fail, request = {}, retryTimes = {}, errorMessage = {}", request, retryTimes, e.getMessage());
            exceptionThrow = e;
        }
        retryTimes++;
    }
    if (rpcClientStatus.compareAndSet(RpcClientStatus.RUNNING, RpcClientStatus.UNHEALTHY)) {
        switchServerAsyncOnRequestFail();
    }
    if (exceptionThrow != null) {
        throw (exceptionThrow instanceof NacosException) ? (NacosException) exceptionThrow : new NacosException(SERVER_ERROR, exceptionThrow);
    } else {
        throw new NacosException(SERVER_ERROR, "Request fail, unknown Error");
    }
}
Also used : ConnectResetResponse(com.alibaba.nacos.api.remote.response.ConnectResetResponse) Response(com.alibaba.nacos.api.remote.response.Response) ClientDetectionResponse(com.alibaba.nacos.api.remote.response.ClientDetectionResponse) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse) NacosException(com.alibaba.nacos.api.exception.NacosException) NacosException(com.alibaba.nacos.api.exception.NacosException) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse)

Example 18 with Response

use of com.alibaba.nacos.api.remote.response.Response in project nacos by alibaba.

the class RpcClient method handleServerRequest.

/**
 * handle server request.
 *
 * @param request request.
 * @return response.
 */
protected Response handleServerRequest(final Request request) {
    LoggerUtils.printIfInfoEnabled(LOGGER, "[{}] Receive server push request, request = {}, requestId = {}", name, request.getClass().getSimpleName(), request.getRequestId());
    lastActiveTimeStamp = System.currentTimeMillis();
    for (ServerRequestHandler serverRequestHandler : serverRequestHandlers) {
        try {
            Response response = serverRequestHandler.requestReply(request);
            if (response != null) {
                LoggerUtils.printIfInfoEnabled(LOGGER, "[{}] Ack server push request, request = {}, requestId = {}", name, request.getClass().getSimpleName(), request.getRequestId());
                return response;
            }
        } catch (Exception e) {
            LoggerUtils.printIfInfoEnabled(LOGGER, "[{}] HandleServerRequest:{}, errorMessage = {}", name, serverRequestHandler.getClass().getName(), e.getMessage());
        }
    }
    return null;
}
Also used : ConnectResetResponse(com.alibaba.nacos.api.remote.response.ConnectResetResponse) Response(com.alibaba.nacos.api.remote.response.Response) ClientDetectionResponse(com.alibaba.nacos.api.remote.response.ClientDetectionResponse) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse) NacosException(com.alibaba.nacos.api.exception.NacosException)

Example 19 with Response

use of com.alibaba.nacos.api.remote.response.Response in project nacos by alibaba.

the class GrpcClient method bindRequestStream.

private StreamObserver<Payload> bindRequestStream(final BiRequestStreamGrpc.BiRequestStreamStub streamStub, final GrpcConnection grpcConn) {
    return streamStub.requestBiStream(new StreamObserver<Payload>() {

        @Override
        public void onNext(Payload payload) {
            LoggerUtils.printIfDebugEnabled(LOGGER, "[{}]Stream server request receive, original info: {}", grpcConn.getConnectionId(), payload.toString());
            try {
                Object parseBody = GrpcUtils.parse(payload);
                final Request request = (Request) parseBody;
                if (request != null) {
                    try {
                        Response response = handleServerRequest(request);
                        if (response != null) {
                            response.setRequestId(request.getRequestId());
                            sendResponse(response);
                        } else {
                            LOGGER.warn("[{}]Fail to process server request, ackId->{}", grpcConn.getConnectionId(), request.getRequestId());
                        }
                    } catch (Exception e) {
                        LoggerUtils.printIfErrorEnabled(LOGGER, "[{}]Handle server request exception: {}", grpcConn.getConnectionId(), payload.toString(), e.getMessage());
                        Response errResponse = ErrorResponse.build(NacosException.CLIENT_ERROR, "Handle server request error");
                        errResponse.setRequestId(request.getRequestId());
                        sendResponse(errResponse);
                    }
                }
            } catch (Exception e) {
                LoggerUtils.printIfErrorEnabled(LOGGER, "[{}]Error to process server push response: {}", grpcConn.getConnectionId(), payload.getBody().getValue().toStringUtf8());
            }
        }

        @Override
        public void onError(Throwable throwable) {
            boolean isRunning = isRunning();
            boolean isAbandon = grpcConn.isAbandon();
            if (isRunning && !isAbandon) {
                LoggerUtils.printIfErrorEnabled(LOGGER, "[{}]Request stream error, switch server,error={}", grpcConn.getConnectionId(), throwable);
                if (rpcClientStatus.compareAndSet(RpcClientStatus.RUNNING, RpcClientStatus.UNHEALTHY)) {
                    switchServerAsync();
                }
            } else {
                LoggerUtils.printIfWarnEnabled(LOGGER, "[{}]Ignore error event,isRunning:{},isAbandon={}", grpcConn.getConnectionId(), isRunning, isAbandon);
            }
        }

        @Override
        public void onCompleted() {
            boolean isRunning = isRunning();
            boolean isAbandon = grpcConn.isAbandon();
            if (isRunning && !isAbandon) {
                LoggerUtils.printIfErrorEnabled(LOGGER, "[{}]Request stream onCompleted, switch server", grpcConn.getConnectionId());
                if (rpcClientStatus.compareAndSet(RpcClientStatus.RUNNING, RpcClientStatus.UNHEALTHY)) {
                    switchServerAsync();
                }
            } else {
                LoggerUtils.printIfInfoEnabled(LOGGER, "[{}]Ignore complete event,isRunning:{},isAbandon={}", grpcConn.getConnectionId(), isRunning, isAbandon);
            }
        }
    });
}
Also used : ServerCheckResponse(com.alibaba.nacos.api.remote.response.ServerCheckResponse) Response(com.alibaba.nacos.api.remote.response.Response) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse) Request(com.alibaba.nacos.api.remote.request.Request) ConnectionSetupRequest(com.alibaba.nacos.api.remote.request.ConnectionSetupRequest) ServerCheckRequest(com.alibaba.nacos.api.remote.request.ServerCheckRequest) Payload(com.alibaba.nacos.api.grpc.auto.Payload) NacosException(com.alibaba.nacos.api.exception.NacosException)

Example 20 with Response

use of com.alibaba.nacos.api.remote.response.Response in project nacos by alibaba.

the class GrpcClient method serverCheck.

/**
 * check server if success.
 *
 * @param requestBlockingStub requestBlockingStub used to check server.
 * @return success or not
 */
private Response serverCheck(String ip, int port, RequestGrpc.RequestFutureStub requestBlockingStub) {
    try {
        if (requestBlockingStub == null) {
            return null;
        }
        ServerCheckRequest serverCheckRequest = new ServerCheckRequest();
        Payload grpcRequest = GrpcUtils.convert(serverCheckRequest);
        ListenableFuture<Payload> responseFuture = requestBlockingStub.request(grpcRequest);
        Payload response = responseFuture.get(3000L, TimeUnit.MILLISECONDS);
        // receive connection unregister response here,not check response is success.
        return (Response) GrpcUtils.parse(response);
    } catch (Exception e) {
        LoggerUtils.printIfErrorEnabled(LOGGER, "Server check fail, please check server {} ,port {} is available , error ={}", ip, port, e);
        return null;
    }
}
Also used : ServerCheckResponse(com.alibaba.nacos.api.remote.response.ServerCheckResponse) Response(com.alibaba.nacos.api.remote.response.Response) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse) ServerCheckRequest(com.alibaba.nacos.api.remote.request.ServerCheckRequest) Payload(com.alibaba.nacos.api.grpc.auto.Payload) NacosException(com.alibaba.nacos.api.exception.NacosException)

Aggregations

Response (com.alibaba.nacos.api.remote.response.Response)31 NacosException (com.alibaba.nacos.api.exception.NacosException)23 Payload (com.alibaba.nacos.api.grpc.auto.Payload)9 ErrorResponse (com.alibaba.nacos.api.remote.response.ErrorResponse)9 Member (com.alibaba.nacos.core.cluster.Member)8 Test (org.junit.Test)7 Request (com.alibaba.nacos.api.remote.request.Request)6 RequestMeta (com.alibaba.nacos.api.remote.request.RequestMeta)6 RequestCallBack (com.alibaba.nacos.api.remote.RequestCallBack)5 ConnectionSetupRequest (com.alibaba.nacos.api.remote.request.ConnectionSetupRequest)4 ServerCheckResponse (com.alibaba.nacos.api.remote.response.ServerCheckResponse)4 DistroDataRequest (com.alibaba.nacos.naming.cluster.remote.request.DistroDataRequest)4 DistroDataResponse (com.alibaba.nacos.naming.cluster.remote.response.DistroDataResponse)4 ConnectResetRequest (com.alibaba.nacos.api.remote.request.ConnectResetRequest)3 HealthCheckRequest (com.alibaba.nacos.api.remote.request.HealthCheckRequest)3 ServerCheckRequest (com.alibaba.nacos.api.remote.request.ServerCheckRequest)3 ConnectResetResponse (com.alibaba.nacos.api.remote.response.ConnectResetResponse)3 ArrayList (java.util.ArrayList)3 LinkedList (java.util.LinkedList)3 InstanceRequest (com.alibaba.nacos.api.naming.remote.request.InstanceRequest)2