forked from testcontainers/testcontainers-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker.go
577 lines (489 loc) · 14.3 KB
/
docker.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
package testcontainers
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"os/exec"
"strings"
"github.com/cenkalti/backoff"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/archive"
"github.com/docker/go-connections/nat"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"github.com/testcontainers/testcontainers-go/wait"
)
// Implement interfaces
var _ Container = (*DockerContainer)(nil)
// DockerContainer represents a container started using Docker
type DockerContainer struct {
// Container ID from Docker
ID string
WaitingFor wait.Strategy
// Cache to retrieve container infromation without re-fetching them from dockerd
raw *types.ContainerJSON
provider *DockerProvider
sessionID uuid.UUID
terminationSignal chan bool
skipReaper bool
}
func (c *DockerContainer) GetContainerID() string {
return c.ID
}
// Endpoint gets proto://host:port string for the first exposed port
// Will returns just host:port if proto is ""
func (c *DockerContainer) Endpoint(ctx context.Context, proto string) (string, error) {
ports, err := c.Ports(ctx)
if err != nil {
return "", err
}
// get first port
var firstPort nat.Port
for p := range ports {
firstPort = p
break
}
return c.PortEndpoint(ctx, firstPort, proto)
}
// PortEndpoint gets proto://host:port string for the given exposed port
// Will returns just host:port if proto is ""
func (c *DockerContainer) PortEndpoint(ctx context.Context, port nat.Port, proto string) (string, error) {
host, err := c.Host(ctx)
if err != nil {
return "", err
}
outerPort, err := c.MappedPort(ctx, port)
if err != nil {
return "", err
}
protoFull := ""
if proto != "" {
protoFull = fmt.Sprintf("%s://", proto)
}
return fmt.Sprintf("%s%s:%s", protoFull, host, outerPort.Port()), nil
}
// Host gets host (ip or name) of the docker daemon where the container port is exposed
// Warning: this is based on your Docker host setting. Will fail if using an SSH tunnel
// You can use the "TC_HOST" env variable to set this yourself
func (c *DockerContainer) Host(ctx context.Context) (string, error) {
host, err := c.provider.daemonHost()
if err != nil {
return "", err
}
return host, nil
}
// MappedPort gets externally mapped port for a container port
func (c *DockerContainer) MappedPort(ctx context.Context, port nat.Port) (nat.Port, error) {
ports, err := c.Ports(ctx)
if err != nil {
return "", err
}
for k, p := range ports {
if k.Port() != port.Port() {
continue
}
if port.Proto() != "" && k.Proto() != port.Proto() {
continue
}
return nat.NewPort(k.Proto(), p[0].HostPort)
}
return "", errors.New("port not found")
}
// Ports gets the exposed ports for the container.
func (c *DockerContainer) Ports(ctx context.Context) (nat.PortMap, error) {
inspect, err := c.inspectContainer(ctx)
if err != nil {
return nil, err
}
return inspect.NetworkSettings.Ports, nil
}
// SessionID gets the current session id
func (c *DockerContainer) SessionID() string {
return c.sessionID.String()
}
// Start will start an already created container
func (c *DockerContainer) Start(ctx context.Context) error {
if err := c.provider.client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{}); err != nil {
return err
}
// if a Wait Strategy has been specified, wait before returning
if c.WaitingFor != nil {
if err := c.WaitingFor.WaitUntilReady(ctx, c); err != nil {
return err
}
}
return nil
}
// Terminate is used to kill the container. It is usally triggered by as defer function.
func (c *DockerContainer) Terminate(ctx context.Context) error {
err := c.provider.client.ContainerRemove(ctx, c.GetContainerID(), types.ContainerRemoveOptions{
RemoveVolumes: true,
Force: true,
})
if err == nil {
c.sessionID = uuid.UUID{}
c.raw = nil
}
return err
}
func (c *DockerContainer) inspectContainer(ctx context.Context) (*types.ContainerJSON, error) {
if c.raw != nil {
return c.raw, nil
}
inspect, err := c.provider.client.ContainerInspect(ctx, c.ID)
if err != nil {
return nil, err
}
c.raw = &inspect
return c.raw, nil
}
// Logs will fetch both STDOUT and STDERR from the current container. Returns a
// ReadCloser and leaves it up to the caller to extract what it wants.
func (c *DockerContainer) Logs(ctx context.Context) (io.ReadCloser, error) {
options := types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
}
return c.provider.client.ContainerLogs(ctx, c.ID, options)
}
// Name gets the name of the container.
func (c *DockerContainer) Name(ctx context.Context) (string, error) {
inspect, err := c.inspectContainer(ctx)
if err != nil {
return "", err
}
return inspect.Name, nil
}
// Networks gets the names of the networks the container is attached to.
func (c *DockerContainer) Networks(ctx context.Context) ([]string, error) {
inspect, err := c.inspectContainer(ctx)
if err != nil {
return []string{}, err
}
networks := inspect.NetworkSettings.Networks
n := []string{}
for k := range networks {
n = append(n, k)
}
return n, nil
}
// NetworkAliases gets the aliases of the container for the networks it is attached to.
func (c *DockerContainer) NetworkAliases(ctx context.Context) (map[string][]string, error) {
inspect, err := c.inspectContainer(ctx)
if err != nil {
return map[string][]string{}, err
}
networks := inspect.NetworkSettings.Networks
a := map[string][]string{}
for k := range networks {
a[k] = networks[k].Aliases
}
return a, nil
}
// DockerNetwork represents a network started using Docker
type DockerNetwork struct {
ID string // Network ID from Docker
Driver string
Name string
provider *DockerProvider
terminationSignal chan bool
}
// Remove is used to remove the network. It is usually triggered by as defer function.
func (n *DockerNetwork) Remove(_ context.Context) error {
if n.terminationSignal != nil {
n.terminationSignal <- true
}
return nil
}
// DockerProvider implements the ContainerProvider interface
type DockerProvider struct {
client *client.Client
hostCache string
}
var _ ContainerProvider = (*DockerProvider)(nil)
// NewDockerProvider creates a Docker provider with the EnvClient
func NewDockerProvider() (*DockerProvider, error) {
client, err := client.NewEnvClient()
if err != nil {
return nil, err
}
client.NegotiateAPIVersion(context.Background())
p := &DockerProvider{
client: client,
}
return p, nil
}
// BuildImage will build and image from context and Dockerfile, then return the tag
func (p *DockerProvider) BuildImage(ctx context.Context, img ImageBuildInfo) (string, error) {
repo := uuid.NewV4()
tag := uuid.NewV4()
repoTag := fmt.Sprintf("%s:%s", repo, tag)
buildContext, err := archive.TarWithOptions(img.GetContext(), &archive.TarOptions{})
if err != nil {
return "", err
}
buildOptions := types.ImageBuildOptions{
Dockerfile: img.GetDockerfile(),
Context: buildContext,
Tags: []string{repoTag},
}
resp, err := p.client.ImageBuild(ctx, buildContext, buildOptions)
if err != nil {
return "", err
}
// need to read the response from Docker, I think otherwise the image
// might not finish building before continuing to execute here
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return "", err
}
resp.Body.Close()
return repoTag, nil
}
// CreateContainer fulfills a request for a container without starting it
func (p *DockerProvider) CreateContainer(ctx context.Context, req ContainerRequest) (Container, error) {
exposedPortSet, exposedPortMap, err := nat.ParsePortSpecs(req.ExposedPorts)
if err != nil {
return nil, err
}
env := []string{}
for envKey, envVar := range req.Env {
env = append(env, envKey+"="+envVar)
}
if req.Labels == nil {
req.Labels = make(map[string]string)
}
sessionID := uuid.NewV4()
var termSignal chan bool
if !req.SkipReaper {
r, err := NewReaper(ctx, sessionID.String(), p)
if err != nil {
return nil, errors.Wrap(err, "creating reaper failed")
}
termSignal, err = r.Connect()
if err != nil {
return nil, errors.Wrap(err, "connecting to reaper failed")
}
for k, v := range r.Labels() {
if _, ok := req.Labels[k]; !ok {
req.Labels[k] = v
}
}
}
if err = req.Validate(); err != nil {
return nil, err
}
var tag string
if req.FromDockerfile.Context != "" {
tag, err = p.BuildImage(ctx, &req)
if err != nil {
return nil, err
}
} else {
tag = req.Image
_, _, err = p.client.ImageInspectWithRaw(ctx, tag)
if err != nil {
if client.IsErrNotFound(err) {
pullOpt := types.ImagePullOptions{}
if req.RegistryCred != "" {
pullOpt.RegistryAuth = req.RegistryCred
}
var pull io.ReadCloser
err := backoff.Retry(func() error {
var err error
pull, err = p.client.ImagePull(ctx, tag, pullOpt)
return err
}, backoff.NewExponentialBackOff())
if err != nil {
return nil, err
}
defer pull.Close()
// download of docker image finishes at EOF of the pull request
_, err = ioutil.ReadAll(pull)
if err != nil {
return nil, err
}
} else {
return nil, err
}
}
}
dockerInput := &container.Config{
Image: tag,
Env: env,
ExposedPorts: exposedPortSet,
Labels: req.Labels,
Cmd: req.Cmd,
}
// prepare mounts
bindMounts := []mount.Mount{}
for hostPath, innerPath := range req.BindMounts {
bindMounts = append(bindMounts, mount.Mount{
Type: mount.TypeBind,
Source: hostPath,
Target: innerPath,
})
}
hostConfig := &container.HostConfig{
PortBindings: exposedPortMap,
Mounts: bindMounts,
AutoRemove: true,
Privileged: req.Privileged,
}
endpointConfigs := map[string]*network.EndpointSettings{}
for _, n := range req.Networks {
nw, err := p.GetNetwork(ctx, NetworkRequest{
Name: n,
})
if err == nil {
endpointSetting := network.EndpointSettings{
Aliases: req.NetworkAliases[n],
NetworkID: nw.ID,
}
endpointConfigs[n] = &endpointSetting
}
}
networkingConfig := network.NetworkingConfig{
EndpointsConfig: endpointConfigs,
}
resp, err := p.client.ContainerCreate(ctx, dockerInput, hostConfig, &networkingConfig, req.Name)
if err != nil {
return nil, err
}
c := &DockerContainer{
ID: resp.ID,
WaitingFor: req.WaitingFor,
sessionID: sessionID,
provider: p,
terminationSignal: termSignal,
skipReaper: req.SkipReaper,
}
return c, nil
}
// RunContainer takes a RequestContainer as input and it runs a container via the docker sdk
func (p *DockerProvider) RunContainer(ctx context.Context, req ContainerRequest) (Container, error) {
c, err := p.CreateContainer(ctx, req)
if err != nil {
return nil, err
}
if err := c.Start(ctx); err != nil {
return c, errors.Wrap(err, "could not start container")
}
return c, nil
}
// daemonHost gets the host or ip of the Docker daemon where ports are exposed on
// Warning: this is based on your Docker host setting. Will fail if using an SSH tunnel
// You can use the "TC_HOST" env variable to set this yourself
func (p *DockerProvider) daemonHost() (string, error) {
if p.hostCache != "" {
return p.hostCache, nil
}
host, exists := os.LookupEnv("TC_HOST")
if exists {
p.hostCache = host
return p.hostCache, nil
}
// infer from Docker host
url, err := url.Parse(p.client.DaemonHost())
if err != nil {
return "", err
}
switch url.Scheme {
case "http", "https", "tcp":
p.hostCache = url.Hostname()
case "unix", "npipe":
if inAContainer() {
ip, err := getGatewayIp()
if err != nil {
return "", err
}
p.hostCache = ip
} else {
p.hostCache = "localhost"
}
default:
return "", errors.New("Could not determine host through env or docker host")
}
return p.hostCache, nil
}
// CreateNetwork returns the object representing a new network identified by its name
func (p *DockerProvider) CreateNetwork(ctx context.Context, req NetworkRequest) (Network, error) {
if req.Labels == nil {
req.Labels = make(map[string]string)
}
nc := types.NetworkCreate{
Driver: req.Driver,
CheckDuplicate: req.CheckDuplicate,
Internal: req.Internal,
EnableIPv6: req.EnableIPv6,
Attachable: req.Attachable,
Labels: req.Labels,
}
sessionID := uuid.NewV4()
var termSignal chan bool
if !req.SkipReaper {
r, err := NewReaper(ctx, sessionID.String(), p)
if err != nil {
return nil, errors.Wrap(err, "creating network reaper failed")
}
termSignal, err = r.Connect()
if err != nil {
return nil, errors.Wrap(err, "connecting to network reaper failed")
}
for k, v := range r.Labels() {
if _, ok := req.Labels[k]; !ok {
req.Labels[k] = v
}
}
}
response, err := p.client.NetworkCreate(ctx, req.Name, nc)
if err != nil {
return &DockerNetwork{}, err
}
n := &DockerNetwork{
ID: response.ID,
Driver: req.Driver,
Name: req.Name,
terminationSignal: termSignal,
}
return n, nil
}
// GetNetwork returns the object representing the network identified by its name
func (p *DockerProvider) GetNetwork(ctx context.Context, req NetworkRequest) (types.NetworkResource, error) {
networkResource, err := p.client.NetworkInspect(ctx, req.Name, types.NetworkInspectOptions{
Verbose: true,
})
if err != nil {
return types.NetworkResource{}, err
}
return networkResource, err
}
func inAContainer() bool {
// see https://github.com/testcontainers/testcontainers-java/blob/3ad8d80e2484864e554744a4800a81f6b7982168/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java#L15
if _, err := os.Stat("/.dockerenv"); err == nil {
return true
}
return false
}
func getGatewayIp() (string, error) {
// see https://github.com/testcontainers/testcontainers-java/blob/3ad8d80e2484864e554744a4800a81f6b7982168/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java#L27
cmd := exec.Command("sh", "-c", "ip route|awk '/default/ { print $3 }'")
stdout, err := cmd.Output()
if err != nil {
return "", errors.New("Failed to detect docker host")
}
ip := strings.TrimSpace(string(stdout))
if len(ip) == 0 {
return "", errors.New("Failed to parse default gateway IP")
}
return string(ip), nil
}