Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
linters:
enable:
- revive
- misspell

issues:
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ listener, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
listener = conntrack.NewListener(listener,
conntrack.TrackWithName("http"),
conntrack.TrackWithTracing(),
conntrack.TrackWithTcpKeepAlive(5 * time.Minute))
conntrack.TrackWithTCPKeepAlive(5 * time.Minute))
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.
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

Expand All @@ -69,9 +69,9 @@ 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)
conntrack.TrackWithTCPKeepAlive(5 * time.Minutes))
tlsConfig, err := connhelpers.TLSConfigForServerCerts(*tlsCertFilePath, *tlsKeyFilePath)
tlsConfig, err = connhelpers.TLSConfigWithHTTP2Enabled(tlsConfig)
tlsListener := tls.NewListener(listener, tlsConfig)
httpServer.Serve(listener)
```
Expand Down
8 changes: 4 additions & 4 deletions connhelpers/tls.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import (
"fmt"
)

// TlsConfigForServerCerts is a returns a simple `tls.Config` with the given server cert loaded.
// TLSConfigForServerCerts is a returns a simple `tls.Config` with the given server cert loaded.
// This is useful if you can't use `http.ListenAndServerTLS` when using a custom `net.Listener`.
func TlsConfigForServerCerts(certFile string, keyFile string) (*tls.Config, error) {
func TLSConfigForServerCerts(certFile string, keyFile string) (*tls.Config, error) {
var err error
config := new(tls.Config)
config.Certificates = make([]tls.Certificate, 1)
Expand All @@ -21,9 +21,9 @@ func TlsConfigForServerCerts(certFile string, keyFile string) (*tls.Config, erro
return config, nil
}

// TlsConfigWithHttp2Enabled makes it easy to configure the given `tls.Config` to prefer H2 connections.
// TLSConfigWithHTTP2Enabled makes it easy to configure the given `tls.Config` to prefer H2 connections.
// This is useful if you can't use `http.ListenAndServerTLS` when using a custom `net.Listener`.
func TlsConfigWithHttp2Enabled(config *tls.Config) (*tls.Config, error) {
func TLSConfigWithHTTP2Enabled(config *tls.Config) (*tls.Config, error) {
// mostly based on http2 code in the standards library.
if config.CipherSuites != nil {
// If they already provided a CipherSuite list, return
Expand Down
10 changes: 5 additions & 5 deletions dialer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func (s *DialerTestSuite) SetupSuite() {
s.serverListener, err = net.Listen("tcp", "127.0.0.1:0")
require.NoError(s.T(), err, "must be able to allocate a port for serverListener")
s.httpServer = http.Server{
Handler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
Handler: http.HandlerFunc(func(resp http.ResponseWriter, _ *http.Request) {
resp.WriteHeader(http.StatusOK)
}),
}
Expand All @@ -45,7 +45,7 @@ func (s *DialerTestSuite) TestDialerMetricsArePreregistered() {
conntrack.NewDialContextFunc() // dialer name = default
conntrack.NewDialContextFunc(conntrack.DialWithName("foobar"))
conntrack.PreRegisterDialerMetrics("something_manual")
for testId, testCase := range []struct {
for testID, testCase := range []struct {
metricName string
existingLabels []string
}{
Expand All @@ -67,13 +67,13 @@ func (s *DialerTestSuite) TestDialerMetricsArePreregistered() {
{"net_conntrack_dialer_conn_open", []string{"something_manual"}},
} {
lineCount := len(fetchPrometheusLines(s.T(), testCase.metricName, testCase.existingLabels...))
assert.NotEqual(s.T(), 0, lineCount, "metrics must exist for test case %d", testId)
assert.NotEqual(s.T(), 0, lineCount, "metrics must exist for test case %d", testID)
}
}

func (s *DialerTestSuite) TestDialerMetricsAreNotPreregisteredWithMonitoringOff() {
conntrack.NewDialContextFunc(conntrack.DialWithName("nomon"), conntrack.DialWithoutMonitoring())
for testId, testCase := range []struct {
for testID, testCase := range []struct {
metricName string
existingLabels []string
}{
Expand All @@ -87,7 +87,7 @@ func (s *DialerTestSuite) TestDialerMetricsAreNotPreregisteredWithMonitoringOff(
{"net_conntrack_dialer_conn_open", []string{"nomon"}},
} {
lineCount := len(fetchPrometheusLines(s.T(), testCase.metricName, testCase.existingLabels...))
assert.Equal(s.T(), 0, lineCount, "metrics should not be registered exist for test case %d", testId)
assert.Equal(s.T(), 0, lineCount, "metrics should not be registered exist for test case %d", testID)
}
}

Expand Down
8 changes: 4 additions & 4 deletions example/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (

var (
port = flag.Int("port", 9090, "whether to use tls or not")
useTls = flag.Bool("tls", true, "Whether to use TLS and HTTP2.")
useTLS = flag.Bool("tls", true, "Whether to use TLS and HTTP2.")
tlsCertFilePath = flag.String("tls_cert_file", "certs/localhost.crt", "Path to the CRT/PEM file.")
tlsKeyFilePath = flag.String("tls_key_file", "certs/localhost.key", "Path to the private key file.")
)
Expand Down Expand Up @@ -64,14 +64,14 @@ func main() {
log.Fatalf("Failed to listen: %v", err)
}
listener = conntrack.NewListener(listener, conntrack.TrackWithTracing())
if !*useTls {
if !*useTLS {
httpListener = listener
} else {
tlsConfig, err := connhelpers.TlsConfigForServerCerts(*tlsCertFilePath, *tlsKeyFilePath)
tlsConfig, err := connhelpers.TLSConfigForServerCerts(*tlsCertFilePath, *tlsKeyFilePath)
if err != nil {
log.Fatalf("Failed configuring TLS: %v", err)
}
tlsConfig, err = connhelpers.TlsConfigWithHttp2Enabled(tlsConfig)
tlsConfig, err = connhelpers.TLSConfigWithHTTP2Enabled(tlsConfig)
if err != nil {
log.Fatalf("Failed configuring TLS: %v", err)
}
Expand Down
6 changes: 3 additions & 3 deletions listener_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (s *ListenerTestSuite) SetupSuite() {
require.NoError(s.T(), err, "must be able to allocate a port for serverListener")
s.serverListener = conntrack.NewListener(s.serverListener, conntrack.TrackWithName(listenerName), conntrack.TrackWithTracing())
s.httpServer = http.Server{
Handler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
Handler: http.HandlerFunc(func(resp http.ResponseWriter, _ *http.Request) {
resp.WriteHeader(http.StatusOK)
}),
}
Expand All @@ -52,7 +52,7 @@ func (s *ListenerTestSuite) TestTrackingMetricsPreregistered() {
// this will create the default listener, check if it is registered
conntrack.NewListener(s.serverListener)

for testId, testCase := range []struct {
for testID, testCase := range []struct {
metricName string
existingLabels []string
}{
Expand All @@ -64,7 +64,7 @@ func (s *ListenerTestSuite) TestTrackingMetricsPreregistered() {
{"net_conntrack_listener_conn_open", []string{listenerName}},
} {
lineCount := len(fetchPrometheusLines(s.T(), testCase.metricName, testCase.existingLabels...))
assert.NotEqual(s.T(), 0, lineCount, "metrics must exist for test case %d", testId)
assert.NotEqual(s.T(), 0, lineCount, "metrics must exist for test case %d", testID)
}
}

Expand Down
16 changes: 8 additions & 8 deletions listener_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,42 +25,42 @@ type listenerOpts struct {
retryBackoff *backoff.Backoff
}

type listenerOpt func(*listenerOpts)
type ListenerOpt func(*listenerOpts)

// TrackWithName sets the name of the Listener for use in tracking and monitoring.
func TrackWithName(name string) listenerOpt {
func TrackWithName(name string) ListenerOpt {
return func(opts *listenerOpts) {
opts.name = name
}
}

// TrackWithoutMonitoring turns *off* Prometheus monitoring for this listener.
func TrackWithoutMonitoring() listenerOpt {
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 {
func TrackWithTracing() ListenerOpt {
return func(opts *listenerOpts) {
opts.tracing = true
}
}

// TrackWithRetries enables retrying of temporary Accept() errors, with the given backoff between attempts.
// Concurrent accept calls that receive temporary errors have independent backoff scaling.
func TrackWithRetries(b backoff.Backoff) listenerOpt {
func TrackWithRetries(b backoff.Backoff) ListenerOpt {
return func(opts *listenerOpts) {
opts.retryBackoff = &b
}
}

// TrackWithTcpKeepAlive makes sure that any `net.TCPConn` that get accepted have a keep-alive.
// 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 {
func TrackWithTCPKeepAlive(keepalive time.Duration) ListenerOpt {
return func(opts *listenerOpts) {
opts.tcpKeepAlive = keepalive
}
Expand All @@ -72,7 +72,7 @@ type connTrackListener struct {
}

// NewListener returns the given listener wrapped in connection tracking listener.
func NewListener(inner net.Listener, optFuncs ...listenerOpt) net.Listener {
func NewListener(inner net.Listener, optFuncs ...ListenerOpt) net.Listener {
opts := &listenerOpts{
name: defaultName,
monitoring: true,
Expand Down
3 changes: 1 addition & 2 deletions promhelper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@ func fetchPrometheusLines(t *testing.T, metricName string, matchingLabelValues .
line, err := reader.ReadString('\n')
if err == io.EOF {
break
} else {
require.NoError(t, err, "error reading stuff")
}
require.NoError(t, err, "error reading stuff")
if !strings.HasPrefix(line, metricName) {
continue
}
Expand Down