问题现象
生产环境有个golang应用上线一个月来,占用内存不断增多,约30个G,这个应用的DAU估计最多几十,初步怀疑有内存泄露问题。
下面是排查步骤:
分析
内存泄露可能点:
- goroutine没有释放
- time.NewTicker资源未及时释放
- slice切割的误用…
开启pprof
我们的web框架使用的是gin,结合pprof- package main
- import (
- "github.com/gin-contrib/pprof"
- "github.com/gin-gonic/gin"
- )
- func main() {
- router := gin.Default()
- pprof.Register(router)
- router.Run(":8090")
- }
复制代码 浏览器访问:http://ip:port/debug/pprof
着重看下heap和goroutine
heap中发现代码中一个内存缓冲bigcache比较占用内存,goroutine中发现总共466700个goroutine,第一处代码占了466615个,这是肯定不正常的。至此,已基本确定内存泄露的点了,继续验证:- go tool pprof http://ip:port/debug/pprof/heap
复制代码 输入top命令:
之前通过http://ip:port/debug/pprof/heap?debug=1查看到的bigcache占用内存,go tool 分析之后排除了内存泄露的可能性,因为程序在运行一段时间后,bigcache占用内存并未增长,goph.NewUnknown方法的代码位置和goroutine中client.go:72的指向是一致的,所以可以确定就是这块代码的问题。
代码分析
问题代码:- func NewUnknown(user string, addr string, auth Auth, t time.Duration) (*Client, error) {
- type st struct {
- cli *Client
- err error
- }
- var ch = make(chan st) # 无缓冲队列
- go func() {
- cli, err := NewConn(&Config{
- User: user,
- Addr: addr,
- Port: 22,
- Auth: auth,
- Timeout: DefaultTimeout,
- Callback: ssh.InsecureIgnoreHostKey(),
- })
- ch <- st{ # 写阻塞 ①
- cli: cli,
- err: err,
- }
- }()
- for {
- select {
- case <-time.After(t): # ②
- return nil, fmt.Errorf("new ssh client time out")
- case res := <-ch:
- return res.cli, res.err
- }
- }
- }
复制代码 由于ch是无缓冲的channel,①处写数据可能会阻塞,当②超时返回时,由于ch没有被接收方,①处的goroutine会一直阻塞,造成内存泄露。
修复方案
- var ch = make(chan st, 1)
复制代码 设置一个有缓冲队列的channel,这样就算没有接收方,也能往里写数据。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
来源:互联网
免责声明:如果侵犯了您的权益,请联系站长(1277306191@qq.com),我们会及时删除侵权内容,谢谢合作! |