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

The following examples show how to use com.alipay.sofa.rpc.context.RpcInternalContext#getContext() . 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: 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 2
Source File: BoltClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void oneWaySend(SofaRequest request, int timeout) throws SofaRpcException {
    checkConnection();
    RpcInternalContext context = RpcInternalContext.getContext();
    InvokeContext invokeContext = createInvokeContext(request);
    SofaRpcException throwable = null;
    try {
        beforeSend(context, request);
        doOneWay(request, invokeContext, timeout);
    } catch (Exception e) { // 其它异常
        throwable = convertToRpcException(e);
        throw throwable;
    } finally {
        afterSend(context, invokeContext, request);
        if (EventBus.isEnable(ClientSyncReceiveEvent.class)) {
            EventBus.post(new ClientSyncReceiveEvent(transportConfig.getConsumerConfig(),
                transportConfig.getProviderInfo(), request, null, throwable));
        }
    }
}
 
Example 3
Source File: SofaRpcMetrics.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void onEvent(ClientEndInvokeEvent event) {
    InvokeMeta meta = new InvokeMeta(
        event.getRequest(),
        event.getResponse(),
        getLongAvoidNull(RpcInternalContext.getContext().getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE))
    );
    RpcInternalContext context = RpcInternalContext.getContext();
    Duration elapsed = meta.elapsed();
    Tags tags = meta.tags(this.common);

    clientTotal.apply(tags).record(elapsed);
    if (!meta.success()) {
        clientFail.apply(tags).record(elapsed);
    }
    requestSize.apply(tags).record(getLongAvoidNull(
        context.getAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE)));
    responseSize.apply(tags).record(getLongAvoidNull(
        context.getAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE)));
}
 
Example 4
Source File: DefaultClientProxyInvoker.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected void decorateResponse(SofaResponse response) {
    // 公共的设置
    super.decorateResponse(response);
    // 上下文内转外
    RpcInternalContext context = RpcInternalContext.getContext();
    ResponseFuture future = context.getFuture();
    RpcInvokeContext invokeCtx = null;
    if (future != null) {
        invokeCtx = RpcInvokeContext.getContext();
        invokeCtx.setFuture(future);
    }
    if (RpcInvokeContext.isBaggageEnable()) {
        BaggageResolver.pickupFromResponse(invokeCtx, response, true);
    }
    // bad code
    if (RpcInternalContext.isAttachmentEnable()) {
        String resultCode = (String) context.getAttachment(INTERNAL_KEY_RESULT_CODE);
        if (resultCode != null) {
            if (invokeCtx == null) {
                invokeCtx = RpcInvokeContext.getContext();
            }
            invokeCtx.put(RemotingConstants.INVOKE_CTX_RPC_RESULT_CODE, resultCode);
        }
    }
}
 
Example 5
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 6
Source File: RestTracerAdapter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 存入tracer信息
 *
 * @param requestContext ClientRequestContext
 */
public static void beforeSend(ClientRequestContext requestContext) {

    // tracer信息放入request 发到服务端
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    SofaTracerSpan clientSpan = sofaTraceContext.getCurrentSpan();
    RpcInternalContext context = RpcInternalContext.getContext();
    if (clientSpan != null) {
        requestContext.getHeaders().add(RemotingConstants.NEW_RPC_TRACE_NAME,
            clientSpan.getSofaTracerSpanContext().serializeSpanContext());
    }
    // 客户端发送自己的应用名
    String appName = (String) context.getAttachment(INTERNAL_KEY_APP_NAME);
    if (appName != null) {
        requestContext.getHeaders().add(RemotingConstants.HEAD_APP_NAME, appName);
    }

    RestBaggageItemsHandler.encodeBaggageItemToRequest(requestContext.getHeaders());
}
 
