Java Code Examples for com.alipay.sofa.rpc.core.request.SofaRequest#addRequestProp()

The following examples show how to use com.alipay.sofa.rpc.core.request.SofaRequest#addRequestProp() . 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: RestTracerAdapter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Decode baggage items from netty request to sofa request context
 *
 * @param request       netty http request
 * @param sofaRequest   rpc request holder
 */
private static void decodeBaggageItemsFromRequest(NettyHttpRequest request,
                                                  SofaRequest sofaRequest) {
    HttpHeaders headers = request.getHttpHeaders();
    // Decode baggage items
    MultivaluedMap<String, String> headerMaps = headers.getRequestHeaders();
    if (!RpcInvokeContext.isBaggageEnable() || headerMaps == null || headerMaps.isEmpty()) {
        return;
    }

    Map<String, String> baggageItems = new HashMap<String, String>();
    for (Map.Entry<String, List<String>> entry : headerMaps.entrySet()) {
        if (!entry.getKey().startsWith(RPC_REQUEST_BAGGAGE_PREFIX) ||
            entry.getValue() == null ||
            entry.getValue().isEmpty()) {
            continue;
        }

        String value = entry.getValue().get(0);
        String key = entry.getKey().substring(RPC_REQUEST_BAGGAGE_PREFIX_LEN);
        baggageItems.put(key, value);
    }
    sofaRequest.addRequestProp(RemotingConstants.RPC_REQUEST_BAGGAGE, baggageItems);

    BaggageResolver.pickupFromRequest(RpcInvokeContext.peekContext(), sofaRequest, true);
}
 
Example 2
Source File: RestLookoutAdapter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static void sendRestServerSendEvent(RestServerSendEvent restServerSendEvent) {
    //this is special for rest
    if (EventBus.isEnable(ServerSendEvent.class)) {
        SofaRequest request = new SofaRequest();

        String appName = (String) RpcRuntimeContext.get(RpcRuntimeContext.KEY_APPNAME);
        request.setTargetAppName(appName);
        request.addRequestProp(RemotingConstants.HEAD_APP_NAME, restServerSendEvent.getRequest().getHttpHeaders()
            .getHeaderString(RemotingConstants.HEAD_APP_NAME));
        RpcInternalContext context = RpcInternalContext.getContext();
        request.setTargetServiceUniqueName((String) context.getAttachment(INTERNAL_KEY_PREFIX +
            RestConstants.REST_SERVICE_KEY));

        request.setMethodName((String) context.getAttachment(INTERNAL_KEY_PREFIX +
            RestConstants.REST_METHODNAME_KEY));
        request.addRequestProp(RemotingConstants.HEAD_PROTOCOL, RpcConstants.PROTOCOL_TYPE_REST);
        request.setInvokeType(RpcConstants.INVOKER_TYPE_SYNC);
        SofaResponse response = new SofaResponse();

        if (restServerSendEvent.getThrowable() != null) {
            response.setErrorMsg(restServerSendEvent.getThrowable().getMessage());
        }
        final ServerSendEvent event = new ServerSendEvent(request, response, restServerSendEvent.getThrowable());
        EventBus.post(event);
    }
}
 
Example 3
Source File: JacksonSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void decodeSofaRequest(AbstractByteBuf data, SofaRequest sofaRequest, Map<String, String> head) {
    if (head == null) {
        throw buildDeserializeError("head is null!");
    }
    // 解析request信息
    String targetService = head.remove(RemotingConstants.HEAD_TARGET_SERVICE);
    if (targetService != null) {
        sofaRequest.setTargetServiceUniqueName(targetService);
        String interfaceName = ConfigUniqueNameGenerator.getInterfaceName(targetService);
        sofaRequest.setInterfaceName(interfaceName);
    } else {
        throw buildDeserializeError("HEAD_TARGET_SERVICE is null");
    }
    String methodName = head.remove(RemotingConstants.HEAD_METHOD_NAME);
    if (methodName != null) {
        sofaRequest.setMethodName(methodName);
    } else {
        throw buildDeserializeError("HEAD_METHOD_NAME is null");
    }
    String targetApp = head.remove(RemotingConstants.HEAD_TARGET_APP);
    if (targetApp != null) {
        sofaRequest.setTargetAppName(targetApp);
    }

    // parse tracer and baggage
    parseRequestHeader(RemotingConstants.RPC_TRACE_NAME, head, sofaRequest);
    if (RpcInvokeContext.isBaggageEnable()) {
        parseRequestHeader(RemotingConstants.RPC_REQUEST_BAGGAGE, head, sofaRequest);
    }
    for (Map.Entry<String, String> entry : head.entrySet()) {
        sofaRequest.addRequestProp(entry.getKey(), entry.getValue());
    }

    // according interface and method name to find parameter types
    JavaType[] requestClassList = jacksonHelper.getReqClass(targetService, sofaRequest.getMethodName());
    Object[] reqList = decode(data, requestClassList);
    sofaRequest.setMethodArgs(reqList);
    sofaRequest.setMethodArgSigs(parseArgSigs(requestClassList));
}
 
