-
Notifications
You must be signed in to change notification settings - Fork 9
/
client.go
222 lines (184 loc) · 7.59 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package docker
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
configtypes "github.com/docker/cli/cli/config/types"
"github.com/docker/cli/cli/connhelper"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/go-connections/tlsconfig"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"namespacelabs.dev/foundation/internal/fnerrors"
)
// Client implements the Docker client, but only with the bits that Namespace requires.
// It also performs Namespace-specific error handling
type Client interface {
ServerVersion(ctx context.Context) (types.Version, error)
Info(ctx context.Context) (types.Info, error)
ContainerCreate(context.Context, *container.Config, *container.HostConfig, *network.NetworkingConfig, *specs.Platform, string) (container.CreateResponse, error)
ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error)
ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error)
ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error
ContainerRemove(ctx context.Context, containerID string, options types.ContainerRemoveOptions) error
ContainerWait(ctx context.Context, containerID string, condition container.WaitCondition) (<-chan container.WaitResponse, <-chan error)
ImageInspectWithRaw(ctx context.Context, imageID string) (types.ImageInspect, []byte, error)
ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error)
ImageTag(ctx context.Context, source, target string) error
VolumeRemove(ctx context.Context, volumeID string, force bool) error
Close() error
}
func clientConfiguration() *Configuration {
config := &Configuration{}
fillConfigFromEnv(config)
return config
}
func NewClient() (Client, error) {
config := clientConfiguration()
var opts []client.Opt
helper, err := connhelper.GetConnectionHelper(config.Host)
if err != nil {
return nil, err
}
if helper == nil {
opts = append(opts, client.WithHost(config.Host))
} else {
httpClient := &http.Client{
// No tls
// No proxy
Transport: &http.Transport{
DialContext: helper.Dialer,
},
}
opts = append(opts,
client.WithHTTPClient(httpClient),
client.WithHost(helper.Host),
client.WithDialContext(helper.Dialer),
)
}
opts = append(opts, client.WithAPIVersionNegotiation())
if config.CertPath != "" {
options := tlsconfig.Options{
CAFile: filepath.Join(config.CertPath, "ca.pem"),
CertFile: filepath.Join(config.CertPath, "cert.pem"),
KeyFile: filepath.Join(config.CertPath, "key.pem"),
InsecureSkipVerify: !config.VerifyTls,
}
tlsc, err := tlsconfig.Client(options)
if err != nil {
return nil, err
}
httpClient := &http.Client{
Transport: &http.Transport{TLSClientConfig: tlsc},
CheckRedirect: client.CheckRedirect,
}
opts = append(opts, client.WithHTTPClient(httpClient))
}
if config.Version != "" {
opts = append(opts, client.WithVersion(config.Version))
}
cli, err := client.NewClientWithOpts(opts...)
return wrappedClient{cli}, err
}
func fillConfigFromEnv(config *Configuration) {
config.Version = os.Getenv("DOCKER_API_VERSION")
config.CertPath = os.Getenv("DOCKER_CERT_PATH")
config.VerifyTls = os.Getenv("DOCKER_TLS_VERIFY") != ""
config.Host = os.Getenv("DOCKER_HOST")
if config.Host == "" {
config.Host = client.DefaultDockerHost
}
}
// From "github.com/docker/cli/cli/command", but avoiding dep creep.
func EncodeAuthToBase64(authConfig configtypes.AuthConfig) (string, error) {
buf, err := json.Marshal(authConfig)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(buf), nil
}
type wrappedClient struct {
cli *client.Client
}
func (w wrappedClient) ServerVersion(ctx context.Context) (types.Version, error) {
v, err := w.cli.ServerVersion(ctx)
return v, maybeReplaceErr(err)
}
func (w wrappedClient) Info(ctx context.Context) (types.Info, error) {
v, err := w.cli.Info(ctx)
return v, maybeReplaceErr(err)
}
func (w wrappedClient) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *specs.Platform, containerName string) (container.CreateResponse, error) {
v, err := w.cli.ContainerCreate(ctx, config, hostConfig, networkingConfig, platform, containerName)
return v, maybeReplaceErr(err)
}
func (w wrappedClient) ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) {
v, err := w.cli.ContainerAttach(ctx, container, options)
return v, maybeReplaceErr(err)
}
func (w wrappedClient) ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error) {
v, err := w.cli.ContainerInspect(ctx, containerID)
return v, maybeReplaceErr(err)
}
func (w wrappedClient) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error {
return maybeReplaceErr(w.cli.ContainerStart(ctx, containerID, options))
}
func (w wrappedClient) ContainerRemove(ctx context.Context, containerID string, options types.ContainerRemoveOptions) error {
return maybeReplaceErr(w.cli.ContainerRemove(ctx, containerID, options))
}
func (w wrappedClient) ContainerWait(ctx context.Context, containerID string, condition container.WaitCondition) (<-chan container.WaitResponse, <-chan error) {
// XXX we assume wrapping errors is not necessary here as ContainerWait is not used in isolation.
return w.cli.ContainerWait(ctx, containerID, condition)
}
func (w wrappedClient) ImageInspectWithRaw(ctx context.Context, imageID string) (types.ImageInspect, []byte, error) {
i, b, err := w.cli.ImageInspectWithRaw(ctx, imageID)
return i, b, maybeReplaceErr(err)
}
func (w wrappedClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) {
v, err := w.cli.ImageLoad(ctx, input, quiet)
return v, maybeReplaceErr(err)
}
func (w wrappedClient) ImageTag(ctx context.Context, source, target string) error {
return maybeReplaceErr(w.cli.ImageTag(ctx, source, target))
}
func (w wrappedClient) VolumeRemove(ctx context.Context, volumeID string, force bool) error {
return maybeReplaceErr(w.cli.VolumeRemove(ctx, volumeID, force))
}
func (w wrappedClient) Close() error {
return maybeReplaceErr(w.cli.Close())
}
func maybeReplaceErr(err error) error {
switch {
case errors.Is(err, os.ErrPermission):
var lines = []string{
"Failed to connect to Docker, due to lack of permissions. This is likely",
"due to your user not being in the right group to be able to use Docker.",
}
var usage []string
if runtime.GOOS == "linux" {
usage = append(usage,
"Checkout the following URL for instructions on how to handle this error:",
"",
"https://docs.docker.com/engine/install/linux-postinstall/")
} else {
usage = append(usage, "Please refer to Docker's documentation on how to solve this issue.")
}
return fnerrors.UsageError(strings.Join(usage, "\n"), strings.Join(lines, "\n"))
case client.IsErrConnectionFailed(err):
return fnerrors.UsageError("If you don't have Docker installed, please visit https://namespace.so/docs/getting-started", "unable to connect to Docker: %w", err)
default:
return err
}
}