Example 7
Source File: ConsumerTracerFilter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {

    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    SofaTracerSpan clientSpan = sofaTraceContext.getCurrentSpan();

    clientSpan.setTag(RpcSpanTags.INVOKE_TYPE, request.getInvokeType());

    RpcInternalContext context = RpcInternalContext.getContext();
    clientSpan.setTag(RpcSpanTags.ROUTE_RECORD,
        (String) context.getAttachment(RpcConstants.INTERNAL_KEY_ROUTER_RECORD));

    ProviderInfo providerInfo = context.getProviderInfo();
    if (providerInfo != null) {
        clientSpan.setTag(RpcSpanTags.REMOTE_APP, providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME));
        clientSpan.setTag(RpcSpanTags.REMOTE_IP, providerInfo.getHost() + ":" + providerInfo.getPort());
    }

    return invoker.invoke(request);
    // 因为异步的场景,所以received不写在这里
}
 
Example 8
Source File: BoltClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseFuture asyncSend(SofaRequest request, int timeout) throws SofaRpcException {
    checkConnection();
    RpcInternalContext context = RpcInternalContext.getContext();
    InvokeContext boltInvokeContext = createInvokeContext(request);
    try {
        beforeSend(context, request);
        boltInvokeContext.put(RemotingConstants.INVOKE_CTX_RPC_CTX, context);
        return doInvokeAsync(request, context, boltInvokeContext, timeout);
    } catch (Exception e) {
        throw convertToRpcException(e);
    } finally {
        afterSend(context, boltInvokeContext, request);
    }
}
 
Example 9
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 10
Source File: ClientProxyInvoker.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * proxy拦截的调用
 *
 * @param request 请求消息
 * @return 调用结果
 */
@Override
public SofaResponse invoke(SofaRequest request) throws SofaRpcException {
    SofaResponse response = null;
    Throwable throwable = null;
    try {
        RpcInternalContext.pushContext();
        RpcInternalContext context = RpcInternalContext.getContext();
        context.setProviderSide(false);
        // 包装请求
        decorateRequest(request);
        try {
            // 产生开始调用事件
            if (EventBus.isEnable(ClientStartInvokeEvent.class)) {
                EventBus.post(new ClientStartInvokeEvent(request));
            }
            // 得到结果
            response = cluster.invoke(request);
        } catch (SofaRpcException e) {
            throwable = e;
            throw e;
        } finally {
            // 产生调用结束事件
            if (!request.isAsync()) {
                if (EventBus.isEnable(ClientEndInvokeEvent.class)) {
                    EventBus.post(new ClientEndInvokeEvent(request, response, throwable));
                }
            }
        }
        // 包装响应
        decorateResponse(response);
        return response;
    } finally {
        RpcInternalContext.removeContext();
        RpcInternalContext.popContext();
    }
}
 
Example 11
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 12
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 13
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 14
Source File: RpcServiceContextFilter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
    RpcServiceContext serviceCtx = new RpcServiceContext();
    RpcInternalContext internalCtx = RpcInternalContext.getContext();
    serviceCtx.setServiceName(request.getTargetServiceUniqueName());
    serviceCtx.setMethodName(request.getMethodName());
    serviceCtx.setTraceId((String) internalCtx.getAttachment(RpcConstants.INTERNAL_KEY_TRACE_ID));
    serviceCtx.setRpcId((String) internalCtx.getAttachment(RpcConstants.INTERNAL_KEY_SPAN_ID));
    serviceCtx.setCallerAppName((String) request.getRequestProp(RemotingConstants.HEAD_APP_NAME));
    serviceCtx.setCallerUrl(internalCtx.getRemoteHostName());

    RpcInvokeContext.getContext().put(RemotingConstants.INVOKE_CTX_RPC_SER_CTX, serviceCtx);

    return invoker.invoke(request);
}
 
