使用pprof分析golang内存泄露问题

问题现象

生产环境有个golang应用上线一个月来,占用内存不断增多,约30个G,这个应用的DAU估计最多几十,初步怀疑有内存泄露问题。下面是排查步骤:

分析

内存泄露可能点:

  1. goroutine没有释放
  2. time.NewTicker资源未及时释放
  3. 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
使用pprof分析golang内存泄露问题_第1张图片
着重看下heap和goroutine
使用pprof分析golang内存泄露问题_第2张图片
使用pprof分析golang内存泄露问题_第3张图片
heap中发现代码中一个内存缓冲bigcache比较占用内存,goroutine中发现总共466700个goroutine,第一处代码占了466615个,这是肯定不正常的。至此,已基本确定内存泄露的点了,继续验证:
go tool pprof http://ip:port/debug/pprof/heap
输入top命令:
使用pprof分析golang内存泄露问题_第4张图片
使用pprof分析golang内存泄露问题_第5张图片

之前通过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,这样就算没有接收方,也能往里写数据。

你可能感兴趣的:(golang)