Java Code Examples for com.alipay.sofa.rpc.context.RpcInternalContext#setAttachment()

The following examples show how to use com.alipay.sofa.rpc.context.RpcInternalContext#setAttachment() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TraceClientRequestFilter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    try {

        if (RpcInternalContext.isAttachmentEnable()) {
            // 补充客户端request长度
            RpcInternalContext context = RpcInternalContext.getContext();
            context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE,
                requestContext.getHeaderString(HttpHeaders.CONTENT_LENGTH));

        }

        RestTracerAdapter.beforeSend(requestContext);
    } catch (Exception e) {
        logger.error(LogCodes.getLog(LogCodes.ERROR_TRACER_UNKNOWN_EXP, "filter", "rest", "client"), e);
    }
}
 
Example 2
Source File: SofaRpcSerialization.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 客户端记录序列化请求的耗时和
 *
 * @param requestCommand 请求对象
 */
protected void recordSerializeRequest(RequestCommand requestCommand, InvokeContext invokeContext) {
    if (!RpcInternalContext.isAttachmentEnable()) {
        return;
    }
    RpcInternalContext context = null;
    if (invokeContext != null) {
        // 客户端异步调用的情况下,上下文会放在InvokeContext中传递
        context = invokeContext.get(RemotingConstants.INVOKE_CTX_RPC_CTX);
    }
    if (context == null) {
        context = RpcInternalContext.getContext();
    }
    int cost = context.getStopWatch().tick().read();
    int requestSize = RpcProtocol.getRequestHeaderLength()
        + requestCommand.getClazzLength()
        + requestCommand.getContentLength()
        + requestCommand.getHeaderLength();
    // 记录请求序列化大小和请求序列化耗时
    context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE, requestSize);
    context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SERIALIZE_TIME, cost);
}
 
Example 3
Source File: SofaRpcSerialization.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 客户端记录响应反序列化大小和响应反序列化耗时
 *
 * @param responseCommand 响应体
 */
private void recordDeserializeResponse(RpcResponseCommand responseCommand, InvokeContext invokeContext) {
    if (!RpcInternalContext.isAttachmentEnable()) {
        return;
    }
    RpcInternalContext context = null;
    if (invokeContext != null) {
        // 客户端异步调用的情况下,上下文会放在InvokeContext中传递
        context = invokeContext.get(RemotingConstants.INVOKE_CTX_RPC_CTX);
    }
    if (context == null) {
        context = RpcInternalContext.getContext();
    }
    int cost = context.getStopWatch().tick().read();
    int respSize = RpcProtocol.getResponseHeaderLength()
        + responseCommand.getClazzLength()
        + responseCommand.getContentLength()
        + responseCommand.getHeaderLength();
    // 记录响应反序列化大小和响应反序列化耗时
    context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE, respSize);
    context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_DESERIALIZE_TIME, cost);
}
 
Example 4
Source File: AbstractInvokeCallbackTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecordClientElapseTime() {
    BoltInvokerCallback invokerCallback = new BoltInvokerCallback(null, null,
        null, null, null, null);
    invokerCallback.recordClientElapseTime();
    Long elapse = (Long) RpcInternalContext.getContext().getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
    Assert.assertNull(elapse);

    RpcInternalContext context = RpcInternalContext.getContext();
    invokerCallback = new BoltInvokerCallback(null, null,
        null, null, context, null);
    invokerCallback.recordClientElapseTime();
    elapse = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
    Assert.assertNull(elapse);

    context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now() - 1000);
    invokerCallback.recordClientElapseTime();
    elapse = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
    Assert.assertNotNull(elapse);
}
 
