Search in sources :

Example 1 with Cleanable

use of org.apache.dubbo.common.serialize.Cleanable in project dubbo by alibaba.

the class ExchangeCodec method encodeResponse.

protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response res) throws IOException {
    int savedWriteIndex = buffer.writerIndex();
    try {
        Serialization serialization = getSerialization(channel, res);
        // header.
        byte[] header = new byte[HEADER_LENGTH];
        // set magic number.
        Bytes.short2bytes(MAGIC, header);
        // set request and serialization flag.
        header[2] = serialization.getContentTypeId();
        if (res.isHeartbeat()) {
            header[2] |= FLAG_EVENT;
        }
        // set response status.
        byte status = res.getStatus();
        header[3] = status;
        // set request id.
        Bytes.long2bytes(res.getId(), header, 4);
        buffer.writerIndex(savedWriteIndex + HEADER_LENGTH);
        ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer);
        // encode response data or error message.
        if (status == Response.OK) {
            if (res.isHeartbeat()) {
                // heartbeat response data is always null
                bos.write(CodecSupport.getNullBytesOf(serialization));
            } else {
                ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
                if (res.isEvent()) {
                    encodeEventData(channel, out, res.getResult());
                } else {
                    encodeResponseData(channel, out, res.getResult(), res.getVersion());
                }
                out.flushBuffer();
                if (out instanceof Cleanable) {
                    ((Cleanable) out).cleanup();
                }
            }
        } else {
            ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
            out.writeUTF(res.getErrorMessage());
            out.flushBuffer();
            if (out instanceof Cleanable) {
                ((Cleanable) out).cleanup();
            }
        }
        bos.flush();
        bos.close();
        int len = bos.writtenBytes();
        checkPayload(channel, len);
        Bytes.int2bytes(len, header, 12);
        // write
        buffer.writerIndex(savedWriteIndex);
        // write header.
        buffer.writeBytes(header);
        buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len);
    } catch (Throwable t) {
        // clear buffer
        buffer.writerIndex(savedWriteIndex);
        // send error message to Consumer, otherwise, Consumer will wait till timeout.
        if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) {
            Response r = new Response(res.getId(), res.getVersion());
            r.setStatus(Response.BAD_RESPONSE);
            if (t instanceof ExceedPayloadLimitException) {
                logger.warn(t.getMessage(), t);
                try {
                    r.setErrorMessage(t.getMessage());
                    channel.send(r);
                    return;
                } catch (RemotingException e) {
                    logger.warn("Failed to send bad_response info back: " + t.getMessage() + ", cause: " + e.getMessage(), e);
                }
            } else {
                // FIXME log error message in Codec and handle in caught() of IoHanndler?
                logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t);
                try {
                    r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t));
                    channel.send(r);
                    return;
                } catch (RemotingException e) {
                    logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e);
                }
            }
        }
        // Rethrow exception
        if (t instanceof IOException) {
            throw (IOException) t;
        } else if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else if (t instanceof Error) {
            throw (Error) t;
        } else {
            throw new RuntimeException(t.getMessage(), t);
        }
    }
}
Also used : ChannelBufferOutputStream(org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) IOException(java.io.IOException) Serialization(org.apache.dubbo.common.serialize.Serialization) Response(org.apache.dubbo.remoting.exchange.Response) RemotingException(org.apache.dubbo.remoting.RemotingException) ExceedPayloadLimitException(org.apache.dubbo.remoting.transport.ExceedPayloadLimitException) Cleanable(org.apache.dubbo.common.serialize.Cleanable)

Example 2 with Cleanable

use of org.apache.dubbo.common.serialize.Cleanable in project dubbo by alibaba.

the class ExchangeCodec method encodeRequest.

protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) throws IOException {
    Serialization serialization = getSerialization(channel, req);
    // header.
    byte[] header = new byte[HEADER_LENGTH];
    // set magic number.
    Bytes.short2bytes(MAGIC, header);
    // set request and serialization flag.
    header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());
    if (req.isTwoWay()) {
        header[2] |= FLAG_TWOWAY;
    }
    if (req.isEvent()) {
        header[2] |= FLAG_EVENT;
    }
    // set request id.
    Bytes.long2bytes(req.getId(), header, 4);
    // encode request data.
    int savedWriteIndex = buffer.writerIndex();
    buffer.writerIndex(savedWriteIndex + HEADER_LENGTH);
    ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer);
    if (req.isHeartbeat()) {
        // heartbeat request data is always null
        bos.write(CodecSupport.getNullBytesOf(serialization));
    } else {
        ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
        if (req.isEvent()) {
            encodeEventData(channel, out, req.getData());
        } else {
            encodeRequestData(channel, out, req.getData(), req.getVersion());
        }
        out.flushBuffer();
        if (out instanceof Cleanable) {
            ((Cleanable) out).cleanup();
        }
    }
    bos.flush();
    bos.close();
    int len = bos.writtenBytes();
    checkPayload(channel, len);
    Bytes.int2bytes(len, header, 12);
    // write
    buffer.writerIndex(savedWriteIndex);
    // write header.
    buffer.writeBytes(header);
    buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len);
}
Also used : Serialization(org.apache.dubbo.common.serialize.Serialization) ChannelBufferOutputStream(org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) Cleanable(org.apache.dubbo.common.serialize.Cleanable)

Example 3 with Cleanable

use of org.apache.dubbo.common.serialize.Cleanable in project dubbo by alibaba.

the class TransportCodec method encode.

@Override
public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {
    OutputStream output = new ChannelBufferOutputStream(buffer);
    ObjectOutput objectOutput = getSerialization(channel).serialize(channel.getUrl(), output);
    encodeData(channel, objectOutput, message);
    objectOutput.flushBuffer();
    if (objectOutput instanceof Cleanable) {
        ((Cleanable) objectOutput).cleanup();
    }
}
Also used : ChannelBufferOutputStream(org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) OutputStream(java.io.OutputStream) ChannelBufferOutputStream(org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream) Cleanable(org.apache.dubbo.common.serialize.Cleanable)

Example 4 with Cleanable

use of org.apache.dubbo.common.serialize.Cleanable in project dubbo by alibaba.

the class TransportCodec method decode.

@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
    InputStream input = new ChannelBufferInputStream(buffer);
    ObjectInput objectInput = getSerialization(channel).deserialize(channel.getUrl(), input);
    Object object = decodeData(channel, objectInput);
    if (objectInput instanceof Cleanable) {
        ((Cleanable) objectInput).cleanup();
    }
    return object;
}
Also used : ChannelBufferInputStream(org.apache.dubbo.remoting.buffer.ChannelBufferInputStream) InputStream(java.io.InputStream) ChannelBufferInputStream(org.apache.dubbo.remoting.buffer.ChannelBufferInputStream) ObjectInput(org.apache.dubbo.common.serialize.ObjectInput) Cleanable(org.apache.dubbo.common.serialize.Cleanable)

Example 5 with Cleanable

use of org.apache.dubbo.common.serialize.Cleanable in project dubbo by alibaba.

the class DecodeableRpcInvocation method decode.

