From cf039e7af471fbc4fdf20d06c48ff9ddeb45a293 Mon Sep 17 00:00:00 2001 From: Tim Gross Date: Wed, 6 Apr 2022 14:42:30 -0400 Subject: [PATCH] api: use `cleanhttp.DefaultPooledTransport` for default API client We expect every Nomad API client to use a single connection to any given agent, so take advantage of keep-alive by switching the default transport to `DefaultPooledClient`. Provide a facility to close idle connections for testing purposes. Restores the previously reverted #12409 Co-authored-by: Ben Buzbee --- .changelog/12492.txt | 3 +++ api/api.go | 14 +++++++++++++- command/agent/http_test.go | 2 ++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 .changelog/12492.txt diff --git a/.changelog/12492.txt b/.changelog/12492.txt new file mode 100644 index 000000000000..9cf526e85bf9 --- /dev/null +++ b/.changelog/12492.txt @@ -0,0 +1,3 @@ +```release-note:improvement +api: default to using `DefaultPooledTransport` client to support keep-alive by default +``` diff --git a/api/api.go b/api/api.go index 2dc00a3f69ca..e32707ebfdbf 100644 --- a/api/api.go +++ b/api/api.go @@ -264,7 +264,7 @@ func (t *TLSConfig) Copy() *TLSConfig { } func defaultHttpClient() *http.Client { - httpClient := cleanhttp.DefaultClient() + httpClient := cleanhttp.DefaultPooledClient() transport := httpClient.Transport.(*http.Transport) transport.TLSHandshakeTimeout = 10 * time.Second transport.TLSClientConfig = &tls.Config{ @@ -476,6 +476,18 @@ func NewClient(config *Config) (*Client, error) { return client, nil } +// Close closes the client's idle keep-alived connections. The default +// client configuration uses keep-alive to maintain connections and +// you should instantiate a single Client and reuse it for all +// requests from the same host. Connections will be closed +// automatically once the client is garbage collected. If you are +// creating multiple clients on the same host (for example, for +// testing), it may be useful to call Close() to avoid hitting +// connection limits. +func (c *Client) Close() { + c.httpClient.CloseIdleConnections() +} + // Address return the address of the Nomad agent func (c *Client) Address() string { return c.config.Address diff --git a/command/agent/http_test.go b/command/agent/http_test.go index e5cb115716fe..8346243173ad 100644 --- a/command/agent/http_test.go +++ b/command/agent/http_test.go @@ -1113,6 +1113,8 @@ func TestHTTPServer_Limits_OK(t *testing.T) { conf.Address = a.HTTPAddr() conf.TLSConfig.Insecure = true client, err := api.NewClient(conf) + defer client.Close() + require.NoError(t, err) // Assert a blocking query isn't timed out by the