Search in sources :

Example 6 with Connection

use of com.alibaba.nacos.core.remote.Connection in project nacos by alibaba.

the class CommunicationController method getSubClientConfigByIp.

/**
 * Get client config listener lists of subscriber in local machine.
 */
@GetMapping("/watcherConfigs")
public SampleResult getSubClientConfigByIp(HttpServletRequest request, HttpServletResponse response, @RequestParam("ip") String ip, ModelMap modelMap) {
    SampleResult result = longPollingService.getCollectSubscribleInfoByIp(ip);
    List<Connection> connectionsByIp = connectionManager.getConnectionByIp(ip);
    for (Connection connectionByIp : connectionsByIp) {
        Map<String, String> listenKeys = configChangeListenContext.getListenKeys(connectionByIp.getMetaInfo().getConnectionId());
        if (listenKeys != null) {
            result.getLisentersGroupkeyStatus().putAll(listenKeys);
        }
    }
    return result;
}
Also used : Connection(com.alibaba.nacos.core.remote.Connection) SampleResult(com.alibaba.nacos.config.server.model.SampleResult) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 7 with Connection

use of com.alibaba.nacos.core.remote.Connection in project nacos by alibaba.

the class CommunicationController method getSubClientConfig.

/**
 * Get client config information of subscriber in local machine.
 */
@GetMapping("/configWatchers")
public SampleResult getSubClientConfig(@RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam(value = "tenant", required = false) String tenant, ModelMap modelMap) {
    group = StringUtils.isBlank(group) ? Constants.DEFAULT_GROUP : group;
    // long polling listners.
    SampleResult result = longPollingService.getCollectSubscribleInfo(dataId, group, tenant);
    // rpc listeners.
    String groupKey = GroupKey2.getKey(dataId, group, tenant);
    Set<String> listenersClients = configChangeListenContext.getListeners(groupKey);
    if (CollectionUtils.isEmpty(listenersClients)) {
        return result;
    }
    Map<String, String> lisentersGroupkeyStatus = new HashMap<>(listenersClients.size(), 1);
    for (String connectionId : listenersClients) {
        Connection client = connectionManager.getConnection(connectionId);
        if (client != null) {
            String md5 = configChangeListenContext.getListenKeyMd5(connectionId, groupKey);
            if (md5 != null) {
                lisentersGroupkeyStatus.put(client.getMetaInfo().getClientIp(), md5);
            }
        }
    }
    result.getLisentersGroupkeyStatus().putAll(lisentersGroupkeyStatus);
    return result;
}
Also used : HashMap(java.util.HashMap) Connection(com.alibaba.nacos.core.remote.Connection) SampleResult(com.alibaba.nacos.config.server.model.SampleResult) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 8 with Connection

use of com.alibaba.nacos.core.remote.Connection in project nacos by alibaba.

the class ClientMetricsController method getClientMetrics.

/**
 * Get client config listener lists of subscriber in local machine.
 */
@GetMapping("/current")
public Map<String, Object> getClientMetrics(@RequestParam("ip") String ip, @RequestParam(value = "dataId", required = false) String dataId, @RequestParam(value = "group", required = false) String group, @RequestParam(value = "tenant", required = false) String tenant) {
    Map<String, Object> metrics = new HashMap<>(16);
    List<Connection> connectionsByIp = connectionManager.getConnectionByIp(ip);
    for (Connection connectionByIp : connectionsByIp) {
        try {
            ClientConfigMetricRequest clientMetrics = new ClientConfigMetricRequest();
            if (StringUtils.isNotBlank(dataId)) {
                clientMetrics.getMetricsKeys().add(ClientConfigMetricRequest.MetricsKey.build(CACHE_DATA, GroupKey2.getKey(dataId, group, tenant)));
                clientMetrics.getMetricsKeys().add(ClientConfigMetricRequest.MetricsKey.build(SNAPSHOT_DATA, GroupKey2.getKey(dataId, group, tenant)));
            }
            ClientConfigMetricResponse request1 = (ClientConfigMetricResponse) connectionByIp.request(clientMetrics, 1000L);
            metrics.putAll(request1.getMetrics());
        } catch (Exception e) {
            Loggers.CORE.error("Get config metrics error from client ip={},dataId={},group={},tenant={},error={}", ip, dataId, group, tenant, e);
        }
    }
    return metrics;
}
Also used : ClientConfigMetricRequest(com.alibaba.nacos.api.config.remote.request.ClientConfigMetricRequest) HashMap(java.util.HashMap) Connection(com.alibaba.nacos.core.remote.Connection) ClientConfigMetricResponse(com.alibaba.nacos.api.config.remote.response.ClientConfigMetricResponse) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 9 with Connection