@Override
public Object decode(Channel channel, InputStream input) throws IOException {
    ObjectInput in = CodecSupport.getSerialization(channel.getUrl(), serializationType).deserialize(channel.getUrl(), input);
    this.put(SERIALIZATION_ID_KEY, serializationType);
    String dubboVersion = in.readUTF();
    request.setVersion(dubboVersion);
    setAttachment(DUBBO_VERSION_KEY, dubboVersion);
    String path = in.readUTF();
    setAttachment(PATH_KEY, path);
    String version = in.readUTF();
    setAttachment(VERSION_KEY, version);
    setMethodName(in.readUTF());
    String desc = in.readUTF();
    setParameterTypesDesc(desc);
    try {
        if (ConfigurationUtils.getSystemConfiguration().getBoolean(SERIALIZATION_SECURITY_CHECK_KEY, false)) {
            CodecSupport.checkSerialization(path, version, serializationType);
        }
        Object[] args = DubboCodec.EMPTY_OBJECT_ARRAY;
        Class<?>[] pts = DubboCodec.EMPTY_CLASS_ARRAY;
        if (desc.length() > 0) {
            // if (RpcUtils.isGenericCall(path, getMethodName()) || RpcUtils.isEcho(path, getMethodName())) {
            // pts = ReflectUtils.desc2classArray(desc);
            // } else {
            ServiceRepository repository = ApplicationModel.getServiceRepository();
            ServiceDescriptor serviceDescriptor = repository.lookupService(path);
            if (serviceDescriptor != null) {
                MethodDescriptor methodDescriptor = serviceDescriptor.getMethod(getMethodName(), desc);
                if (methodDescriptor != null) {
                    pts = methodDescriptor.getParameterClasses();
                    this.setReturnTypes(methodDescriptor.getReturnTypes());
                }
            }
            if (pts == DubboCodec.EMPTY_CLASS_ARRAY) {
                if (!RpcUtils.isGenericCall(desc, getMethodName()) && !RpcUtils.isEcho(desc, getMethodName())) {
                    throw new IllegalArgumentException("Service not found:" + path + ", " + getMethodName());
                }
                pts = ReflectUtils.desc2classArray(desc);
            }
            // }
            args = new Object[pts.length];
            for (int i = 0; i < args.length; i++) {
                try {
                    args[i] = in.readObject(pts[i]);
                } catch (Exception e) {
                    if (log.isWarnEnabled()) {
                        log.warn("Decode argument failed: " + e.getMessage(), e);
                    }
                }
            }
        }
        setParameterTypes(pts);
        Map<String, Object> map = in.readAttachments();
        if (map != null && map.size() > 0) {
            Map<String, Object> attachment = getObjectAttachments();
            if (attachment == null) {
                attachment = new HashMap<>();
            }
            attachment.putAll(map);
            setObjectAttachments(attachment);
        }
        // decode argument ,may be callback
        for (int i = 0; i < args.length; i++) {
            args[i] = decodeInvocationArgument(channel, this, pts, i, args[i]);
        }
        setArguments(args);
        String targetServiceName = buildKey(getAttachment(PATH_KEY), getAttachment(GROUP_KEY), getAttachment(VERSION_KEY));
        setTargetServiceUniqueName(targetServiceName);
    } catch (ClassNotFoundException e) {
        throw new IOException(StringUtils.toString("Read invocation data failed.", e));
    } finally {
        if (in instanceof Cleanable) {
            ((Cleanable) in).cleanup();
        }
    }
    return this;
}
Also used : IOException(java.io.IOException) ServiceRepository(org.apache.dubbo.rpc.model.ServiceRepository) MethodDescriptor(org.apache.dubbo.rpc.model.MethodDescriptor) IOException(java.io.IOException) ServiceDescriptor(org.apache.dubbo.rpc.model.ServiceDescriptor) ObjectInput(org.apache.dubbo.common.serialize.ObjectInput) Cleanable(org.apache.dubbo.common.serialize.Cleanable)

Aggregations

Cleanable (org.apache.dubbo.common.serialize.Cleanable)6 IOException (java.io.IOException)3 ObjectInput (org.apache.dubbo.common.serialize.ObjectInput)3 ObjectOutput (org.apache.dubbo.common.serialize.ObjectOutput)3 ChannelBufferOutputStream (org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream)3 Serialization (org.apache.dubbo.common.serialize.Serialization)2 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 RemotingException (org.apache.dubbo.remoting.RemotingException)1 ChannelBufferInputStream (org.apache.dubbo.remoting.buffer.ChannelBufferInputStream)1 Response (org.apache.dubbo.remoting.exchange.Response)1 ExceedPayloadLimitException (org.apache.dubbo.remoting.transport.ExceedPayloadLimitException)1 MethodDescriptor (org.apache.dubbo.rpc.model.MethodDescriptor)1 ServiceDescriptor (org.apache.dubbo.rpc.model.ServiceDescriptor)1 ServiceRepository (org.apache.dubbo.rpc.model.ServiceRepository)1