使用 systemtap 脚本采样 ngx_http_lua_run_thread 热点,输出火焰图

解读

国内一线互联网公司在做 Nginx+Lua(OpenResty)性能调优时,普遍把「火焰图」作为终态交付物:

  1. 运维/内核团队只给 5 分钟采样窗口,不能挂 gdb、不能重启进程;
  2. 结果要能在 Confluence 上直接贴图,方便开发、测试、SRE 三方评审;
  3. 面试官重点考察两点:
    • 是否知道 ngx_http_lua_run_thread 是 Lua 协程调度入口,采样必须落在该符号;
    • 是否能把 systemtap 的「探针开销」「栈深度」「内联优化」三件事在脚本里闭环处理。
      一句话:题目不是让你“跑通” stap,而是让你“跑准”并“跑出能拍板决策”的火焰图。

知识点

  1. stap 探针类型:
    • kernel.function / module.function 用于内核;
    • process.function 用于用户态,需与 /usr/bin/stap -d 指定带 debuginfo 的 nginx 二进制对应。
  2. ngx_http_lua_run_thread 符号:
    • 只在启用 --with-debug 或保留符号表的 nginx 里可见;
    • 可能被内联,需 stap -DSTP_NO_INLINE 或编译时加 -fno-inline。
  3. 栈回溯限制:
    • maxstack=100 默认,Lua 协程切换后栈深度常超 64,需显式 stap -DMAXBACKTRACE=128。
  4. 火焰图生成链:
    stap → 折叠栈行格式(; 分隔)→ 输出到临时文件 → 用 FlameGraph 仓库的 stackcollapse-stap.pl → flamegraph.pl → svg。
  5. 国内生产合规:
    • 内核版本 ≤ 3.10 时 stap 需额外 sign 模块(staprun -u);
    • 容器场景下要加 --privilege 并把 /sys/kernel/debug 挂到容器内;
    • 采样频率 99Hz 是惯例,既避开工频 100Hz 又足够密。

答案

步骤 1:确认符号存在

nm -D /opt/nginx/sbin/nginx | grep ngx_http_lua_run_thread

有输出则继续;否则重新编译 nginx:

./configure --with-debug … && make && make install

步骤 2:编写采样脚本 ngx_lua_profile.stp

global stacktrace;
probe process("/opt/nginx/sbin/nginx").function("ngx_http_lua_run_thread") {
    if (pid() == target()) {
        stacktrace[backtrace()] <<< 1;
    }
}
probe timer.s(30) {   # 采样 30 秒
    foreach (bt in stacktrace-) {
        print_stack(bt);
        printf(" %d\n", @count(stacktrace[bt]));
    }
    exit();
}

步骤 3:运行脚本

stap -DMAXBACKTRACE=128 -DSTP_NO_INLINE \
     -d /opt/nginx/sbin/nginx \
     -d /opt/nginx/modules/ngx_http_lua_module.so \
     ngx_lua_profile.stp -x $(pgrep -f 'nginx: worker') > lua.stap.txt

步骤 4:生成火焰图

git clone https://github.com/brendangregg/FlameGraph  # 国内可放 gitee 镜像
./FlameGraph/stackcollapse-stap.pl lua.stap.txt | \
./FlameGraph/flamegraph.pl --title "ngx_http_lua_run_thread on-CPU" > lua.svg

步骤 5:交付
把 lua.svg 贴到评审文档,并给出结论:
“采样 30 s,命中 47 k 次,热点 38% 落在 lj_BC_TFORL,说明 json 轮询解析在热循环;建议把 cjson.decode 提前到 access 阶段,并开启 lua_code_cache 预编译。”

拓展思考

  1. 如果线上 nginx 是静态链接 LuaJIT,ngx_http_lua_run_thread 可能被优化成局部符号,stap 找不到怎么办?
    答:改用 dwarf 探针

    probe process("/opt/nginx/sbin/nginx").mark("lua:run_thread")
    

    需要在 LuaJIT 编译时打开 -DLUAJIT_USE_SYSMARK。

  2. 容器内无法 stap 时,如何零侵入拿到等价火焰图?
    答:

    • 用 perf record -F 99 -p PID --call-graph dwarf 采样;
    • 用 OpenResty 的 openresty-systemtap-toolkit 中的 ngx-lua-bt 工具,把 perf.data 转成带 Lua 符号的折叠栈;
    • 最后仍走 flamegraph.pl。
  3. 火焰图只能看 on-CPU,如何同时看 off-CPU(阻塞在 cosocket)?
    答:

    • 对 ngx_http_lua_sleep、ngx_http_lua_socket_tcp_receive 等函数做 stap 计时;
    • 把 on-CPU 与 off-CPU 两张图左右并列,能快速区分“计算慢”还是“等待后端慢”,这是国内高阶 SRE 面试的加分项。