use of com.alibaba.nacos.core.remote.Connection 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 10 with Connection

use of com.alibaba.nacos.core.remote.Connection in project nacos by alibaba.

the class GrpcRequestAcceptor method request.

@Override
public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) {
    traceIfNecessary(grpcRequest, true);
    String type = grpcRequest.getMetadata().getType();
    // server is on starting.
    if (!ApplicationUtils.isStarted()) {
        Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(NacosException.INVALID_SERVER_STATUS, "Server is starting,please try later."));
        traceIfNecessary(payloadResponse, false);
        responseObserver.onNext(payloadResponse);
        responseObserver.onCompleted();
        return;
    }
    // server check.
    if (ServerCheckRequest.class.getSimpleName().equals(type)) {
        Payload serverCheckResponseP = GrpcUtils.convert(new ServerCheckResponse(CONTEXT_KEY_CONN_ID.get()));
        traceIfNecessary(serverCheckResponseP, false);
        responseObserver.onNext(serverCheckResponseP);
        responseObserver.onCompleted();
        return;
    }
    RequestHandler requestHandler = requestHandlerRegistry.getByRequestType(type);
    // no handler found.
    if (requestHandler == null) {
        Loggers.REMOTE_DIGEST.warn(String.format("[%s] No handler for request type : %s :", "grpc", type));
        Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(NacosException.NO_HANDLER, "RequestHandler Not Found"));
        traceIfNecessary(payloadResponse, false);
        responseObserver.onNext(payloadResponse);
        responseObserver.onCompleted();
        return;
    }
    // check connection status.
    String connectionId = CONTEXT_KEY_CONN_ID.get();
    boolean requestValid = connectionManager.checkValid(connectionId);
    if (!requestValid) {
        Loggers.REMOTE_DIGEST.warn("[{}] Invalid connection Id ,connection [{}] is un registered ,", "grpc", connectionId);
        Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(NacosException.UN_REGISTER, "Connection is unregistered."));
        traceIfNecessary(payloadResponse, false);
        responseObserver.onNext(payloadResponse);
        responseObserver.onCompleted();
        return;
    }
    Object parseObj = null;
    try {
        parseObj = GrpcUtils.parse(grpcRequest);
    } catch (Exception e) {
        Loggers.REMOTE_DIGEST.warn("[{}] Invalid request receive from connection [{}] ,error={}", "grpc", connectionId, e);
        Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(NacosException.BAD_GATEWAY, e.getMessage()));
        traceIfNecessary(payloadResponse, false);
        responseObserver.onNext(payloadResponse);
        responseObserver.onCompleted();
        return;
    }
    if (parseObj == null) {
        Loggers.REMOTE_DIGEST.warn("[{}] Invalid request receive  ,parse request is null", connectionId);
        Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(NacosException.BAD_GATEWAY, "Invalid request"));
        traceIfNecessary(payloadResponse, false);
        responseObserver.onNext(payloadResponse);
        responseObserver.onCompleted();
        return;
    }
    if (!(parseObj instanceof Request)) {
        Loggers.REMOTE_DIGEST.warn("[{}] Invalid request receive  ,parsed payload is not a request,parseObj={}", connectionId, parseObj);
        Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(NacosException.BAD_GATEWAY, "Invalid request"));
        traceIfNecessary(payloadResponse, false);
        responseObserver.onNext(payloadResponse);
        responseObserver.onCompleted();
        return;
    }
    Request request = (Request) parseObj;
    try {
        Connection connection = connectionManager.getConnection(CONTEXT_KEY_CONN_ID.get());
        RequestMeta requestMeta = new RequestMeta();
        requestMeta.setClientIp(connection.getMetaInfo().getClientIp());
        requestMeta.setConnectionId(CONTEXT_KEY_CONN_ID.get());
        requestMeta.setClientVersion(connection.getMetaInfo().getVersion());
        requestMeta.setLabels(connection.getMetaInfo().getLabels());
        connectionManager.refreshActiveTime(requestMeta.getConnectionId());
        Response response = requestHandler.handleRequest(request, requestMeta);
        Payload payloadResponse = GrpcUtils.convert(response);
        traceIfNecessary(payloadResponse, false);
        responseObserver.onNext(payloadResponse);
        responseObserver.onCompleted();
    } catch (Throwable e) {
        Loggers.REMOTE_DIGEST.error("[{}] Fail to handle request from connection [{}] ,error message :{}", "grpc", connectionId, e);
        Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build((e instanceof NacosException) ? ((NacosException) e).getErrCode() : ResponseCode.FAIL.getCode(), e.getMessage()));
        traceIfNecessary(payloadResponse, false);
        responseObserver.onNext(payloadResponse);
        responseObserver.onCompleted();
    }
}
Also used : ServerCheckResponse(com.alibaba.nacos.api.remote.response.ServerCheckResponse) RequestMeta(com.alibaba.nacos.api.remote.request.RequestMeta) ServerCheckRequest(com.alibaba.nacos.api.remote.request.ServerCheckRequest) Request(com.alibaba.nacos.api.remote.request.Request) Connection(com.alibaba.nacos.core.remote.Connection) NacosException(com.alibaba.nacos.api.exception.NacosException) NacosException(com.alibaba.nacos.api.exception.NacosException) Response(com.alibaba.nacos.api.remote.response.Response) ServerCheckResponse(com.alibaba.nacos.api.remote.response.ServerCheckResponse) ErrorResponse(com.alibaba.nacos.api.remote.response.ErrorResponse) ServerCheckRequest(com.alibaba.nacos.api.remote.request.ServerCheckRequest) RequestHandler(com.alibaba.nacos.core.remote.RequestHandler) Payload(com.alibaba.nacos.api.grpc.auto.Payload)

