Search in sources :

Example 1 with RpcMethodInfo

use of com.baidu.brpc.RpcMethodInfo in project brpc-java by baidu.

the class HuluRpcProtocol method decodeRequest.

@Override
public Request decodeRequest(Object packet) throws Exception {
    Request request = this.createRequest();
    HuluRpcDecodePacket requestPacket = (HuluRpcDecodePacket) packet;
    ByteBuf metaBuf = requestPacket.getMetaBuf();
    ByteBuf protoAndAttachmentBuf = requestPacket.getProtoAndAttachmentBuf();
    ByteBuf protoBuf = null;
    try {
        HuluRpcProto.HuluRpcRequestMeta requestMeta = (HuluRpcProto.HuluRpcRequestMeta) ProtobufUtils.parseFrom(metaBuf, defaultRpcRequestMetaInstance);
        request.setCorrelationId(requestMeta.getCorrelationId());
        request.setLogId(requestMeta.getLogId());
        int compressType = requestMeta.getCompressType();
        request.setCompressType(compressType);
        // service info
        ServiceManager serviceManager = ServiceManager.getInstance();
        RpcMethodInfo rpcMethodInfo = serviceManager.getService(requestMeta.getServiceName(), String.valueOf(requestMeta.getMethodIndex()));
        if (rpcMethodInfo == null) {
            String errorMsg = String.format("Fail to find service=%s, methodIndex=%s", requestMeta.getServiceName(), requestMeta.getMethodIndex());
            request.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errorMsg));
            return request;
        }
        if (requestMeta.hasTraceId()) {
            request.setTraceId(requestMeta.getTraceId());
        }
        if (requestMeta.hasSpanId()) {
            request.setSpanId(request.getSpanId());
        }
        if (requestMeta.hasParentSpanId()) {
            request.setParentSpanId(requestMeta.getParentSpanId());
        }
        if (requestMeta.getExtFieldsCount() > 0) {
            if (request.getKvAttachment() == null) {
                request.setKvAttachment(new HashMap<String, Object>());
            }
            for (HuluRpcProto.HuluRpcRequestMetaExtField extField : requestMeta.getExtFieldsList()) {
                request.getKvAttachment().put(extField.getKey(), extField.getValue());
            }
        }
        request.setServiceName(rpcMethodInfo.getServiceName());
        request.setMethodName(rpcMethodInfo.getMethodName());
        request.setRpcMethodInfo(rpcMethodInfo);
        request.setTargetMethod(rpcMethodInfo.getMethod());
        request.setTarget(rpcMethodInfo.getTarget());
        // proto body
        try {
            Compress compress = compressManager.getCompress(compressType);
            int userMessageSize = requestMeta.getUserMessageSize();
            if (userMessageSize > 0) {
                protoBuf = protoAndAttachmentBuf.readSlice(userMessageSize);
            } else {
                protoBuf = protoAndAttachmentBuf;
            }
            Object requestProto = compress.uncompressInput(protoBuf, rpcMethodInfo);
            request.setArgs(new Object[] { requestProto });
            // attachment
            if (userMessageSize > 0) {
                request.setBinaryAttachment(protoAndAttachmentBuf);
                protoAndAttachmentBuf = null;
            }
        } catch (Exception ex) {
            String errorMsg = String.format("decode failed, msg=%s", ex.getMessage());
            LOG.error(errorMsg);
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, errorMsg, ex);
        }
        return request;
    } finally {
        if (metaBuf != null) {
            metaBuf.release();
        }
        if (protoAndAttachmentBuf != null) {
            protoAndAttachmentBuf.release();
        }
    }
}
Also used : Compress(com.baidu.brpc.compress.Compress) RpcMethodInfo(com.baidu.brpc.RpcMethodInfo) Request(com.baidu.brpc.protocol.Request) ByteBuf(io.netty.buffer.ByteBuf) DynamicCompositeByteBuf(com.baidu.brpc.buffer.DynamicCompositeByteBuf) RpcException(com.baidu.brpc.exceptions.RpcException) TooBigDataException(com.baidu.brpc.exceptions.TooBigDataException) NotEnoughDataException(com.baidu.brpc.exceptions.NotEnoughDataException) BadSchemaException(com.baidu.brpc.exceptions.BadSchemaException) IOException(java.io.IOException) ServiceManager(com.baidu.brpc.server.ServiceManager) RpcException(com.baidu.brpc.exceptions.RpcException)

