AsyncHBase 使用 Netty 堆外内存,如何监控
解读
在国内生产环境,OpenTSDB 的写入链路几乎都会启用 AsyncHBase Client,而 AsyncHBase 底层依赖 Netty 3/4 的 堆外内存(DirectBuffer) 做零拷贝收发。堆外内存不受 GC 管控,一旦泄漏,进程会触发 "java.lang.OutOfMemoryError: Direct buffer memory" 直接崩溃,但 JVM 自带的 jstat、jmap 又无法直观看到其使用量,因此面试官想确认候选人是否:
- 知道 Netty 堆外内存的分配与回收机制
- 能在 Linux 层面、JVM 层面、应用层面做立体化监控
- 能否把监控指标落到 Prometheus + Grafana,实现提前预警,而不是事后查 core
知识点
- Netty 内存模型:UnpooledDirectByteBuf、PooledUnsafeDirectByteBuf、Arena、Chunk、Page
- -XX:MaxDirectMemorySize 参数与 VM.maxDirectMemory() 关系
- JDK 8/11 的 Bits.reserveMemory / tryReserveMemory 计数器
- Netty 4 的 io.netty.maxDirectMemory / io.netty.leakDetection.level
- OpenTSDB 的 StatsCollector 接口与 /api/stats 端点
- Prometheus JMX Exporter + Grafana 模板变量
- Linux 系统级:/proc/pid/smaps 中的 VmRSS:Anonymous 与 Private_Dirty 差值估算
- eBPF + bcc 工具:memleak 跟踪 malloc/free 对,定位 native 泄漏
- Netty 自带指标:io.netty.buffer.PooledByteBufAllocator.metric() 暴露 directArenas[i].chunkLists 占用
- AsyncHBase 源码位置:org.hbase.async.HBaseClient 的 sendRpc() 与 ChannelBuffer.writeBytes() 是主要分配点
答案
线上落地分四层监控:
-
JVM 层
启动参数固定上限:-XX:MaxDirectMemorySize=4g,打开 -XX:+PrintGCDetails -XX:+PrintGCTimeStamps,配合 -XX:+UnlockDiagnosticVMOptions -XX:+PrintJNIGCStalls 可在 GC 日志里观察 "GC (Allocation Failure) 16384K->16384K(16384K), 0.0001234 secs]" 是否频繁。
代码里通过 io.netty.util.internal.PlatformDependent.usedDirectMemory() 每 30 s 采样一次,推送到 OpenTSDB 自带的 StatsCollector,指标名 "tsd.netty.direct.used",tag 含 host=、port=、cluster=。 -
Netty 层
在 opentsdb.conf 新增:
async.hbase.netty.leak_detection.level=advanced
async.hbase.netty.max_direct_memory=4294967296
重启后,AsyncHBase 会打印 "LEAK: ByteBuf.release() was not called before it's garbage-colculated" 到 logs/opentsdb.log。
同时把 PooledByteBufAllocatorMetric 所有字段(directArenas、chunkSize、activeBytes)通过 JMX MBean 暴露,名称域 "org.apache.async.hbase.netty:type=ByteBufAllocator"。 -
系统层
写 systemd 的 service 文件时加 MemoryMax=6G,一旦 RSS 超限直接由 cgroup OOM Kill,避免把机器拖死。
用 node_exporter 的 textfile 收集脚本 每 60 s 执行:
cat /proc/$(pidof opentsdb)/smaps | awk '/Anonymous/ {sum+=$2} END {print "node_process_anon_kb ",sum}'
推送到 /var/lib/node_exporter/heap.prom,Grafana 面板上与 "tsd.netty.direct.used" 做对比,若 anon 远大于 direct.used 即可怀疑 native 泄漏。 -
告警
Prometheus 规则:
tsd_netty_direct_used / 4294967296 > 0.85持续 5 min 就 page 到值班手机;
increase(tsd_netty_direct_used[10m]) > 268435456(每 10 min 涨 256 MB)立即 熔断写入,临时调大 -XX:MaxDirectMemorySize 并重启。
拓展思考
- 如果 JDK 升级到 17,Netty 4.1.80+ 已支持 Foreign Memory API (Panama),可用 MemorySegment.ofAddress 精确统计,不再需要 Bits.counter,此时监控脚本要改走 jdk.internal.misc.VM 的 directMemoryUsed() 反射调用。
- 国内部分云主机对 /proc/pid/smaps 做了权限裁剪,可改用 eBPF 的 memleak 工具 做无侵入采样,把结果通过 pushgateway 打到 Prometheus,实现 "函数级" 泄漏定位。
- 当 OpenTSDB 3.0 彻底切到 Netty 4 + ArrowBuf 后,上述 PooledByteBufAllocatorMetric 会替换为 ArrowBufAllocator.getAllocatedMemory(),监控脚本只需换 MBean 名称即可,逻辑不变。