Aggregations

Connection (com.alibaba.nacos.core.remote.Connection)11 ConnectionMeta (com.alibaba.nacos.core.remote.ConnectionMeta)6 Test (org.junit.Test)5 SampleResult (com.alibaba.nacos.config.server.model.SampleResult)4 Payload (com.alibaba.nacos.api.grpc.auto.Payload)3 GrpcConnection (com.alibaba.nacos.core.remote.grpc.GrpcConnection)3 HashMap (java.util.HashMap)3 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)3 GetMapping (org.springframework.web.bind.annotation.GetMapping)3 ClientConfigMetricResponse (com.alibaba.nacos.api.config.remote.response.ClientConfigMetricResponse)2 RequestMeta (com.alibaba.nacos.api.remote.request.RequestMeta)2 Response (com.alibaba.nacos.api.remote.response.Response)2 StreamObserver (io.grpc.stub.StreamObserver)2 ArrayList (java.util.ArrayList)2 ClientConfigMetricRequest (com.alibaba.nacos.api.config.remote.request.ClientConfigMetricRequest)1 ConfigChangeNotifyRequest (com.alibaba.nacos.api.config.remote.request.ConfigChangeNotifyRequest)1 NacosException (com.alibaba.nacos.api.exception.NacosException)1 ConnectResetRequest (com.alibaba.nacos.api.remote.request.ConnectResetRequest)1 ConnectionSetupRequest (com.alibaba.nacos.api.remote.request.ConnectionSetupRequest)1 HealthCheckRequest (com.alibaba.nacos.api.remote.request.HealthCheckRequest)1