-
-
Notifications
You must be signed in to change notification settings - Fork 580
/
dockerutils.go
1806 lines (1588 loc) · 55.9 KB
/
dockerutils.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 dockerutil
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"net"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"github.com/ddev/ddev/pkg/archive"
dockerImages "github.com/ddev/ddev/pkg/docker"
ddevexec "github.com/ddev/ddev/pkg/exec"
"github.com/ddev/ddev/pkg/fileutil"
"github.com/ddev/ddev/pkg/globalconfig"
"github.com/ddev/ddev/pkg/nodeps"
"github.com/ddev/ddev/pkg/output"
"github.com/ddev/ddev/pkg/util"
docker "github.com/fsouza/go-dockerclient"
)
// NetName provides the default network name for ddev.
const NetName = "ddev_default"
type ComposeCmdOpts struct {
ComposeFiles []string
Action []string
Progress bool // Add dots every second while the compose command is running
RealTime bool // Print stdout as it happens
}
// EnsureNetwork will ensure the Docker network for DDEV is created.
func EnsureNetwork(client *docker.Client, name string, netOptions docker.CreateNetworkOptions) error {
// Pre-check for network duplicates
RemoveNetworkDuplicates(client, name)
if !NetExists(client, name) {
_, err := client.CreateNetwork(netOptions)
if err != nil {
return err
}
output.UserOut.Println("Network", name, "created")
}
return nil
}
// EnsureDdevNetwork creates or ensures the DDEV network exists or
// exits with fatal.
func EnsureDdevNetwork() {
// Ensure we have the fallback global DDEV network
client := GetDockerClient()
netOptions := docker.CreateNetworkOptions{
Name: NetName,
Driver: "bridge",
Internal: false,
Labels: map[string]string{"com.ddev.platform": "ddev"},
}
err := EnsureNetwork(client, NetName, netOptions)
if err != nil {
log.Fatalf("Failed to ensure Docker network %s: %v", NetName, err)
}
}
// EnsureProjectNetwork creates or ensures the project network exists or
// exits with fatal.
func EnsureProjectNetwork() {
if os.Getenv("COMPOSE_PROJECT_NAME") == "" {
log.Fatalf("dockerutil.EnsureProjectNetwork() must be called after app.DockerEnv()")
}
networkName := os.Getenv("COMPOSE_PROJECT_NAME") + "_default"
client := GetDockerClient()
netOptions := docker.CreateNetworkOptions{
Name: networkName,
Driver: "bridge",
Internal: false,
Labels: map[string]string{
"com.ddev.platform": "ddev",
// add docker-compose labels needed for "docker compose up"
"com.docker.compose.network": "default",
"com.docker.compose.project": os.Getenv("COMPOSE_PROJECT_NAME"),
"com.docker.compose.version": func() string {
version, _ := GetDockerComposeVersion()
return strings.TrimPrefix(version, "v")
}()},
}
// see https://github.com/ddev/ddev/issues/3766
if nodeps.IsGitpod() {
netOptions.Options = map[string]any{
"com.docker.network.driver.mtu": "1440",
}
}
err := EnsureNetwork(client, networkName, netOptions)
if err != nil {
log.Fatalf("Failed to ensure Docker network %s: %v", networkName, err)
}
}
// NetworkExists returns true if the named network exists
// Mostly intended for tests
func NetworkExists(netName string) bool {
// Ensure we have Docker network
client := GetDockerClient()
return NetExists(client, strings.ToLower(netName))
}
// RemoveNetwork removes the named Docker network
// netName can also be network's ID
func RemoveNetwork(netName string) error {
client := GetDockerClient()
networks, _ := client.ListNetworks()
// the loop below may not contain such a network
var err error = &docker.NoSuchNetwork{ID: netName}
// loop through all networks because there may be duplicates
// and delete only by ID - it's unique, but the name isn't
for _, network := range networks {
if network.Name == netName || network.ID == netName {
err = client.RemoveNetwork(network.ID)
}
}
return err
}
// RemoveNetworkWithWarningOnError removes the named Docker network
func RemoveNetworkWithWarningOnError(netName string) {
err := RemoveNetwork(netName)
_, isNoSuchNetwork := err.(*docker.NoSuchNetwork)
// If it's a "no such network" there's no reason to report error
if err != nil && !isNoSuchNetwork {
util.Warning("Unable to remove network %s: %v", netName, err)
} else if err == nil {
output.UserOut.Println("Network", netName, "removed")
}
}
// RemoveNetworkDuplicates removes the duplicates for the named Docker network
// This means that if there is only one network with this name - no action,
// and if there are several such networks, then we leave the first one, and delete the others
func RemoveNetworkDuplicates(client *docker.Client, netName string) {
networks, _ := client.ListNetworks()
networkMatchFound := false
for _, network := range networks {
if network.Name == netName || network.ID == netName {
if networkMatchFound == true {
err := client.RemoveNetwork(network.ID)
_, isNoSuchNetwork := err.(*docker.NoSuchNetwork)
// If it's a "no such network" there's no reason to report error
if err != nil && !isNoSuchNetwork {
util.Warning("Unable to remove network %s: %v", netName, err)
}
} else {
networkMatchFound = true
}
}
}
}
var DockerHost string
var DockerContext string
// GetDockerClient returns a Docker client respecting the current Docker context
// but DOCKER_HOST gets priority
func GetDockerClient() *docker.Client {
var err error
// This section is skipped if $DOCKER_HOST is set
if DockerHost == "" {
DockerContext, DockerHost, err = GetDockerContext()
// ddev --version may be called without Docker client or context available, ignore err
if err != nil && len(os.Args) > 1 && os.Args[1] != "--version" && os.Args[1] != "hostname" {
util.Failed("Unable to get Docker context: %v", err)
}
util.Debug("GetDockerClient: DockerContext=%s, DockerHost=%s", DockerContext, DockerHost)
}
// Respect DOCKER_HOST in case it's set, otherwise use host we got from context
if os.Getenv("DOCKER_HOST") == "" {
util.Debug("GetDockerClient: Setting DOCKER_HOST to '%s'", DockerHost)
_ = os.Setenv("DOCKER_HOST", DockerHost)
}
client, err := docker.NewClientFromEnv()
if err != nil {
output.UserOut.Warnf("Could not get Docker client. Is Docker running? Error: %v", err)
// Use os.Exit instead of util.Failed() to avoid import cycle with util.
os.Exit(100)
}
return client
}
// GetDockerContext() returns the currently set Docker context, host, and error
func GetDockerContext() (string, string, error) {
context := ""
dockerHost := ""
// This is a cheap way of using Docker contexts by running `docker context inspect`
// I would wish for something far better, but trying to transplant the code from
// docker/cli did not succeed. rfay 2021-12-16
// `docker context inspect` will already respect $DOCKER_CONTEXT so we don't have to do that.
contextInfo, err := ddevexec.RunHostCommand("docker", "context", "inspect", "-f", `{{ .Name }} {{ .Endpoints.docker.Host }}`)
if err != nil {
return "", "", fmt.Errorf("unable to run 'docker context inspect' - please make sure Docker client is in path and up-to-date: %v", err)
}
contextInfo = strings.Trim(contextInfo, " \r\n")
util.Debug("GetDockerContext: contextInfo='%s'", contextInfo)
parts := strings.SplitN(contextInfo, " ", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("unable to run split Docker context info %s: %v", contextInfo, err)
}
context = parts[0]
dockerHost = parts[1]
util.Debug("Using Docker context %s (%v)", context, dockerHost)
return context, dockerHost, nil
}
// GetDockerHostID returns DOCKER_HOST but with all special characters removed
// It stands in for Docker context, but Docker context name is not a reliable indicator
func GetDockerHostID() string {
_, dockerHost, err := GetDockerContext()
if err != nil {
util.Warning("Unable to GetDockerContext: %v", err)
}
// Make it shorter so we don't hit Mutagen 63-char limit
dockerHost = strings.TrimPrefix(dockerHost, "unix://")
dockerHost = strings.TrimSuffix(dockerHost, "docker.sock")
dockerHost = strings.Trim(dockerHost, "/.")
// Convert remaining descriptor to alphanumeric
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
log.Fatal(err)
}
alphaOnly := reg.ReplaceAllString(dockerHost, "-")
return alphaOnly
}
// InspectContainer returns the full result of inspection
func InspectContainer(name string) (*docker.Container, error) {
client, err := docker.NewClientFromEnv()
if err != nil {
return nil, err
}
c, err := FindContainerByName(name)
if err != nil || c == nil {
return nil, err
}
x, err := client.InspectContainerWithOptions(docker.InspectContainerOptions{ID: c.ID})
return x, err
}
// FindContainerByName takes a container name and returns the container
// If container is not found, returns nil with no error
func FindContainerByName(name string) (*docker.APIContainers, error) {
client := GetDockerClient()
containers, err := client.ListContainers(docker.ListContainersOptions{
All: true,
Filters: map[string][]string{"name": {name}},
})
if err != nil {
return nil, err
}
if len(containers) == 0 {
return nil, nil
}
// ListContainers can return partial matches. Make sure we only match the exact one
// we're after.
for _, c := range containers {
if c.Names[0] == "/"+name {
return &c, nil
}
}
return nil, nil
}
// GetContainerStateByName returns container state for the named container
func GetContainerStateByName(name string) (string, error) {
container, err := FindContainerByName(name)
if err != nil || container == nil {
return "doesnotexist", fmt.Errorf("container %s does not exist", name)
}
if container.State == "running" {
return container.State, nil
}
return container.State, fmt.Errorf("container %s is in state=%s so can't be accessed", name, container.State)
}
// FindContainerByLabels takes a map of label names and values and returns any Docker containers which match all labels.
func FindContainerByLabels(labels map[string]string) (*docker.APIContainers, error) {
containers, err := FindContainersByLabels(labels)
if err != nil {
return nil, err
}
if len(containers) > 0 {
return &containers[0], nil
}
return nil, nil
}
// GetDockerContainers returns a slice of all Docker containers on the host system.
func GetDockerContainers(allContainers bool) ([]docker.APIContainers, error) {
client := GetDockerClient()
containers, err := client.ListContainers(docker.ListContainersOptions{All: allContainers})
return containers, err
}
// FindContainersByLabels takes a map of label names and values and returns any Docker containers which match all labels.
// Explanation of the query:
// * docs: https://docs.docker.com/engine/api/v1.23/
// * Stack Overflow: https://stackoverflow.com/questions/28054203/docker-remote-api-filter-exited
func FindContainersByLabels(labels map[string]string) ([]docker.APIContainers, error) {
if len(labels) < 1 {
return []docker.APIContainers{{}}, fmt.Errorf("the provided list of labels was empty")
}
filterList := []string{}
for k, v := range labels {
filterList = append(filterList, fmt.Sprintf("%s=%s", k, v))
}
client := GetDockerClient()
containers, err := client.ListContainers(docker.ListContainersOptions{
All: true,
Filters: map[string][]string{"label": filterList},
})
if err != nil {
return nil, err
}
return containers, nil
}
// FindContainersWithLabel returns all containers with the given label
// It ignores the value of the label, is only interested that the label exists.
func FindContainersWithLabel(label string) ([]docker.APIContainers, error) {
client := GetDockerClient()
containers, err := client.ListContainers(docker.ListContainersOptions{
All: true,
Filters: map[string][]string{"label": {label}},
})
if err != nil {
return nil, err
}
return containers, nil
}
// NetExists checks to see if the Docker network for DDEV exists.
func NetExists(client *docker.Client, name string) bool {
nets, _ := client.ListNetworks()
for _, n := range nets {
if n.Name == name {
return true
}
}
return false
}
// FindNetworksWithLabel returns all networks with the given label
// It ignores the value of the label, is only interested that the label exists.
func FindNetworksWithLabel(label string) ([]docker.Network, error) {
client := GetDockerClient()
networks, err := client.ListNetworks()
if err != nil {
return nil, err
}
var matchingNetworks []docker.Network
for _, network := range networks {
if network.Labels != nil {
if _, exists := network.Labels[label]; exists {
matchingNetworks = append(matchingNetworks, network)
}
}
}
return matchingNetworks, nil
}
// ContainerWait provides a wait loop to check for a single container in "healthy" status.
// waittime is in seconds.
// This is modeled on https://gist.github.com/ngauthier/d6e6f80ce977bedca601
// Returns logoutput, error, returns error if not "healthy"
func ContainerWait(waittime int, labels map[string]string) (string, error) {
durationWait := time.Duration(waittime) * time.Second
timeoutChan := time.NewTimer(durationWait)
tickChan := time.NewTicker(500 * time.Millisecond)
defer tickChan.Stop()
defer timeoutChan.Stop()
status := ""
for {
select {
case <-timeoutChan.C:
_ = timeoutChan.Stop()
return "", fmt.Errorf("health check timed out after %v: labels %v timed out without becoming healthy, status=%v", durationWait, labels, status)
case <-tickChan.C:
container, err := FindContainerByLabels(labels)
if err != nil || container == nil {
return "", fmt.Errorf("failed to query container labels=%v: %v", labels, err)
}
health, logOutput := GetContainerHealth(container)
switch health {
case "healthy":
return logOutput, nil
case "unhealthy":
return logOutput, fmt.Errorf("container %s unhealthy: %s", container.Names[0], logOutput)
case "exited":
service := container.Labels["com.docker.compose.service"]
suggestedCommand := fmt.Sprintf("ddev logs -s %s", service)
if service == "ddev-router" || service == "ddev-ssh-agent" {
suggestedCommand = fmt.Sprintf("docker logs %s", service)
}
return logOutput, fmt.Errorf("container exited, please use '%s' to find out why it failed", suggestedCommand)
}
}
}
// We should never get here.
//nolint: govet
return "", fmt.Errorf("inappropriate break out of for loop in ContainerWait() waiting for container labels %v", labels)
}
// ContainersWait provides a wait loop to check for multiple containers in "healthy" status.
// waittime is in seconds.
// Returns logoutput, error, returns error if not "healthy"
func ContainersWait(waittime int, labels map[string]string) error {
timeoutChan := time.After(time.Duration(waittime) * time.Second)
tickChan := time.NewTicker(500 * time.Millisecond)
defer tickChan.Stop()
status := ""
for {
select {
case <-timeoutChan:
desc := ""
containers, err := FindContainersByLabels(labels)
if err == nil && containers != nil {
for _, c := range containers {
health, _ := GetContainerHealth(&c)
if health != "healthy" {
n := strings.TrimPrefix(c.Names[0], "/")
desc = desc + fmt.Sprintf(" %s:%s - more info with `docker inspect --format \"{{json .State.Health }}\" %s`", n, health, n)
}
}
}
return fmt.Errorf("health check timed out: labels %v timed out without becoming healthy, status=%v, detail=%s ", labels, status, desc)
case <-tickChan.C:
containers, err := FindContainersByLabels(labels)
allHealthy := true
for _, c := range containers {
if err != nil || containers == nil {
return fmt.Errorf("failed to query container labels=%v: %v", labels, err)
}
health, logOutput := GetContainerHealth(&c)
switch health {
case "healthy":
continue
case "unhealthy":
return fmt.Errorf("container %s is unhealthy: %s", c.Names[0], logOutput)
case "exited":
service := c.Labels["com.docker.compose.service"]
suggestedCommand := fmt.Sprintf("ddev logs -s %s", service)
if service == "ddev-router" || service == "ddev-ssh-agent" {
suggestedCommand = fmt.Sprintf("docker logs %s", service)
}
return fmt.Errorf("container '%s' exited, please use '%s' to find out why it failed", service, suggestedCommand)
default:
allHealthy = false
}
}
if allHealthy {
return nil
}
}
}
// We should never get here.
//nolint: govet
return fmt.Errorf("inappropriate break out of for loop in ContainerWait() waiting for container labels %v", labels)
}
// ContainerWaitLog provides a wait loop to check for container in "healthy" status.
// with a given log output
// timeout is in seconds.
// This is modeled on https://gist.github.com/ngauthier/d6e6f80ce977bedca601
// Returns logoutput, error, returns error if not "healthy"
func ContainerWaitLog(waittime int, labels map[string]string, expectedLog string) (string, error) {
timeoutChan := time.After(time.Duration(waittime) * time.Second)
tickChan := time.NewTicker(500 * time.Millisecond)
defer tickChan.Stop()
status := ""
for {
select {
case <-timeoutChan:
return "", fmt.Errorf("health check timed out: labels %v timed out without becoming healthy, status=%v", labels, status)
case <-tickChan.C:
container, err := FindContainerByLabels(labels)
if err != nil || container == nil {
return "", fmt.Errorf("failed to query container labels=%v: %v", labels, err)
}
status, logOutput := GetContainerHealth(container)
switch {
case status == "healthy" && expectedLog == logOutput:
return logOutput, nil
case status == "unhealthy":
return logOutput, fmt.Errorf("container %s unhealthy: %s", container.Names[0], logOutput)
case status == "exited":
service := container.Labels["com.docker.compose.service"]
return logOutput, fmt.Errorf("container exited, please use 'ddev logs -s %s` to find out why it failed", service)
}
}
}
// We should never get here.
//nolint: govet
return "", fmt.Errorf("inappropriate break out of for loop in ContainerWaitLog() waiting for container labels %v", labels)
}
// ContainerName returns the container's human readable name.
func ContainerName(container docker.APIContainers) string {
return container.Names[0][1:]
}
// GetContainerHealth retrieves the health status of a given container.
// returns status, most-recent-log
func GetContainerHealth(container *docker.APIContainers) (string, string) {
if container == nil {
return "no container", ""
}
// If the container is not running, then return exited as the health.
// "exited" means stopped.
if container.State == "exited" || container.State == "restarting" {
return container.State, ""
}
client := GetDockerClient()
inspect, err := client.InspectContainerWithOptions(docker.InspectContainerOptions{
ID: container.ID,
})
if err != nil || inspect == nil {
output.UserOut.Warnf("Error getting container to inspect: %v", err)
return "", ""
}
logOutput := ""
status := inspect.State.Health.Status
// The last log is the most recent
if inspect.State.Health.Status != "" {
numLogs := len(inspect.State.Health.Log)
if numLogs > 0 {
logOutput = fmt.Sprintf("%v", inspect.State.Health.Log)
}
} else {
// Some containers may not have a healthcheck. In that case
// we use State to determine health
switch inspect.State.Status {
case "running":
status = "healthy"
case "exited":
status = "exited"
}
}
return status, logOutput
}
// ComposeWithStreams executes a docker-compose command but allows the caller to specify
// stdin/stdout/stderr
func ComposeWithStreams(composeFiles []string, stdin io.Reader, stdout io.Writer, stderr io.Writer, action ...string) error {
defer util.TimeTrack()()
var arg []string
_, err := DownloadDockerComposeIfNeeded()
if err != nil {
return err
}
for _, file := range composeFiles {
arg = append(arg, "-f")
arg = append(arg, file)
}
arg = append(arg, action...)
path, err := globalconfig.GetDockerComposePath()
if err != nil {
return err
}
proc := exec.Command(path, arg...)
proc.Stdout = stdout
proc.Stdin = stdin
proc.Stderr = stderr
err = proc.Run()
return err
}
// ComposeCmd executes docker-compose commands via shell.
// returns stdout, stderr, error/nil
func ComposeCmd(cmd *ComposeCmdOpts) (string, string, error) {
var arg []string
var action []string
var stdout bytes.Buffer
var lineBytes bytes.Buffer
var stderr string
_, err := DownloadDockerComposeIfNeeded()
if err != nil {
return "", "", err
}
for _, file := range cmd.ComposeFiles {
arg = append(arg, "-f", file)
}
arg = append(arg, cmd.Action...)
path, err := globalconfig.GetDockerComposePath()
if err != nil {
return "", "", err
}
proc := exec.Command(path, arg...)
proc.Stdin = os.Stdin
stdoutPipe, err := proc.StdoutPipe()
if err != nil {
return "", "", fmt.Errorf("failed to proc.StdoutPipe(): %v", err)
}
stderrPipe, err := proc.StderrPipe()
if err != nil {
return "", "", fmt.Errorf("failed to proc.StderrPipe(): %v", err)
}
if err = proc.Start(); err != nil {
return "", "", fmt.Errorf("failed to exec docker-compose: %v", err)
}
chanOut := make(chan []byte)
chanErr := make(chan string)
stopOut := make(chan struct{})
stopErr := make(chan struct{})
endOut := false
endErr := false
// Read command's stdout and stderr line by line
inOut := bufio.NewScanner(stdoutPipe)
inErr := bufio.NewScanner(stderrPipe)
inOut.Split(bufio.ScanBytes)
// Ignore chatty things from docker-compose like:
// Container (or Volume) ... Creating or Created or Stopping or Starting or Removing
// Container Stopped or Created
// No resource found to remove (when doing a stop and no project exists)
ignoreRegex := "(^ *(Network|Container|Volume) .* (Creat|Start|Stopp|Remov)ing$|^Container .*(Stopp|Creat)(ed|ing)$|Warning: No resource found to remove|Pulling fs layer|Waiting|Downloading|Extracting|Verifying Checksum|Download complete|Pull complete)"
downRE, err := regexp.Compile(ignoreRegex)
if err != nil {
util.Warning("Failed to compile regex %v: %v", ignoreRegex, err)
}
go func() {
for inOut.Scan() {
chanOut <- inOut.Bytes()
}
close(stopOut)
}()
go func() {
for inErr.Scan() {
chanErr <- inErr.Text()
}
close(stopErr)
}()
for !endOut || !endErr {
select {
case <-time.After(1 * time.Second):
if cmd.Progress {
_, _ = fmt.Fprintf(os.Stderr, ".")
}
case b := <-chanOut:
stdout.Write(b)
if cmd.RealTime {
if string(b) == "\n" {
output.UserOut.Println(lineBytes.String())
lineBytes.Reset()
} else {
lineBytes.Write(b)
}
}
case line := <-chanErr:
if len(stderr) > 0 {
stderr = stderr + "\n"
}
stderr = stderr + line
line = strings.Trim(line, "\n\r")
switch {
case downRE.MatchString(line):
break
default:
output.UserOut.Println(line)
}
case <-stopOut:
endOut = true
case <-stopErr:
endErr = true
}
}
err = proc.Wait()
if err != nil {
return stdout.String(), stderr, fmt.Errorf("composeCmd failed to run 'COMPOSE_PROJECT_NAME=%s docker-compose %v', action='%v', err='%v', stdout='%s', stderr='%s'", os.Getenv("COMPOSE_PROJECT_NAME"), strings.Join(arg, " "), action, err, stdout.String(), stderr)
}
return stdout.String(), stderr, nil
}
// GetAppContainers retrieves docker containers for a given sitename.
func GetAppContainers(sitename string) ([]docker.APIContainers, error) {
label := map[string]string{"com.ddev.site-name": sitename}
containers, err := FindContainersByLabels(label)
if err != nil {
return containers, err
}
return containers, nil
}
// GetContainerEnv returns the value of a given environment variable from a given container.
func GetContainerEnv(key string, container docker.APIContainers) string {
client := GetDockerClient()
inspect, err := client.InspectContainerWithOptions(docker.InspectContainerOptions{
ID: container.ID,
})
if err == nil {
envVars := inspect.Config.Env
for _, env := range envVars {
if strings.HasPrefix(env, key) {
return strings.TrimPrefix(env, key+"=")
}
}
}
return ""
}
// CheckDockerVersion determines if the Docker version of the host system meets the provided version
// constraints. See https://godoc.org/github.com/Masterminds/semver#hdr-Checking_Version_Constraints
// for examples defining version constraints.
func CheckDockerVersion(versionConstraint string) error {
defer util.TimeTrack()()
currentVersion, err := GetDockerVersion()
if err != nil {
return fmt.Errorf("no docker")
}
// If Docker version has "_ce", remove it. This happens on OpenSUSE Tumbleweed at least
currentVersion = strings.TrimSuffix(currentVersion, "_ce")
dockerVersion, err := semver.NewVersion(currentVersion)
if err != nil {
return err
}
// See if they're using broken Docker Desktop on Linux
if runtime.GOOS == "linux" && !nodeps.IsWSL2() {
client := GetDockerClient()
info, err := client.Info()
if err != nil {
return fmt.Errorf("unable to get Docker info: %v", err)
}
if info.Name == "docker-desktop" {
return fmt.Errorf("docker desktop on Linux is not yet compatible with DDEV")
}
}
constraint, err := semver.NewConstraint(versionConstraint)
if err != nil {
return err
}
match, errs := constraint.Validate(dockerVersion)
if !match {
if len(errs) <= 1 {
return errs[0]
}
msgs := "\n"
for _, err := range errs {
msgs = fmt.Sprint(msgs, err, "\n")
}
return fmt.Errorf(msgs)
}
return nil
}
// CheckDockerCompose determines if docker-compose is present and executable on the host system. This
// relies on docker-compose being somewhere in the user's $PATH.
func CheckDockerCompose() error {
defer util.TimeTrack()()
_, err := DownloadDockerComposeIfNeeded()
if err != nil {
return err
}
versionConstraint := DockerComposeVersionConstraint
v, err := GetDockerComposeVersion()
if err != nil {
return err
}
dockerComposeVersion, err := semver.NewVersion(v)
if err != nil {
return err
}
constraint, err := semver.NewConstraint(versionConstraint)
if err != nil {
return err
}
match, errs := constraint.Validate(dockerComposeVersion)
if !match {
if len(errs) <= 1 {
return errs[0]
}
msgs := "\n"
for _, err := range errs {
msgs = fmt.Sprint(msgs, err, "\n")
}
return fmt.Errorf(msgs)
}
return nil
}
// GetPublishedPort returns the published port for a given private port.
func GetPublishedPort(privatePort int64, container docker.APIContainers) int {
for _, port := range container.Ports {
if port.PrivatePort == privatePort {
return int(port.PublicPort)
}
}
return 0
}
// CheckForHTTPS determines if a container has the HTTPS_EXPOSE var
// set to route 443 traffic to 80
func CheckForHTTPS(container docker.APIContainers) bool {
env := GetContainerEnv("HTTPS_EXPOSE", container)
if env != "" && strings.Contains(env, "443:80") {
return true
}
return false
}
var dockerHostRawURL string
var DockerIP string
// GetDockerIP returns either the default Docker IP address (127.0.0.1)
// or the value as configured by $DOCKER_HOST (if DOCKER_HOST is an tcp:// URL)
func GetDockerIP() (string, error) {
if DockerIP == "" {
DockerIP = "127.0.0.1"
dockerHostRawURL = os.Getenv("DOCKER_HOST")
// If DOCKER_HOST is empty, then the client hasn't been initialized
// from the Docker context
if dockerHostRawURL == "" {
_ = GetDockerClient()
dockerHostRawURL = os.Getenv("DOCKER_HOST")
}
if dockerHostRawURL != "" {
dockerHostURL, err := url.Parse(dockerHostRawURL)
if err != nil {
return "", fmt.Errorf("failed to parse $DOCKER_HOST=%s: %v", dockerHostRawURL, err)
}
hostPart := dockerHostURL.Hostname()
if hostPart != "" {
// Check to see if the hostname we found is an IP address
addr := net.ParseIP(hostPart)
if addr == nil {
// If it wasn't an IP address, look it up to get IP address
ip, err := net.LookupHost(hostPart)
if err == nil && len(ip) > 0 {
hostPart = ip[0]
} else {
return "", fmt.Errorf("failed to look up IP address for $DOCKER_HOST=%s, hostname=%s: %v", dockerHostRawURL, hostPart, err)
}
}
DockerIP = hostPart
}
}
}
return DockerIP, nil
}
// RunSimpleContainer runs a container (non-daemonized) and captures the stdout/stderr.
// It will block, so not to be run on a container whose entrypoint or cmd might hang or run too long.
// This should be the equivalent of something like
// docker run -t -u '%s:%s' -e SNAPSHOT_NAME='%s' -v '%s:/mnt/ddev_config' -v '%s:/var/lib/mysql' --rm --entrypoint=/migrate_file_to_volume.sh %s:%s"
// Example code from https://gist.github.com/fsouza/b0bf3043827f8e39c4589e88cec067d8
// Returns containerID, output, error
func RunSimpleContainer(image string, name string, cmd []string, entrypoint []string, env []string, binds []string, uid string, removeContainerAfterRun bool, detach bool, labels map[string]string, portBindings map[docker.Port][]docker.PortBinding) (containerID string, output string, returnErr error) {
client := GetDockerClient()
// Ensure image string includes a tag
imageChunks := strings.Split(image, ":")
if len(imageChunks) == 1 {
// Image does not specify tag
return "", "", fmt.Errorf("image name must specify tag: %s", image)
}
if tag := imageChunks[len(imageChunks)-1]; len(tag) == 0 {
// Image specifies malformed tag (ends with ':')
return "", "", fmt.Errorf("malformed tag provided: %s", image)
}
existsLocally, err := ImageExistsLocally(image)
if err != nil {
return "", "", fmt.Errorf("failed to check if image %s is available locally: %v", image, err)
}
if !existsLocally {
pullErr := Pull(image)
if pullErr != nil {
return "", "", fmt.Errorf("failed to pull image %s: %v", image, pullErr)
}
}
// Windows 10 Docker toolbox won't handle a bind mount like C:\..., so must convert to /c/...
if runtime.GOOS == "windows" {
for i := range binds {
binds[i] = strings.Replace(binds[i], `\`, `/`, -1)
if strings.Index(binds[i], ":") == 1 {
binds[i] = strings.Replace(binds[i], ":", "", 1)
binds[i] = "/" + binds[i]
// And amazingly, the drive letter must be lower-case.
re := regexp.MustCompile("^/[A-Z]/")
driveLetter := re.FindString(binds[i])
if len(driveLetter) == 3 {
binds[i] = strings.TrimPrefix(binds[i], driveLetter)
binds[i] = strings.ToLower(driveLetter) + binds[i]
}
}
}
}
options := docker.CreateContainerOptions{
Name: name,
Config: &docker.Config{
Image: image,
Cmd: cmd,
Env: env,
User: uid,
Labels: labels,
Entrypoint: entrypoint,
AttachStderr: true,
AttachStdout: true,
},
HostConfig: &docker.HostConfig{
Binds: binds,
PortBindings: portBindings,
},
}
if runtime.GOOS == "linux" && !IsDockerDesktop() {
options.HostConfig.ExtraHosts = []string{"host.docker.internal:host-gateway"}
}
container, err := client.CreateContainer(options)
if err != nil {
return "", "", fmt.Errorf("failed to create/start Docker container (%v):%v", options, err)
}
if removeContainerAfterRun {