Example 5
Source File: RpcSofaTracer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void startRpc(SofaRequest request) {
    //客户端的启动
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    SofaTracerSpan serverSpan = sofaTraceContext.pop();

    SofaTracerSpan clientSpan = (SofaTracerSpan) this.sofaTracer.buildSpan(request.getInterfaceName())
        .asChildOf(serverSpan)
        .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
        .start();

    if (RpcInternalContext.isAttachmentEnable()) {
        RpcInternalContext context = RpcInternalContext.getContext();
        clientSpan
            .setTag(RpcSpanTags.LOCAL_APP, (String) context.getAttachment(RpcConstants.INTERNAL_KEY_APP_NAME));
        clientSpan.setTag(RpcSpanTags.PROTOCOL,
            (String) context.getAttachment(RpcConstants.INTERNAL_KEY_PROTOCOL_NAME));
        SofaTracerSpanContext spanContext = clientSpan.getSofaTracerSpanContext();
        if (spanContext != null) {
            context.setAttachment(RpcConstants.INTERNAL_KEY_TRACE_ID, spanContext.getTraceId());
            context.setAttachment(RpcConstants.INTERNAL_KEY_SPAN_ID, spanContext.getSpanId());
        }
    }

    clientSpan.setTag(RpcSpanTags.SERVICE, request.getTargetServiceUniqueName());
    clientSpan.setTag(RpcSpanTags.METHOD, request.getMethodName());
    clientSpan.setTag(RpcSpanTags.CURRENT_THREAD_NAME, Thread.currentThread().getName());

    //需要主动缓存自己的 serverSpan,原因是:asChildOf 关注的是 spanContext
    clientSpan.setParentSofaTracerSpan(serverSpan);
    //push
    sofaTraceContext.push(clientSpan);
}
 
Example 6
Source File: RpcSofaTracer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 7
Source File: Router.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 记录路由路径记录
 *
 * @param routerName 路由名字
 * @since 5.2.0
 */
protected void recordRouterWay(String routerName) {
    if (RpcInternalContext.isAttachmentEnable()) {
        RpcInternalContext context = RpcInternalContext.getContext();
        String record = (String) context.getAttachment(RpcConstants.INTERNAL_KEY_ROUTER_RECORD);
        record = record == null ? routerName : record + ">" + routerName;
        context.setAttachment(RpcConstants.INTERNAL_KEY_ROUTER_RECORD, record);
    }
}
 
Example 8
Source File: TraceClientResponseFilter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    if (RpcInternalContext.isAttachmentEnable()) {
        // 补充客户端response长度
        RpcInternalContext context = RpcInternalContext.getContext();
        context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE, responseContext.getLength());
    }
    RestTracerAdapter.clientReceived(responseContext);
}
 
Example 9
Source File: TraceResponseFilter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
    throws IOException {

    // 补充服务端request和response大小
    if (RpcInternalContext.isAttachmentEnable()) {
        RpcInternalContext context = RpcInternalContext.getContext();
        context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE, requestContext.getLength());
        context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE, responseContext.getLength());
        Long startTime = (Long) context.removeAttachment(RpcConstants.INTERNAL_KEY_SERVER_RECEIVE_TIME);
        if (startTime != null) {
            context.setAttachment(RpcConstants.INTERNAL_KEY_IMPL_ELAPSE, RpcRuntimeContext.now() - startTime);
        }
    }
}
 
Example 10
Source File: LookoutRequestFilter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    try {
        SofaResourceMethodInvoker resourceMethodInvoker = (SofaResourceMethodInvoker)
                ((PostMatchContainerRequestContext) requestContext)
                    .getResourceMethod();

        SofaResourceFactory factory = resourceMethodInvoker.getResource();
        String serviceName = factory.getServiceName();
        String appName = factory.getAppName();

        if (serviceName == null) {
            serviceName = resourceMethodInvoker.getResourceClass().getName();
        }

        String methodName = resourceMethodInvoker.getMethod().getName();

        RpcInternalContext context = RpcInternalContext.getContext();
        context.setAttachment(INTERNAL_KEY_PREFIX + RestConstants.REST_SERVICE_KEY, serviceName);
        context.setAttachment(INTERNAL_KEY_PREFIX + RestConstants.REST_METHODNAME_KEY, methodName);

        context.setAttachment(RemotingConstants.HEAD_APP_NAME, appName);
    } catch (Exception e) {
        logger.error(LogCodes.getLog(LogCodes.ERROR_LOOKOUT_PROCESS), e);
    }

}
 
