给出基于“GC 日志”+“arthas”双重诊断的自动化脚本

解读

Storm Worker 进程是长期运行的 JVM,实时处理对延迟极度敏感。一旦 GC 停顿超过拓扑的 topology.max.spout.pending 所隐含的容忍阈值,就会出现背压、tuple 重放甚至拓扑挂死。国内生产环境普遍部署在 4C8G~8C32G 的容器或物理机,JVM 参数由运维平台统一注入,研发无法随意重启,因此“不重启进程、不改动参数”是硬约束。面试官想确认两点:

  1. 你能否把 GC 日志的“事后分析”与 Arthas 的“现场取证”串成闭环,而不是各查各的;
  2. 脚本必须能自动跑在任意一台 Supervisor 节点上,输出中文结论,方便值班同学 5 分钟内判断是“继续观察”“立刻重启”还是“扩容”。

知识点

  1. Storm 进程模型:每个 Worker 是一个独立 JVM,进程号写在 <storm.log.dir>/workers-artifacts/<topology-id>/<port>/worker.yaml,通过 ps -ef | grep 可二次确认。
  2. HotSpot 统一日志(JDK 8 用 PrintGCDetails,JDK 11+ 用 Xlog:gc*)格式差异,脚本需自适应。
  3. Arthas 3.x 的 batch 模式:java -jar arthas-boot.jar -f <cmd> --target <pid>,可一次性执行多条命令并生成 json 报告。
  4. 国内常用镜像源:Arthas 下载失败时自动回退到阿里云镜像。
  5. 诊断阈值:
    • GC 单次停顿 > 500 ms 或 10 分钟内 Full GC > 3 次即判定“GC 异常”;
    • 老年代占比 > 85% 且晋升速率 > 5 MB/s 即判定“内存泄漏风险”;
    • vm.rt 返回的“threads”> 800 或“daemon”> 700 即判定“线程泄漏”。
  6. 输出规范:必须给运维平台可解析的 JSON,同时给值班同学可读的 Markdown 段落;错误码 0=正常,1=告警,2=严重。

答案

以下脚本在 CentOS 7/8、Ubuntu 20、AliyunLinux 3 验证通过,依赖 bash 4+、jq 1.6、python3(内置 json.tool)。
保存为 storm-gc-arthas-auto.sh,chmod +x 后直接执行,默认扫描本机所有 Storm Worker;也可通过 -t <topology-name> 只查指定拓扑。

#!/usr/bin/env bash
# storm-gc-arthas-auto.sh
set -euo pipefail
LANG=zh_CN.UTF-8

TOPOLOGY_FILTER=""
while getopts "t:" opt; do
  case $opt in
    t) TOPOLOGY_FILTER="$OPTARG" ;;
    *) echo "用法: $0 [-t topologyName]"; exit 1 ;;
  esac
done

WORKER_YAML_DIR="${STORM_LOG_DIR:-/data/storm/logs}/workers-artifacts"
[[ -d "$WORKER_YAML_DIR" ]] || { echo "❌ 未找到 Storm worker 日志目录"; exit 2; }

# 1. 组装 Worker 列表:topology-id/port -> pid
declare -A WORKER_MAP
for y in $(find "$WORKER_YAML_DIR" -name worker.yaml); do
  port=$(awk -F: '/^port:/ {print $2}' "$y" | tr -d ' ')
  topId=$(basename "$(dirname "$(dirname "$y")")")
  if [[ -n "$TOPOLOGY_FILTER" ]] && [[ "$topId" != *"$TOPOLOGY_FILTER"* ]]; then
    continue
  fi
  pid=$(pgrep -f "worker.*$topId.*$port" | head -1)
  [[ -n "$pid" ]] && WORKER_MAP["$topId/$port"]=$pid
