Search in sources :

Example 16 with RpcInternalContext

use of com.alipay.sofa.rpc.context.RpcInternalContext in project sofa-rpc by sofastack.

the class RpcSofaTracer method serverReceived.

@Override
public void serverReceived(SofaRequest request) {
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    Map<String, String> tags = new HashMap<String, String>();
    // server tags 必须设置
    tags.put(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER);
    String spanStrs = (String) request.getRequestProp(RemotingConstants.NEW_RPC_TRACE_NAME);
    SofaTracerSpanContext spanContext = null;
    if (StringUtils.isBlank(spanStrs)) {
        // 老
        Object oldInstanceMap = request.getRequestProp(RemotingConstants.RPC_TRACE_NAME);
        spanContext = this.saveSpanContextAndTags(tags, oldInstanceMap);
    } else {
        // 新
        spanContext = SofaTracerSpanContext.deserializeFromString(spanStrs);
    }
    SofaTracerSpan serverSpan;
    // 使用客户端的进行初始化,如果上游没有,需要新建
    if (spanContext == null) {
        serverSpan = (SofaTracerSpan) this.sofaTracer.buildSpan(request.getInterfaceName()).asChildOf(spanContext).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).start();
    } else {
        // 有的话,需要new,采样会正确
        serverSpan = new SofaTracerSpan(this.sofaTracer, System.currentTimeMillis(), request.getInterfaceName(), spanContext, tags);
    }
    // 重新获取
    spanContext = serverSpan.getSofaTracerSpanContext();
    // Record server receive event
    serverSpan.log(LogData.SERVER_RECV_EVENT_VALUE);
    // 放到线程上下文
    sofaTraceContext.push(serverSpan);
    // rpc 上下文
    if (RpcInternalContext.isAttachmentEnable()) {
        RpcInternalContext context = RpcInternalContext.getContext();
        context.setAttachment(RpcConstants.INTERNAL_KEY_TRACE_ID, spanContext.getTraceId());
        context.setAttachment(RpcConstants.INTERNAL_KEY_SPAN_ID, spanContext.getSpanId());
    }
}
Also used : SofaTracerSpan(com.alipay.common.tracer.core.span.SofaTracerSpan) SofaTraceContext(com.alipay.common.tracer.core.context.trace.SofaTraceContext) HashMap(java.util.HashMap) RpcInternalContext(com.alipay.sofa.rpc.context.RpcInternalContext) SofaTracerSpanContext(com.alipay.common.tracer.core.context.span.SofaTracerSpanContext)

Example 17 with RpcInternalContext

use of com.alipay.sofa.rpc.context.RpcInternalContext in project sofa-rpc by sofastack.

the class RpcSofaTracer method clientAsyncAfterSend.

@Override
public void clientAsyncAfterSend(SofaRequest request) {
    // 客户端的启动
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    // 获取并不弹出
    SofaTracerSpan clientSpan = sofaTraceContext.getCurrentSpan();
    if (clientSpan == null) {
        SelfLog.warn("ClientSpan is null.Before call interface=" + request.getInterfaceName() + ",method=" + request.getMethodName());
        return;
    }
    RpcInternalContext rpcInternalContext = RpcInternalContext.getContext();
    // 异步callback同步
    if (request.isAsync()) {
        // 异步,这个时候除了缓存spanContext clientBeforeSendRequest() rpc 已经调用
        // 还需要这个时候需要还原回父 span
        // 弹出;不弹出的话当前线程就会一直是client了
        clientSpan = sofaTraceContext.pop();
        if (clientSpan != null) {
            // Record client send event
            clientSpan.log(LogData.CLIENT_SEND_EVENT_VALUE);
        }
        // 将当前 span 缓存在 request 中,注意:这个只是缓存不需要序列化到服务端
        rpcInternalContext.setAttachment(RpcConstants.INTERNAL_KEY_TRACER_SPAN, clientSpan);
        if (clientSpan != null && clientSpan.getParentSofaTracerSpan() != null) {
            // restore parent
            sofaTraceContext.push(clientSpan.getParentSofaTracerSpan());
        }
    } else {
        // Record client send event
        clientSpan.log(LogData.CLIENT_SEND_EVENT_VALUE);
    }
}
Also used : SofaTracerSpan(com.alipay.common.tracer.core.span.SofaTracerSpan) SofaTraceContext(com.alipay.common.tracer.core.context.trace.SofaTraceContext) RpcInternalContext(com.alipay.sofa.rpc.context.RpcInternalContext)

Example 18 with RpcInternalContext