Example 2 with RpcMethodInfo

use of com.baidu.brpc.RpcMethodInfo in project brpc-java by baidu.

the class PublicPbrpcProtocol method decodeRequest.

@Override
public Request decodeRequest(Object packet) throws Exception {
    Request request = this.createRequest();
    PublicPbRpcPacket pbPacket = (PublicPbRpcPacket) packet;
    ByteBuf bodyBuf = pbPacket.getBody();
    try {
        PublicPbrpcRequest pbRequest = (PublicPbrpcRequest) ProtobufUtils.parseFrom(bodyBuf, PublicPbrpcRequest.getDefaultInstance());
        RequestBody body = pbRequest.getRequestBody(0);
        RequestHead head = pbRequest.getRequestHead();
        request.setCorrelationId(body.getId());
        request.setLogId(head.getLogId());
        int compressType = head.getCompressType();
        request.setCompressType(compressType);
        // service info
        ServiceManager serviceManager = ServiceManager.getInstance();
        RpcMethodInfo rpcMethodInfo = serviceManager.getService(body.getService(), String.valueOf(body.getMethodId()));
        if (rpcMethodInfo == null) {
            String errorMsg = String.format("Fail to find service=%s, methodIndex=%s", body.getService(), body.getMethodId());
            request.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errorMsg));
            return request;
        }
        request.setRpcMethodInfo(rpcMethodInfo);
        request.setTargetMethod(rpcMethodInfo.getMethod());
        request.setTarget(rpcMethodInfo.getTarget());
        // proto body
        try {
            Compress compress = compressManager.getCompress(compressType);
            Object requestProto = compress.uncompressInput(body.getSerializedRequest().toByteArray(), rpcMethodInfo);
            request.setArgs(new Object[] { requestProto });
        } catch (Exception ex) {
            String errorMsg = String.format("decode failed, msg=%s", ex.getMessage());
            log.error(errorMsg);
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, errorMsg, ex);
        }
        return request;
    } finally {
        if (bodyBuf != null) {
            bodyBuf.release();
        }
    }
}
Also used : Compress(com.baidu.brpc.compress.Compress) RpcMethodInfo(com.baidu.brpc.RpcMethodInfo) PublicPbrpcRequest(com.baidu.brpc.protocol.pbrpc.PublicPbrpcProto.PublicPbrpcRequest) Request(com.baidu.brpc.protocol.Request) ByteString(com.google.protobuf.ByteString) ByteBuf(io.netty.buffer.ByteBuf) DynamicCompositeByteBuf(com.baidu.brpc.buffer.DynamicCompositeByteBuf) RpcException(com.baidu.brpc.exceptions.RpcException) TooBigDataException(com.baidu.brpc.exceptions.TooBigDataException) NotEnoughDataException(com.baidu.brpc.exceptions.NotEnoughDataException) BadSchemaException(com.baidu.brpc.exceptions.BadSchemaException) PublicPbrpcRequest(com.baidu.brpc.protocol.pbrpc.PublicPbrpcProto.PublicPbrpcRequest) ServiceManager(com.baidu.brpc.server.ServiceManager) RpcException(com.baidu.brpc.exceptions.RpcException) RequestBody(com.baidu.brpc.protocol.pbrpc.PublicPbrpcProto.RequestBody) RequestHead(com.baidu.brpc.protocol.pbrpc.PublicPbrpcProto.RequestHead)

Example 3 with RpcMethodInfo

use of com.baidu.brpc.RpcMethodInfo in project brpc-java by baidu.

the class SofaRpcProtocol method decodeRequest.

