This repository has been archived by the owner on Nov 30, 2021. It is now read-only.
/
docker.go
342 lines (299 loc) · 9.07 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
package docker
import (
"archive/tar"
"bytes"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Masterminds/cookoo"
"github.com/Masterminds/cookoo/log"
"github.com/Masterminds/cookoo/safely"
"github.com/deis/deis/builder/etcd"
docli "github.com/fsouza/go-dockerclient"
)
// Path to the Docker unix socket.
// TODO: When we switch to a newer Docker library, we should favor this:
// var DockSock = opts.DefaultUnixSocket
var DockSock = "/var/run/docker.sock"
// Cleanup removes any existing Docker artifacts.
//
// Returns true if the file exists (and was deleted), or false if no file
// was deleted.
func Cleanup(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
// If info is returned, then the file is there. If we get an error, we're
// pretty much not going to be able to remove the file (which probably
// doesn't exist).
if _, err := os.Stat(DockSock); err == nil {
log.Infof(c, "Removing leftover docker socket %s", DockSock)
return true, os.Remove(DockSock)
}
return false, nil
}
// CreateClient creates a new Docker client.
//
// Params:
// - url (string): The URI to the Docker daemon. This defaults to the UNIX
// socket /var/run/docker.sock.
//
// Returns:
// - *docker.Client
//
func CreateClient(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
path := p.Get("url", "unix:///var/run/docker.sock").(string)
return docli.NewClient(path)
}
// Start starts a Docker daemon.
//
// This assumes the presence of the docker client on the host. It does not use
// the API.
func Start(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
// Allow insecure Docker registries on all private network ranges in RFC 1918 and RFC 6598.
dargs := []string{
"-d",
"--bip=172.19.42.1/16",
"--insecure-registry",
"10.0.0.0/8",
"--insecure-registry",
"172.16.0.0/12",
"--insecure-registry",
"192.168.0.0/16",
"--insecure-registry",
"100.64.0.0/10",
"--exec-opt",
"native.cgroupdriver=cgroupfs",
}
// For overlay-ish filesystems, force the overlay to kick in if it exists.
// Then we can check the fstype.
if err := os.MkdirAll("/", 0700); err == nil {
cmd := exec.Command("findmnt", "--noheadings", "--output", "FSTYPE", "--target", "/")
if out, err := cmd.Output(); err == nil && strings.TrimSpace(string(out)) == "overlay" {
dargs = append(dargs, "--storage-driver=overlay")
} else {
log.Infof(c, "File system type: '%s' (%v)", out, err)
}
}
log.Infof(c, "Starting docker with %s", strings.Join(dargs, " "))
cmd := exec.Command("docker", dargs...)
if err := cmd.Start(); err != nil {
log.Errf(c, "Failed to start Docker. %s", err)
return -1, err
}
// Get the PID and return it.
return cmd.Process.Pid, nil
}
// WaitForStart delays until Docker appears to be up and running.
//
// Params:
// - client (*docker.Client): Docker client.
// - timeout (time.Duration): Time after which to give up.
//
// Returns:
// - boolean true if the server is up.
func WaitForStart(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
if ok, missing := p.RequiresValue("client"); !ok {
return nil, &cookoo.FatalError{"Missing required fields: " + strings.Join(missing, ", ")}
}
cli := p.Get("client", nil).(*docli.Client)
timeout := p.Get("timeout", 30*time.Second).(time.Duration)
keepon := true
timer := time.AfterFunc(timeout, func() {
keepon = false
})
for keepon == true {
if err := cli.Ping(); err == nil {
timer.Stop()
log.Infof(c, "Docker is running.")
return true, nil
}
time.Sleep(time.Second)
}
return false, fmt.Errorf("Docker timed out after waiting %s for server.", timeout)
}
// BuildImg describes a build image.
type BuildImg struct {
Path, Tag string
}
// ParallelBuild runs multiple docker builds at the same time.
//
// Params:
// -images ([]BuildImg): Images to build
// -alwaysFetch (bool): Default false. If set to true, this will always fetch
// the Docker image even if it already exists in the registry.
//
// Returns:
//
// - Waiter: A *sync.WaitGroup that is waiting for the docker downloads to finish.
//
// Context:
//
// This puts 'ParallelBuild.failN" (int) into the context to indicate how many failures
// occurred during fetches.
func ParallelBuild(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
images := p.Get("images", []BuildImg{}).([]BuildImg)
var wg sync.WaitGroup
var m sync.Mutex
var fails int
for _, img := range images {
img := img
// HACK: ensure "docker build" is serialized by allowing only one entry in
// the WaitGroup. This works around the "simultaneous docker pull" bug.
wg.Wait()
wg.Add(1)
safely.GoDo(c, func() {
log.Infof(c, "Starting build for %s (tag: %s)", img.Path, img.Tag)
if _, err := buildImg(c, img.Path, img.Tag); err != nil {
log.Errf(c, "Failed to build docker image: %s", err)
m.Lock()
fails++
m.Unlock()
}
wg.Done()
})
}
// Number of failures.
c.Put("ParallelBuild.failN", fails)
return &wg, nil
}
// Waiter describes a thing that can wait.
//
// It does not bring you food. I should know. I tried.
type Waiter interface {
Wait()
}
// Wait waits for a sync.WaitGroup to finish.
//
// Params:
// - wg (Waiter): The thing to wait for.
// - msg (string): The message to print when done. If this is empty, nothing is sent.
// - waiting (string): String to tell what we're waiting for. If empty, nothing is displayed.
// - failures (int): The number of failures that occurred while waiting.
//
// Returns:
// Nothing.
func Wait(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
ok, missing := p.RequiresValue("wg")
if !ok {
return nil, &cookoo.FatalError{"Missing required fields: " + strings.Join(missing, ", ")}
}
wg := p.Get("wg", nil).(Waiter)
msg := p.Get("msg", "").(string)
fails := p.Get("failures", 0).(int)
waitmsg := p.Get("waiting", "").(string)
if len(waitmsg) > 0 {
log.Info(c, waitmsg)
}
wg.Wait()
if len(msg) > 0 {
log.Info(c, msg)
}
if fails > 0 {
return nil, fmt.Errorf("There were %d failures while waiting.", fails)
}
return nil, nil
}
// BuildImage builds a docker image.
//
// Essentially, this executes:
// docker build -t TAG PATH
//
// Params:
// - path (string): The path to the image. REQUIRED
// - tag (string): The tag to build.
func BuildImage(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
path := p.Get("path", "").(string)
tag := p.Get("tag", "").(string)
log.Infof(c, "Building docker image %s (tag: %s)", path, tag)
return buildImg(c, path, tag)
}
func buildImg(c cookoo.Context, path, tag string) ([]byte, error) {
dargs := []string{"build"}
if len(tag) > 0 {
dargs = append(dargs, "-t", tag)
}
dargs = append(dargs, path)
out, err := exec.Command("docker", dargs...).CombinedOutput()
if len(out) > 0 {
log.Infof(c, "Docker: %s", out)
}
return out, err
}
// Push pushes an image to the registry.
//
// This finds the appropriate registry by looking it up in etcd.
//
// Params:
// - client (etcd.Getter): Client to do etcd lookups.
// - tag (string): Tag to push.
//
// Returns:
//
func Push(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
// docker tag deis/slugrunner:lastest HOST:PORT/deis/slugrunner:latest
// docker push HOST:PORT/deis/slugrunner:latest
client := p.Get("client", nil).(etcd.Getter)
host, err := client.Get("/deis/registry/host", false, false)
if err != nil || host.Node == nil {
return nil, err
}
port, err := client.Get("/deis/registry/port", false, false)
if err != nil || host.Node == nil {
return nil, err
}
registry := host.Node.Value + ":" + port.Node.Value
tag := p.Get("tag", "").(string)
log.Infof(c, "Pushing %s to %s. This may take some time.", tag, registry)
rem := path.Join(registry, tag)
out, err := exec.Command("docker", "tag", "-f", tag, rem).CombinedOutput()
if err != nil {
log.Warnf(c, "Failed to tag %s on host %s: %s (%s)", tag, rem, err, out)
}
out, err = exec.Command("docker", "-D", "push", rem).CombinedOutput()
if err != nil {
log.Warnf(c, "Failed to push %s to host %s: %s (%s)", tag, rem, err, out)
return nil, err
}
log.Infof(c, "Finished pushing %s to %s.", tag, registry)
return nil, nil
}
/*
* This function only works for very simple docker files that do not have
* local resources.
* Need to suck in all of the files in ADD directives, too.
*/
// build takes a Dockerfile and builds an image.
func build(c cookoo.Context, path, tag string, client *docli.Client) error {
dfile := filepath.Join(path, "Dockerfile")
// Stat the file
info, err := os.Stat(dfile)
if err != nil {
return fmt.Errorf("Dockerfile stat: %s", err)
}
file, err := os.Open(dfile)
if err != nil {
return fmt.Errorf("Dockerfile open: %s", err)
}
defer file.Close()
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
tw.WriteHeader(&tar.Header{
Name: "Dockerfile",
Size: info.Size(),
ModTime: info.ModTime(),
})
io.Copy(tw, file)
if err := tw.Close(); err != nil {
return fmt.Errorf("Dockerfile tar: %s", err)
}
options := docli.BuildImageOptions{
Name: tag,
InputStream: &buf,
OutputStream: os.Stdout,
}
return client.BuildImage(options)
}