use of com.alipay.sofa.rpc.context.RpcInternalContext in project sofa-rpc by sofastack.

the class RpcSofaTracer method serverSend.

@Override
public void serverSend(SofaRequest request, SofaResponse response, Throwable exception) {
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    SofaTracerSpan serverSpan = sofaTraceContext.pop();
    if (serverSpan == null) {
        return;
    }
    // Record server send event
    serverSpan.log(LogData.SERVER_SEND_EVENT_VALUE);
    RpcInternalContext context = RpcInternalContext.getContext();
    RpcInvokeContext invokeContext = RpcInvokeContext.getContext();
    serverSpan.setTag(RpcSpanTags.RESP_SERIALIZE_TIME, (Number) context.getAttachment(RpcConstants.INTERNAL_KEY_RESP_SERIALIZE_TIME));
    serverSpan.setTag(RpcSpanTags.REQ_DESERIALIZE_TIME, (Number) context.getAttachment(RpcConstants.INTERNAL_KEY_REQ_DESERIALIZE_TIME));
    serverSpan.setTag(RpcSpanTags.RESP_SIZE, (Number) context.getAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE));
    serverSpan.setTag(RpcSpanTags.REQ_SIZE, (Number) context.getAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE));
    // 当前线程名
    serverSpan.setTag(RpcSpanTags.CURRENT_THREAD_NAME, Thread.currentThread().getName());
    serverSpan.setTag(RpcSpanTags.SERVER_PHASE_TIME_COST, generateServerPhaseTimeCostSpan(invokeContext));
    serverSpan.setTag(RpcSpanTags.SERVER_SPECIAL_TIME_MARK, generateServerSpecialTimeMark(invokeContext));
    Throwable throwableShow = exception;
    String tracerErrorCode = StringUtils.EMPTY;
    String errorSourceApp = StringUtils.EMPTY;
    String resultCode = StringUtils.EMPTY;
    if (throwableShow != null) {
        // 当前即服务端应用
        errorSourceApp = serverSpan.getTagsWithStr().get(RpcSpanTags.LOCAL_APP);
        // 结果码(00=成功/01=业务异常/02=RPC逻辑错误)
        // 不会业务异常
        resultCode = TracerResultCode.RPC_RESULT_RPC_FAILED;
        tracerErrorCode = TracerResultCode.RPC_ERROR_TYPE_UNKNOWN_ERROR;
    } else if (response != null) {
        // 判断是否是业务异常
        if (response.isError()) {
            errorSourceApp = serverSpan.getTagsWithStr().get(RpcSpanTags.LOCAL_APP);
            resultCode = TracerResultCode.RPC_RESULT_RPC_FAILED;
            tracerErrorCode = TracerResultCode.RPC_ERROR_TYPE_UNKNOWN_ERROR;
            // 改变打印的 throwable
            throwableShow = new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, response.getErrorMsg());
        } else {
            Object ret = response.getAppResponse();
            if (ret instanceof Throwable) {
                throwableShow = (Throwable) ret;
                errorSourceApp = serverSpan.getTagsWithStr().get(RpcSpanTags.LOCAL_APP);
                // 业务异常
                resultCode = TracerResultCode.RPC_RESULT_BIZ_FAILED;
                tracerErrorCode = TracerResultCode.RPC_RESULT_BIZ_FAILED;
            } else {
                resultCode = TracerResultCode.RPC_RESULT_SUCCESS;
            }
        }
    }
    if (throwableShow != null) {
        // 打印错误
        // result code
        Map<String, String> errorContext = new HashMap<String, String>();
        // 记录的上下文信息
        this.generateServerErrorContext(errorContext, request, serverSpan);
        // report
        serverSpan.reportError(tracerErrorCode, errorContext, throwableShow, errorSourceApp, ERROR_SOURCE);
    }
    // 结果码(00=成功/01=业务异常/02=RPC逻辑错误)
    serverSpan.setTag(RpcSpanTags.RESULT_CODE, resultCode);
    serverSpan.finish();
}
Also used : SofaTracerSpan(com.alipay.common.tracer.core.span.SofaTracerSpan) RpcInvokeContext(com.alipay.sofa.rpc.context.RpcInvokeContext) SofaTraceContext(com.alipay.common.tracer.core.context.trace.SofaTraceContext) HashMap(java.util.HashMap) RpcInternalContext(com.alipay.sofa.rpc.context.RpcInternalContext) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException)

Example 19 with RpcInternalContext

use of com.alipay.sofa.rpc.context.RpcInternalContext in project sofa-rpc by sofastack.

the class RpcSofaTracer method clientReceived.

