Search in sources :

Example 16 with Payload

use of com.alibaba.nacos.api.grpc.auto.Payload 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)

Example 17 with Payload

use of com.alibaba.nacos.api.grpc.auto.Payload in project nacos by alibaba.

the class GrpcRequestAcceptorTest method testHandleRequestError.

@Test
public void testHandleRequestError() {
    ApplicationUtils.setStarted(true);
    Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler);
    Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(true);
    RequestMeta metadata = new RequestMeta();
    metadata.setClientIp("127.0.0.1");
    metadata.setConnectionId(connectId);
    InstanceRequest instanceRequest = new InstanceRequest();
    Payload payload = GrpcUtils.convert(instanceRequest, metadata);
    StreamObserver<Payload> streamObserver = new StreamObserver<Payload>() {

        @Override
        public void onNext(Payload payload) {
            System.out.println("Receive data from server: " + payload);
            Object res = GrpcUtils.parse(payload);
            Assert.assertTrue(res instanceof ErrorResponse);
            ErrorResponse errorResponse = (ErrorResponse) res;
            Assert.assertEquals(errorResponse.getErrorCode(), NacosException.SERVER_ERROR);
        }

        @Override
        public void onError(Throwable throwable) {
            Assert.fail(throwable.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("complete");
        }
    };
    streamStub.request(payload, streamObserver);
    ApplicationUtils.setStarted(false);
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) RequestMeta(com.alibaba.nacos.api.remote.request.RequestMeta) Payload(com.alibaba.nacos.api.grpc.auto.Payload) InstanceRequest(com.alibaba.nacos.api.naming.remote.request.InstanceRequest) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse) Test(org.junit.Test)

Example 18 with Payload

use of com.alibaba.nacos.api.grpc.auto.Payload in project nacos by alibaba.

the class GrpcRequestAcceptorTest method testConnectionNotRegister.

@Test
public void testConnectionNotRegister() {
    ApplicationUtils.setStarted(true);
    Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler);
    Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(false);
    RequestMeta metadata = new RequestMeta();
    metadata.setClientIp("127.0.0.1");
    metadata.setConnectionId(connectId);
    InstanceRequest instanceRequest = new InstanceRequest();
    instanceRequest.setRequestId(requestId);
    Payload request = GrpcUtils.convert(instanceRequest, metadata);
    StreamObserver<Payload> streamObserver = new StreamObserver<Payload>() {

        @Override
        public void onNext(Payload payload) {
            System.out.println("Receive data from server: " + payload);
            Object res = GrpcUtils.parse(payload);
            Assert.assertTrue(res instanceof ErrorResponse);
            ErrorResponse errorResponse = (ErrorResponse) res;
            Assert.assertEquals(errorResponse.getErrorCode(), NacosException.UN_REGISTER);
        }

        @Override
        public void onError(Throwable throwable) {
            Assert.fail(throwable.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("complete");
        }
    };
    streamStub.request(request, streamObserver);
    ApplicationUtils.setStarted(false);
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) RequestMeta(com.alibaba.nacos.api.remote.request.RequestMeta) Payload(com.alibaba.nacos.api.grpc.auto.Payload) InstanceRequest(com.alibaba.nacos.api.naming.remote.request.InstanceRequest) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse) Test(org.junit.Test)

Example 19 with Payload

use of com.alibaba.nacos.api.grpc.auto.Payload in project nacos by alibaba.

the class GrpcBiStreamRequestAcceptor method requestBiStream.

