-
Notifications
You must be signed in to change notification settings - Fork 42
/
docker_manager.go
2346 lines (2069 loc) · 89.7 KB
/
docker_manager.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
/*
* Copyright (c) 2021 - present Kurtosis Technologies Inc.
* All Rights Reserved.
*/
package docker_manager
import (
"bufio"
"bytes"
"context"
"crypto/md5"
"encoding/json"
"fmt"
"io"
"math"
"net"
"os"
"os/exec"
"regexp"
"strings"
"sync"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/registry"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/stdcopy"
"github.com/docker/go-connections/nat"
"github.com/docker/go-units"
kurtosis_sdk_version "github.com/kurtosis-tech/kurtosis/api/golang/kurtosis_version"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_impls/docker/docker_kurtosis_backend/consts"
docker_manager_types "github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_impls/docker/docker_manager/types"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_interface/objects/compute_resources"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_interface/objects/exec_result"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_interface/objects/image_build_spec"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_interface/objects/image_download_mode"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_interface/objects/image_registry_spec"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_interface/objects/nix_build_spec"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/concurrent_writer"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/image_utils"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/uuid_generator"
"github.com/kurtosis-tech/kurtosis/path_compression"
"github.com/kurtosis-tech/stacktrace"
"github.com/sirupsen/logrus"
bksession "github.com/moby/buildkit/session"
)
const (
dockerClientTimeout = 30 * time.Second
// We use a bridge network because, as of 2020-08-01, we're only running locally; however, this may need to change
// at some point in the future
dockerNetworkDriver = "bridge"
// Per https://docs.docker.com/engine/reference/commandline/kill/ , this seems to mean "the default
// kill signal"
dockerKillSignal = "KILL"
expectedHostIp = "0.0.0.0"
// When Docker binds a container port to the host machine, it binds it to host interface 0.0.0.0
// Linux machines will use 127.0.0.1 for 0.0.0.0, but Windows machines don't
// We therefore return 127.0.0.1 to the users rather than 0.0.0.0 so everybody can use them
hostPortBindingInterfaceForUserConsumption = "127.0.0.1"
// Character Docker uses to separate the repo from
dockerTagSeparatorChar = ":"
// If no tag is specified for an image, this is the tag Docker will use for the image
dockerDefaultTag = "latest"
// This is the magic domain name inside a container that Docker will give the host machine running Docker itself
// This is available by default on Docker for Mac & Windows because they run in VMs, but needs to be specifically
// bound in Docker for Linux
hostMachineDomainInsideContainer = "host.docker.internal"
// hostGatewayName is the string value that Docker will replace by
// the value of HostGatewayIP daemon config value
hostGatewayName = "host-gateway"
// ------------------ Filter Search Keys ----------------------
// All these defined in https://docs.docker.com/engine/api/v1.24
containerNameSearchFilterKey = "name"
containerLabelSearchFilterKey = "label"
containerNetworkIdSearchFilterKey = "network"
volumeNameSearchFilterKey = "name"
volumeLabelSearchFilterKey = "label"
networkNameSearchFilterKey = "name"
networkIdSearchFilterKey = "id"
networkLabelSearchFilterKey = "label"
// ---------------- End Filter Search Keys ----------------------
// For some reason, when publish-all-ports is requested, Docker will return successfully from starting a
// container, but without having bound the host ports
// See: https://github.com/moby/moby/issues/42860
// To work around this, we retry a few times
timeBetweenHostPortBindingChecks = 500 * time.Millisecond
maxNumHostPortBindingChecks = 4
// Not sure why we'd ever want 'force' set to false when removing volumes & containers
shouldForceVolumeRemoval = true
shouldRemoveAnonymousVolumesWhenRemovingContainers = true
shouldRemoveLinksWhenRemovingContainers = false // We don't use container links
shouldKillContainersWhenRemovingContainers = true
shouldFollowContainerLogsWhenGettingFailedContainerLogs = false
shouldAttachStdinWhenCreatingContainerExec = true
shouldAttachStandardStreamsToTtyWhenCreatingContainerExec = true
shouldAttachStderrWhenCreatingContainerExec = true
shouldAttachStdoutWhenCreatingContainerExec = true
shouldExecuteInDetachModeWhenCreatingContainerExec = false
megabytesToBytesFactor = 1_000_000
millicpusToNanoCPUsFactor = 1_000_000
minMemoryLimit = 6
zombieProcessesCannotRemoveContainerErrMsg = "is zombie and can not be killed"
defaultRemoveProcessesMaxRetries = uint8(3)
defaultRemoveContainerTimeBetweenRetries = 10 * time.Second
containerIsNotRunningErrMsg = "is not running"
cannotKillContainerErrMsg = "cannot kill container"
defaultKillContainerMaxRetries = uint8(3)
defaultKillContainerTimeBetweenRetries = 10 * time.Millisecond
successfulExitCode = 0
emptyNetworkAlias = ""
streamOutputDelimiter = '\n'
isDockerNetworkAttachable = true
linuxAmd64 = "linux/amd64"
defaultPlatform = ""
architectureErrorString = "no matching manifest for linux/arm64/v8"
onlyReturnContainerIds = true
coresToMilliCores = 1000
bytesInMegaBytes = 1000000
dontStreamStats = false
kurtosisTagPrefix = "kurtosistech/"
defaultContainerImageFile = "Dockerfile"
// Per https://github.com/hashicorp/waypoint/pull/1937/files
buildkitSessionSharedKey = ""
nixCmdPath = "/nix/var/nix/profiles/default/bin/nix"
)
type RestartPolicy string
const (
RestartAlways = "always"
RestartOnFailure = "on-failure"
NoRestart = ""
)
/*
InteractiveModeTtySize
The dimensions of the TTY that the container should output to when in interactive mode
*/
type InteractiveModeTtySize struct {
Height uint
Width uint
}
/*
DockerManager
A handle to interacting with the Docker environment running a test.
*/
type DockerManager struct {
// The underlying Docker client that will be used to modify the Docker environment
// This client has a timeout so that request that should return quickly do not end up hanging forever.
dockerClient *client.Client
// We need to use a specific docker client with no timeout for long-running requests on docker, such as tailing
// service logs for a long time, or even downloading large container images than can take longer than the timeout
dockerClientNoTimeout *client.Client
}
/*
CreateDockerManager
Creates a new Docker manager for manipulating the Docker engine using the given client.
Args:
dockerClient: The Docker client that will be used when interacting with the underlying Docker engine the Docker engine.
*/
func CreateDockerManager(dockerClientOpts []client.Opt) (*DockerManager, error) {
optsWithTimeout := []client.Opt{
client.WithTimeout(dockerClientTimeout),
}
optsWithTimeout = append(optsWithTimeout, dockerClientOpts...)
dockerClient, err := client.NewClientWithOpts(optsWithTimeout...)
if err != nil {
return nil, stacktrace.Propagate(err, "Error creating docker client")
}
dockerClientNoTimeout, err := client.NewClientWithOpts(dockerClientOpts...)
if err != nil {
return nil, stacktrace.Propagate(err, "Error creating docker client")
}
return &DockerManager{
dockerClient: dockerClient,
dockerClientNoTimeout: dockerClientNoTimeout,
}, nil
}
/*
CreateNetwork
Creates a new Docker network with the given parameters; does nothing if a network with the given name already exists.
Args:
context: The Context that this request is running in (useful for cancellation)
name: The name to give the new Docker network
subnetMask: The subnet mask defining allowed IPs for the Docker network
gatewayIP: The IP to give the network gateway
labels: Labels to give the network object
Returns:
id: The Docker-managed ID of the network
*/
func (manager *DockerManager) CreateNetwork(context context.Context, name string, subnetMask string, gatewayIP net.IP, labels map[string]string) (id string, err error) {
ipamConfig := []network.IPAMConfig{{
Subnet: subnetMask,
IPRange: "",
Gateway: gatewayIP.String(),
AuxAddress: nil,
}}
resp, err := manager.dockerClient.NetworkCreate(context, name, types.NetworkCreate{
CheckDuplicate: false,
Driver: dockerNetworkDriver,
Scope: "",
EnableIPv6: false,
IPAM: &network.IPAM{
Driver: "",
Options: nil,
Config: ipamConfig,
},
Internal: false,
Attachable: isDockerNetworkAttachable,
Ingress: false,
ConfigOnly: false,
ConfigFrom: nil,
Options: map[string]string{
"com.docker.network.driver.mtu": "1440",
},
Labels: labels,
})
if err != nil {
return "", stacktrace.Propagate(err, "Failed to create network %s with subnet %s", name, subnetMask)
}
return resp.ID, nil
}
func (manager *DockerManager) ListNetworks(ctx context.Context) ([]types.NetworkResource, error) {
networks, err := manager.dockerClient.NetworkList(ctx, types.NetworkListOptions{
Filters: filters.Args{},
})
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred listing the Docker networks")
}
// The Network objects that come back ostensibly, *should* have the Containers field filled out... but they don't
// If we ever need that field, we have to call an InspectNetwork, and even then it seems to have some amount of
// nondeterminism (i.e. brand-new containers won't show up)
return networks, nil
}
func (manager *DockerManager) PruneUnusedImages(ctx context.Context) ([]types.ImageSummary, error) {
unusedImages, err := manager.ListUnusedImages(ctx)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to list unused images")
}
logrus.Debugf("List of unused images to be pruned '%v'", unusedImages)
successfulPrunedImages := []types.ImageSummary{}
for _, image := range unusedImages {
imagePruneResponse, err := manager.dockerClient.ImageRemove(ctx, image.ID, types.ImageRemoveOptions{}) //nolint:exhaustruct
if err != nil {
return successfulPrunedImages, stacktrace.Propagate(err, "Failed to remove image '%v'", image.ID)
}
logrus.Debugf("Pruned image '%v' with response '%v'", image, imagePruneResponse)
successfulPrunedImages = append(successfulPrunedImages, image)
}
return successfulPrunedImages, nil
}
func containsSemVer(s string) bool {
// Matches patterns like X.Y.Z
semVerRegex := `\b(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)\b`
matched, _ := regexp.MatchString(semVerRegex, s)
return matched
}
func (manager *DockerManager) ListUnusedImages(ctx context.Context) ([]types.ImageSummary, error) {
images, err := manager.dockerClient.ImageList(ctx, types.ImageListOptions{}) //nolint:exhaustruct
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to list Docker images")
}
containers, err := manager.dockerClient.ContainerList(ctx, types.ContainerListOptions{All: true}) //nolint:exhaustruct
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to list Docker images")
}
usedImages := make(map[string]bool)
for _, cont := range containers {
usedImages[cont.ImageID] = true
}
unusedImages := []types.ImageSummary{}
for _, image := range images {
if _, used := usedImages[image.ID]; used {
logrus.Debugf("Skipping image '%v' since its in use", image.ID)
continue
}
for _, tag := range image.RepoTags {
if strings.Contains(tag, kurtosisTagPrefix) && containsSemVer(tag) && !strings.Contains(tag, kurtosis_sdk_version.KurtosisVersion) {
unusedImages = append(unusedImages, image)
}
}
}
return unusedImages, nil
}
/*
GetNetworksByName
Returns Network list matching the given name (if any).
*/
// TODO Combine with GetNetworksByLabel using a search filter builder
func (manager *DockerManager) GetNetworksByName(ctx context.Context, name string) ([]*docker_manager_types.Network, error) {
nameSearchArgs := filters.NewArgs(filters.KeyValuePair{
Key: networkNameSearchFilterKey,
Value: name,
})
dockerNetworks, err := manager.getNetworksByFilterArgs(ctx, nameSearchArgs)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred checking for existence of network with name %v", name)
}
networks, err := newNetworkListFromDockerNetworkList(dockerNetworks)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred creating a new network list from Docker network list '%+v'", dockerNetworks)
}
return networks, nil
}
/*
GetNetworksByLabels
Gets networks matching the given labels
*/
func (manager *DockerManager) GetNetworksByLabels(ctx context.Context, labels map[string]string) ([]*docker_manager_types.Network, error) {
labelsSearchArgs := getLabelsFilterArgs(networkLabelSearchFilterKey, labels)
dockerNetworks, err := manager.getNetworksByFilterArgs(ctx, labelsSearchArgs)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred checking for existence of network with labels '%+v'", labels)
}
networks, err := newNetworkListFromDockerNetworkList(dockerNetworks)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred creating a new network list from Docker network list '%+v'", dockerNetworks)
}
return networks, nil
}
func (manager *DockerManager) GetContainerIdsConnectedToNetwork(context context.Context, networkId string) ([]string, error) {
inspectResponse, err := manager.dockerClient.NetworkInspect(context, networkId, types.NetworkInspectOptions{
Scope: "",
Verbose: false,
})
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to get network information for network with ID '%v'", networkId)
}
result := []string{}
for containerId := range inspectResponse.Containers {
result = append(result, containerId)
}
return result, nil
}
/*
RemoveNetwork
Removes the Docker network with the given id
NOTE: All containers attached to the network must be shut off or disconnected, else the call will fail!
otherwise, the remove call will fail)
Args:
context: The Context that this request is running in (useful for cancellation)
networkId: ID of Docker network to remove
*/
func (manager *DockerManager) RemoveNetwork(context context.Context, networkId string) error {
if err := manager.dockerClient.NetworkRemove(context, networkId); err != nil {
return stacktrace.Propagate(err, "An error occurred removing the Docker network with ID %v", networkId)
}
return nil
}
/*
CreateVolume
Creates a Docker volume identified by the given name.
Args:
context: The Context that this request is running in (useful for cancellation)
volumeName: The unique identifier used by Docker to identify this volume (NOTE: at time of writing, Docker doesn't
even give volumes IDs - this name is all there is)
labels: Labels to attach to the volume object
*/
func (manager *DockerManager) CreateVolume(context context.Context, volumeName string, labels map[string]string) error {
volumeConfig := volume.CreateOptions{
ClusterVolumeSpec: nil,
Driver: "",
DriverOpts: nil,
Labels: labels,
Name: volumeName,
}
return manager.createPersistentVolumeInternal(context, volumeConfig)
}
/*
GetVolumesByName
Searches for volumes whose names match the given one
Args:
context: The Context that this request is running in (useful for cancellation)
volumeName: The unique identifier used by Docker to identify this volume (NOTE: at time of writing, Docker doesn't
even give volumes IDs - this name is all there is)
Returns: A list of names of volumes matching the search term
*/
func (manager *DockerManager) GetVolumesByName(ctx context.Context, volumeName string) ([]string, error) {
nameFilter := filters.KeyValuePair{
Key: volumeNameSearchFilterKey,
Value: volumeName,
}
filterArgs := filters.NewArgs(nameFilter)
listOptions := volume.ListOptions{Filters: filterArgs}
resp, err := manager.dockerClient.VolumeList(ctx, listOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred finding volumes with name matching '%v'", volumeName)
}
respNames := []string{}
for _, foundVolume := range resp.Volumes {
respNames = append(respNames, foundVolume.Name)
}
return respNames, nil
}
/*
GetVolumesByLabels
Gets the volumes matching the given labels
*/
func (manager *DockerManager) GetVolumesByLabels(ctx context.Context, labels map[string]string) ([]*volume.Volume, error) {
labelsFilterArgs := getLabelsFilterArgs(volumeLabelSearchFilterKey, labels)
listOptions := volume.ListOptions{Filters: labelsFilterArgs}
resp, err := manager.dockerClient.VolumeList(ctx, listOptions)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred finding volumes with labels '%+v'", labels)
}
result := []*volume.Volume{}
if resp.Volumes != nil {
result = resp.Volumes
}
return result, nil
}
/*
RemoveVolume
Removes a Docker volume identified by the given name, deleting it permanently
Args:
context: The Context that this request is running in (useful for cancellation)
volumeName: The unique identifier used by Docker to identify the volume that will get removed
*/
func (manager *DockerManager) RemoveVolume(ctx context.Context, volumeName string) error {
if err := manager.dockerClient.VolumeRemove(ctx, volumeName, shouldForceVolumeRemoval); err != nil {
return stacktrace.Propagate(err, "An error occurred removing volume '%v'", volumeName)
}
return nil
}
func (manager *DockerManager) InspectContainer(ctx context.Context, containerId string) (types.ContainerJSON, error) {
result, err := manager.dockerClient.ContainerInspect(ctx, containerId)
if err != nil {
return types.ContainerJSON{}, stacktrace.Propagate(err, "An error occurred inspecting container '%v'", containerId)
}
return result, nil
}
/*
CreateAndStartContainer
Creates a Docker container with the given args and starts it.
Returns:
containerId: The Docker container ID of the newly-created container
hostMachinePortBindings: For every port in the args' "usedPorts" object that has publishing turned on, an entry
will be generated in this map with the binding on the host machine where the port can be found
*/
func (manager *DockerManager) CreateAndStartContainer(
ctx context.Context,
args *CreateAndStartContainerArgs,
) (string, map[nat.Port]*nat.PortBinding, error) {
// If the user passed in a Docker image that doesn't have a tag separator (indicating no tag was specified), manually append
// the Docker default tag so that when we search for the image we're searching for a very specific image
dockerImage := args.dockerImage
if !strings.Contains(dockerImage, dockerTagSeparatorChar) {
dockerImage = dockerImage + dockerTagSeparatorChar + dockerDefaultTag
}
_, _, err := manager.FetchImage(ctx, dockerImage, args.imageRegistrySpec, args.imageDownloadMode)
if err != nil {
logrus.Debugf("Error occurred fetching image '%v'. Err:\n%v", dockerImage, err)
return "", nil, stacktrace.Propagate(err, "An error occurred fetching image '%v'", dockerImage)
}
idFilterArgs := filters.NewArgs(filters.KeyValuePair{
Key: networkIdSearchFilterKey,
Value: args.networkId,
})
networks, err := manager.getNetworksByFilterArgs(ctx, idFilterArgs)
if err != nil {
return "", nil, stacktrace.Propagate(err, "An error occurred checking for the existence of network with ID %v", args.networkId)
}
if len(networks) == 0 {
return "", nil, stacktrace.NewError(
"Kurtosis Docker network with ID %v was never created before trying to launch containers. Please call DockerManager.CreateNetwork first.",
args.networkId,
)
} else if len(networks) > 1 {
return "", nil, stacktrace.NewError("Kurtosis Docker network with ID %v matches several networks!", args.networkId)
}
isInteractiveMode := args.interactiveModeTtySize != nil
usedPortsSet := nat.PortSet{}
for port := range args.usedPorts {
usedPortsSet[port] = struct{}{}
}
var userStr string
if args.user != nil {
userStr = args.user.GetUIDGIDPairAsStr()
}
containerConfigPtr, err := manager.getContainerCfg(
dockerImage,
isInteractiveMode,
usedPortsSet,
args.entrypointArgs,
args.cmdArgs,
args.envVariables,
args.labels,
userStr,
)
if err != nil {
return "", nil, stacktrace.Propagate(err, "Failed to configure container from service.")
}
containerHostConfigPtr, err := manager.getContainerHostConfig(
args.addedCapabilities,
args.securityOpts,
args.networkMode,
args.bindMounts,
args.volumeMounts,
args.usedPorts,
args.needsAccessToDockerHostMachine,
args.cpuAllocationMillicpus,
args.memoryAllocationMegabytes,
args.loggingDriverConfig,
args.containerInitEnabled,
args.restartPolicy)
if err != nil {
return "", nil, stacktrace.Propagate(err, "Failed to configure host to container mappings from service.")
}
// note a nil network config would connect to bridge network by default
var networkConfig *network.NetworkingConfig
if args.staticIp != nil && args.skipAddingToBridgeNetworkIfStaticIpIsSet {
targetNetworkEndPointSettings := getEndpointSettingsForIpAddress(args.staticIp.String(), args.alias)
endpointSettingsByNetworkId := map[string]*network.EndpointSettings{}
endpointSettingsByNetworkId[args.networkId] = targetNetworkEndPointSettings
networkConfig = &network.NetworkingConfig{
EndpointsConfig: endpointSettingsByNetworkId,
}
}
// This function dockerClient.ContainerCreate adds the container to the bridge network if the networkConfig is nil or if its empty
// Ideally we'd start with an empty network config, add the target network if its supplied and add the bridge network if the person needs it
// This logic breaks at two places
// If a person doesn't need either of them, and we pass a nil(or empty) we get the bridge network for free
// While starting the enclave, adding both bridge & enclave network to the networkConfig just fails
// I tried creating the container with networkConfig - nil & args.NetworkMode set to none but that stopped me from adding the container to a network
// using manager.ConnectContainerToNetwork
containerCreateResp, err := manager.dockerClient.ContainerCreate(ctx, containerConfigPtr, containerHostConfigPtr, networkConfig, nil, args.name)
if err != nil {
return "", nil, stacktrace.Propagate(err, "Could not create Docker container '%v' from image '%v'", args.name, dockerImage)
}
containerId := containerCreateResp.ID
if containerId == "" {
return "", nil, stacktrace.NewError(
"Creation of container '%v' from image '%v' succeeded without error, but we didn't get a container ID back - this is VERY strange!",
args.name,
dockerImage,
)
}
logrus.Debugf("Created container with ID '%v' from image '%v'", containerId, dockerImage)
// static ip is provided and the user wants the connection to bridge network to happen
// in the container start the bridge network got connected and now we connect to target network
if args.staticIp != nil && !args.skipAddingToBridgeNetworkIfStaticIpIsSet {
if err = manager.ConnectContainerToNetwork(ctx, args.networkId, containerId, args.staticIp, args.alias); err != nil {
return "", nil, stacktrace.Propagate(err, "Failed to connect container %s to network.", containerId)
}
}
// TODO defer a disconnct-from-network if this function doesn't succeed??
err = manager.StartContainer(ctx, containerId)
if err != nil {
return "", nil, stacktrace.Propagate(err, "Could not start Docker container from image '%v'.", dockerImage)
}
functionFinishedSuccessfully := false
defer func() {
if !functionFinishedSuccessfully {
if err := manager.KillContainer(ctx, containerId); err != nil {
logrus.Error("The container creation function didn't finish successfully, meaning we needed to kill the container we created. However, the killing threw an error:")
fmt.Fprintln(logrus.StandardLogger().Out, err)
logrus.Errorf("ACTION NEEDED: You'll need to manually kill this container with ID '%v'", containerId)
}
}
}()
//Check if the container dies because sometimes users starts containers with a wrong configuration and these quickly dies
didContainerStartSuccessfully, err := manager.didContainerStartSuccessfully(ctx, containerId, dockerImage)
if err != nil {
return "", nil, stacktrace.Propagate(err, "An error occurred checking if container '%v' is running", containerId)
}
if isInteractiveMode {
/*
Two notes:
1) Container resizing must be done after the container is started
2) This resize is very important - if we don't do it, then the output will look garbled for
lines longer than the user's terminal
*/
resizeOpts := types.ResizeOptions{
Height: args.interactiveModeTtySize.Height,
Width: args.interactiveModeTtySize.Width,
}
if err := manager.dockerClient.ContainerResize(ctx, containerId, resizeOpts); err != nil {
return "", nil, stacktrace.Propagate(
err,
"An error occurred resizing the new container's TTY size to height %v and width %v to match the user's terminal",
args.interactiveModeTtySize.Height,
args.interactiveModeTtySize.Width,
)
}
}
publishedPortsSet := map[nat.Port]bool{}
for containerPort, publishSpec := range args.usedPorts {
if publishSpec.mustBeFoundAfterContainerStart() {
publishedPortsSet[containerPort] = true
}
}
logrus.Tracef("Published ports set: %+v", publishedPortsSet)
// If the user wanted their ports exposed, Docker will have auto-assigned the ports to ports in the ephemeral range
// on the host. We need to look up what those ports are, so we can return report them back to the user.
resultHostPortBindings := map[nat.Port]*nat.PortBinding{}
numPublishedPorts := len(publishedPortsSet)
if numPublishedPorts > 0 {
// Thanks to https://github.com/moby/moby/issues/42860, we have to retry several times to get the host port bindings
// from Docker
for i := 0; i < maxNumHostPortBindingChecks; i++ {
logrus.Tracef("Trying to get host machine port bindings (%v previous attempts)...", i)
containerInspectResp, err := manager.dockerClient.ContainerInspect(ctx, containerId)
if err != nil {
return "", nil, stacktrace.Propagate(
err,
"%v ports were published to the host machine, but an error occurred inspecting the newly-started "+
"container which is necessary for determining which host machine ports the container's ports were bound to",
numPublishedPorts,
)
}
logrus.Tracef("Container inspect response: %+v", containerInspectResp)
networkSettings := containerInspectResp.NetworkSettings
if networkSettings == nil {
return "", nil, stacktrace.NewError(
"We got a response from inspecting container '%v' which is necessary for determining the "+
"ports published to the host machine, but the network settings object was nil",
containerId,
)
}
logrus.Tracef("Network settings: %+v", networkSettings)
allInterfaceHostPortBindings := networkSettings.Ports
if allInterfaceHostPortBindings == nil {
return "", nil, stacktrace.NewError(
"%v ports on container '%v' were to be published to the host machine, but the container host port bindings were null",
numPublishedPorts,
containerId,
)
}
logrus.Tracef("Network settings -> ports: %+v", allInterfaceHostPortBindings)
allHostPortBindingsOnExpectedInterface := getHostPortBindingsOnExpectedInterface(allInterfaceHostPortBindings)
// Filter to the ports matching the ports we wanted to publish
usedHostPortBindingsOnExpectedInterface := map[nat.Port]*nat.PortBinding{}
for port, hostPortBinding := range allHostPortBindingsOnExpectedInterface {
if _, found := usedPortsSet[port]; !found {
logrus.Tracef("Port '%v' isn't in used port set, so we're skipping its host port binding", port)
continue
}
usedHostPortBindingsOnExpectedInterface[port] = hostPortBinding
}
// If we're missing a host port binding, it's likely because of https://github.com/moby/moby/issues/42860
// We'll retry after a sleep
if len(usedHostPortBindingsOnExpectedInterface) == numPublishedPorts {
resultHostPortBindings = usedHostPortBindingsOnExpectedInterface
break
}
time.Sleep(timeBetweenHostPortBindingChecks)
}
// Final verification that all published ports get a host machine port bindings
if len(resultHostPortBindings) != numPublishedPorts {
if !didContainerStartSuccessfully {
//Then, if the container is running, show the error related to the ports problem
return "", nil, stacktrace.NewError(
"%v ports were to be published to the host machine, but container '%v' never got host machine port"+
" bindings on interface %v for all published ports even after %v checks with %v between checks.",
numPublishedPorts,
containerId,
expectedHostIp,
maxNumHostPortBindingChecks,
timeBetweenHostPortBindingChecks,
)
}
}
}
functionFinishedSuccessfully = true
return containerId, resultHostPortBindings, nil
}
/*
GetContainerIP
Gets the container's IP on a given network
NOTE: Yes, it's a testament to how poorly-designed the Docker API is that we need to use network name here even though
everywhere else in the Docker API uses network ID
*/
func (manager *DockerManager) GetContainerIP(ctx context.Context, networkName string, containerId string) (string, error) {
resp, err := manager.dockerClient.ContainerInspect(ctx, containerId)
if err != nil {
return "", stacktrace.Propagate(err, "An error occurred inspecting container with ID '%v'", containerId)
}
allNetworkInfo := resp.NetworkSettings.Networks
networkInfo, found := allNetworkInfo[networkName]
if !found {
return "", stacktrace.NewError("Container ID '%v' isn't connected to network '%v'", containerId, networkName)
}
return networkInfo.IPAddress, nil
}
/*
GetContainerIps
Gets the container's IPs on all networks
Returns a map of network ID to network IP address
*/
func (manager *DockerManager) GetContainerIps(ctx context.Context, containerId string) (map[string]string, error) {
containerIps := map[string]string{}
resp, err := manager.dockerClient.ContainerInspect(ctx, containerId)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred inspecting container with ID '%v'", containerId)
}
allNetworkInfo := resp.NetworkSettings.Networks
for _, networkInfo := range allNetworkInfo {
containerIps[networkInfo.NetworkID] = networkInfo.IPAddress
}
return containerIps, nil
}
func (manager *DockerManager) AttachToContainer(ctx context.Context, containerId string) (types.HijackedResponse, error) {
attachOpts := types.ContainerAttachOptions{
Stream: true,
Stdin: true,
Stdout: true,
Stderr: true,
DetachKeys: "",
Logs: false,
}
hijackedResponse, err := manager.dockerClient.ContainerAttach(ctx, containerId, attachOpts)
if err != nil {
return types.HijackedResponse{}, stacktrace.Propagate(err, "An error occurred attaching to container '%v'", containerId)
}
return hijackedResponse, nil
}
/*
StartContainer
Starts the container with the given container ID
Args:
context: The context that the starting runs in (useful for cancellation)
containerId: ID of Docker container to start
*/
func (manager *DockerManager) StartContainer(context context.Context, containerId string) error {
options := types.ContainerStartOptions{
CheckpointID: "",
CheckpointDir: "",
}
err := manager.dockerClient.ContainerStart(context, containerId, options)
if err != nil {
containerLogs := manager.getFailedContainerLogsOrErrorString(context, containerId)
containerLogsHeader := "\n--------------------- CONTAINER LOGS -----------------------\n"
containerLogsFooter := "\n------------------- END CONTAINER LOGS --------------------"
return stacktrace.Propagate(err, "Could not start Docker container with ID '%v'; logs are below:%v%v%v", containerId, containerLogsHeader, containerLogs, containerLogsFooter)
}
return nil
}
/*
StopContainer
Stops the container with the given container ID, waiting for the provided timeout before forcefully terminating the container
Args:
context: The context that the stopping runs in (useful for cancellation)
containerId: ID of Docker container to stop
timeout: How long to wait for container stoppage before throwing an error
*/
func (manager *DockerManager) StopContainer(context context.Context, containerId string, timeout time.Duration) error {
timeoutSeconds := int(timeout.Seconds())
stopOpts := container.StopOptions{Signal: "", Timeout: &timeoutSeconds}
err := manager.dockerClient.ContainerStop(context, containerId, stopOpts)
if err != nil {
return stacktrace.Propagate(err, "An error occurred stopping container with ID '%v'", containerId)
}
return nil
}
/*
KillContainer
Kills the container with the given ID if it's running, giving it no opportunity to gracefully exit
Args:
context: The context that the kill runs in
containerId: ID of Docker container to kill
*/
func (manager *DockerManager) KillContainer(ctx context.Context, containerId string) error {
if err := manager.killContainerWithRetriesWhenErrorResponseFromDaemon(
ctx,
containerId,
defaultKillContainerMaxRetries,
defaultKillContainerTimeBetweenRetries,
); err != nil {
return stacktrace.Propagate(
err,
"An error occurred killing container '%v', even after %v retries with '%v' in between retries",
containerId,
defaultKillContainerMaxRetries,
defaultKillContainerTimeBetweenRetries,
)
}
return nil
}
/*
RemoveContainer
Removes the container with the given ID, deleting it permanently
Args:
context: The context that the removal runs in
containerId: ID of Docker container to remove
*/
func (manager *DockerManager) RemoveContainer(ctx context.Context, containerId string) error {
removeOpts := &types.ContainerRemoveOptions{
RemoveVolumes: shouldRemoveAnonymousVolumesWhenRemovingContainers,
RemoveLinks: shouldRemoveLinksWhenRemovingContainers,
Force: shouldKillContainersWhenRemovingContainers,
}
err := manager.removeContainerWithRetriesOnFailureForZombieProcesses(
ctx,
containerId,
removeOpts,
defaultRemoveProcessesMaxRetries,
defaultRemoveContainerTimeBetweenRetries)
if err != nil {
return stacktrace.Propagate(err, "An error occurred removing container with ID '%v'", containerId)
}
return nil
}
/*
WaitForExit
Blocks until the given container exits or the context is cancelled.
Args:
context: Context the waiting will run in (useful for cancellation)
containerId: The ID of the Docker container that should be waited on
Returns:
exitCode: The exit code of the container if it stopped
err: The error if an error occurred waiting for exit
*/
func (manager *DockerManager) WaitForExit(context context.Context, containerId string) (exitCode int64, err error) {
statusChannel, errChannel := manager.dockerClient.ContainerWait(context, containerId, container.WaitConditionNotRunning)
// Blocks until one of the channels returns
select {
case channErr := <-errChannel:
exitCode = 1
err = stacktrace.Propagate(channErr, "Failed to wait for container to return.")
case status := <-statusChannel:
exitCode = status.StatusCode
err = nil
}
return
}
/*
GetContainerLogs gets the logs for the given container as a io.ReadCloser. The caller is responsible for closing the ReadCloser!!!
NOTE: These logs have STDOUT and STDERR multiplexed together, and the 'stdcopy' package needs to be used to
demultiplex them per https://github.com/moby/moby/issues/32794
*/
func (manager *DockerManager) GetContainerLogs(
ctx context.Context,
containerId string,
shouldFollowLogs bool,
) (io.ReadCloser, error) {
// As we're using the docker client with no timeout to be able to follow the logs for a long time, we quickly check
// with the client that has a timeout whether the docker engine is reachable.
if _, err := manager.dockerClient.Ping(ctx); err != nil {
return nil, stacktrace.Propagate(err, "An error occurred communicating with docker engine")
}
containerLogOpts := types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Since: "",
Until: "",
Timestamps: false,
Follow: shouldFollowLogs,
Tail: "",
Details: false,
}
readCloser, err := manager.dockerClientNoTimeout.ContainerLogs(ctx, containerId, containerLogOpts)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred getting logs for container ID '%v'", containerId)
}
return readCloser, nil
}
/*
RunExecCommand
Executes the given command inside the container with the given ID, blocking until the command completes
*/
func (manager *DockerManager) RunExecCommand(context context.Context, containerId string, command []string, logOutput io.Writer) (int32, error) {
dockerClient := manager.dockerClient
execConfig := types.ExecConfig{