@Override
public Request decodeRequest(Object packet) throws Exception {
    Request request = this.createRequest();
    SofaRpcDecodePacket requestPacket = (SofaRpcDecodePacket) packet;
    ByteBuf metaBuf = requestPacket.getMetaBuf();
    ByteBuf protoBuf = requestPacket.getProtoBuf();
    try {
        SofaRpcProto.SofaRpcMeta requestMeta = (SofaRpcProto.SofaRpcMeta) ProtobufUtils.parseFrom(metaBuf, defaultRpcMetaInstance);
        request.setCorrelationId(requestMeta.getSequenceId());
        if (StringUtils.isBlank(requestMeta.getMethod())) {
            String errorMsg = "method is null";
            LOG.error(errorMsg);
            request.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errorMsg));
            return request;
        }
        ServiceManager serviceManager = ServiceManager.getInstance();
        RpcMethodInfo rpcMethodInfo = serviceManager.getService(requestMeta.getMethod().toLowerCase());
        if (rpcMethodInfo == null) {
            String errorMsg = String.format("Fail to find method=%s", requestMeta.getMethod());
            LOG.error(errorMsg);
            request.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errorMsg));
            return request;
        }
        request.setServiceName(rpcMethodInfo.getServiceName());
        request.setMethodName(rpcMethodInfo.getMethodName());
        request.setRpcMethodInfo(rpcMethodInfo);
        request.setTargetMethod(rpcMethodInfo.getMethod());
        request.setTarget(rpcMethodInfo.getTarget());
        int compressType = getStandardCompressType(requestMeta.getCompressType());
        request.setCompressType(compressType);
        Compress compress = compressManager.getCompress(compressType);
        try {
            Object requestProto = compress.uncompressInput(protoBuf, rpcMethodInfo);
            request.setArgs(new Object[] { requestProto });
        } catch (Exception ex) {
            String errorMsg = String.format("decode request failed, msg=%s", ex.getMessage());
            LOG.error(errorMsg);
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, errorMsg);
        }
        return request;
    } finally {
        if (metaBuf != null) {
            metaBuf.release();
        }
        if (protoBuf != null) {
            protoBuf.release();
        }
    }
}
Also used : Compress(com.baidu.brpc.compress.Compress) RpcMethodInfo(com.baidu.brpc.RpcMethodInfo) RpcRequest(com.baidu.brpc.protocol.RpcRequest) Request(com.baidu.brpc.protocol.Request) ByteBuf(io.netty.buffer.ByteBuf) DynamicCompositeByteBuf(com.baidu.brpc.buffer.DynamicCompositeByteBuf) RpcException(com.baidu.brpc.exceptions.RpcException) TooBigDataException(com.baidu.brpc.exceptions.TooBigDataException) NotEnoughDataException(com.baidu.brpc.exceptions.NotEnoughDataException) BadSchemaException(com.baidu.brpc.exceptions.BadSchemaException) ServiceManager(com.baidu.brpc.server.ServiceManager) RpcException(com.baidu.brpc.exceptions.RpcException)

Example 4 with RpcMethodInfo

use of com.baidu.brpc.RpcMethodInfo in project brpc-java by baidu.

the class HttpRpcProtocol method decodeRequest.