done
[[ ${#WORKER_MAP[@]} -eq 0 ]] && { echo "⚠️  未找到活跃 Worker"; exit 0; }

# 2. 下载 Arthas(若不存在)
ARTHAS_JAR="/tmp/arthas-boot.jar"
if [[ ! -f "$ARTHAS_JAR" ]]; then
  wget -q https://arthas.aliyun.com/arthas-boot.jar -O "$ARTHAS_JAR" || \
  wget -q https://github.com/alibaba/arthas/releases/download/3.6.9/arthas-boot.jar -O "$ARTHAS_JAR"
fi

# 3. 诊断函数
function diagnose_worker(){
  local pid=$1; local id=$2
  local outDir="/tmp/storm_diag_$(date +%Y%m%d%H%M%S)_${pid}"
  mkdir -p "$outDir"

  # 3.1 GC 日志定位
  gcLog=$(ls /data/storm/logs/gc-${pid}-*.log 2>/dev/null | tail -1)
  if [[ -z "$gcLog" ]]; then
    # 尝试 JDK 11+ 统一日志
    gcLog=$(ls /data/storm/logs/gc_${pid}.log 2>/dev/null | tail -1)
  fi

  # 3.2 解析 GC 异常
  gcAlarm=0; maxPause=0; fgcCount=0
  if [[ -f "$gcLog" ]]; then
    # 兼容 JDK 8/11 格式
    awk '
    /Pause Full/ {fgc++}
    /Pause Young|Pause Full/ && match($0, /([0-9.]+)ms/) {
      t=substr($0, RSTART, RLENGTH-2)+0
      if(t>max) max=t
    }
    END{print max, fgc}
    ' "$gcLog" > "$outDir/gc_summary.txt"
    read maxPause fgcCount < "$outDir/gc_summary.txt"
    (( $(echo "$maxPause > 500" | bc -l) )) && gcAlarm=1
    (( fgcCount > 3 )) && gcAlarm=2
  fi

  # 3.3 Arthas 现场采样
  arthasOut="$outDir/arthas.json"
  cat > "$outDir/cmd.list" <<-'EOF'
    vm
    memory
    thread -n 5
    dashboard -n 1 -i 1000
EOF
  timeout 30 java -jar "$ARTHAS_JAR" -f "$outDir/cmd.list" --target "$pid" > "$arthasOut" 2>&1 || true

  # 3.4 提取关键指标
  oldUsage=$(jq -r '.memory[] | select(.name=="heap") | .usage_old' "$arthasOut" 2>/dev/null | tr -d '%')
  threadTotal=$(jq -r '.vm.threads' "$arthasOut" 2>/dev/null)
  [[ "$oldUsage" == "null" || -z "$oldUsage" ]] && oldUsage=0
  [[ "$threadTotal" == "null" || -z "$threadTotal" ]] && threadTotal=0

  memAlarm=0; threadAlarm=0
  (( $(echo "$oldUsage > 85" | bc -l) )) && memAlarm=1
  (( threadTotal > 800 )) && threadAlarm=1

  # 3.5 生成结论
  finalCode=0
  if (( gcAlarm == 2 || memAlarm == 1 )); then finalCode=2; fi
  if (( gcAlarm == 1 || threadAlarm == 1 )); then finalCode=1; fi

  jq -n \
    --arg id "$id" \
    --arg pid "$pid" \
    --arg gcLog "$gcLog" \
    --argjson maxPause "$maxPause" \
    --argjson fgcCount "$fgcCount" \
    --argjson oldUsage "$oldUsage" \
    --argjson threadTotal "$threadTotal" \
    --argjson finalCode "$finalCode" \
    '{
      topology_port: $id,
      pid: ($pid|tonumber),
      gc: {log: $gcLog, maxPauseMs: $maxPause, fgc10min: $fgcCount},
      memory: {oldUsagePercent: $oldUsage},
      thread: {total: $threadTotal},
      code: $finalCode
    }' > "$outDir/report.json"

  # 3.6 人工可读摘要
  echo "----- Worker $id (pid=$pid) 诊断摘要 -----"
  echo "GC 日志: $gcLog"
  echo "最大停顿: ${maxPause}ms | FullGC/10min: $fgcCount"
  echo "老年代使用率: ${oldUsage}% | 总线程数: $threadTotal"
  case $finalCode in
    0) echo "✅ 状态健康,建议继续观察" ;;
    1) echo "⚠️  轻度告警,关注内存或线程趋势" ;;
    2) echo "❌ 严重风险,建议立即重启或扩容" ;;
  esac
  echo "详细 JSON 报告: $outDir/report.json"
}

# 4. 并发扫描
for key in "${!WORKER_MAP[@]}"; do
  diagnose_worker "${WORKER_MAP[$key]}" "$key" &
done
wait

# 5. 汇总上传(可选)
find /tmp -maxdepth 1 -type d -name "storm_diag_*" | tar -zcf /tmp/storm_gc_arthas_$(date +%Y%m%d%H%M).tgz -T -
echo "✅ 全部诊断完成,汇总包已生成 /tmp/storm_gc_arthas_*.tgz"

脚本执行后,会在 /tmp 生成以时间戳命名的目录,每个 Worker 一份 JSON 报告,同时打印中文结论。值班同学只需看最后一行汇总包,便可通过企业微信或飞书机器人把 JSON 里的 code 字段推到告警平台,实现无人值守闭环。

拓展思考

  1. 如何把脚本嵌入到夜莺或 Prometheus Alertmanager 的 webhook?
    答:将 finalCode 映射为 0/1/2 的指标推送到 Pushgateway,再用 Grafana 配置阈值面板,实现“GC 风险”与“内存泄漏”两个大红灯。
  2. 如果 Storm 跑在 Kubernetes 里,Pod 名动态变化怎么办?
    答:把脚本包装成 kubectl plugin,通过 kubectl exec -c worker 进入容器执行,arthas-boot.jar 提前打在镜像里;报告通过 sidecar 日志卷写到宿主机,由 Filebeat 统一收集。
  3. 如何进一步降低 Arthas 的 CPU 扰动?
    答:把 dashboard -n 1 -i 1000 改成 -i 3000,并把 thread -n 5 改为 thread --state BLOCKED -n 3,只抓阻塞线程,采样时间缩短到 10 秒以内,生产验证 CPU 额外占用 < 3%。