/
docker_client.go
578 lines (509 loc) · 19.3 KB
/
docker_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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
package cloud
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"path"
"path/filepath"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
docker "github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/model/distro"
"github.com/evergreen-ci/evergreen/model/host"
"github.com/evergreen-ci/utility"
"github.com/mongodb/grip"
"github.com/mongodb/grip/message"
"github.com/pkg/errors"
)
// The DockerClient interface wraps the Docker dockerClient interaction.
type DockerClient interface {
Init(string) error
EnsureImageDownloaded(context.Context, *host.Host, host.DockerOptions) (string, error)
BuildImageWithAgent(context.Context, *host.Host, string) (string, error)
CreateContainer(context.Context, *host.Host, *host.Host) error
GetContainer(context.Context, *host.Host, string) (*types.ContainerJSON, error)
GetDockerLogs(context.Context, string, *host.Host, types.ContainerLogsOptions) (io.Reader, error)
GetDockerStatus(context.Context, string, *host.Host) (*ContainerStatus, error)
ListContainers(context.Context, *host.Host) ([]types.Container, error)
RemoveImage(context.Context, *host.Host, string) error
RemoveContainer(context.Context, *host.Host, string) error
StartContainer(context.Context, *host.Host, string) error
AttachToContainer(context.Context, *host.Host, string, host.DockerOptions) (*types.HijackedResponse, error)
ListImages(context.Context, *host.Host) ([]types.ImageSummary, error)
}
type dockerClientImpl struct {
// apiVersion specifies the version of the Docker API.
apiVersion string
// httpDockerClient for making HTTP requests within the Docker dockerClient wrapper.
httpClient *http.Client
client *docker.Client
evergreenSettings *evergreen.Settings
}
type ContainerStatus struct {
IsRunning bool
HasStarted bool
}
// template string for new images with agent
const (
provisionedImageTag = "%s:provisioned"
imageImportTimeout = 10 * time.Minute
)
func GetDockerClient(s *evergreen.Settings) DockerClient {
var client DockerClient = &dockerClientImpl{evergreenSettings: s}
return client
}
// generateClient generates a Docker client that can talk to the specified host
// machine. The Docker client must be exposed and available for requests at the
// client port 3369 on the host machine.
func (c *dockerClientImpl) generateClient(h *host.Host) (*docker.Client, error) {
if h == nil {
return nil, errors.New("host cannot be nil")
}
if h.Host == "" {
return nil, errors.New("HostIP must not be blank")
}
// cache the *docker.Client in dockerClientImpl
if c.client != nil {
return c.client, nil
}
// Create a Docker client to wrap Docker API calls. The Docker TCP endpoint must
// be exposed and available for requests at the client port on the host machine.
var err error
endpoint := fmt.Sprintf("tcp://%s:%v", h.Host, h.ContainerPoolSettings.Port)
c.client, err = docker.NewClient(endpoint, c.apiVersion, c.httpClient, nil)
if err != nil {
grip.Error(message.Fields{
"message": "Docker initialize client API call failed",
"host_id": h.Id,
"error": err,
"endpoint": endpoint,
"api_version": c.apiVersion,
})
return nil, errors.Wrapf(err, "Docker initialize client API call failed at endpoint '%s'", endpoint)
}
return c.client, nil
}
// changeTimeout changes the timeout of dockerClient's internal httpClient and
// returns a new docker.Client with the updated timeout
func (c *dockerClientImpl) changeTimeout(h *host.Host, newTimeout time.Duration) (*docker.Client, error) {
var err error
c.httpClient.Timeout = newTimeout
c.client = nil // don't want to use cached client
c.client, err = c.generateClient(h)
if err != nil {
return nil, errors.Wrap(err, "Failed to generate docker client")
}
return c.client, nil
}
// Init sets the Docker API version to use for API calls to the Docker client.
func (c *dockerClientImpl) Init(apiVersion string) error {
if apiVersion == "" {
return errors.Errorf("Docker API version '%s' is invalid", apiVersion)
}
c.apiVersion = apiVersion
// Create HTTP client
c.httpClient = utility.GetHTTPClient()
// allow connections to Docker daemon with self-signed certificates
transport, ok := c.httpClient.Transport.(*http.Transport)
if !ok {
return errors.Errorf("Type assertion failed: type %T does not hold a *http.Transport", c.httpClient.Transport)
}
transport.TLSClientConfig.InsecureSkipVerify = true
return nil
}
// EnsureImageDownloaded checks if the image in s3 specified by the URL already exists,
// and if not, creates a new image from the remote tarball.
func (c *dockerClientImpl) EnsureImageDownloaded(ctx context.Context, h *host.Host, options host.DockerOptions) (string, error) {
start := time.Now()
dockerClient, err := c.generateClient(h)
if err != nil {
return "", errors.Wrap(err, "Failed to generate docker client")
}
// Extract image name from url
baseName := path.Base(options.Image)
imageName := strings.TrimSuffix(baseName, filepath.Ext(baseName))
// Check if image already exists on host
_, _, err = dockerClient.ImageInspectWithRaw(ctx, imageName)
grip.Info(message.Fields{
"operation": "EnsureImageDownloaded",
"details": "ImageInspectWithRaw",
"host_id": h.Id,
"duration_secs": time.Since(start).Seconds(),
})
if err == nil {
// Image already exists
return imageName, nil
} else if strings.Contains(err.Error(), "No such image") {
if options.Method == distro.DockerImageBuildTypeImport {
err = c.importImage(ctx, h, imageName, options.Image)
grip.Info(message.Fields{
"operation": "EnsureImageDownloaded",
"details": "import image",
"options_image": options.Image,
"host_id": h.Id,
"duration_secs": time.Since(start).Seconds(),
})
return imageName, errors.Wrap(err, "error importing image")
} else if options.Method == distro.DockerImageBuildTypePull {
image := options.Image
if options.RegistryName != "" {
image = fmt.Sprintf("%s/%s", options.RegistryName, imageName)
}
err = c.pullImage(ctx, h, image, options.RegistryUsername, options.RegistryPassword)
grip.Info(message.Fields{
"operation": "EnsureImageDownloaded",
"details": "pull image",
"options_image": options.Image,
"host_id": h.Id,
"duration_secs": time.Since(start).Seconds(),
})
return imageName, errors.Wrap(err, "error pulling image")
}
return imageName, errors.Errorf("unrecognized image build method: %s", options.Method)
}
return "", errors.Wrapf(err, "Error inspecting image %s", imageName)
}
func (c *dockerClientImpl) importImage(ctx context.Context, h *host.Host, name, url string) error {
// Extend http client timeout for ImageImport
normalTimeout := c.httpClient.Timeout
dockerClient, err := c.changeTimeout(h, imageImportTimeout)
if err != nil {
return errors.Wrap(err, "Error changing http client timeout")
}
// Image does not exist, import from remote tarball
source := types.ImageImportSource{SourceName: url}
var resp io.ReadCloser
resp, err = dockerClient.ImageImport(ctx, source, name, types.ImageImportOptions{})
if err != nil {
return errors.Wrapf(err, "Error importing image from %s", url)
}
// Wait until ImageImport finishes
_, err = io.ReadAll(resp)
if err != nil {
return errors.Wrap(err, "Error reading ImageImport response")
}
// Reset http client timeout
_, err = c.changeTimeout(h, normalTimeout)
return errors.Wrap(err, "Error changing http client timeout")
}
func (c *dockerClientImpl) pullImage(ctx context.Context, h *host.Host, url, username, password string) error {
normalTimeout := c.httpClient.Timeout
dockerClient, err := c.changeTimeout(h, imageImportTimeout)
if err != nil {
return errors.Wrap(err, "Error changing http client timeout")
}
var auth string
if username != "" {
authConfig := types.AuthConfig{
Username: username,
Password: password,
}
var jsonBytes []byte
jsonBytes, err = json.Marshal(authConfig)
if err != nil {
return errors.Wrap(err, "error marshaling auth config")
}
auth = base64.URLEncoding.EncodeToString(jsonBytes)
}
resp, err := dockerClient.ImagePull(ctx, url, types.ImagePullOptions{RegistryAuth: auth})
if err != nil {
return errors.Wrap(err, "error pulling image from registry")
}
_, err = io.ReadAll(resp)
if err != nil {
return errors.Wrap(err, "error reading image pull response")
}
_, err = c.changeTimeout(h, normalTimeout)
return errors.Wrap(err, "Error changing http client timeout")
}
// BuildImageWithAgent takes a base image and builds a new image on the specified
// host from a Dockfile in the root directory, which adds the Evergreen binary
func (c *dockerClientImpl) BuildImageWithAgent(ctx context.Context, h *host.Host, baseImage string) (string, error) {
const dockerfileRoute = "dockerfile"
start := time.Now()
dockerClient, err := c.generateClient(h)
if err != nil {
return "", errors.Wrap(err, "Failed to generate docker client")
}
grip.Info(message.Fields{
"operation": "BuildImageWithAgent",
"details": "generateclient",
"duration": time.Since(start),
"host_id": h.Id,
"span": time.Since(start).String(),
})
// modify tag for new image
provisionedImage := fmt.Sprintf(provisionedImageTag, baseImage)
executableSubPath := h.Distro.ExecutableSubPath()
binaryName := h.Distro.BinaryName()
// build dockerfile route
dockerfileUrl := strings.Join([]string{
c.evergreenSettings.ApiUrl,
evergreen.APIRoutePrefix,
dockerfileRoute,
}, "/")
options := types.ImageBuildOptions{
BuildArgs: map[string]*string{
"BASE_IMAGE": &baseImage,
"EXECUTABLE_SUB_PATH": &executableSubPath,
"BINARY_NAME": &binaryName,
"URL": &c.evergreenSettings.Ui.Url,
},
Remove: true,
RemoteContext: dockerfileUrl,
Tags: []string{provisionedImage},
}
msg := makeDockerLogMessage("ImageBuild", h.Id, message.Fields{
"base_image": options.BuildArgs["BASE_IMAGE"],
"dockerfile_url": options.RemoteContext,
})
// build the image
resp, err := dockerClient.ImageBuild(ctx, nil, options)
if err != nil {
return "", errors.Wrapf(err, "Error building Docker image from base image %s", baseImage)
}
grip.Info(message.Fields{
"operation": "BuildImageWithAgent",
"details": "ImageBuild",
"duration": time.Since(start),
"host_id": h.Id,
"span": time.Since(start).String(),
})
grip.Info(msg)
// wait for ImageBuild to complete -- success response otherwise returned
// before building from Dockerfile is over, and next ContainerCreate will fail
_, err = io.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "Error reading ImageBuild response")
}
grip.Info(message.Fields{
"operation": "BuildImageWithAgent",
"details": "ReadAll",
"duration": time.Since(start),
"host_id": h.Id,
"span": time.Since(start).String(),
})
return provisionedImage, nil
}
// CreateContainer creates a new Docker container with Evergreen agent.
func (c *dockerClientImpl) CreateContainer(ctx context.Context, parentHost, containerHost *host.Host) error {
dockerClient, err := c.generateClient(parentHost)
if err != nil {
return errors.Wrap(err, "Failed to generate docker client")
}
provisionedImage := containerHost.DockerOptions.Image
// Extract image name from url
if containerHost.DockerOptions.Method == distro.DockerImageBuildTypeImport {
baseName := path.Base(containerHost.DockerOptions.Image)
provisionedImage = strings.TrimSuffix(baseName, filepath.Ext(baseName))
}
if !containerHost.DockerOptions.SkipImageBuild {
provisionedImage = fmt.Sprintf(provisionedImageTag, provisionedImage)
}
var agentCmdParts []string
if containerHost.DockerOptions.Command != "" {
agentCmdParts = append(agentCmdParts, containerHost.DockerOptions.Command)
} else if containerHost.DockerOptions.Command == "" && !containerHost.SpawnOptions.SpawnedByTask {
// Generate the host secret for container if none exists.
if containerHost.Secret == "" {
if err = containerHost.CreateSecret(ctx, false); err != nil {
return errors.Wrapf(err, "creating secret for %s", containerHost.Id)
}
}
// Build path to Evergreen executable.
pathToExecutable := filepath.Join("/", "evergreen")
if parentHost.Distro.IsWindows() {
pathToExecutable += ".exe"
}
// Build Evergreen agent command.
agentCmdParts = containerHost.AgentCommand(c.evergreenSettings, pathToExecutable)
containerHost.DockerOptions.Command = strings.Join(agentCmdParts, "\n")
}
// Populate container settings with command and new image.
containerConf := &container.Config{
Cmd: agentCmdParts,
Image: provisionedImage,
Env: containerHost.DockerOptions.EnvironmentVars,
}
networkConf := &network.NetworkingConfig{}
hostConf := &container.HostConfig{
PublishAllPorts: containerHost.DockerOptions.PublishPorts,
ExtraHosts: containerHost.DockerOptions.ExtraHosts,
}
if len(containerHost.DockerOptions.StdinData) != 0 {
containerConf.AttachStdin = true
containerConf.StdinOnce = true
containerConf.OpenStdin = true
}
grip.Info(makeDockerLogMessage("ContainerCreate", parentHost.Id, message.Fields{"image": containerConf.Image}))
// Build container
if _, err := dockerClient.ContainerCreate(ctx, containerConf, hostConf, networkConf, nil, containerHost.Id); err != nil {
grip.Error(message.WrapError(err, message.Fields{
"message": "Docker create API call failed",
"container": containerHost.Id,
"parent": parentHost.Id,
"image": provisionedImage,
}))
return errors.Wrapf(err, "Docker create API call failed for container '%s' on parent '%s'", containerHost.Id, parentHost.Id)
}
return nil
}
// GetDockerLogs returns output logs or error logs, based on the given options.
// This assumes the container is not using TTY.
func (c *dockerClientImpl) GetDockerLogs(ctx context.Context, containerID string, parent *host.Host, options types.ContainerLogsOptions) (io.Reader, error) {
dockerClient, err := c.generateClient(parent)
if err != nil {
return nil, errors.Wrap(err, "Failed to generate docker client")
}
stream, err := dockerClient.ContainerLogs(ctx, containerID, options)
if err != nil {
return nil, errors.Wrapf(err, "Docker logs API call failed for container %s", containerID)
}
tempout := &bytes.Buffer{}
temperr := &bytes.Buffer{}
_, err = stdcopy.StdCopy(tempout, temperr, stream)
if err != nil {
return nil, errors.Wrapf(err, "Error copying stream for container %s", containerID)
}
if options.ShowStdout {
return tempout, nil
}
return temperr, nil
}
func (c *dockerClientImpl) GetDockerStatus(ctx context.Context, containerID string, parent *host.Host) (*ContainerStatus, error) {
if utility.StringSliceContains(evergreen.NotRunningStatus, parent.Status) {
return &ContainerStatus{HasStarted: false}, nil
}
container, err := c.GetContainer(ctx, parent, containerID)
if err != nil {
if docker.IsErrNotFound(err) || docker.IsErrConnectionFailed(err) {
return &ContainerStatus{HasStarted: false}, nil
}
return nil, errors.Wrapf(err, "Error getting container %s", containerID)
}
if container == nil {
return nil, errors.Errorf("Container '%s' returned empty", containerID)
}
status := ContainerStatus{
HasStarted: true,
IsRunning: container.State.Running,
}
return &status, nil
}
// GetContainer returns low-level information on the Docker container with the
// specified ID running on the specified host machine.
func (c *dockerClientImpl) GetContainer(ctx context.Context, h *host.Host, containerID string) (*types.ContainerJSON, error) {
dockerClient, err := c.generateClient(h)
if err != nil {
return nil, errors.Wrap(err, "Failed to generate docker client")
}
container, err := dockerClient.ContainerInspect(ctx, containerID)
if err != nil {
return nil, errors.Wrapf(err, "Docker inspect API call failed for container '%s'", containerID)
}
return &container, nil
}
// ListContainers lists all containers running on the specified host machine.
func (c *dockerClientImpl) ListContainers(ctx context.Context, h *host.Host) ([]types.Container, error) {
dockerClient, err := c.generateClient(h)
if err != nil {
return nil, errors.Wrap(err, "Failed to generate docker client")
}
// Get all running containers
opts := types.ContainerListOptions{All: false}
containers, err := dockerClient.ContainerList(ctx, opts)
if err != nil {
return nil, errors.Wrap(err, "Docker list API call failed")
}
return containers, nil
}
// ListImages lists all images on the specified host machine.
func (c *dockerClientImpl) ListImages(ctx context.Context, h *host.Host) ([]types.ImageSummary, error) {
dockerClient, err := c.generateClient(h)
if err != nil {
return nil, errors.Wrap(err, "Failed to generate docker client")
}
// Get all container images
opts := types.ImageListOptions{All: false}
images, err := dockerClient.ImageList(ctx, opts)
if err != nil {
err = errors.Wrap(err, "Docker list API call failed")
return nil, err
}
return images, nil
}
// RemoveImage forcibly removes an image from its host machine
func (c *dockerClientImpl) RemoveImage(ctx context.Context, h *host.Host, imageID string) error {
dockerClient, err := c.generateClient(h)
if err != nil {
return errors.Wrap(err, "generating Docker client")
}
opts := types.ImageRemoveOptions{Force: true}
removed, err := dockerClient.ImageRemove(ctx, imageID, opts)
if err != nil {
return errors.Wrapf(err, "removing image '%s'", imageID)
}
// check to make sure an image was removed
if len(removed) <= 0 {
return errors.Errorf("image '%s' was not removed", imageID)
}
return nil
}
// RemoveContainer forcibly removes a running or stopped container by ID from its host machine.
func (c *dockerClientImpl) RemoveContainer(ctx context.Context, h *host.Host, containerID string) error {
dockerClient, err := c.generateClient(h)
if err != nil {
return errors.Wrap(err, "generating Docker client")
}
opts := types.ContainerRemoveOptions{Force: true}
if err = dockerClient.ContainerRemove(ctx, containerID, opts); err != nil {
return errors.Wrapf(err, "removing container '%s'", containerID)
}
return nil
}
// StartContainer starts a stopped or new container by ID on the host machine.
func (c *dockerClientImpl) StartContainer(ctx context.Context, h *host.Host, containerID string) error {
dockerClient, err := c.generateClient(h)
if err != nil {
return errors.Wrap(err, "generating Docker client")
}
opts := types.ContainerStartOptions{}
if err := dockerClient.ContainerStart(ctx, containerID, opts); err != nil {
return errors.Wrapf(err, "starting container '%s'", containerID)
}
return nil
}
func (c *dockerClientImpl) AttachToContainer(ctx context.Context, h *host.Host, containerID string, opts host.DockerOptions) (*types.HijackedResponse, error) {
if len(opts.StdinData) == 0 {
return nil, nil
}
dockerClient, err := c.generateClient(h)
if err != nil {
return nil, errors.Wrap(err, "generating Docker client")
}
stream, err := dockerClient.ContainerAttach(ctx, containerID, types.ContainerAttachOptions{
Stream: true,
Stdin: true,
})
if err != nil {
return nil, errors.Wrap(err, "attaching stdin to container")
}
return &stream, nil
}
func makeDockerLogMessage(name, parent string, data interface{}) message.Fields {
return message.Fields{
"message": "Docker API call",
"api_name": name,
"parent": parent,
"data": data,
}
}