Example 15
Source File: SofaRpcConsumerInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    SofaRequest sofaRequest = (SofaRequest) allArguments[0];
    RpcInternalContext rpcContext = RpcInternalContext.getContext();

    ProviderInfo providerInfo = rpcContext.getProviderInfo();

    AbstractSpan span = null;

    final String host = providerInfo.getHost();
    final int port = providerInfo.getPort();
    final ContextCarrier contextCarrier = new ContextCarrier();
    final String operationName = generateOperationName(providerInfo, sofaRequest);
    span = ContextManager.createExitSpan(operationName, contextCarrier, host + ":" + port);
    CarrierItem next = contextCarrier.items();
    while (next.hasNext()) {
        next = next.next();
        String key = next.getHeadKey();
        String skyWalkingKey = SKYWALKING_PREFIX + key;
        sofaRequest.addRequestProp(skyWalkingKey, next.getHeadValue());
    }

    Tags.URL.set(span, generateRequestURL(providerInfo, sofaRequest));
    span.setComponent(ComponentsDefine.SOFARPC);
    SpanLayer.asRPCFramework(span);
}
 
Example 16
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 17
Source File: AbstractHttp2ClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 同步调用
 *
 * @param request 请求对象
 * @param timeout 超时时间(毫秒)
 * @return 返回对象
 * @throws InterruptedException 中断异常
 * @throws ExecutionException   执行异常
 * @throws TimeoutException     超时异常
 */
protected SofaResponse doInvokeSync(SofaRequest request, int timeout) throws InterruptedException,
    ExecutionException, TimeoutException {
    HttpResponseFuture future = new HttpResponseFuture(request, timeout);
    AbstractHttpClientHandler callback = new SyncInvokeClientHandler(transportConfig.getConsumerConfig(),
        transportConfig.getProviderInfo(), future, request, RpcInternalContext.getContext(),
        ClassLoaderUtils.getCurrentClassLoader());
    future.setSentTime();
    doSend(request, callback, timeout);
    future.setSentTime();
    return future.getSofaResponse(timeout, TimeUnit.MILLISECONDS);
}
 
Example 18
Source File: RpcSofaTracer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void clientBeforeSend(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;
    }
    SofaTracerSpanContext sofaTracerSpanContext = clientSpan.getSofaTracerSpanContext();
    //获取 RPC 上下文
    RpcInternalContext rpcInternalContext = RpcInternalContext.getContext();
    ProviderInfo providerInfo;
    if ((providerInfo = rpcInternalContext.getProviderInfo()) != null &&
        providerInfo.getRpcVersion() >= 50100) { // 版本>5.1.0
        //新调用新:缓存在 Request 中
        String serializedSpanContext = sofaTracerSpanContext.serializeSpanContext();
        request.addRequestProp(RemotingConstants.NEW_RPC_TRACE_NAME, serializedSpanContext);
    } else {
        //新调用老
        Map<String, String> oldTracerContext = new HashMap<String, String>();
        oldTracerContext.put(TracerCompatibleConstants.TRACE_ID_KEY, sofaTracerSpanContext.getTraceId());
        oldTracerContext.put(TracerCompatibleConstants.RPC_ID_KEY, sofaTracerSpanContext.getSpanId());
        // 将采样标记解析并传递
        oldTracerContext.put(TracerCompatibleConstants.SAMPLING_MARK,
            String.valueOf(sofaTracerSpanContext.isSampled()));
        //业务
        oldTracerContext.put(TracerCompatibleConstants.PEN_ATTRS_KEY,
            sofaTracerSpanContext.getBizSerializedBaggage());
        //系统
        oldTracerContext.put(TracerCompatibleConstants.PEN_SYS_ATTRS_KEY,
            sofaTracerSpanContext.getSysSerializedBaggage());
        request.addRequestProp(RemotingConstants.RPC_TRACE_NAME, oldTracerContext);
    }
}
 
Example 19
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 20
Source File: AbstractCluster.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * 发起调用链
 *
 * @param providerInfo 服务端信息
 * @param request      请求对象
 * @return 执行后返回的响应
 * @throws SofaRpcException 请求RPC异常
 */
protected SofaResponse filterChain(ProviderInfo providerInfo, SofaRequest request) throws SofaRpcException {
    RpcInternalContext context = RpcInternalContext.getContext();
    context.setProviderInfo(providerInfo);
    return filterChain.invoke(request);
}