Golang Web服务器在crypto/tls泄漏内存.(*block).reserve

zem*_*rco 10 ssl memory-leaks go tls1.2

我有一个用Go编写的Web服务器.

tlsConfig := &tls.Config{
    PreferServerCipherSuites: true,
    MinVersion:               tls.VersionTLS12,
    CurvePreferences: []tls.CurveID{
        tls.CurveP256,
        tls.X25519,
    },
    CipherSuites: []uint16{
        tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
        tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
        tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
        tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
        tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
        tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
    },
}

s := &http.Server{
    ReadTimeout:  5 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout:  120 * time.Second,
    Handler:      r, // where r is my router
    TLSConfig:    tlsConfig,
}

// redirect http to https
redirect := &http.Server{
    ReadTimeout:  5 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout:  120 * time.Second,
    Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Connection", "close")
        url := "https://" + r.Host + r.URL.String()
        http.Redirect(w, r, url, http.StatusMovedPermanently)
    }),
}
go func() {
    log.Fatal(redirect.ListenAndServe())
}()

log.Fatal(s.ListenAndServeTLS(certFile, keyFile))
Run Code Online (Sandbox Code Playgroud)

这是我的数字海洋仪表板的截图.

在此输入图像描述

正如您所看到的,内存不断增长和增长.所以我开始关注https://github.com/google/pprof.这是输出top5.

Type: inuse_space
Time: Nov 7, 2018 at 10:31am (CET)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top5
Showing nodes accounting for 289.50MB, 79.70% of 363.24MB total
Dropped 90 nodes (cum <= 1.82MB)
Showing top 5 nodes out of 88
      flat  flat%   sum%        cum   cum%
  238.98MB 65.79% 65.79%   238.98MB 65.79%  crypto/tls.(*block).reserve
   20.02MB  5.51% 71.30%    20.02MB  5.51%  crypto/tls.Server
   11.50MB  3.17% 74.47%    11.50MB  3.17%  crypto/aes.newCipher
   10.50MB  2.89% 77.36%    10.50MB  2.89%  crypto/aes.(*aesCipherGCM).NewGCM
Run Code Online (Sandbox Code Playgroud)

SVG显示了由crypto/tls分配的相同大量内存.(*block).reserve.

在此输入图像描述

这是确切的代码.

在此输入图像描述

我花了最后几天阅读我能找到的每篇文章,文档,博客文章,源代码,帮助文件.但没有任何帮助.代码在Ubuntu 17.10 x64机器上运行,在Docker容器中使用Go 1.11.

看起来服务器不会关闭与客户端的连接.我认为设置所有xyzTimeout会有所帮助,但事实并非如此.

有任何想法吗?

编辑12/20/2018:

现在修复https://github.com/golang/go/issues/28654#issuecomment-448477056

Joh*_*don 1

添加答案,以便该答案不会一直显示在已投票和未回答的问题列表中。

看来内存泄漏与 gorilla 上下文错误https://github.com/gorilla/sessions/commit/12bd4761fc66ac946e16fcc2a32b1e0b066f6177有关,与 stdlib 中的 tls 无关。