/
docker.go
101 lines (95 loc) · 2.03 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
package util
import (
"context"
"fmt"
"io/ioutil"
"time"
"github.com/midcontinentcontrols/kb/pkg/logger"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"go.uber.org/zap"
)
func EnsureImagePulled(imageName string, cli client.APIClient, log logger.Logger) error {
imgs, err := cli.ImageList(context.TODO(), types.ImageListOptions{})
if err != nil {
return fmt.Errorf("docker: %v", err)
}
for _, img := range imgs {
if img.ID == "1fd8e1b0bb7e" {
// Already pulled!
return nil
}
}
resp, err := cli.ImagePull(context.TODO(), imageName, types.ImagePullOptions{})
if err != nil {
return fmt.Errorf("docker: %v", err)
}
body, err := ioutil.ReadAll(resp)
if err != nil {
return err
}
log.Debug(
"Pulled registry image",
zap.String("response", string(body)),
zap.String("imageName", imageName))
return nil
}
func WaitForContainer(
containerName string,
cli client.APIClient,
log logger.Logger,
) error {
done := make(chan int)
go func() {
log := log.With(zap.String("name", containerName))
for {
select {
case <-time.After(5 * time.Second):
log.Info("Still waiting for container")
case <-done:
return
}
}
}()
defer func() {
done <- 0
close(done)
}()
for {
info, err := cli.ContainerInspect(context.TODO(), containerName)
if err != nil {
return err
}
if info.State == nil {
panic("nil container state")
}
switch info.State.Status {
case "created":
if err := cli.ContainerStart(
context.TODO(),
containerName,
types.ContainerStartOptions{},
); err != nil {
return fmt.Errorf("error starting container: %v", err)
}
time.Sleep(time.Second)
case "running":
return nil
default:
return fmt.Errorf("unexpected container state '%s'", info.State.Status)
}
}
}
func SanitizeImageName(host, image, tag string) string {
if tag == "" {
tag = "latest"
}
n := len(host)
if n == 0 {
return fmt.Sprintf("%s:%s", image, tag)
}
if host[n-1] == '/' {
host = host[:n-1]
}
return fmt.Sprintf("%s/%s:%s", host, image, tag)
}