Search in sources :

Example 76 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project sofa-rpc by sofastack.

the class SofaRpcMetricsTest method testMicrometerMetrics.

@Test
public void testMicrometerMetrics() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    try (SofaRpcMetrics metrics = new SofaRpcMetrics()) {
        metrics.bindTo(registry);
        Method handleEvent = EventBus.class.getDeclaredMethod("handleEvent", Subscriber.class, Event.class);
        handleEvent.setAccessible(true);
        SofaRequest request = buildRequest();
        SofaResponse response = buildResponse();
        RpcInternalContext.getContext().setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, 100).setAttachment(RpcConstants.INTERNAL_KEY_IMPL_ELAPSE, 10).setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE, 3).setAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE, 4);
        handleEvent.invoke(EventBus.class, metrics, new ClientEndInvokeEvent(request, response, null));
        handleEvent.invoke(EventBus.class, metrics, new ServerSendEvent(request, response, null));
        ServerConfig serverConfig = new ServerConfig();
        handleEvent.invoke(EventBus.class, metrics, new ServerStartedEvent(serverConfig, new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>())));
        handleEvent.invoke(EventBus.class, metrics, new ServerStoppedEvent(serverConfig));
        handleEvent.invoke(EventBus.class, metrics, new ProviderPubEvent(new ProviderConfig<>()));
        handleEvent.invoke(EventBus.class, metrics, new ConsumerSubEvent(new ConsumerConfig<>()));
        Assert.assertEquals(12, registry.getMeters().size());
    }
}
Also used : ClientEndInvokeEvent(com.alipay.sofa.rpc.event.ClientEndInvokeEvent) SofaRequest(com.alipay.sofa.rpc.core.request.SofaRequest) ServerSendEvent(com.alipay.sofa.rpc.event.ServerSendEvent) ConsumerSubEvent(com.alipay.sofa.rpc.event.ConsumerSubEvent) ProviderConfig(com.alipay.sofa.rpc.config.ProviderConfig) SimpleMeterRegistry(io.micrometer.core.instrument.simple.SimpleMeterRegistry) Method(java.lang.reflect.Method) ServerConfig(com.alipay.sofa.rpc.config.ServerConfig) ServerStartedEvent(com.alipay.sofa.rpc.event.ServerStartedEvent) ServerStoppedEvent(com.alipay.sofa.rpc.event.ServerStoppedEvent) ConsumerConfig(com.alipay.sofa.rpc.config.ConsumerConfig) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ProviderPubEvent(com.alipay.sofa.rpc.event.ProviderPubEvent) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) Test(org.junit.Test)

Example 77 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project sofa-rpc by sofastack.

the class SofaAsyncHystrixCommand method buildEmptyResponse.

// Copy from AbstractCluster#buildEmptyResponse
private SofaResponse buildEmptyResponse(SofaRequest request) {
    SofaResponse response = new SofaResponse();
    Method method = request.getMethod();
    if (method != null) {
        response.setAppResponse(ClassUtils.getDefaultPrimitiveValue(method.getReturnType()));
    }
    return response;
}
Also used : Method(java.lang.reflect.Method) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse)

Example 78 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project sofa-rpc by sofastack.

the class SofaHystrixCommand method getFallback.

protected SofaResponse getFallback(SofaResponse response, Throwable t) {
    FallbackFactory fallbackFactory = SofaHystrixConfig.loadFallbackFactory((ConsumerConfig) invoker.getConfig());
    if (fallbackFactory == null) {
        return super.getFallback();
    }
    Object fallback = fallbackFactory.create(new FallbackContext(invoker, request, response, t));
    if (fallback == null) {
        return super.getFallback();
    }
    try {
        Object fallbackResult = request.getMethod().invoke(fallback, request.getMethodArgs());
        SofaResponse actualResponse = new SofaResponse();
        actualResponse.setAppResponse(fallbackResult);
        return actualResponse;
    } catch (IllegalAccessException e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_HYSTRIX_FALLBACK_FAIL), e);
    } catch (InvocationTargetException e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_HYSTRIX_FALLBACK_FAIL), e.getTargetException());
    }
}
Also used : SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 79 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project sofa-rpc by sofastack.

the class SofaHystrixCommand method run.

@Override
protected SofaResponse run() throws Exception {
    RpcInternalContext.setContext(rpcInternalContext);
    RpcInvokeContext.setContext(rpcInvokeContext);
    SofaResponse sofaResponse = invoker.invoke(request);
    if (!sofaResponse.isError()) {
        return sofaResponse;
    }
    return getFallback(sofaResponse, null);
}
Also used : SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse)

Example 80 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project sofa-rpc by sofastack.