@Override
public void clientReceived(SofaRequest request, SofaResponse response, Throwable exceptionThrow) {
    // 客户端的启动
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    SofaTracerSpan clientSpan = sofaTraceContext.pop();
    if (clientSpan == null) {
        return;
    }
    // Record client receive event
    clientSpan.log(LogData.CLIENT_RECV_EVENT_VALUE);
    // rpc 上下文
    RpcInternalContext context = null;
    if (RpcInternalContext.isAttachmentEnable()) {
        context = RpcInternalContext.getContext();
        if (!clientSpan.getTagsWithStr().containsKey(RpcSpanTags.ROUTE_RECORD)) {
            clientSpan.setTag(RpcSpanTags.ROUTE_RECORD, (String) context.getAttachment(RpcConstants.INTERNAL_KEY_ROUTER_RECORD));
        }
        clientSpan.setTag(RpcSpanTags.REQ_SERIALIZE_TIME, (Number) context.getAttachment(RpcConstants.INTERNAL_KEY_REQ_SERIALIZE_TIME));
        clientSpan.setTag(RpcSpanTags.RESP_DESERIALIZE_TIME, (Number) context.getAttachment(RpcConstants.INTERNAL_KEY_RESP_DESERIALIZE_TIME));
        clientSpan.setTag(RpcSpanTags.RESP_SIZE, (Number) context.getAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE));
        clientSpan.setTag(RpcSpanTags.REQ_SIZE, (Number) context.getAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE));
        clientSpan.setTag(RpcSpanTags.CLIENT_CONN_TIME, (Number) context.getAttachment(RpcConstants.INTERNAL_KEY_CONN_CREATE_TIME));
        Long ce = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
        if (ce != null) {
            clientSpan.setTag(RpcSpanTags.CLIENT_ELAPSE_TIME, ce);
        }
        InetSocketAddress address = context.getLocalAddress();
        if (address != null) {
            clientSpan.setTag(RpcSpanTags.LOCAL_IP, NetUtils.toIpString(address));
            clientSpan.setTag(RpcSpanTags.LOCAL_PORT, address.getPort());
        }
        // adjust for generic invoke
        clientSpan.setTag(RpcSpanTags.METHOD, request.getMethodName());
    }
    RpcInvokeContext invokeContext = RpcInvokeContext.getContext();
    clientSpan.setTag(RpcSpanTags.PHASE_TIME_COST, generateClientPhaseTimeCostSpan(invokeContext));
    clientSpan.setTag(RpcSpanTags.SPECIAL_TIME_MARK, generateClientSpecialTimeMarkSpan(invokeContext));
    Throwable throwableShow = exceptionThrow;
    // 区分出各个异常信息
    String resultCode = StringUtils.EMPTY;
    // 当前应用或者目标应用
    String errorSourceApp = StringUtils.EMPTY;
    String tracerErrorCode = StringUtils.EMPTY;
    if (throwableShow != null) {
        // 客户端异常
        if (throwableShow instanceof SofaRpcException) {
            SofaRpcException exception = (SofaRpcException) throwableShow;
            // 摘要打印
            int errorType = exception.getErrorType();
            switch(errorType) {
                case RpcErrorType.CLIENT_TIMEOUT:
                    resultCode = TracerResultCode.RPC_RESULT_TIMEOUT_FAILED;
                    // filter 已经存放
                    errorSourceApp = clientSpan.getTagsWithStr().get(RpcSpanTags.LOCAL_APP);
                    tracerErrorCode = TracerResultCode.RPC_ERROR_TYPE_TIMEOUT_ERROR;
                    break;
                case RpcErrorType.CLIENT_ROUTER:
                    resultCode = TracerResultCode.RPC_RESULT_ROUTE_FAILED;
                    errorSourceApp = clientSpan.getTagsWithStr().get(RpcSpanTags.LOCAL_APP);
                    tracerErrorCode = TracerResultCode.RPC_ERROR_TYPE_ADDRESS_ROUTE_ERROR;
                    break;
                case RpcErrorType.CLIENT_SERIALIZE:
                case RpcErrorType.CLIENT_DESERIALIZE:
                    resultCode = TracerResultCode.RPC_RESULT_RPC_FAILED;
                    errorSourceApp = clientSpan.getTagsWithStr().get(RpcSpanTags.LOCAL_APP);
                    tracerErrorCode = TracerResultCode.RPC_ERROR_TYPE_SERIALIZE_ERROR;
                    break;
                default:
                    resultCode = TracerResultCode.RPC_RESULT_RPC_FAILED;
                    errorSourceApp = ExceptionUtils.isServerException(exception) ? clientSpan.getTagsWithStr().get(RpcSpanTags.REMOTE_APP) : clientSpan.getTagsWithStr().get(RpcSpanTags.LOCAL_APP);
                    tracerErrorCode = TracerResultCode.RPC_ERROR_TYPE_UNKNOWN_ERROR;
                    break;
            }
        } else {
            // 这里是客户端的未知异常,目前不会走到这里
            resultCode = TracerResultCode.RPC_RESULT_RPC_FAILED;
            errorSourceApp = clientSpan.getTagsWithStr().get(RpcSpanTags.LOCAL_APP);
            tracerErrorCode = TracerResultCode.RPC_ERROR_TYPE_UNKNOWN_ERROR;
        }
    } else if (response != null) {
        // 服务端rpc异常
        if (response.isError()) {
            errorSourceApp = clientSpan.getTagsWithStr().get(RpcSpanTags.REMOTE_APP);
            tracerErrorCode = TracerResultCode.RPC_ERROR_TYPE_UNKNOWN_ERROR;
            resultCode = TracerResultCode.RPC_RESULT_RPC_FAILED;
            // 客户端服务端均打印
            throwableShow = new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, response.getErrorMsg());
        } else {
            Object ret = response.getAppResponse();
            // for server throw exception ,but this class can not be found in current
            if (ret instanceof Throwable || "true".equals(response.getResponseProp(RemotingConstants.HEAD_RESPONSE_ERROR))) {
                errorSourceApp = clientSpan.getTagsWithStr().get(RpcSpanTags.REMOTE_APP);
                // 业务异常
                resultCode = TracerResultCode.RPC_RESULT_BIZ_FAILED;
                tracerErrorCode = TracerResultCode.RPC_ERROR_TYPE_BIZ_ERROR;
            } else {
                resultCode = TracerResultCode.RPC_RESULT_SUCCESS;
            }
        }
    }
    if (throwableShow != null) {
        Map<String, String> contextMap = new HashMap<String, String>();
        this.generateClientErrorContext(contextMap, request, clientSpan);
        clientSpan.reportError(tracerErrorCode, contextMap, throwableShow, errorSourceApp, ERROR_SOURCE);
    }
    clientSpan.setTag(RpcSpanTags.RESULT_CODE, resultCode);
    // finish client
    clientSpan.finish();
    if (context != null) {
        context.setAttachment(RpcConstants.INTERNAL_KEY_RESULT_CODE, resultCode);
    }
    // client span
    if (clientSpan.getParentSofaTracerSpan() != null) {
        // restore parent
        sofaTraceContext.push(clientSpan.getParentSofaTracerSpan());
    }
}
Also used : RpcInvokeContext(com.alipay.sofa.rpc.context.RpcInvokeContext) SofaTraceContext(com.alipay.common.tracer.core.context.trace.SofaTraceContext) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) RpcInternalContext(com.alipay.sofa.rpc.context.RpcInternalContext) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaTracerSpan(com.alipay.common.tracer.core.span.SofaTracerSpan)