Example 11
Source File: AbstractHttp2ClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 调用后设置一些属性(注意,在异步的情况较多下)
 *
 * @param context RPC上下文
 * @param request 请求对象
 */
protected void afterSend(RpcInternalContext context, SofaRequest request) {
    currentRequests.decrementAndGet();
    int cost = context.getStopWatch().tick().read();
    context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SERIALIZE_TIME, cost);
    if (EventBus.isEnable(ClientAfterSendEvent.class)) {
        EventBus.post(new ClientAfterSendEvent(request));
    }
}
 
Example 12
Source File: BoltClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected void putToContextIfNotNull(InvokeContext invokeContext, String oldKey,
                                     RpcInternalContext context, String key) {
    Object value = invokeContext.get(oldKey);
    if (value != null) {
        context.setAttachment(key, value);
    }
}
 
Example 13
Source File: BoltServerProcessor.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void putToContextIfNotNull(InvokeContext invokeContext, String oldKey,
                                   RpcInternalContext context, String key) {
    Object value = invokeContext.get(oldKey);
    if (value != null) {
        context.setAttachment(key, value);
    }
}
 
Example 14
Source File: SofaRpcSerialization.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 服务端记录反序列化请求的大小和耗时
 *
 * @param requestCommand 请求对象
 */
private void recordDeserializeRequest(RequestCommand requestCommand) {
    if (!RpcInternalContext.isAttachmentEnable()) {
        return;
    }
    RpcInternalContext context = RpcInternalContext.getContext();
    int cost = context.getStopWatch().tick().read();
    int requestSize = RpcProtocol.getRequestHeaderLength()
        + requestCommand.getClazzLength()
        + requestCommand.getContentLength()
        + requestCommand.getHeaderLength();
    // 记录请求反序列化大小和请求反序列化耗时
    context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE, requestSize);
    context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_DESERIALIZE_TIME, cost);
}
 
Example 15
Source File: SofaRpcSerialization.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 服务端记录序列化响应的大小和耗时
 *
 * @param responseCommand 响应体
 */
private void recordSerializeResponse(RpcResponseCommand responseCommand) {
    if (!RpcInternalContext.isAttachmentEnable()) {
        return;
    }
    RpcInternalContext context = RpcInternalContext.getContext();
    int cost = context.getStopWatch().tick().read();
    int respSize = RpcProtocol.getResponseHeaderLength()
        + responseCommand.getClazzLength()
        + responseCommand.getContentLength()
        + responseCommand.getHeaderLength();
    // 记录响应序列化大小和请求序列化耗时
    context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE, respSize);
    context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SERIALIZE_TIME, cost);
}
 