@Override
public Request decodeRequest(Object packet) {
    try {
        HttpRequest httpRequest = (HttpRequest) this.createRequest();
        httpRequest.setMsg(packet);
        long correlationId = parseCorrelationId(httpRequest.headers().get(CORRELATION_ID), null);
        httpRequest.setCorrelationId(correlationId);
        String contentTypeAndEncoding = httpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (StringUtils.isBlank(contentTypeAndEncoding)) {
            String errMsg = String.format("content-type is null, uri:%s", httpRequest.uri());
            LOG.warn(errMsg);
            httpRequest.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errMsg));
            return httpRequest;
        }
        contentTypeAndEncoding = contentTypeAndEncoding.toLowerCase();
        String[] splits = StringUtils.split(contentTypeAndEncoding, ";");
        int protocolType = HttpRpcProtocol.parseProtocolType(splits[0]);
        String encoding = this.encoding;
        for (String split : splits) {
            split = split.trim();
            if (split.startsWith("charset=")) {
                encoding = split.substring("charset=".length());
            }
        }
        httpRequest.headers().set(PROTOCOL_TYPE, protocolType);
        httpRequest.headers().set(HttpHeaderNames.CONTENT_ENCODING, encoding);
        // set http headers to attachment
        if (httpRequest.getKvAttachment() == null) {
            httpRequest.setKvAttachment(new HashMap<String, Object>());
        }
        for (Map.Entry<String, String> entry : httpRequest.headers()) {
            httpRequest.getKvAttachment().put(entry.getKey(), entry.getValue());
        }
        ByteBuf byteBuf = httpRequest.content();
        int bodyLen = byteBuf.readableBytes();
        if (bodyLen == 0) {
            String errMsg = String.format("body should not be null, uri:%s", httpRequest.uri());
            LOG.warn(errMsg);
            httpRequest.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errMsg));
            return httpRequest;
        }
        byte[] requestBytes = new byte[bodyLen];
        byteBuf.readBytes(requestBytes, 0, bodyLen);
        Object body = decodeBody(protocolType, encoding, requestBytes);
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.uri());
        String path = queryStringDecoder.path();
        String serviceName = null;
        String methodName = null;
        if (protocolType == Options.ProtocolType.PROTOCOL_HTTP_PROTOBUF_VALUE || protocolType == Options.ProtocolType.PROTOCOL_HTTP_JSON_VALUE) {
            boolean pathError;
            try {
                serviceName = path.substring(1, path.lastIndexOf("/"));
                methodName = path.substring(path.lastIndexOf("/") + 1);
                pathError = serviceName == null || serviceName.isEmpty() || methodName == null || methodName.isEmpty();
            } catch (Exception e) {
                LOG.warn("url format is error", e);
                pathError = true;
            }
            if (pathError) {
                String errMsg = String.format("url format is error, path:%s", path);
                httpRequest.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errMsg));
                return httpRequest;
            }
        } else {
            JsonObject bodyObject = (JsonObject) body;
            methodName = bodyObject.get("method").getAsString();
            serviceName = path;
        }
        ServiceManager serviceManager = ServiceManager.getInstance();
        RpcMethodInfo rpcMethodInfo = serviceManager.getService(serviceName, methodName);
        if (rpcMethodInfo == null) {
            String errMsg = String.format("Fail to find path=%s", path);
            LOG.warn(errMsg);
            httpRequest.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errMsg));
            return httpRequest;
        }
        httpRequest.setServiceName(rpcMethodInfo.getServiceName());
        httpRequest.setMethodName(rpcMethodInfo.getMethodName());
        httpRequest.setRpcMethodInfo(rpcMethodInfo);
        httpRequest.setTargetMethod(rpcMethodInfo.getMethod());
        httpRequest.setTarget(rpcMethodInfo.getTarget());
        try {
            httpRequest.setArgs(parseRequestParam(protocolType, body, rpcMethodInfo));
        } catch (RpcException e) {
            LOG.error("parse request param error", e);
            httpRequest.setException(e);
            return httpRequest;
        }
        return httpRequest;
    } finally {
        ((FullHttpRequest) packet).release();
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpRequest(com.baidu.brpc.protocol.HttpRequest) ProtobufRpcMethodInfo(com.baidu.brpc.ProtobufRpcMethodInfo) RpcMethodInfo(com.baidu.brpc.RpcMethodInfo) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) JsonObject(com.google.gson.JsonObject) ByteBuf(io.netty.buffer.ByteBuf) DynamicCompositeByteBuf(com.baidu.brpc.buffer.DynamicCompositeByteBuf) RpcException(com.baidu.brpc.exceptions.RpcException) NotEnoughDataException(com.baidu.brpc.exceptions.NotEnoughDataException) TooBigDataException(com.baidu.brpc.exceptions.TooBigDataException) BadSchemaException(com.baidu.brpc.exceptions.BadSchemaException) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) ServiceManager(com.baidu.brpc.server.ServiceManager) RpcException(com.baidu.brpc.exceptions.RpcException) JsonObject(com.google.gson.JsonObject) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with RpcMethodInfo

use of com.baidu.brpc.RpcMethodInfo in project brpc-java by baidu.