the class ServerReqHeaderInterceptor method interceptCall.

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata requestHeaders, ServerCallHandler<ReqT, RespT> next) {
    final ServerServiceDefinition serverServiceDefinition = this.getServerServiceDefinition();
    SofaResponse sofaResponse = new SofaResponse();
    final Throwable[] throwable = { null };
    SofaRequest sofaRequest = new SofaRequest();
    TripleTracerAdapter.serverReceived(sofaRequest, serverServiceDefinition, call, requestHeaders);
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    SofaTracerSpan serverSpan = sofaTraceContext.getCurrentSpan();
    Context ctxWithSpan = Context.current().withValue(TracingContextKey.getKey(), serverSpan).withValue(TracingContextKey.getSpanContextKey(), serverSpan.context()).withValue(TracingContextKey.getKeySofaRequest(), sofaRequest);
    // 这里和下面不在一个线程
    if (RpcRunningState.isDebugMode()) {
        LOGGER.info("[1]header received from client:" + requestHeaders);
    }
    ServerCall<ReqT, RespT> realCall = new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {

        @Override
        public void sendHeaders(Metadata responseHeaders) {
            if (RpcRunningState.isDebugMode()) {
                LOGGER.info("[4]send response header:{}", responseHeaders);
            }
            super.sendHeaders(responseHeaders);
        }

        // 服务端发完了
        @Override
        public void sendMessage(RespT message) {
            if (RpcRunningState.isDebugMode()) {
                LOGGER.info("[5]send response message:{}", message);
            }
            super.sendMessage(message);
            sofaResponse.setAppResponse(message);
        }

        @Override
        public void close(Status status, Metadata trailers) {
            if (RpcRunningState.isDebugMode()) {
                LOGGER.info("[6]send response message:{},trailers:{}", status, trailers);
            }
            super.close(status, trailers);
        }
    };
    ServerCall.Listener<ReqT> listenerWithContext = Contexts.interceptCall(ctxWithSpan, realCall, requestHeaders, next);
    ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT> result = new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(listenerWithContext) {

        // 完成的时候走到这里
        @Override
        public void onComplete() {
            // 和代码执行不一定在一个线程池
            super.onComplete();
            if (RpcRunningState.isDebugMode()) {
                LOGGER.info("[7]server processed done received from client:" + requestHeaders);
            }
            TripleTracerAdapter.serverReceived(sofaRequest, serverServiceDefinition, call, requestHeaders);
            // 进行一下补偿
            SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
            SofaTracerSpan serverSpan = sofaTraceContext.getCurrentSpan();
            SofaTracerSpan originalSpan = (SofaTracerSpan) TracingContextKey.getKey().get(ctxWithSpan);
            serverSpan.setStartTime(originalSpan.getStartTime());
            serverSpan.setTag("remote.ip", originalSpan.getTagsWithStr().get("remote.ip"));
            long endTime = RpcRuntimeContext.now();
            serverSpan.setTag("biz.impl.time", endTime - originalSpan.getStartTime());
            TripleTracerAdapter.serverSend(sofaRequest, requestHeaders, sofaResponse, throwable[0]);
        }

        // 客户端发完了
        @Override
        public void onHalfClose() {
            try {
                doOnHalfClose();
            } finally {
                RpcInvokeContext.removeContext();
            }
        }

        private void doOnHalfClose() {
            if (RpcRunningState.isDebugMode()) {
                LOGGER.info("[2]body received done from client:" + requestHeaders);
            }
            // 服务端收到所有信息
            TripleTracerAdapter.serverReceived(sofaRequest, serverServiceDefinition, call, requestHeaders);
            try {
                super.onHalfClose();
            } catch (Throwable t) {
                // 统一处理异常
                StatusRuntimeException exception = fromThrowable(t);
                // 调用 call.close() 发送 Status 和 metadata
                // 这个方式和 onError()本质是一样的
                call.close(exception.getStatus(), exception.getTrailers());
                throwable[0] = t;
            }
        }

        private StatusRuntimeException fromThrowable(Throwable t) {
            final Metadata trailers = new Metadata();
            return new StatusRuntimeException(Status.UNKNOWN, trailers);
        }
    };
    return result;
}
Also used : RpcRuntimeContext(com.alipay.sofa.rpc.context.RpcRuntimeContext) SofaTraceContext(com.alipay.common.tracer.core.context.trace.SofaTraceContext) Context(io.grpc.Context) RpcInvokeContext(com.alipay.sofa.rpc.context.RpcInvokeContext) Status(io.grpc.Status) SofaRequest(com.alipay.sofa.rpc.core.request.SofaRequest) SofaTraceContext(com.alipay.common.tracer.core.context.trace.SofaTraceContext) Metadata(io.grpc.Metadata) SofaTracerSpan(com.alipay.common.tracer.core.span.SofaTracerSpan) ForwardingServerCallListener(io.grpc.ForwardingServerCallListener) ForwardingServerCall(io.grpc.ForwardingServerCall) ServerCall(io.grpc.ServerCall) ServerServiceDefinition(io.grpc.ServerServiceDefinition) StatusRuntimeException(io.grpc.StatusRuntimeException) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse)

Aggregations

SofaResponse (com.alipay.sofa.rpc.core.response.SofaResponse)85 SofaRpcException (com.alipay.sofa.rpc.core.exception.SofaRpcException)25 Test (org.junit.Test)21 SofaRequest (com.alipay.sofa.rpc.core.request.SofaRequest)19 RpcInternalContext (com.alipay.sofa.rpc.context.RpcInternalContext)12 Method (java.lang.reflect.Method)10 AbstractByteBuf (com.alipay.sofa.rpc.transport.AbstractByteBuf)9 HashMap (java.util.HashMap)9 ProviderConfig (com.alipay.sofa.rpc.config.ProviderConfig)6 ClientEndInvokeEvent (com.alipay.sofa.rpc.event.ClientEndInvokeEvent)6 ByteArrayWrapperByteBuf (com.alipay.sofa.rpc.transport.ByteArrayWrapperByteBuf)6 ProviderInfo (com.alipay.sofa.rpc.client.ProviderInfo)5 ClientAsyncReceiveEvent (com.alipay.sofa.rpc.event.ClientAsyncReceiveEvent)5 ClientSyncReceiveEvent (com.alipay.sofa.rpc.event.ClientSyncReceiveEvent)5 Serializer (com.alipay.sofa.rpc.codec.Serializer)4 ConsumerConfig (com.alipay.sofa.rpc.config.ConsumerConfig)4 FilterChain (com.alipay.sofa.rpc.filter.FilterChain)4 Hessian2Input (com.caucho.hessian.io.Hessian2Input)4 BlockException (com.alibaba.csp.sentinel.slots.block.BlockException)3 DeserializationException (com.alipay.remoting.exception.DeserializationException)3