Example 4
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 5
Source File: BaggageResolver.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 通过请求透传数据
 *
 * @param context RpcInvokeContext
 * @param request 请求
 */
public static void carryWithRequest(RpcInvokeContext context, SofaRequest request) {
    if (context != null) {
        Map<String, String> requestBaggage = context.getAllRequestBaggage();
        if (CommonUtils.isNotEmpty(requestBaggage)) { // 需要透传
            request.addRequestProp(RemotingConstants.RPC_REQUEST_BAGGAGE, requestBaggage);
        }
    }
}
 
Example 6
Source File: ProtostuffSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void parseRequestHeader(String key, Map<String, String> headerMap,
                                SofaRequest sofaRequest) {
    Map<String, String> traceMap = new HashMap<String, String>(8);
    CodecUtils.treeCopyTo(key + ".", headerMap, traceMap, true);
    if (!traceMap.isEmpty()) {
        sofaRequest.addRequestProp(key, traceMap);
    }
}
 
Example 7
Source File: ProtostuffSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void decodeSofaRequest(AbstractByteBuf data, SofaRequest sofaRequest, Map<String, String> head) {
    if (head == null) {
        throw buildDeserializeError("head is null!");
    }
    // 解析request信息
    String targetService = head.remove(RemotingConstants.HEAD_TARGET_SERVICE);
    if (targetService != null) {
        sofaRequest.setTargetServiceUniqueName(targetService);
        String interfaceName = ConfigUniqueNameGenerator.getInterfaceName(targetService);
        sofaRequest.setInterfaceName(interfaceName);
    } else {
        throw buildDeserializeError("HEAD_TARGET_SERVICE is null");
    }
    String methodName = head.remove(RemotingConstants.HEAD_METHOD_NAME);
    if (methodName != null) {
        sofaRequest.setMethodName(methodName);
    } else {
        throw buildDeserializeError("HEAD_METHOD_NAME is null");
    }
    String targetApp = head.remove(RemotingConstants.HEAD_TARGET_APP);
    if (targetApp != null) {
        sofaRequest.setTargetAppName(targetApp);
    }

    // 解析tracer等信息
    parseRequestHeader(RemotingConstants.RPC_TRACE_NAME, head, sofaRequest);
    if (RpcInvokeContext.isBaggageEnable()) {
        parseRequestHeader(RemotingConstants.RPC_REQUEST_BAGGAGE, head, sofaRequest);
    }
    for (Map.Entry<String, String> entry : head.entrySet()) {
        sofaRequest.addRequestProp(entry.getKey(), entry.getValue());
    }

    // 根据接口+方法名找到参数类型 此处要处理byte[]为空的吗
    Class requestClass = protostuffHelper.getReqClass(targetService,
        sofaRequest.getMethodName());
    Object pbReq = decode(data, requestClass, head);
    sofaRequest.setMethodArgs(new Object[] { pbReq });
    sofaRequest.setMethodArgSigs(new String[] { requestClass.getName() });
}
 
Example 8
Source File: MsgPackSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void parseRequestHeader(String key, Map<String, String> headerMap,
                                SofaRequest sofaRequest) {
    Map<String, String> traceMap = new HashMap<>(8);
    CodecUtils.treeCopyTo(key + ".", headerMap, traceMap, true);
    if (!traceMap.isEmpty()) {
        sofaRequest.addRequestProp(key, traceMap);
    }
}
 
Example 9
Source File: JacksonSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void parseRequestHeader(String key, Map<String, String> headerMap,
                                SofaRequest sofaRequest) {
    Map<String, String> traceMap = new HashMap<String, String>(8);
    CodecUtils.treeCopyTo(key + ".", headerMap, traceMap, true);
    if (!traceMap.isEmpty()) {
        sofaRequest.addRequestProp(key, traceMap);
    }
}
 