the class MethodUtils method getRpcMethodInfo.

public static RpcMethodInfo getRpcMethodInfo(Class clazz, String methodName) {
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        if (!method.getName().equals(methodName)) {
            continue;
        }
        Class[] parameterTypes = method.getParameterTypes();
        int paramLength = parameterTypes.length;
        if (paramLength < 1) {
            throw new IllegalArgumentException("invalid params, the correct is ([RpcContext], Request, [Callback])");
        }
        if (Future.class.isAssignableFrom(method.getReturnType()) && (paramLength < 1 || !RpcCallback.class.isAssignableFrom(parameterTypes[paramLength - 1]))) {
            throw new IllegalArgumentException("returnType is Future, but last argument is not RpcCallback");
        }
        Method syncMethod = method;
        if (paramLength > 1) {
            int startIndex = 0;
            int endIndex = paramLength - 1;
            // has callback, async rpc
            if (RpcCallback.class.isAssignableFrom(parameterTypes[paramLength - 1])) {
                endIndex--;
                paramLength--;
            }
            Class[] actualParameterTypes = new Class[paramLength];
            for (int i = 0; startIndex <= endIndex; i++) {
                actualParameterTypes[i] = parameterTypes[startIndex++];
            }
            try {
                syncMethod = method.getDeclaringClass().getMethod(method.getName(), actualParameterTypes);
            } catch (NoSuchMethodException ex) {
                throw new IllegalArgumentException("can not find sync method:" + method.getName());
            }
        }
        RpcMethodInfo methodInfo;
        ProtobufUtils.MessageType messageType = ProtobufUtils.getMessageType(syncMethod);
        if (messageType == ProtobufUtils.MessageType.PROTOBUF) {
            methodInfo = new ProtobufRpcMethodInfo(syncMethod);
        } else if (messageType == ProtobufUtils.MessageType.JPROTOBUF) {
            methodInfo = new JprotobufRpcMethodInfo(syncMethod);
        } else {
            methodInfo = new RpcMethodInfo(syncMethod);
        }
        return methodInfo;
    }
    return null;
}
Also used : RpcMethodInfo(com.baidu.brpc.RpcMethodInfo) JprotobufRpcMethodInfo(com.baidu.brpc.JprotobufRpcMethodInfo) ProtobufRpcMethodInfo(com.baidu.brpc.ProtobufRpcMethodInfo) JprotobufRpcMethodInfo(com.baidu.brpc.JprotobufRpcMethodInfo) Method(java.lang.reflect.Method) ProtobufUtils(com.baidu.brpc.utils.ProtobufUtils) Future(java.util.concurrent.Future) ProtobufRpcMethodInfo(com.baidu.brpc.ProtobufRpcMethodInfo)

Aggregations

RpcMethodInfo (com.baidu.brpc.RpcMethodInfo)19 RpcException (com.baidu.brpc.exceptions.RpcException)9 Request (com.baidu.brpc.protocol.Request)8 ByteBuf (io.netty.buffer.ByteBuf)7 Method (java.lang.reflect.Method)6 ProtobufRpcMethodInfo (com.baidu.brpc.ProtobufRpcMethodInfo)5 DynamicCompositeByteBuf (com.baidu.brpc.buffer.DynamicCompositeByteBuf)5 BadSchemaException (com.baidu.brpc.exceptions.BadSchemaException)5 NotEnoughDataException (com.baidu.brpc.exceptions.NotEnoughDataException)5 TooBigDataException (com.baidu.brpc.exceptions.TooBigDataException)5 ServiceManager (com.baidu.brpc.server.ServiceManager)5 JprotobufRpcMethodInfo (com.baidu.brpc.JprotobufRpcMethodInfo)4 Compress (com.baidu.brpc.compress.Compress)4 RpcRequest (com.baidu.brpc.protocol.RpcRequest)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 RpcContext (com.baidu.brpc.RpcContext)2 Response (com.baidu.brpc.protocol.Response)2 SPHead (com.baidu.brpc.protocol.push.SPHead)2 ServerPushProtocol (com.baidu.brpc.protocol.push.ServerPushProtocol)2