From 41830d450f900cbf2596e45dc9a717cd5e7515b8 Mon Sep 17 00:00:00 2001 From: Rob Best Date: Fri, 5 Jun 2020 13:59:50 +0100 Subject: [PATCH] Fix connection leak (#31) Connections were being left around after requests and in some cases this could result in file descriptor errors when open files built up. Closing the http response body and the tcp connection, as well as disabling http keep alives seems to resolve this. --- ssl_exporter.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/ssl_exporter.go b/ssl_exporter.go index fa8f5b9..69e8019 100644 --- a/ssl_exporter.go +++ b/ssl_exporter.go @@ -5,6 +5,7 @@ import ( "crypto/x509" "errors" "fmt" + "io" "io/ioutil" "net" "net/http" @@ -96,8 +97,9 @@ func (e *Exporter) Collect(ch chan<- prometheus.Metric) { return http.ErrUseLastResponse }, Transport: &http.Transport{ - TLSClientConfig: e.tlsConfig, - Proxy: http.ProxyFromEnvironment, + TLSClientConfig: e.tlsConfig, + Proxy: http.ProxyFromEnvironment, + DisableKeepAlives: true, }, Timeout: e.timeout, } @@ -111,6 +113,13 @@ func (e *Exporter) Collect(ch chan<- prometheus.Metric) { ) return } + defer func() { + _, err := io.Copy(ioutil.Discard, resp.Body) + if err != nil { + log.Errorln(err) + } + resp.Body.Close() + }() // Check if the response from the target is encrypted if resp.TLS == nil { @@ -136,6 +145,7 @@ func (e *Exporter) Collect(ch chan<- prometheus.Metric) { ) return } + defer conn.Close() state = conn.ConnectionState() } else {