Example 20 with RpcInternalContext

use of com.alipay.sofa.rpc.context.RpcInternalContext in project sofa-rpc by sofastack.

the class RpcClientStatTest method testClientStat.

@Test
@Ignore
public void testClientStat() {
    try {
        Tracer rpcSofaTracer = Tracers.getTracer();
        Field tracerField = null;
        try {
            tracerField = RpcSofaTracer.class.getDeclaredField("sofaTracer");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        tracerField.setAccessible(true);
        SofaTracer tracer = null;
        // OpenTracing tracer 标准实现
        try {
            tracer = (SofaTracer) tracerField.get(rpcSofaTracer);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        Reporter clientReporter = tracer.getClientReporter();
        assertNotNull(clientReporter);
        assertTrue(clientReporter instanceof MemoryReporterImpl);
        memoryReporter = (MemoryReporterImpl) clientReporter;
        final SofaRequest request = new SofaRequest();
        request.setInterfaceName("a");
        request.setTargetServiceUniqueName("app.service:1.0");
        request.setMethodName("method");
        RpcInternalContext context = RpcInternalContext.getContext();
        context.setAttachment(RpcConstants.INTERNAL_KEY_APP_NAME, "client");
        // this will not be used, only in real invoke
        final ProviderInfo providerInfo = new ProviderInfo();
        providerInfo.setStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME, "server");
        context.setProviderInfo(providerInfo);
        for (int i = 0; i < 10; i++) {
            rpcSofaTracer.startRpc(request);
            rpcSofaTracer.clientBeforeSend(request);
            final SofaResponse response = new SofaResponse();
            response.setAppResponse("b");
            rpcSofaTracer.clientReceived(request, response, null);
        }
        Map<StatKey, StatValues> datas = memoryReporter.getStoreDatas();
        LOGGER.info("1" + datas);
        Assert.assertEquals(1, datas.size());
        for (Map.Entry entry : datas.entrySet()) {
            final StatMapKey key = (StatMapKey) entry.getKey();
            final StatValues value = (StatValues) entry.getValue();
            Assert.assertEquals("client,,app.service:1.0,method", key.getKey());
            Assert.assertEquals(10, value.getCurrentValue()[0]);
        }
        request.setTargetServiceUniqueName("app.service:2.0");
        for (int i = 0; i < 20; i++) {
            rpcSofaTracer.startRpc(request);
            rpcSofaTracer.clientBeforeSend(request);
            final SofaResponse response = new SofaResponse();
            response.setAppResponse("b");
            rpcSofaTracer.clientReceived(request, response, null);
        }
        LOGGER.info("2" + datas);
        int i = 0;
        for (Map.Entry entry : datas.entrySet()) {
            if (i == 0) {
                continue;
            }
            final StatMapKey key = (StatMapKey) entry.getKey();
            final StatValues value = (StatValues) entry.getValue();
            Assert.assertEquals("client,,app.service:2.0,method", key.getKey());
            Assert.assertEquals(20, value.getCurrentValue()[0]);
        }
        Assert.assertEquals(2, datas.size());
    } catch (Throwable e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }
}
Also used : MemoryReporterImpl(com.alipay.sofa.rpc.tracer.sofatracer.factory.MemoryReporterImpl) SofaRequest(com.alipay.sofa.rpc.core.request.SofaRequest) Tracer(com.alipay.sofa.rpc.tracer.Tracer) SofaTracer(com.alipay.common.tracer.core.SofaTracer) RpcSofaTracer(com.alipay.sofa.rpc.tracer.sofatracer.RpcSofaTracer) Reporter(com.alipay.common.tracer.core.reporter.facade.Reporter) RpcInternalContext(com.alipay.sofa.rpc.context.RpcInternalContext) StatKey(com.alipay.common.tracer.core.reporter.stat.model.StatKey) Field(java.lang.reflect.Field) StatMapKey(com.alipay.common.tracer.core.reporter.stat.model.StatMapKey) ProviderInfo(com.alipay.sofa.rpc.client.ProviderInfo) RpcSofaTracer(com.alipay.sofa.rpc.tracer.sofatracer.RpcSofaTracer) StatValues(com.alipay.common.tracer.core.reporter.stat.model.StatValues) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) Map(java.util.Map) SofaTracer(com.alipay.common.tracer.core.SofaTracer) RpcSofaTracer(com.alipay.sofa.rpc.tracer.sofatracer.RpcSofaTracer) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