@Override
public StreamObserver<Payload> requestBiStream(StreamObserver<Payload> responseObserver) {
    StreamObserver<Payload> streamObserver = new StreamObserver<Payload>() {

        final String connectionId = CONTEXT_KEY_CONN_ID.get();

        final Integer localPort = CONTEXT_KEY_CONN_LOCAL_PORT.get();

        final int remotePort = CONTEXT_KEY_CONN_REMOTE_PORT.get();

        String remoteIp = CONTEXT_KEY_CONN_REMOTE_IP.get();

        String clientIp = "";

        @Override
        public void onNext(Payload payload) {
            clientIp = payload.getMetadata().getClientIp();
            traceDetailIfNecessary(payload);
            Object parseObj;
            try {
                parseObj = GrpcUtils.parse(payload);
            } catch (Throwable throwable) {
                Loggers.REMOTE_DIGEST.warn("[{}]Grpc request bi stream,payload parse error={}", connectionId, throwable);
                return;
            }
            if (parseObj == null) {
                Loggers.REMOTE_DIGEST.warn("[{}]Grpc request bi stream,payload parse null ,body={},meta={}", connectionId, payload.getBody().getValue().toStringUtf8(), payload.getMetadata());
                return;
            }
            if (parseObj instanceof ConnectionSetupRequest) {
                ConnectionSetupRequest setUpRequest = (ConnectionSetupRequest) parseObj;
                Map<String, String> labels = setUpRequest.getLabels();
                String appName = "-";
                if (labels != null && labels.containsKey(Constants.APPNAME)) {
                    appName = labels.get(Constants.APPNAME);
                }
                ConnectionMeta metaInfo = new ConnectionMeta(connectionId, payload.getMetadata().getClientIp(), remoteIp, remotePort, localPort, ConnectionType.GRPC.getType(), setUpRequest.getClientVersion(), appName, setUpRequest.getLabels());
                metaInfo.setTenant(setUpRequest.getTenant());
                Connection connection = new GrpcConnection(metaInfo, responseObserver, CONTEXT_KEY_CHANNEL.get());
                connection.setAbilities(setUpRequest.getAbilities());
                boolean rejectSdkOnStarting = metaInfo.isSdkSource() && !ApplicationUtils.isStarted();
                if (rejectSdkOnStarting || !connectionManager.register(connectionId, connection)) {
                    // Not register to the connection manager if current server is over limit or server is starting.
                    try {
                        Loggers.REMOTE_DIGEST.warn("[{}]Connection register fail,reason:{}", connectionId, rejectSdkOnStarting ? " server is not started" : " server is over limited.");
                        connection.request(new ConnectResetRequest(), 3000L);
                        connection.close();
                    } catch (Exception e) {
                        // Do nothing.
                        if (connectionManager.traced(clientIp)) {
                            Loggers.REMOTE_DIGEST.warn("[{}]Send connect reset request error,error={}", connectionId, e);
                        }
                    }
                }
            } else if (parseObj instanceof Response) {
                Response response = (Response) parseObj;
                if (connectionManager.traced(clientIp)) {
                    Loggers.REMOTE_DIGEST.warn("[{}]Receive response of server request  ,response={}", connectionId, response);
                }
                RpcAckCallbackSynchronizer.ackNotify(connectionId, response);
                connectionManager.refreshActiveTime(connectionId);
            } else {
                Loggers.REMOTE_DIGEST.warn("[{}]Grpc request bi stream,unknown payload receive ,parseObj={}", connectionId, parseObj);
            }
        }

        @Override
        public void onError(Throwable t) {
            if (connectionManager.traced(clientIp)) {
                Loggers.REMOTE_DIGEST.warn("[{}]Bi stream on error,error={}", connectionId, t);
            }
            if (responseObserver instanceof ServerCallStreamObserver) {
                ServerCallStreamObserver serverCallStreamObserver = ((ServerCallStreamObserver) responseObserver);
                if (serverCallStreamObserver.isCancelled()) {
                // client close the stream.
                } else {
                    try {
                        serverCallStreamObserver.onCompleted();
                    } catch (Throwable throwable) {
                    // ignore
                    }
                }
            }
        }

        @Override
        public void onCompleted() {
            if (connectionManager.traced(clientIp)) {
                Loggers.REMOTE_DIGEST.warn("[{}]Bi stream on completed", connectionId);
            }
            if (responseObserver instanceof ServerCallStreamObserver) {
                ServerCallStreamObserver serverCallStreamObserver = ((ServerCallStreamObserver) responseObserver);
                if (serverCallStreamObserver.isCancelled()) {
                // client close the stream.
                } else {
                    try {
                        serverCallStreamObserver.onCompleted();
                    } catch (Throwable throwable) {
                    // ignore
                    }
                }
            }
        }
    };
    return streamObserver;
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Connection(com.alibaba.nacos.core.remote.Connection) ConnectResetRequest(com.alibaba.nacos.api.remote.request.ConnectResetRequest) Response(com.alibaba.nacos.api.remote.response.Response) Payload(com.alibaba.nacos.api.grpc.auto.Payload) ConnectionMeta(com.alibaba.nacos.core.remote.ConnectionMeta) ConnectionSetupRequest(com.alibaba.nacos.api.remote.request.ConnectionSetupRequest)

Example 20 with Payload

use of com.alibaba.nacos.api.grpc.auto.Payload in project nacos by alibaba.

the class GrpcConnection method sendRequestNoAck.

private void sendRequestNoAck(Request request) throws NacosException {
    try {
        // StreamObserver#onNext() is not thread-safe,synchronized is required to avoid direct memory leak.
        synchronized (streamObserver) {
            Payload payload = GrpcUtils.convert(request);
            traceIfNecessary(payload);
            streamObserver.onNext(payload);
        }
    } catch (Exception e) {
        if (e instanceof StatusRuntimeException) {
            throw new ConnectionAlreadyClosedException(e);
        }
        throw e;
    }
}
Also used : ConnectionAlreadyClosedException(com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException) StatusRuntimeException(io.grpc.StatusRuntimeException) Payload(com.alibaba.nacos.api.grpc.auto.Payload) StatusRuntimeException(io.grpc.StatusRuntimeException) ConnectionAlreadyClosedException(com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException) NacosException(com.alibaba.nacos.api.exception.NacosException)

Aggregations

Payload (com.alibaba.nacos.api.grpc.auto.Payload)22 ErrorResponse (com.alibaba.nacos.api.remote.response.ErrorResponse)12 Response (com.alibaba.nacos.api.remote.response.Response)9 StreamObserver (io.grpc.stub.StreamObserver)9 NacosException (com.alibaba.nacos.api.exception.NacosException)8 RequestMeta (com.alibaba.nacos.api.remote.request.RequestMeta)8 Test (org.junit.Test)8 ServerCheckRequest (com.alibaba.nacos.api.remote.request.ServerCheckRequest)5 ServerCheckResponse (com.alibaba.nacos.api.remote.response.ServerCheckResponse)5 ConnectionSetupRequest (com.alibaba.nacos.api.remote.request.ConnectionSetupRequest)4 InstanceRequest (com.alibaba.nacos.api.naming.remote.request.InstanceRequest)3 Connection (com.alibaba.nacos.core.remote.Connection)3 Metadata (com.alibaba.nacos.api.grpc.auto.Metadata)2 ConnectResetRequest (com.alibaba.nacos.api.remote.request.ConnectResetRequest)2 Request (com.alibaba.nacos.api.remote.request.Request)2 ConnectionMeta (com.alibaba.nacos.core.remote.ConnectionMeta)2 ByteString (com.google.protobuf.ByteString)2 CancellationException (java.util.concurrent.CancellationException)2 TimeoutException (java.util.concurrent.TimeoutException)2 BiRequestStreamGrpc (com.alibaba.nacos.api.grpc.auto.BiRequestStreamGrpc)1