Example 16
Source File: DefaultClientProxyInvoker.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
protected void decorateRequest(SofaRequest request) {
    // 公共的设置
    super.decorateRequest(request);

    // 缓存是为了加快速度
    request.setTargetServiceUniqueName(serviceName);
    request.setSerializeType(serializeType == null ? 0 : serializeType);

    if (!consumerConfig.isGeneric()) {
        // 找到调用类型, generic的时候类型在filter里进行判断
        request.setInvokeType(consumerConfig.getMethodInvokeType(request.getMethodName()));
    }

    RpcInvokeContext invokeCtx = RpcInvokeContext.peekContext();
    RpcInternalContext internalContext = RpcInternalContext.getContext();
    if (invokeCtx != null) {
        // 如果用户设置了调用级别回调函数
        SofaResponseCallback responseCallback = invokeCtx.getResponseCallback();
        if (responseCallback != null) {
            request.setSofaResponseCallback(responseCallback);
            invokeCtx.setResponseCallback(null); // 一次性用完
            invokeCtx.put(RemotingConstants.INVOKE_CTX_IS_ASYNC_CHAIN,
                isSendableResponseCallback(responseCallback));
        }
        // 如果用户设置了调用级别超时时间
        Integer timeout = invokeCtx.getTimeout();
        if (timeout != null) {
            request.setTimeout(timeout);
            invokeCtx.setTimeout(null);// 一次性用完
        }
        // 如果用户指定了调用的URL
        String targetURL = invokeCtx.getTargetURL();
        if (targetURL != null) {
            internalContext.setAttachment(HIDDEN_KEY_PINPOINT, targetURL);
            invokeCtx.setTargetURL(null);// 一次性用完
        }
        // 如果用户指定了透传数据
        if (RpcInvokeContext.isBaggageEnable()) {
            // 需要透传
            BaggageResolver.carryWithRequest(invokeCtx, request);
            internalContext.setAttachment(HIDDEN_KEY_INVOKE_CONTEXT, invokeCtx);
        }
    }
    if (RpcInternalContext.isAttachmentEnable()) {
        internalContext.setAttachment(INTERNAL_KEY_APP_NAME, consumerConfig.getAppName());
        internalContext.setAttachment(INTERNAL_KEY_PROTOCOL_NAME, consumerConfig.getProtocol());
    }

    // 额外属性通过HEAD传递给服务端
    request.addRequestProp(RemotingConstants.HEAD_APP_NAME, consumerConfig.getAppName());
    request.addRequestProp(RemotingConstants.HEAD_PROTOCOL, consumerConfig.getProtocol());
}
 
Example 17
Source File: RestTracerAdapter.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
/**
 * 适配服务端filter
 *
 * @param requestContext ContainerRequestContext
 */
public static void serverFilter(ContainerRequestContext requestContext) {
    try {
        SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
        SofaTracerSpan serverSpan = sofaTraceContext.getCurrentSpan();
        if (serverSpan != null) {
            RpcInternalContext context = RpcInternalContext.getContext();

            context.setAttachment(RpcConstants.INTERNAL_KEY_SERVER_RECEIVE_TIME, RpcRuntimeContext.now());

            SofaResourceMethodInvoker resourceMethodInvoker = (SofaResourceMethodInvoker)
                    ((PostMatchContainerRequestContext) requestContext)
                        .getResourceMethod();

            SofaResourceFactory factory = resourceMethodInvoker.getResource();
            String serviceName = factory.getServiceName();
            String appName = factory.getAppName();

            if (serviceName == null) {
                serviceName = resourceMethodInvoker.getResourceClass().getName();
            }
            serverSpan.setTag(RpcSpanTags.SERVICE, serviceName);
            if (resourceMethodInvoker.getMethod() != null) {
                serverSpan.setTag(RpcSpanTags.METHOD, resourceMethodInvoker.getMethod().getName());
                //serverSend需要
                context.setAttachment(METHOD_TYPE_STRING, resourceMethodInvoker.getMethod());
            }

            serverSpan.setTag(RpcSpanTags.REMOTE_IP, context.getRemoteHostName()); // 客户端地址

            String remoteAppName = requestContext.getHeaderString(RemotingConstants.HEAD_APP_NAME);
            if (StringUtils.isNotBlank(remoteAppName)) {
                serverSpan.setTag(RpcSpanTags.REMOTE_APP, remoteAppName);
            }
            serverSpan.setTag(RpcSpanTags.PROTOCOL, RpcConstants.PROTOCOL_TYPE_REST);
            serverSpan.setTag(RpcSpanTags.INVOKE_TYPE, RpcConstants.INVOKER_TYPE_SYNC);
            if (appName == null) {
                appName = (String) RpcRuntimeContext.get(RpcRuntimeContext.KEY_APPNAME);
            }
            serverSpan.setTag(RpcSpanTags.LOCAL_APP, appName);
        }
    } catch (Throwable t) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("the process of rest tracer server filter occur error ", t);
        }
    }
}
 
Example 18
Source File: RpcSofaTracer.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@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());
    }
}