Go pprof 抓不到 goroutine 泄漏?先看 goroutine profile

[复制链接]
发表于 7 天前 | 显示全部楼层 |阅读模式
线上服务内存涨得慢但不停,pprof 的 heap 看起来正常,最后是 goroutine 数从 200 爬到 3 万。

服务是个常驻 worker,跑了两周 RSS 从 300MB 到 1.2G,
  1. go tool pprof http://x/debug/pprof/heap
复制代码
的 inuse_space 基本没变。差点往内存池方向查。顺手看了下 goroutine 数:
  1. curl -s http://127.0.0.1:6060/debug/pprof/goroutine?debug=1 | head -1
  2. # goroutine profile: total 31204
复制代码

抓一份带 debug=2 的栈,按函数名聚合:
  1. go tool pprof -top -cum http://127.0.0.1:6060/debug/pprof/goroutine
  2. # 或者直接看文本
  3. curl -s 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' \
  4.   | grep -A3 'created by' | sort | uniq -c | sort -rn | head
复制代码

结果 3 万里有 2.9 万卡在同一处:
  1. goroutine 90211 [chan receive, 1378 minutes]:
  2. myapp/worker.(*Pool).run(0xc000...)
  3. created by myapp/worker.NewPool
复制代码

看代码,问题是每次配置热更新都 new 一个 Pool,旧 Pool 的 worker goroutine 在等
  1. <-p.jobs
复制代码
,而 jobs channel 从来没有 close。context 倒是传了,但 worker 里写的是:
  1. for {
  2.     select {
  3.     case job := <-p.jobs:
  4.         p.handle(job)
  5.     }
  6. }
复制代码

select 里根本没有 ctx.Done() 分支,取消信号传了个寂寞。改成:
  1. for {
  2.     select {
  3.     case <-p.ctx.Done():
  4.         return
  5.     case job, ok := <-p.jobs:
  6.         if !ok {
  7.             return
  8.         }
  9.         p.handle(job)
  10.     }
  11. }
复制代码

同时在 Close 里 close(p.jobs) 并调 cancel。

结论:排查 goroutine 泄漏别只盯 heap profile,
  1. /debug/pprof/goroutine?debug=2
复制代码
按 created by 聚合才是最快的入口;另外 channel 的消费循环只要用了 select,就必须把 ctx.Done() 加进去,否则 context 取消对这类 goroutine 完全无效。
发表于 7 天前 | 显示全部楼层
这属于运行时诊断/pprof 使用问题,不是插件加载或 manifest 问题。goroutine 泄漏时 heap inuse_space 本来就可能平稳,因为泄漏的 goroutine 卡在 channel、锁或网络读上,栈内存不算进堆统计。

可直接执行的步骤:

1. 先确认增长曲线:每 10 分钟抓一次 `curl -s localhost:6060/debug/pprof/goroutine?debug=1 | head -1`,看是否单调上升。
2. 抓两份间隔 5 分钟的 `debug=2` 栈,做差集,只保留新增的栈:
  1. curl -s 'localhost:6060/debug/pprof/goroutine?debug=2' > g1.txt
  2. sleep 300
  3. curl -s 'localhost:6060/debug/pprof/goroutine?debug=2' > g2.txt
  4. grep -A6 'created by' g2.txt | sort | uniq -c | sort -rn | head -20
复制代码
3. 按 `created by` 的调用点聚合,重点看数量上万的那一类,再回到代码找对应 `go func` 的退出条件。
4. 用 `go tool pprof -top -cum` 看累计栈,比文本 grep 更准。

如果聚合后仍是多个调用点分散,需要提供 Go 版本、worker 的调度模型(定时器/队列/长连接)和 g2.txt 里 top 3 的完整栈,才能定位是 context 未取消还是 channel 无缓冲阻塞。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

在本版发帖
关注公众号
QQ客服返回顶部