Example 10
Source File: SofaRpcUtilsTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetApplicationName() {
    SofaRequest request = new SofaRequest();
    String applicationName = SofaRpcUtils.getApplicationName(request);
    assertEquals("", applicationName);

    request.addRequestProp("app", "test-app");
    applicationName = SofaRpcUtils.getApplicationName(request);
    assertEquals("test-app", applicationName);
}
 
Example 11
Source File: ProtobufSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void parseRequestHeader(String key, Map<String, String> headerMap,
                                SofaRequest sofaRequest) {
    Map<String, String> traceMap = new HashMap<String, String>(8);
    CodecUtils.treeCopyTo(key + ".", headerMap, traceMap, true);
    if (!traceMap.isEmpty()) {
        sofaRequest.addRequestProp(key, traceMap);
    }
}
 
Example 12
Source File: ProtobufSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void decodeSofaRequest(AbstractByteBuf data, SofaRequest sofaRequest, Map<String, String> head) {
    if (head == null) {
        throw buildDeserializeError("head is null!");
    }
    // 解析request信息
    String targetService = head.remove(RemotingConstants.HEAD_TARGET_SERVICE);
    if (targetService != null) {
        sofaRequest.setTargetServiceUniqueName(targetService);
        String interfaceName = ConfigUniqueNameGenerator.getInterfaceName(targetService);
        sofaRequest.setInterfaceName(interfaceName);
    } else {
        throw buildDeserializeError("HEAD_TARGET_SERVICE is null");
    }
    String methodName = head.remove(RemotingConstants.HEAD_METHOD_NAME);
    if (methodName != null) {
        sofaRequest.setMethodName(methodName);
    } else {
        throw buildDeserializeError("HEAD_METHOD_NAME is null");
    }
    String targetApp = head.remove(RemotingConstants.HEAD_TARGET_APP);
    if (targetApp != null) {
        sofaRequest.setTargetAppName(targetApp);
    }

    // 解析tracer等信息
    parseRequestHeader(RemotingConstants.RPC_TRACE_NAME, head, sofaRequest);
    if (RpcInvokeContext.isBaggageEnable()) {
        parseRequestHeader(RemotingConstants.RPC_REQUEST_BAGGAGE, head, sofaRequest);
    }
    for (Map.Entry<String, String> entry : head.entrySet()) {
        sofaRequest.addRequestProp(entry.getKey(), entry.getValue());
    }

    // 根据接口+方法名找到参数类型 此处要处理byte[]为空的吗
    Class requestClass = protobufHelper.getReqClass(targetService,
        sofaRequest.getMethodName());
    Object pbReq = decode(data, requestClass, head);
    sofaRequest.setMethodArgs(new Object[] { pbReq });
    sofaRequest.setMethodArgSigs(new String[] { requestClass.getName() });
}
 
Example 13
Source File: Http2ServerChannelHandler.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void parseHttp2Request(Http2Headers headers, SofaRequest sofaRequest) {
    String targetApp = StringUtils.toString(headers.get(RemotingConstants.HEAD_TARGET_APP));
    sofaRequest.setTargetAppName(targetApp);
    // 获取序列化类型
    byte serializeType;
    CharSequence codeName = headers.get(RemotingConstants.HEAD_SERIALIZE_TYPE);
    if (codeName != null) {
        serializeType = HttpTransportUtils.getSerializeTypeByName(codeName.toString());
    } else {
        String contentType = StringUtils.toString(headers.get(HttpHeaderNames.CONTENT_TYPE));
        serializeType = HttpTransportUtils.getSerializeTypeByContentType(contentType);
    }
    sofaRequest.setSerializeType(serializeType);

    // 解析trace信息
    Map<String, String> traceMap = new HashMap<String, String>(8);
    Iterator<Map.Entry<CharSequence, CharSequence>> it = headers.iterator();
    while (it.hasNext()) {
        Map.Entry<CharSequence, CharSequence> entry = it.next();
        String key = entry.getKey().toString();
        if (HttpTracerUtils.isTracerKey(key)) {
            HttpTracerUtils.parseTraceKey(traceMap, key, StringUtils.toString(entry.getValue()));
        } else if (!key.startsWith(":")) {
            sofaRequest.addRequestProp(key, StringUtils.toString(entry.getValue()));
        }
    }
    if (!traceMap.isEmpty()) {
        sofaRequest.addRequestProp(RemotingConstants.RPC_TRACE_NAME, traceMap);
    }
}
 
