-
-
Notifications
You must be signed in to change notification settings - Fork 512
/
docker.go
1445 lines (1226 loc) · 37.9 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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package testcontainers
import (
"archive/tar"
"bufio"
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/docker/docker/api/types/filters"
"github.com/cenkalti/backoff/v4"
"github.com/containerd/containerd/platforms"
"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/docker/errdefs"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/go-connections/nat"
"github.com/google/uuid"
"github.com/magiconair/properties"
"github.com/moby/term"
specs "github.com/opencontainers/image-spec/specs-go/v1"
tcexec "github.com/testcontainers/testcontainers-go/exec"
"github.com/testcontainers/testcontainers-go/internal"
"github.com/testcontainers/testcontainers-go/internal/testcontainersdocker"
"github.com/testcontainers/testcontainers-go/internal/testcontainerssession"
"github.com/testcontainers/testcontainers-go/wait"
)
var (
// Implement interfaces
_ Container = (*DockerContainer)(nil)
logOnce sync.Once
ErrDuplicateMountTarget = errors.New("duplicate mount target detected")
)
const (
Bridge = "bridge" // Bridge network name (as well as driver)
Podman = "podman"
ReaperDefault = "reaper_default" // Default network name when bridge is not available
packagePath = "github.com/testcontainers/testcontainers-go"
)
// DockerContainer represents a container started using Docker
type DockerContainer struct {
// Container ID from Docker
ID string
WaitingFor wait.Strategy
Image string
isRunning bool
imageWasBuilt bool
provider *DockerProvider
sessionID uuid.UUID
terminationSignal chan bool
skipReaper bool
consumers []LogConsumer
raw *types.ContainerJSON
stopProducer chan bool
logger Logging
}
// SetLogger sets the logger for the container
func (c *DockerContainer) SetLogger(logger Logging) {
c.logger = logger
}
// SetProvider sets the provider for the container
func (c *DockerContainer) SetProvider(provider *DockerProvider) {
c.provider = provider
}
func (c *DockerContainer) GetContainerID() string {
return c.ID
}
func (c *DockerContainer) IsRunning() bool {
return c.isRunning
}
// 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(ctx)
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) {
inspect, err := c.inspectContainer(ctx)
if err != nil {
return "", err
}
if inspect.ContainerJSONBase.HostConfig.NetworkMode == "host" {
return port, nil
}
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
}
if len(p) == 0 {
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 {
shortID := c.ID[:12]
c.logger.Printf("Starting container id: %s image: %s", shortID, c.Image)
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 {
c.logger.Printf("Waiting for container id %s image: %s", shortID, c.Image)
if err := c.WaitingFor.WaitUntilReady(ctx, c); err != nil {
return err
}
}
c.logger.Printf("Container is ready id: %s image: %s", shortID, c.Image)
c.isRunning = true
return nil
}
// Stop will stop an already started container
//
// In case the container fails to stop
// gracefully within a time frame specified by the timeout argument,
// it is forcefully terminated (killed).
//
// If the timeout is nil, the container's StopTimeout value is used, if set,
// otherwise the engine default. A negative timeout value can be specified,
// meaning no timeout, i.e. no forceful termination is performed.
func (c *DockerContainer) Stop(ctx context.Context, timeout *time.Duration) error {
shortID := c.ID[:12]
c.logger.Printf("Stopping container id: %s image: %s", shortID, c.Image)
var options container.StopOptions
if timeout != nil {
timeoutSeconds := int(timeout.Seconds())
options.Timeout = &timeoutSeconds
}
if err := c.provider.client.ContainerStop(ctx, c.ID, options); err != nil {
return err
}
c.logger.Printf("Container is stopped id: %s image: %s", shortID, c.Image)
c.isRunning = false
return nil
}
// Terminate is used to kill the container. It is usually triggered by as defer function.
func (c *DockerContainer) Terminate(ctx context.Context) error {
select {
// close reaper if it was created
case c.terminationSignal <- true:
default:
}
err := c.provider.client.ContainerRemove(ctx, c.GetContainerID(), types.ContainerRemoveOptions{
RemoveVolumes: true,
Force: true,
})
if err != nil {
return err
}
if c.imageWasBuilt {
_, err := c.provider.client.ImageRemove(ctx, c.Image, types.ImageRemoveOptions{
Force: true,
PruneChildren: true,
})
if err != nil {
return err
}
}
if err := c.provider.client.Close(); err != nil {
return err
}
c.sessionID = uuid.UUID{}
c.isRunning = false
return nil
}
// update container raw info
func (c *DockerContainer) inspectRawContainer(ctx context.Context) (*types.ContainerJSON, error) {
inspect, err := c.provider.client.ContainerInspect(ctx, c.ID)
if err != nil {
return nil, err
}
c.raw = &inspect
return c.raw, nil
}
func (c *DockerContainer) inspectContainer(ctx context.Context) (*types.ContainerJSON, error) {
inspect, err := c.provider.client.ContainerInspect(ctx, c.ID)
if err != nil {
return nil, err
}
return &inspect, 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) {
const streamHeaderSize = 8
options := types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
}
rc, err := c.provider.client.ContainerLogs(ctx, c.ID, options)
if err != nil {
return nil, err
}
pr, pw := io.Pipe()
r := bufio.NewReader(rc)
go func() {
var lineStarted = true
for err == nil {
line, isPrefix, err := r.ReadLine()
if lineStarted && len(line) >= streamHeaderSize {
line = line[streamHeaderSize:] // trim stream header
lineStarted = false
}
if !isPrefix {
lineStarted = true
}
_, errW := pw.Write(line)
if errW != nil {
return
}
if !isPrefix {
_, errW := pw.Write([]byte("\n"))
if errW != nil {
return
}
}
if err != nil {
_ = pw.CloseWithError(err)
return
}
}
}()
return pr, nil
}
// FollowOutput adds a LogConsumer to be sent logs from the container's
// STDOUT and STDERR
func (c *DockerContainer) FollowOutput(consumer LogConsumer) {
if c.consumers == nil {
c.consumers = []LogConsumer{
consumer,
}
} else {
c.consumers = append(c.consumers, consumer)
}
}
// 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
}
// State returns container's running state
func (c *DockerContainer) State(ctx context.Context) (*types.ContainerState, error) {
inspect, err := c.inspectRawContainer(ctx)
if err != nil {
if c.raw != nil {
return c.raw.State, err
}
return nil, err
}
return inspect.State, 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
}
// ContainerIP gets the IP address of the primary network within the container.
func (c *DockerContainer) ContainerIP(ctx context.Context) (string, error) {
inspect, err := c.inspectContainer(ctx)
if err != nil {
return "", err
}
ip := inspect.NetworkSettings.IPAddress
if ip == "" {
// use IP from "Networks" if only single network defined
networks := inspect.NetworkSettings.Networks
if len(networks) == 1 {
for _, v := range networks {
ip = v.IPAddress
}
}
}
return ip, nil
}
// ContainerIPs gets the IP addresses of all the networks within the container.
func (c *DockerContainer) ContainerIPs(ctx context.Context) ([]string, error) {
ips := make([]string, 0)
inspect, err := c.inspectContainer(ctx)
if err != nil {
return nil, err
}
networks := inspect.NetworkSettings.Networks
for _, nw := range networks {
ips = append(ips, nw.IPAddress)
}
return ips, 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
}
func (c *DockerContainer) Exec(ctx context.Context, cmd []string, options ...tcexec.ProcessOption) (int, io.Reader, error) {
cli := c.provider.client
response, err := cli.ContainerExecCreate(ctx, c.ID, types.ExecConfig{
Cmd: cmd,
Detach: false,
AttachStdout: true,
AttachStderr: true,
})
if err != nil {
return 0, nil, err
}
hijack, err := cli.ContainerExecAttach(ctx, response.ID, types.ExecStartCheck{})
if err != nil {
return 0, nil, err
}
opt := &tcexec.ProcessOptions{
Reader: hijack.Reader,
}
for _, o := range options {
o.Apply(opt)
}
var exitCode int
for {
execResp, err := cli.ContainerExecInspect(ctx, response.ID)
if err != nil {
return 0, nil, err
}
if !execResp.Running {
exitCode = execResp.ExitCode
break
}
time.Sleep(100 * time.Millisecond)
}
return exitCode, opt.Reader, nil
}
type FileFromContainer struct {
underlying *io.ReadCloser
tarreader *tar.Reader
}
func (fc *FileFromContainer) Read(b []byte) (int, error) {
return (*fc.tarreader).Read(b)
}
func (fc *FileFromContainer) Close() error {
return (*fc.underlying).Close()
}
func (c *DockerContainer) CopyFileFromContainer(ctx context.Context, filePath string) (io.ReadCloser, error) {
r, _, err := c.provider.client.CopyFromContainer(ctx, c.ID, filePath)
if err != nil {
return nil, err
}
tarReader := tar.NewReader(r)
// if we got here we have exactly one file in the TAR-stream
// so we advance the index by one so the next call to Read will start reading it
_, err = tarReader.Next()
if err != nil {
return nil, err
}
ret := &FileFromContainer{
underlying: &r,
tarreader: tarReader,
}
return ret, nil
}
// CopyDirToContainer copies the contents of a directory to a parent path in the container. This parent path must exist in the container first
// as we cannot create it
func (c *DockerContainer) CopyDirToContainer(ctx context.Context, hostDirPath string, containerParentPath string, fileMode int64) error {
dir, err := isDir(hostDirPath)
if err != nil {
return err
}
if !dir {
// it's not a dir: let the consumer to handle an error
return fmt.Errorf("path %s is not a directory", hostDirPath)
}
buff, err := tarDir(hostDirPath, fileMode)
if err != nil {
return err
}
// create the directory under its parent
parent := filepath.Dir(containerParentPath)
return c.provider.client.CopyToContainer(ctx, c.ID, parent, buff, types.CopyToContainerOptions{})
}
func (c *DockerContainer) CopyFileToContainer(ctx context.Context, hostFilePath string, containerFilePath string, fileMode int64) error {
dir, err := isDir(hostFilePath)
if err != nil {
return err
}
if dir {
return c.CopyDirToContainer(ctx, hostFilePath, containerFilePath, fileMode)
}
fileContent, err := os.ReadFile(hostFilePath)
if err != nil {
return err
}
return c.CopyToContainer(ctx, fileContent, containerFilePath, fileMode)
}
// CopyToContainer copies fileContent data to a file in container
func (c *DockerContainer) CopyToContainer(ctx context.Context, fileContent []byte, containerFilePath string, fileMode int64) error {
buffer, err := tarFile(fileContent, containerFilePath, fileMode)
if err != nil {
return err
}
return c.provider.client.CopyToContainer(ctx, c.ID, filepath.Dir(containerFilePath), buffer, types.CopyToContainerOptions{})
}
// StartLogProducer will start a concurrent process that will continuously read logs
// from the container and will send them to each added LogConsumer
func (c *DockerContainer) StartLogProducer(ctx context.Context) error {
go func() {
since := ""
// if the socket is closed we will make additional logs request with updated Since timestamp
BEGIN:
options := types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
Since: since,
}
ctx, cancel := context.WithTimeout(ctx, time.Second*5)
defer cancel()
r, err := c.provider.client.ContainerLogs(ctx, c.GetContainerID(), options)
if err != nil {
// if we can't get the logs, panic, we can't return an error to anything
// from within this goroutine
panic(err)
}
for {
select {
case <-c.stopProducer:
err := r.Close()
if err != nil {
// we can't close the read closer, this should never happen
panic(err)
}
return
default:
h := make([]byte, 8)
_, err := r.Read(h)
if err != nil {
// proper type matching requires https://go-review.googlesource.com/c/go/+/250357/ (go 1.16)
if strings.Contains(err.Error(), "use of closed network connection") {
now := time.Now()
since = fmt.Sprintf("%d.%09d", now.Unix(), int64(now.Nanosecond()))
goto BEGIN
}
// this explicitly ignores errors
// because we want to keep procesing even if one of our reads fails
continue
}
count := binary.BigEndian.Uint32(h[4:])
if count == 0 {
continue
}
logType := h[0]
if logType > 2 {
_, _ = fmt.Fprintf(os.Stderr, "received invalid log type: %d", logType)
// sometimes docker returns logType = 3 which is an undocumented log type, so treat it as stdout
logType = 1
}
// a map of the log type --> int representation in the header, notice the first is blank, this is stdin, but the go docker client doesn't allow following that in logs
logTypes := []string{"", StdoutLog, StderrLog}
b := make([]byte, count)
_, err = r.Read(b)
if err != nil {
// TODO: add-logger: use logger to log out this error
_, _ = fmt.Fprintf(os.Stderr, "error occurred reading log with known length %s", err.Error())
continue
}
for _, c := range c.consumers {
c.Accept(Log{
LogType: logTypes[logType],
Content: b,
})
}
}
}
}()
return nil
}
// StopLogProducer will stop the concurrent process that is reading logs
// and sending them to each added LogConsumer
func (c *DockerContainer) StopLogProducer() error {
c.stopProducer <- true
return 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(ctx context.Context) error {
select {
// close reaper if it was created
case n.terminationSignal <- true:
default:
}
return n.provider.client.NetworkRemove(ctx, n.ID)
}
// DockerProvider implements the ContainerProvider interface
type DockerProvider struct {
*DockerProviderOptions
client client.APIClient
host string
hostCache string
config TestContainersConfig
}
// Client gets the docker client used by the provider
func (p *DockerProvider) Client() client.APIClient {
return p.client
}
// SetClient sets the docker client to be used by the provider
func (p *DockerProvider) SetClient(c client.APIClient) {
p.client = c
}
var _ ContainerProvider = (*DockerProvider)(nil)
// or through Decode
type TestContainersConfig struct {
Host string `properties:"docker.host,default="`
TLSVerify int `properties:"docker.tls.verify,default=0"`
CertPath string `properties:"docker.cert.path,default="`
RyukPrivileged bool `properties:"ryuk.container.privileged,default=false"`
}
type (
// DockerProviderOptions defines options applicable to DockerProvider
DockerProviderOptions struct {
defaultBridgeNetworkName string
*GenericProviderOptions
}
// DockerProviderOption defines a common interface to modify DockerProviderOptions
// These can be passed to NewDockerProvider in a variadic way to customize the returned DockerProvider instance
DockerProviderOption interface {
ApplyDockerTo(opts *DockerProviderOptions)
}
// DockerProviderOptionFunc is a shorthand to implement the DockerProviderOption interface
DockerProviderOptionFunc func(opts *DockerProviderOptions)
)
func (f DockerProviderOptionFunc) ApplyDockerTo(opts *DockerProviderOptions) {
f(opts)
}
func Generic2DockerOptions(opts ...GenericProviderOption) []DockerProviderOption {
converted := make([]DockerProviderOption, 0, len(opts))
for _, o := range opts {
switch c := o.(type) {
case DockerProviderOption:
converted = append(converted, c)
default:
converted = append(converted, DockerProviderOptionFunc(func(opts *DockerProviderOptions) {
o.ApplyGenericTo(opts.GenericProviderOptions)
}))
}
}
return converted
}
func WithDefaultBridgeNetwork(bridgeNetworkName string) DockerProviderOption {
return DockerProviderOptionFunc(func(opts *DockerProviderOptions) {
opts.defaultBridgeNetworkName = bridgeNetworkName
})
}
func NewDockerClient() (cli *client.Client, host string, tcConfig TestContainersConfig, err error) {
tcConfig = configureTC()
host = tcConfig.Host
opts := []client.Opt{client.FromEnv}
if host != "" {
opts = append(opts, client.WithHost(host))
// for further informacion, read https://docs.docker.com/engine/security/protect-access/
if tcConfig.TLSVerify == 1 {
cacertPath := filepath.Join(tcConfig.CertPath, "ca.pem")
certPath := filepath.Join(tcConfig.CertPath, "cert.pem")
keyPath := filepath.Join(tcConfig.CertPath, "key.pem")
opts = append(opts, client.WithTLSClientConfig(cacertPath, certPath, keyPath))
}
} else if dockerHostEnv := os.Getenv("DOCKER_HOST"); dockerHostEnv != "" {
host = dockerHostEnv
} else {
host = "unix:///var/run/docker.sock"
}
opts = append(opts, client.WithHTTPHeaders(
map[string]string{
"x-tc-sid": testcontainerssession.String(),
}),
)
cli, err = client.NewClientWithOpts(opts...)
if err != nil {
return nil, "", TestContainersConfig{}, err
}
cli.NegotiateAPIVersion(context.Background())
return cli, host, tcConfig, nil
}
// NewDockerProvider creates a Docker provider with the EnvClient
func NewDockerProvider(provOpts ...DockerProviderOption) (*DockerProvider, error) {
o := &DockerProviderOptions{
GenericProviderOptions: &GenericProviderOptions{
Logger: Logger,
},
}
for idx := range provOpts {
provOpts[idx].ApplyDockerTo(o)
}
c, host, tcConfig, err := NewDockerClient()
if err != nil {
return nil, err
}
_, err = c.Ping(context.TODO())
if err != nil {
// fallback to environment
c, err = client.NewClientWithOpts(client.FromEnv)
if err != nil {
return nil, err
}
}
c.NegotiateAPIVersion(context.Background())
p := &DockerProvider{
DockerProviderOptions: o,
host: host,
client: c,
config: tcConfig,
}
// log docker server info only once
logOnce.Do(func() {
LogDockerServerInfo(context.Background(), p.client, p.Logger)
})
return p, nil
}
// configureTC reads from testcontainers properties file, if it exists
// it is possible that certain values get overridden when set as environment variables
func configureTC() TestContainersConfig {
config := TestContainersConfig{}
applyEnvironmentConfiguration := func(config TestContainersConfig) TestContainersConfig {
ryukPrivilegedEnv := os.Getenv("TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED")
if ryukPrivilegedEnv != "" {
config.RyukPrivileged = ryukPrivilegedEnv == "true"
}
return config
}
home, err := os.UserHomeDir()
if err != nil {
return applyEnvironmentConfiguration(config)
}
tcProp := filepath.Join(home, ".testcontainers.properties")
// init from a file
properties, err := properties.LoadFile(tcProp, properties.UTF8)
if err != nil {
return applyEnvironmentConfiguration(config)
}
if err := properties.Decode(&config); err != nil {
fmt.Printf("invalid testcontainers properties file, returning an empty Testcontainers configuration: %v\n", err)
return applyEnvironmentConfiguration(config)
}
return applyEnvironmentConfiguration(config)
}
// 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.New()
tag := uuid.New()
repoTag := fmt.Sprintf("%s:%s", repo, tag)
buildContext, err := img.GetContext()
if err != nil {
return "", err
}
buildOptions := types.ImageBuildOptions{
BuildArgs: img.GetBuildArgs(),
Dockerfile: img.GetDockerfile(),
AuthConfigs: img.GetAuthConfigs(),
Context: buildContext,
Tags: []string{repoTag},
Remove: true,
ForceRemove: true,
}
var resp types.ImageBuildResponse
err = backoff.Retry(func() error {
resp, err = p.client.ImageBuild(ctx, buildContext, buildOptions)
if err != nil {
if _, ok := err.(errdefs.ErrNotFound); ok {
return backoff.Permanent(err)
}
Logger.Printf("Failed to build image: %s, will retry", err)
return err
}
return nil
}, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
if err != nil {
return "", err
}
if img.ShouldPrintBuildLog() {
termFd, isTerm := term.GetFdInfo(os.Stderr)
err = jsonmessage.DisplayJSONMessagesStream(resp.Body, os.Stderr, termFd, isTerm, nil)
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) {
var err error
// Make sure that bridge network exists
// In case it is disabled we will create reaper_default network
if p.DefaultNetwork == "" {
p.DefaultNetwork, err = p.getDefaultNetwork(ctx, p.client)
if err != nil {
return nil, err
}
}
// If default network is not bridge make sure it is attached to the request
// as container won't be attached to it automatically
// in case of Podman the bridge network is called 'podman' as 'bridge' would conflict
if p.DefaultNetwork != p.defaultBridgeNetworkName {
isAttached := false
for _, net := range req.Networks {
if net == p.DefaultNetwork {
isAttached = true
break
}
}
if !isAttached {
req.Networks = append(req.Networks, p.DefaultNetwork)
}
}
env := []string{}
for envKey, envVar := range req.Env {
env = append(env, envKey+"="+envVar)
}
if req.Labels == nil {
req.Labels = make(map[string]string)
}
reaperOpts := containerOptions{
ImageName: req.ReaperImage,
}
for _, opt := range req.ReaperOptions {
opt(&reaperOpts)
}
var termSignal chan bool
// the reaper does not need to start a reaper for itself
isReaperContainer := strings.EqualFold(req.Image, reaperImage(reaperOpts.ImageName))
if !req.SkipReaper && !isReaperContainer {
r, err := reuseOrCreateReaper(context.WithValue(ctx, testcontainersdocker.DockerHostContextKey, p.host), testcontainerssession.String(), p, req.ReaperOptions...)
if err != nil {
return nil, fmt.Errorf("%w: creating reaper failed", err)
}
termSignal, err = r.Connect()
if err != nil {
return nil, fmt.Errorf("%w: connecting to reaper failed", err)
}
for k, v := range r.Labels() {
if _, ok := req.Labels[k]; !ok {
req.Labels[k] = v
}
}