Memoize docker client to avoid consuming a new ssh connection each time

Signed-off-by: David Gageot <david.gageot@docker.com>
This commit is contained in:
David Gageot 2022-10-03 15:16:21 +02:00
parent ea863184ce
commit 780c28dba7
No known key found for this signature in database
GPG Key ID: 93C3F22BE5D3A40B

View File

@ -5,6 +5,7 @@ import (
"errors" "errors"
"io" "io"
"os" "os"
"sync"
"github.com/containerd/containerd/reference" "github.com/containerd/containerd/reference"
"github.com/docker/cli/cli/connhelper" "github.com/docker/cli/cli/connhelper"
@ -14,12 +15,23 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
var (
clientOnce sync.Once
memoizedClient *client.Client
errClient error
)
// Client get a docker client. // Client get a docker client.
func Client() (*client.Client, error) { func Client() (*client.Client, error) {
clientOnce.Do(func() {
memoizedClient, errClient = createClient()
})
return memoizedClient, errClient
}
func createClient() (*client.Client, error) {
options := []client.Opt{ options := []client.Opt{
// for maximum compatibility as we use nothing new client.WithAPIVersionNegotiation(),
// 1.30 corresponds to Docker 17.06, supported until 2020.
client.WithVersion("1.30"),
client.WithTLSClientConfigFromEnv(), client.WithTLSClientConfigFromEnv(),
client.WithHostFromEnv(), client.WithHostFromEnv(),
} }