Added go-conntrack for monitoring http connections (#3241)

Added metrics for in- and outgoing traffic with go-conntrack.
This commit is contained in:
Marc Sluiter 2017-10-06 12:22:19 +02:00 committed by Brian Brazil
parent 012e52e3f9
commit 6a633eece1
18 changed files with 809 additions and 23 deletions

View file

@ -17,6 +17,7 @@ package main
import (
"fmt"
"net"
"net/http"
_ "net/http/pprof" // Comment this line to disable pprof endpoint.
"net/url"
"os"
@ -37,6 +38,7 @@ import (
"gopkg.in/alecthomas/kingpin.v2"
k8s_runtime "k8s.io/apimachinery/pkg/util/runtime"
"github.com/mwitkow/go-conntrack"
"github.com/prometheus/common/promlog"
promlogflag "github.com/prometheus/common/promlog/flag"
"github.com/prometheus/prometheus/config"
@ -267,6 +269,11 @@ func main() {
webHandler := web.New(log.With(logger, "component", "web"), &cfg.web)
// Monitor outgoing connections on default transport with conntrack.
http.DefaultTransport.(*http.Transport).DialContext = conntrack.NewDialContextFunc(
conntrack.DialWithTracing(),
)
reloadables := []Reloadable{
remoteStorage,
targetManager,

View file

@ -24,6 +24,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
consul "github.com/hashicorp/consul/api"
"github.com/mwitkow/go-conntrack"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/config"
@ -106,7 +107,13 @@ func NewDiscovery(conf *config.ConsulSDConfig, logger log.Logger) (*Discovery, e
if err != nil {
return nil, err
}
transport := &http.Transport{TLSClientConfig: tls}
transport := &http.Transport{
TLSClientConfig: tls,
DialContext: conntrack.NewDialContextFunc(
conntrack.DialWithTracing(),
conntrack.DialWithName("consul_sd"),
),
}
wrapper := &http.Client{Transport: transport}
clientConf := &consul.Config{

View file

@ -28,6 +28,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/mwitkow/go-conntrack"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/config"
@ -117,6 +118,10 @@ func NewDiscovery(conf *config.MarathonSDConfig, logger log.Logger) (*Discovery,
Timeout: time.Duration(conf.Timeout),
Transport: &http.Transport{
TLSClientConfig: tls,
DialContext: conntrack.NewDialContextFunc(
conntrack.DialWithTracing(),
conntrack.DialWithName("marathon_sd"),
),
},
}

View file

@ -22,6 +22,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/mwitkow/go-conntrack"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/config"
@ -87,7 +88,13 @@ func New(logger log.Logger, conf *config.TritonSDConfig) (*Discovery, error) {
return nil, err
}
transport := &http.Transport{TLSClientConfig: tls}
transport := &http.Transport{
TLSClientConfig: tls,
DialContext: conntrack.NewDialContextFunc(
conntrack.DialWithTracing(),
conntrack.DialWithName("triton_sd"),
),
}
client := &http.Client{Transport: transport}
return &Discovery{

View file

@ -515,7 +515,7 @@ type alertmanagerSet struct {
}
func newAlertmanagerSet(cfg *config.AlertmanagerConfig, logger log.Logger) (*alertmanagerSet, error) {
client, err := httputil.NewClientFromConfig(cfg.HTTPClientConfig)
client, err := httputil.NewClientFromConfig(cfg.HTTPClientConfig, "alertmanager")
if err != nil {
return nil, err
}

View file

@ -141,7 +141,7 @@ func newScrapePool(ctx context.Context, cfg *config.ScrapeConfig, app Appendable
logger = log.NewNopLogger()
}
client, err := httputil.NewClientFromConfig(cfg.HTTPClientConfig)
client, err := httputil.NewClientFromConfig(cfg.HTTPClientConfig, cfg.JobName)
if err != nil {
// Any errors that could occur here should be caught during config validation.
level.Error(logger).Log("msg", "Error creating HTTP client", "err", err)
@ -202,7 +202,7 @@ func (sp *scrapePool) reload(cfg *config.ScrapeConfig) {
sp.mtx.Lock()
defer sp.mtx.Unlock()
client, err := httputil.NewClientFromConfig(cfg.HTTPClientConfig)
client, err := httputil.NewClientFromConfig(cfg.HTTPClientConfig, cfg.JobName)
if err != nil {
// Any errors that could occur here should be caught during config validation.
level.Error(sp.logger).Log("msg", "Error creating HTTP client", "err", err)

View file

@ -151,7 +151,7 @@ func TestNewHTTPBearerToken(t *testing.T) {
cfg := config.HTTPClientConfig{
BearerToken: "1234",
}
c, err := httputil.NewClientFromConfig(cfg)
c, err := httputil.NewClientFromConfig(cfg, "test")
if err != nil {
t.Fatal(err)
}
@ -178,7 +178,7 @@ func TestNewHTTPBearerTokenFile(t *testing.T) {
cfg := config.HTTPClientConfig{
BearerTokenFile: "testdata/bearertoken.txt",
}
c, err := httputil.NewClientFromConfig(cfg)
c, err := httputil.NewClientFromConfig(cfg, "test")
if err != nil {
t.Fatal(err)
}
@ -207,7 +207,7 @@ func TestNewHTTPBasicAuth(t *testing.T) {
Password: "password123",
},
}
c, err := httputil.NewClientFromConfig(cfg)
c, err := httputil.NewClientFromConfig(cfg, "test")
if err != nil {
t.Fatal(err)
}
@ -235,7 +235,7 @@ func TestNewHTTPCACert(t *testing.T) {
CAFile: caCertPath,
},
}
c, err := httputil.NewClientFromConfig(cfg)
c, err := httputil.NewClientFromConfig(cfg, "test")
if err != nil {
t.Fatal(err)
}
@ -269,7 +269,7 @@ func TestNewHTTPClientCert(t *testing.T) {
KeyFile: "testdata/client.key",
},
}
c, err := httputil.NewClientFromConfig(cfg)
c, err := httputil.NewClientFromConfig(cfg, "test")
if err != nil {
t.Fatal(err)
}
@ -298,7 +298,7 @@ func TestNewHTTPWithServerName(t *testing.T) {
ServerName: "prometheus.rocks",
},
}
c, err := httputil.NewClientFromConfig(cfg)
c, err := httputil.NewClientFromConfig(cfg, "test")
if err != nil {
t.Fatal(err)
}
@ -327,7 +327,7 @@ func TestNewHTTPWithBadServerName(t *testing.T) {
ServerName: "badname",
},
}
c, err := httputil.NewClientFromConfig(cfg)
c, err := httputil.NewClientFromConfig(cfg, "test")
if err != nil {
t.Fatal(err)
}
@ -366,7 +366,7 @@ func TestNewClientWithBadTLSConfig(t *testing.T) {
KeyFile: "testdata/nonexistent_client.key",
},
}
_, err := httputil.NewClientFromConfig(cfg)
_, err := httputil.NewClientFromConfig(cfg, "test")
if err == nil {
t.Fatalf("Expected error, got nil.")
}

View file

@ -51,7 +51,7 @@ type clientConfig struct {
// NewClient creates a new Client.
func NewClient(index int, conf *clientConfig) (*Client, error) {
httpClient, err := httputil.NewClientFromConfig(conf.httpClientConfig)
httpClient, err := httputil.NewClientFromConfig(conf.httpClientConfig, "remote_storage")
if err != nil {
return nil, err
}

View file

@ -22,17 +22,18 @@ import (
"strings"
"time"
"github.com/mwitkow/go-conntrack"
"github.com/prometheus/prometheus/config"
)
// NewClient returns a http.Client using the specified http.RoundTripper.
func NewClient(rt http.RoundTripper) *http.Client {
func newClient(rt http.RoundTripper) *http.Client {
return &http.Client{Transport: rt}
}
// NewClientFromConfig returns a new HTTP client configured for the
// given config.HTTPClientConfig.
func NewClientFromConfig(cfg config.HTTPClientConfig) (*http.Client, error) {
// given config.HTTPClientConfig. The name is used as go-conntrack metric label.
func NewClientFromConfig(cfg config.HTTPClientConfig, name string) (*http.Client, error) {
tlsConfig, err := NewTLSConfig(cfg.TLSConfig)
if err != nil {
return nil, err
@ -48,6 +49,10 @@ func NewClientFromConfig(cfg config.HTTPClientConfig) (*http.Client, error) {
// 5 minutes is typically above the maximum sane scrape interval. So we can
// use keepalive for all configurations.
IdleConnTimeout: 5 * time.Minute,
DialContext: conntrack.NewDialContextFunc(
conntrack.DialWithTracing(),
conntrack.DialWithName(name),
),
}
// If a bearer token is provided, create a round tripper that will set the
@ -70,7 +75,7 @@ func NewClientFromConfig(cfg config.HTTPClientConfig) (*http.Client, error) {
}
// Return a new client with the configured round tripper.
return NewClient(rt), nil
return newClient(rt), nil
}
type bearerAuthRoundTripper struct {

View file

@ -177,7 +177,7 @@ func TestNewClientFromConfig(t *testing.T) {
}
defer testServer.Close()
client, err := NewClientFromConfig(validConfig.clientConfig)
client, err := NewClientFromConfig(validConfig.clientConfig, "test")
if err != nil {
t.Errorf("Can't create a client from this config: %+v", validConfig.clientConfig)
continue
@ -233,7 +233,7 @@ func TestNewClientFromInvalidConfig(t *testing.T) {
}
for _, invalidConfig := range newClientInvalidConfig {
client, err := NewClientFromConfig(invalidConfig.clientConfig)
client, err := NewClientFromConfig(invalidConfig.clientConfig, "test")
if client != nil {
t.Errorf("A client instance was returned instead of nil using this config: %+v", invalidConfig.clientConfig)
}

201
vendor/github.com/mwitkow/go-conntrack/LICENSE generated vendored Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

88
vendor/github.com/mwitkow/go-conntrack/README.md generated vendored Normal file
View file

@ -0,0 +1,88 @@
# Go tracing and monitoring (Prometheus) for `net.Conn`
[![Travis Build](https://travis-ci.org/mwitkow/go-conntrack.svg)](https://travis-ci.org/mwitkow/go-conntrack)
[![Go Report Card](https://goreportcard.com/badge/github.com/mwitkow/go-conntrack)](http://goreportcard.com/report/mwitkow/go-conntrack)
[![GoDoc](http://img.shields.io/badge/GoDoc-Reference-blue.svg)](https://godoc.org/github.com/mwitkow/go-conntrack)
[![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[Prometheus](https://prometheus.io/) monitoring and [`x/net/trace`](https://godoc.org/golang.org/x/net/trace#EventLog) tracing wrappers `net.Conn`, both inbound (`net.Listener`) and outbound (`net.Dialer`).
## Why?
Go standard library does a great job of doing "the right" things with your connections: `http.Transport` pools outbound ones, and `http.Server` sets good *Keep Alive* defaults.
However, it is still easy to get it wrong, see the excellent [*The complete guide to Go net/http timeouts*](https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts/).
That's why you should be able to monitor (using Prometheus) how many connections your Go frontend servers have inbound, and how big are the connection pools to your backends. You should also be able to inspect your connection without `ssh` and `netstat`.
![Events page with connections](https://raw.githubusercontent.com/mwitkow/go-conntrack/images/events.png)
## How to use?
All of these examples can be found in [`example/server.go`](example/server.go):
### Conntrack Dialer for HTTP DefaultClient
Most often people use the default `http.DefaultClient` that uses `http.DefaultTransport`. The easiest way to make sure all your outbound connections monitored and trace is:
```go
http.DefaultTransport.(*http.Transport).DialContext = conntrack.NewDialContextFunc(
conntrack.DialWithTracing(),
conntrack.DialWithDialer(&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}),
)
```
#### Dialer Name
Tracked outbound connections are organised by *dialer name* (with `default` being default). The *dialer name* is used for monitoring (`dialer_name` label) and tracing (`net.ClientConn.<dialer_name>` family).
You can pass `conntrack.WithDialerName()` to `NewDialContextFunc` to set the name for the dialer. Moreover, you can set the *dialer name* per invocation of the dialer, by passing it in the `Context`. For example using the [`ctxhttp`](https://godoc.org/golang.org/x/net/context/ctxhttp) lib:
```go
callCtx := conntrack.DialNameToContext(parentCtx, "google")
ctxhttp.Get(callCtx, http.DefaultClient, "https://www.google.com")
```
### Conntrack Listener for HTTP Server
Tracked inbound connections are organised by *listener name* (with `default` being default). The *listener name* is used for monitoring (`listener_name` label) and tracing (`net.ServerConn.<listener_name>` family). For example, a simple `http.Server` can be instrumented like this:
```go
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
listener = conntrack.NewListener(listener,
conntrack.TrackWithName("http"),
conntrack.TrackWithTracing(),
conntrack.TrackWithTcpKeepAlive(5 * time.Minutes))
httpServer.Serve(listener)
```
Note, the `TrackWithTcpKeepAlive`. The default `http.ListenAndServe` adds a tcp keep alive wrapper to inbound TCP connections. `conntrack.NewListener` allows you to do that without another layer of wrapping.
#### TLS server example
The standard lobrary `http.ListenAndServerTLS` does a lot to bootstrap TLS connections, including supporting HTTP2 negotiation. Unfortunately, that is hard to do if you want to provide your own `net.Listener`. That's why this repo comes with `connhelpers` package, which takes care of configuring `tls.Config` for that use case. Here's an example of use:
```go
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
listener = conntrack.NewListener(listener,
conntrack.TrackWithName("https"),
conntrack.TrackWithTracing(),
conntrack.TrackWithTcpKeepAlive(5 * time.Minutes))
tlsConfig, err := connhelpers.TlsConfigForServerCerts(*tlsCertFilePath, *tlsKeyFilePath)
tlsConfig, err = connhelpers.TlsConfigWithHttp2Enabled(tlsConfig)
tlsListener := tls.NewListener(listener, tlsConfig)
httpServer.Serve(listener)
```
# Status
This code is used by Improbable's HTTP frontending and proxying stack for debuging and monitoring of established user connections.
Additional tooling will be added if needed, and contributions are welcome.
#License
`go-conntrack` is released under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details.

View file

@ -0,0 +1,108 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package conntrack
import (
"context"
"net"
"os"
"syscall"
prom "github.com/prometheus/client_golang/prometheus"
)
type failureReason string
const (
failedResolution = "resolution"
failedConnRefused = "refused"
failedTimeout = "timeout"
failedUnknown = "unknown"
)
var (
dialerAttemptedTotal = prom.NewCounterVec(
prom.CounterOpts{
Namespace: "net",
Subsystem: "conntrack",
Name: "dialer_conn_attempted_total",
Help: "Total number of connections attempted by the given dialer a given name.",
}, []string{"dialer_name"})
dialerConnEstablishedTotal = prom.NewCounterVec(
prom.CounterOpts{
Namespace: "net",
Subsystem: "conntrack",
Name: "dialer_conn_established_total",
Help: "Total number of connections successfully established by the given dialer a given name.",
}, []string{"dialer_name"})
dialerConnFailedTotal = prom.NewCounterVec(
prom.CounterOpts{
Namespace: "net",
Subsystem: "conntrack",
Name: "dialer_conn_failed_total",
Help: "Total number of connections failed to dial by the dialer a given name.",
}, []string{"dialer_name", "reason"})
dialerConnClosedTotal = prom.NewCounterVec(
prom.CounterOpts{
Namespace: "net",
Subsystem: "conntrack",
Name: "dialer_conn_closed_total",
Help: "Total number of connections closed which originated from the dialer of a given name.",
}, []string{"dialer_name"})
)
func init() {
prom.MustRegister(dialerAttemptedTotal)
prom.MustRegister(dialerConnEstablishedTotal)
prom.MustRegister(dialerConnFailedTotal)
prom.MustRegister(dialerConnClosedTotal)
}
// preRegisterDialerMetrics pre-populates Prometheus labels for the given dialer name, to avoid Prometheus missing labels issue.
func PreRegisterDialerMetrics(dialerName string) {
dialerAttemptedTotal.WithLabelValues(dialerName)
dialerConnEstablishedTotal.WithLabelValues(dialerName)
for _, reason := range []failureReason{failedTimeout, failedResolution, failedConnRefused, failedUnknown} {
dialerConnFailedTotal.WithLabelValues(dialerName, string(reason))
}
dialerConnClosedTotal.WithLabelValues(dialerName)
}
func reportDialerConnAttempt(dialerName string) {
dialerAttemptedTotal.WithLabelValues(dialerName).Inc()
}
func reportDialerConnEstablished(dialerName string) {
dialerConnEstablishedTotal.WithLabelValues(dialerName).Inc()
}
func reportDialerConnClosed(dialerName string) {
dialerConnClosedTotal.WithLabelValues(dialerName).Inc()
}
func reportDialerConnFailed(dialerName string, err error) {
if netErr, ok := err.(*net.OpError); ok {
switch nestErr := netErr.Err.(type) {
case *net.DNSError:
dialerConnFailedTotal.WithLabelValues(dialerName, string(failedResolution)).Inc()
return
case *os.SyscallError:
if nestErr.Err == syscall.ECONNREFUSED {
dialerConnFailedTotal.WithLabelValues(dialerName, string(failedConnRefused)).Inc()
}
dialerConnFailedTotal.WithLabelValues(dialerName, string(failedUnknown)).Inc()
return
}
if netErr.Timeout() {
dialerConnFailedTotal.WithLabelValues(dialerName, string(failedTimeout)).Inc()
}
} else if err == context.Canceled || err == context.DeadlineExceeded {
dialerConnFailedTotal.WithLabelValues(dialerName, string(failedTimeout)).Inc()
return
}
dialerConnFailedTotal.WithLabelValues(dialerName, string(failedUnknown)).Inc()
}

View file

@ -0,0 +1,166 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package conntrack
import (
"context"
"fmt"
"net"
"sync"
"golang.org/x/net/trace"
)
var (
dialerNameKey = "conntrackDialerKey"
)
type dialerOpts struct {
name string
monitoring bool
tracing bool
parentDialContextFunc dialerContextFunc
}
type dialerOpt func(*dialerOpts)
type dialerContextFunc func(context.Context, string, string) (net.Conn, error)
// DialWithName sets the name of the dialer for tracking and monitoring.
// This is the name for the dialer (default is `default`), but for `NewDialContextFunc` can be overwritten from the
// Context using `DialNameToContext`.
func DialWithName(name string) dialerOpt {
return func(opts *dialerOpts) {
opts.name = name
}
}
// DialWithoutMonitoring turns *off* Prometheus monitoring for this dialer.
func DialWithoutMonitoring() dialerOpt {
return func(opts *dialerOpts) {
opts.monitoring = false
}
}
// DialWithTracing turns *on* the /debug/events tracing of the dial calls.
func DialWithTracing() dialerOpt {
return func(opts *dialerOpts) {
opts.tracing = true
}
}
// DialWithDialer allows you to override the `net.Dialer` instance used to actually conduct the dials.
func DialWithDialer(parentDialer *net.Dialer) dialerOpt {
return DialWithDialContextFunc(parentDialer.DialContext)
}
// DialWithDialContextFunc allows you to override func gets used for the actual dialing. The default is `net.Dialer.DialContext`.
func DialWithDialContextFunc(parentDialerFunc dialerContextFunc) dialerOpt {
return func(opts *dialerOpts) {
opts.parentDialContextFunc = parentDialerFunc
}
}
// DialNameFromContext returns the name of the dialer from the context of the DialContext func, if any.
func DialNameFromContext(ctx context.Context) string {
val, ok := ctx.Value(dialerNameKey).(string)
if !ok {
return ""
}
return val
}
// DialNameToContext returns a context that will contain a dialer name override.
func DialNameToContext(ctx context.Context, dialerName string) context.Context {
return context.WithValue(ctx, dialerNameKey, dialerName)
}
// NewDialContextFunc returns a `DialContext` function that tracks outbound connections.
// The signature is compatible with `http.Tranport.DialContext` and is meant to be used there.
func NewDialContextFunc(optFuncs ...dialerOpt) func(context.Context, string, string) (net.Conn, error) {
opts := &dialerOpts{name: defaultName, monitoring: true, parentDialContextFunc: (&net.Dialer{}).DialContext}
for _, f := range optFuncs {
f(opts)
}
if opts.monitoring {
PreRegisterDialerMetrics(opts.name)
}
return func(ctx context.Context, network string, addr string) (net.Conn, error) {
name := opts.name
if ctxName := DialNameFromContext(ctx); ctxName != "" {
name = ctxName
}
return dialClientConnTracker(ctx, network, addr, name, opts)
}
}
// NewDialFunc returns a `Dial` function that tracks outbound connections.
// The signature is compatible with `http.Tranport.Dial` and is meant to be used there for Go < 1.7.
func NewDialFunc(optFuncs ...dialerOpt) func(string, string) (net.Conn, error) {
dialContextFunc := NewDialContextFunc(optFuncs...)
return func(network string, addr string) (net.Conn, error) {
return dialContextFunc(context.TODO(), network, addr)
}
}
type clientConnTracker struct {
net.Conn
opts *dialerOpts
dialerName string
event trace.EventLog
mu sync.Mutex
}
func dialClientConnTracker(ctx context.Context, network string, addr string, dialerName string, opts *dialerOpts) (net.Conn, error) {
var event trace.EventLog
if opts.tracing {
event = trace.NewEventLog(fmt.Sprintf("net.ClientConn.%s", dialerName), fmt.Sprintf("%v", addr))
}
if opts.monitoring {
reportDialerConnAttempt(dialerName)
}
conn, err := opts.parentDialContextFunc(ctx, network, addr)
if err != nil {
if event != nil {
event.Errorf("failed dialing: %v", err)
event.Finish()
}
if opts.monitoring {
reportDialerConnFailed(dialerName, err)
}
return nil, err
}
if event != nil {
event.Printf("established: %s -> %s", conn.LocalAddr(), conn.RemoteAddr())
}
if opts.monitoring {
reportDialerConnEstablished(dialerName)
}
tracker := &clientConnTracker{
Conn: conn,
opts: opts,
dialerName: dialerName,
event: event,
}
return tracker, nil
}
func (ct *clientConnTracker) Close() error {
err := ct.Conn.Close()
ct.mu.Lock()
if ct.event != nil {
if err != nil {
ct.event.Errorf("failed closing: %v", err)
} else {
ct.event.Printf("closing")
}
ct.event.Finish()
ct.event = nil
}
ct.mu.Unlock()
if ct.opts.monitoring {
reportDialerConnClosed(ct.dialerName)
}
return err
}

View file

@ -0,0 +1,43 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package conntrack
import prom "github.com/prometheus/client_golang/prometheus"
var (
listenerAcceptedTotal = prom.NewCounterVec(
prom.CounterOpts{
Namespace: "net",
Subsystem: "conntrack",
Name: "listener_conn_accepted_total",
Help: "Total number of connections opened to the listener of a given name.",
}, []string{"listener_name"})
listenerClosedTotal = prom.NewCounterVec(
prom.CounterOpts{
Namespace: "net",
Subsystem: "conntrack",
Name: "listener_conn_closed_total",
Help: "Total number of connections closed that were made to the listener of a given name.",
}, []string{"listener_name"})
)
func init() {
prom.MustRegister(listenerAcceptedTotal)
prom.MustRegister(listenerClosedTotal)
}
// preRegisterListener pre-populates Prometheus labels for the given listener name, to avoid Prometheus missing labels issue.
func preRegisterListenerMetrics(listenerName string) {
listenerAcceptedTotal.WithLabelValues(listenerName)
listenerClosedTotal.WithLabelValues(listenerName)
}
func reportListenerConnAccepted(listenerName string) {
listenerAcceptedTotal.WithLabelValues(listenerName).Inc()
}
func reportListenerConnClosed(listenerName string) {
listenerClosedTotal.WithLabelValues(listenerName).Inc()
}

View file

@ -0,0 +1,137 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package conntrack
import (
"fmt"
"net"
"sync"
"golang.org/x/net/trace"
"time"
)
const (
defaultName = "default"
)
type listenerOpts struct {
name string
monitoring bool
tracing bool
tcpKeepAlive time.Duration
}
type listenerOpt func(*listenerOpts)
// TrackWithName sets the name of the Listener for use in tracking and monitoring.
func TrackWithName(name string) listenerOpt {
return func(opts *listenerOpts) {
opts.name = name
}
}
// TrackWithoutMonitoring turns *off* Prometheus monitoring for this listener.
func TrackWithoutMonitoring() listenerOpt {
return func(opts *listenerOpts) {
opts.monitoring = false
}
}
// TrackWithTracing turns *on* the /debug/events tracing of the live listener connections.
func TrackWithTracing() listenerOpt {
return func(opts *listenerOpts) {
opts.tracing = true
}
}
// TrackWithTcpKeepAlive makes sure that any `net.TCPConn` that get accepted have a keep-alive.
// This is useful for HTTP servers in order for, for example laptops, to not use up resources on the
// server while they don't utilise their connection.
// A value of 0 disables it.
func TrackWithTcpKeepAlive(keepalive time.Duration) listenerOpt {
return func(opts *listenerOpts) {
opts.tcpKeepAlive = keepalive
}
}
type connTrackListener struct {
net.Listener
opts *listenerOpts
}
// NewListener returns the given listener wrapped in connection tracking listener.
func NewListener(inner net.Listener, optFuncs ...listenerOpt) net.Listener {
opts := &listenerOpts{
name: defaultName,
monitoring: true,
tracing: false,
}
for _, f := range optFuncs {
f(opts)
}
if opts.monitoring {
preRegisterListenerMetrics(opts.name)
}
return &connTrackListener{
Listener: inner,
opts: opts,
}
}
func (ct *connTrackListener) Accept() (net.Conn, error) {
// TODO(mwitkow): Add monitoring of failed accept.
conn, err := ct.Listener.Accept()
if err != nil {
return nil, err
}
if tcpConn, ok := conn.(*net.TCPConn); ok && ct.opts.tcpKeepAlive > 0 {
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(ct.opts.tcpKeepAlive)
}
return newServerConnTracker(conn, ct.opts), nil
}
type serverConnTracker struct {
net.Conn
opts *listenerOpts
event trace.EventLog
mu sync.Mutex
}
func newServerConnTracker(inner net.Conn, opts *listenerOpts) net.Conn {
tracker := &serverConnTracker{
Conn: inner,
opts: opts,
}
if opts.tracing {
tracker.event = trace.NewEventLog(fmt.Sprintf("net.ServerConn.%s", opts.name), fmt.Sprintf("%v", inner.RemoteAddr()))
tracker.event.Printf("accepted: %v -> %v", inner.RemoteAddr(), inner.LocalAddr())
}
if opts.monitoring {
reportListenerConnAccepted(opts.name)
}
return tracker
}
func (ct *serverConnTracker) Close() error {
err := ct.Conn.Close()
ct.mu.Lock()
if ct.event != nil {
if err != nil {
ct.event.Errorf("failed closing: %v", err)
} else {
ct.event.Printf("closing")
}
ct.event.Finish()
ct.event = nil
}
ct.mu.Unlock()
if ct.opts.monitoring {
reportListenerConnClosed(ct.opts.name)
}
return err
}

6
vendor/vendor.json vendored
View file

@ -719,6 +719,12 @@
"revision": "672033dedc09500ca4d340760d0b80b9c0b198bd",
"revisionTime": "2017-02-13T20:16:50Z"
},
{
"checksumSHA1": "ZYfqG6bNE3cRlbsvpJBL0bF6DSc=",
"path": "github.com/mwitkow/go-conntrack",
"revision": "cc309e4a22231782e8893f3c35ced0967807a33e",
"revisionTime": "2016-11-29T09:58:57Z"
},
{
"checksumSHA1": "aCtmlyAgau9n0UHs8Pk+3xfIaVk=",
"path": "github.com/nightlyone/lockfile",

View file

@ -51,6 +51,7 @@ import (
"golang.org/x/net/context"
"golang.org/x/net/netutil"
"github.com/mwitkow/go-conntrack"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/notifier"
"github.com/prometheus/prometheus/pkg/labels"
@ -377,14 +378,19 @@ func (h *Handler) Reload() <-chan chan error {
func (h *Handler) Run(ctx context.Context) error {
level.Info(h.logger).Log("msg", "Start listening for connections", "address", h.options.ListenAddress)
l, err := net.Listen("tcp", h.options.ListenAddress)
listener, err := net.Listen("tcp", h.options.ListenAddress)
if err != nil {
return err
}
l = netutil.LimitListener(l, h.options.MaxConnections)
listener = netutil.LimitListener(listener, h.options.MaxConnections)
// Monitor incoming connections with conntrack.
listener = conntrack.NewListener(listener,
conntrack.TrackWithName("http"),
conntrack.TrackWithTracing())
var (
m = cmux.New(l)
m = cmux.New(listener)
grpcl = m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
httpl = m.Match(cmux.HTTP1Fast())
grpcSrv = grpc.NewServer()