zoukankan      html  css  js  c++  java
  • Thrift反序列化导致OOM(转)

    概述

    最近线上的日志处理服务偶尔会出现Out Of Memory的问题,从Exception的call stack中顺藤摸瓜,最终定位到是thrift反序列化的问题。

    发现问题

    先交代一下问题现场:

    • thirft版本: 0.5.0,很久远的版本,但是公司统一使用的版本;
    • 反序列化使用的协议:TCompactProtocol协议;
    • 出错的call stack:

      Exception in thread "pool-10-thread-1" java.lang.RuntimeException: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
      at com.lmax.disruptor.FatalExceptionHandler.handleEventException(FatalExceptionHandler.java:45)
      at com.lmax.disruptor.BatchEventProcessor.run(BatchEventProcessor.java:152)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at java.lang.Thread.run(Thread.java:745)
      Caused by: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
      at org.apache.thrift.protocol.TCompactProtocol.readBinary(TCompactProtocol.java:651)
      at org.apache.thrift.protocol.TCompactProtocol.readString(TCompactProtocol.java:626)
      at com.xiaomi.data.spec.log.push.XmPushMessageInfo.read(XmPushMessageInfo.java:2779)

    寻找原因

    从上面的call stack可以看出,问题出在thrift TCompactProtocol类的651行,看看这一行干了些什么:

    /**
    * Read a byte[] of a known length from the wire.
    */
    private byte[] readBinary(int length) throws TException {
    if (length == 0) return new byte[0];

    byte[] buf = new byte[length]; // TCompactProtocol第651行
    trans_.readAll(buf, 0, length);
    return buf;
    }

    从上面代码可以看到,TCompactProtocol类的651行申请了一个长度为length的byte数组,而此时可用内存已经不足以分配这么大的空间,所以报了java.lang.OutOfMemoryError错误,导致程序异常退出。

    这个length是怎么来的呢?还是从call stack寻找答案,看看TCompactProtocol类的626行:


    /**
    * Reads a byte[] (via readBinary), and then UTF-8 decodes it.
    */
    public String readString() throws TException {
    int length = readVarint32();

    if (length == 0) {
    return "";
    }

    try {
    if (trans_.getBytesRemainingInBuffer() >= length) {
    String str = new String(trans_.getBuffer(), trans_.getBufferPosition(), length, "UTF-8");
    trans_.consumeBuffer(length);
    return str;
    } else {
    return new String(readBinary(length), "UTF-8"); // 626行
    }
    } catch (UnsupportedEncodingException e) {
    throw new TException("UTF-8 not supported!");
    }
    }

    从上面的代码可以看到,length是通过 readVarint32 这个函数读到的一个int型数字,然后thrift使用这个数字来申请内存。

    这种方式在正常情况下是没有问题的,但是如果源binary数据被写坏了,或者网络传输过程中出现了差错,就有可能导致 readVarint32 读到的是一个非常大的数字(可能达到10多亿),这种情况下申请内存必然会OOM。

    解决问题

    问题原因找到了,但是怎么解决呢? 
    下面是一个比较简单的解决方案:

    每次读取到length之后都做一下长度的check,如果这个长度超过一定的长度,则直接抛出异常,不要再申请内存。

    thrift中需要check读取到的langth的地方有以下几个地方(如果使用其他Protocol也类似):

    /** 
    * Read a map header off the wire. If the size is zero, skip reading the key
    * and value type. This means that 0-length maps will yield TMaps without the
    * "correct" types.
    */
    public TMap readMapBegin() throws TException {
    int size = readVarint32(); //此处需要check size
    byte keyAndValueType = size == 0 ? 0 : readByte();
    return new TMap(getTType((byte)(keyAndValueType >> 4)), getTType((byte)(keyAndValueType & 0xf)), size);
    }
    /**
    * Read a list header off the wire. If the list size is 0-14, the size will
    * be packed into the element type header. If it's a longer list, the 4 MSB
    * of the element type header will be 0xF, and a varint will follow with the
    * true size.
    */
    public TList readListBegin() throws TException {
    byte size_and_type = readByte();
    int size = (size_and_type >> 4) & 0x0f;
    if (size == 15) {
    size = readVarint32(); // 此处需要check size
    }
    byte type = getTType(size_and_type);
    return new TList(type, size);
    }
    /**
    * Reads a byte[] (via readBinary), and then UTF-8 decodes it.
    */
    public String readString() throws TException {
    int length = readVarint32(); // 此处需要check length

    if (length == 0) {
    return "";
    }

    try {
    if (trans_.getBytesRemainingInBuffer() >= length) {
    String str = new String(trans_.getBuffer(), trans_.getBufferPosition(), length, "UTF-8");
    trans_.consumeBuffer(length);
    return str;
    } else {
    return new String(readBinary(length), "UTF-8");
    }
    } catch (UnsupportedEncodingException e) {
    throw new TException("UTF-8 not supported!");
    }
    }

    以 readMapBegin 举例,可以这样修改:

    /**
    * Read a map header off the wire. If the size is zero, skip reading the key
    * and value type. This means that 0-length maps will yield TMaps without the
    * "correct" types.
    */
    public TMap readMapBegin() throws TException {
    int size = readVarint32();
    if (size > trans_.getBytesRemainingInBuffer() || size > MAX_THRIFT_MAP_SIZE) {
    throw new TPushProtocolException(TProtocolException.SIZE_LIMIT, "Thrift map size " + size + " out of range, remaining size = " + trans_.getBytesRemainingInBuffer());
    }
    byte keyAndValueType = size == 0 ? 0 : readByte();
    return new TMap(getTType((byte)(keyAndValueType >> 4)), getTType((byte)(keyAndValueType & 0xf)), size);
    }

    其中的 MAX_THRIFT_MAP_SIZE 是一个常量,一个自定义的thrift map的最大size,此处是10000。

    后记

    看了一下thrift 0.9.3版本的源码,这个版本中已经加上了类似的check逻辑。

    http://outofmemory.cn/java/thrift-desearialize-outOfMemory

  • 相关阅读:
    用反射的方法获取枚举值(数据字典)
    使用哈希加盐法来为密码加密(补充JAVA的实现)
    Mybatis使用TypeHandler实现数据的加解密转换
    学习Hadoop和Spark的好的资源
    Scala基本语法学习笔记
    Scala & IntelliJ IDEA环境搭建升级版:在JAVA中调用Scala的helloworld
    Scala & IntelliJ IDEA:环境搭建、helloworld
    【转】解决yum安装软件报Couldn't resolve host 'mirrorlist.centos.org问题
    使用nfs映射远程服务器磁盘目录
    MacOS系统升级后,IDEA的SVN不好用的问题
  • 原文地址:https://www.cnblogs.com/softidea/p/5416765.html
Copyright © 2011-2022 走看看