Example 14
Source File: RestTracerAdapter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 适配服务端serverReceived
 */
public static void serverReceived(NettyHttpRequest request) {
    try {
        SofaRequest sofaRequest = new SofaRequest();

        HttpHeaders headers = request.getHttpHeaders();
        String rpcTraceContext = headers.getHeaderString(RemotingConstants.NEW_RPC_TRACE_NAME);
        if (StringUtils.isNotBlank(rpcTraceContext)) {
            // 新格式
            sofaRequest.addRequestProp(RemotingConstants.NEW_RPC_TRACE_NAME, rpcTraceContext);
        } else {
            String traceIdKey = headers.getHeaderString(RemotingConstants.HTTP_HEADER_TRACE_ID_KEY);
            String rpcIdKey = headers.getHeaderString(RemotingConstants.HTTP_HEADER_RPC_ID_KEY);
            if (StringUtils.isEmpty(rpcIdKey)) {
                rpcIdKey = request.getUri().getQueryParameters().getFirst(RemotingConstants.RPC_ID_KEY);
            }
            if (StringUtils.isEmpty(traceIdKey)) {
                traceIdKey = request.getUri().getQueryParameters().getFirst(RemotingConstants.TRACE_ID_KEY);
            }

            if (StringUtils.isNotEmpty(traceIdKey) && StringUtils.isNotEmpty(rpcIdKey)) {
                Map<String, String> map = new HashMap<String, String>();
                map.put(RemotingConstants.TRACE_ID_KEY, traceIdKey);
                map.put(RemotingConstants.RPC_ID_KEY, rpcIdKey);
                String penAttrs = headers.getHeaderString(RemotingConstants.PEN_ATTRS_KEY);
                map.put(RemotingConstants.PEN_ATTRS_KEY, penAttrs);
                sofaRequest.addRequestProp(RemotingConstants.RPC_TRACE_NAME, map);
            }
        }
        Tracers.serverReceived(sofaRequest);

        RestBaggageItemsHandler.decodeBaggageItemsFromRequest(request, sofaRequest);
    } catch (Throwable t) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(LogCodes.getLog(LogCodes.ERROR_TRACER_UNKNOWN_EXP, "receive", "rest", "server"), t);
        }
    }
}
 
Example 15
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 16
Source File: MsgPackSerializer.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
private void decodeSofaRequest(AbstractByteBuf data, SofaRequest sofaRequest, Map<String, String> head) {
    if (head == null) {
        throw buildDeserializeError("head is null!");
    }
    // 解析request信息
    String targetService = head.remove(RemotingConstants.HEAD_TARGET_SERVICE);
    if (targetService != null) {
        sofaRequest.setTargetServiceUniqueName(targetService);
        String interfaceName = ConfigUniqueNameGenerator.getInterfaceName(targetService);
        sofaRequest.setInterfaceName(interfaceName);
    } else {
        throw buildDeserializeError("HEAD_TARGET_SERVICE is null");
    }
    String methodName = head.remove(RemotingConstants.HEAD_METHOD_NAME);
    if (methodName != null) {
        sofaRequest.setMethodName(methodName);
    } else {
        throw buildDeserializeError("HEAD_METHOD_NAME is null");
    }
    String targetApp = head.remove(RemotingConstants.HEAD_TARGET_APP);
    if (targetApp != null) {
        sofaRequest.setTargetAppName(targetApp);
    }

    // parse tracer and baggage
    parseRequestHeader(RemotingConstants.RPC_TRACE_NAME, head, sofaRequest);
    if (RpcInvokeContext.isBaggageEnable()) {
        parseRequestHeader(RemotingConstants.RPC_REQUEST_BAGGAGE, head, sofaRequest);
    }
    for (Map.Entry<String, String> entry : head.entrySet()) {
        sofaRequest.addRequestProp(entry.getKey(), entry.getValue());
    }

    // according interface and method name to find paramter types
    Class requestClass = helper.getReqClass(targetService,
            sofaRequest.getMethodName());

    Object pbReq = decode(data, requestClass, head);
    sofaRequest.setMethodArgs(new Object[]{pbReq});
    sofaRequest.setMethodArgSigs(new String[]{requestClass.getName()});
}
 
Example 17
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());
}