RpcInternalContext (com.alipay.sofa.rpc.context.RpcInternalContext)52 SofaRpcException (com.alipay.sofa.rpc.core.exception.SofaRpcException)15 SofaTraceContext (com.alipay.common.tracer.core.context.trace.SofaTraceContext)13 SofaTracerSpan (com.alipay.common.tracer.core.span.SofaTracerSpan)12 SofaResponse (com.alipay.sofa.rpc.core.response.SofaResponse)12 RpcInvokeContext (com.alipay.sofa.rpc.context.RpcInvokeContext)10 SofaTimeOutException (com.alipay.sofa.rpc.core.exception.SofaTimeOutException)6 ProviderInfo (com.alipay.sofa.rpc.client.ProviderInfo)5 HashMap (java.util.HashMap)5 InvokeContext (com.alipay.remoting.InvokeContext)4 SofaRpcRuntimeException (com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException)4 SofaRequest (com.alipay.sofa.rpc.core.request.SofaRequest)4 ClientSyncReceiveEvent (com.alipay.sofa.rpc.event.ClientSyncReceiveEvent)4 Test (org.junit.Test)4 SofaTracerSpanContext (com.alipay.common.tracer.core.context.span.SofaTracerSpanContext)3 ConnectionClosedException (com.alipay.remoting.exception.ConnectionClosedException)3 DeserializationException (com.alipay.remoting.exception.DeserializationException)3 RemotingException (com.alipay.remoting.exception.RemotingException)3 SerializationException (com.alipay.remoting.exception.SerializationException)3 InvokeSendFailedException (com.alipay.remoting.rpc.exception.InvokeSendFailedException)3