use of com.alibaba.nacos.api.remote.response.Response 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;
}
use of com.alibaba.nacos.api.remote.response.Response 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();
}
}
use of com.alibaba.nacos.api.remote.response.Response in project nacos by alibaba.
the class GrpcRequestFilter method filter.
@Override
protected Response filter(Request request, RequestMeta meta, Class handlerClazz) throws NacosException {
if (request instanceof AbstractNamingRequest && !upgradeJudgement.isUseGrpcFeatures()) {
Response response = getDefaultResponseInstance(handlerClazz);
response.setErrorInfo(NacosException.SERVER_ERROR, "Nacos cluster is running with 1.X mode, can't accept gRPC request temporarily. Please check the server status or close Double write to force open 2.0 mode. Detail https://nacos.io/en-us/docs/2.0.0-upgrading.html.");
return response;
}
return null;
}
use of com.alibaba.nacos.api.remote.response.Response in project nacos by alibaba.
the class GrpcBiStreamRequestAcceptorTest method testConnectionSetupRequest.
@Test
public void testConnectionSetupRequest() {
StreamObserver<Payload> streamObserver = new StreamObserver<Payload>() {
@Override
public void onNext(Payload payload) {
System.out.println("Receive data from server, data: " + payload);
Assert.assertNotNull(payload);
ConnectResetRequest connectResetRequest = (ConnectResetRequest) GrpcUtils.parse(payload);
Response response = new ConnectResetResponse();
response.setRequestId(connectResetRequest.getRequestId());
Payload res = GrpcUtils.convert(response);
payloadStreamObserver.onNext(res);
payloadStreamObserver.onCompleted();
}
@Override
public void onError(Throwable throwable) {
Assert.fail(throwable.getMessage());
}
@Override
public void onCompleted() {
System.out.println("complete");
}
};
payloadStreamObserver = streamStub.requestBiStream(streamObserver);
RequestMeta metadata = new RequestMeta();
metadata.setClientIp("127.0.0.1");
metadata.setConnectionId(connectId);
ConnectionSetupRequest connectionSetupRequest = new ConnectionSetupRequest();
connectionSetupRequest.setRequestId(requestId);
connectionSetupRequest.setClientVersion("2.0.3");
Payload payload = GrpcUtils.convert(connectionSetupRequest, metadata);
payloadStreamObserver.onNext(payload);
}
use of com.alibaba.nacos.api.remote.response.Response in project nacos by alibaba.
the class TpsControlRequestFilter method filter.
@Override
protected Response filter(Request request, RequestMeta meta, Class handlerClazz) {
Method method = null;
try {
method = getHandleMethod(handlerClazz);
} catch (NacosException e) {
return null;
}
if (method.isAnnotationPresent(TpsControl.class) && TpsControlConfig.isTpsControlEnabled()) {
TpsControl tpsControl = method.getAnnotation(TpsControl.class);
String pointName = tpsControl.pointName();
Class[] parsers = tpsControl.parsers();
List<MonitorKey> monitorKeys = new ArrayList<>();
monitorKeys.add(new ClientIpMonitorKey(meta.getClientIp()));
if (parsers != null) {
for (Class clazz : parsers) {
try {
if (MonitorKeyParser.class.isAssignableFrom(clazz)) {
MonitorKey parseKey = ((MonitorKeyParser) (clazz.newInstance())).parse(request, meta);
if (parseKey != null) {
monitorKeys.add(parseKey);
}
}
} catch (Throwable throwable) {
// ignore
}
}
}
boolean pass = tpsMonitorManager.applyTps(pointName, meta.getConnectionId(), monitorKeys);
if (!pass) {
Response response;
try {
response = super.getDefaultResponseInstance(handlerClazz);
response.setErrorInfo(NacosException.OVER_THRESHOLD, "Tps Flow restricted");
return response;
} catch (Exception e) {
Loggers.TPS_CONTROL_DETAIL.warn("Tps monitor fail , request: {},exception:{}", request.getClass().getSimpleName(), e);
return null;
}
}
}
return null;
}
Aggregations