forked from hashicorp/packer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver_docker.go
381 lines (314 loc) · 8.4 KB
/
driver_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
package docker
import (
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
"sync"
"github.com/hashicorp/go-version"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/template/interpolate"
)
type DockerDriver struct {
Ui packer.Ui
Ctx *interpolate.Context
l sync.Mutex
}
func (d *DockerDriver) DeleteImage(id string) error {
var stderr bytes.Buffer
cmd := exec.Command("docker", "rmi", id)
cmd.Stderr = &stderr
log.Printf("Deleting image: %s", id)
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
err = fmt.Errorf("Error deleting image: %s\nStderr: %s",
err, stderr.String())
return err
}
return nil
}
func (d *DockerDriver) Commit(id string, author string, changes []string, message string) (string, error) {
var stdout bytes.Buffer
var stderr bytes.Buffer
args := []string{"commit"}
if author != "" {
args = append(args, "--author", author)
}
for _, change := range changes {
args = append(args, "--change", change)
}
if message != "" {
args = append(args, "--message", message)
}
args = append(args, id)
log.Printf("Committing container with args: %v", args)
cmd := exec.Command("docker", args...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return "", err
}
if err := cmd.Wait(); err != nil {
err = fmt.Errorf("Error committing container: %s\nStderr: %s",
err, stderr.String())
return "", err
}
return strings.TrimSpace(stdout.String()), nil
}
func (d *DockerDriver) Export(id string, dst io.Writer) error {
var stderr bytes.Buffer
cmd := exec.Command("docker", "export", id)
cmd.Stdout = dst
cmd.Stderr = &stderr
log.Printf("Exporting container: %s", id)
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
err = fmt.Errorf("Error exporting: %s\nStderr: %s",
err, stderr.String())
return err
}
return nil
}
func (d *DockerDriver) Import(path string, repo string) (string, error) {
var stdout, stderr bytes.Buffer
cmd := exec.Command("docker", "import", "-", repo)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
stdin, err := cmd.StdinPipe()
if err != nil {
return "", err
}
// There should be only one artifact of the Docker builder
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
if err := cmd.Start(); err != nil {
return "", err
}
go func() {
defer stdin.Close()
io.Copy(stdin, file)
}()
if err := cmd.Wait(); err != nil {
return "", fmt.Errorf("Error importing container: %s\n\nStderr: %s", err, stderr.String())
}
return strings.TrimSpace(stdout.String()), nil
}
func (d *DockerDriver) IPAddress(id string) (string, error) {
var stderr, stdout bytes.Buffer
cmd := exec.Command(
"docker",
"inspect",
"--format",
"{{ .NetworkSettings.IPAddress }}",
id)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("Error: %s\n\nStderr: %s", err, stderr.String())
}
return strings.TrimSpace(stdout.String()), nil
}
func (d *DockerDriver) Login(repo, user, pass string) error {
d.l.Lock()
version_running, err := d.Version()
if err != nil {
d.l.Unlock()
return err
}
// Version 17.07.0 of Docker adds support for the new
// `--password-stdin` option which can be used to offer
// password via the standard input, rather than passing
// the password and/or token using a command line switch.
constraint, err := version.NewConstraint(">= 17.07.0")
if err != nil {
d.l.Unlock()
return err
}
cmd := exec.Command("docker")
cmd.Args = append(cmd.Args, "login")
if user != "" {
cmd.Args = append(cmd.Args, "-u", user)
}
if pass != "" {
if constraint.Check(version_running) {
cmd.Args = append(cmd.Args, "--password-stdin")
stdin, err := cmd.StdinPipe()
if err != nil {
d.l.Unlock()
return err
}
io.WriteString(stdin, pass)
stdin.Close()
} else {
cmd.Args = append(cmd.Args, "-p", pass)
}
}
if repo != "" {
cmd.Args = append(cmd.Args, repo)
}
err = runAndStream(cmd, d.Ui)
if err != nil {
d.l.Unlock()
return err
}
return nil
}
func (d *DockerDriver) Logout(repo string) error {
args := []string{"logout"}
if repo != "" {
args = append(args, repo)
}
cmd := exec.Command("docker", args...)
err := runAndStream(cmd, d.Ui)
d.l.Unlock()
return err
}
func (d *DockerDriver) Pull(image string) error {
cmd := exec.Command("docker", "pull", image)
return runAndStream(cmd, d.Ui)
}
func (d *DockerDriver) Push(name string) error {
cmd := exec.Command("docker", "push", name)
return runAndStream(cmd, d.Ui)
}
func (d *DockerDriver) SaveImage(id string, dst io.Writer) error {
var stderr bytes.Buffer
cmd := exec.Command("docker", "save", id)
cmd.Stdout = dst
cmd.Stderr = &stderr
log.Printf("Exporting image: %s", id)
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
err = fmt.Errorf("Error exporting: %s\nStderr: %s",
err, stderr.String())
return err
}
return nil
}
func (d *DockerDriver) StartContainer(config *ContainerConfig) (string, error) {
// Build up the template data
var tplData startContainerTemplate
tplData.Image = config.Image
ctx := *d.Ctx
ctx.Data = &tplData
// Args that we're going to pass to Docker
args := []string{"run"}
if config.Privileged {
args = append(args, "--privileged")
}
for host, guest := range config.Volumes {
if runtime.GOOS == "windows" {
// docker-toolbox can't handle the normal C:\filepath format in CLI
host = strings.Replace(host, "\\", "/", -1)
host = strings.Replace(host, "C:/", "/c/", 1)
}
args = append(args, "-v", fmt.Sprintf("%s:%s", host, guest))
}
for _, v := range config.RunCommand {
v, err := interpolate.Render(v, &ctx)
if err != nil {
return "", err
}
args = append(args, v)
}
d.Ui.Message(fmt.Sprintf(
"Run command: docker %s", strings.Join(args, " ")))
// Start the container
var stdout, stderr bytes.Buffer
cmd := exec.Command("docker", args...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
log.Printf("Starting container with args: %v", args)
if err := cmd.Start(); err != nil {
return "", err
}
log.Println("Waiting for container to finish starting")
if err := cmd.Wait(); err != nil {
if _, ok := err.(*exec.ExitError); ok {
err = fmt.Errorf("Docker exited with a non-zero exit status.\nStderr: %s",
stderr.String())
}
return "", err
}
// Capture the container ID, which is alone on stdout
return strings.TrimSpace(stdout.String()), nil
}
func (d *DockerDriver) StopContainer(id string) error {
if err := exec.Command("docker", "kill", id).Run(); err != nil {
return err
}
return exec.Command("docker", "rm", id).Run()
}
func (d *DockerDriver) TagImage(id string, repo string, force bool) error {
args := []string{"tag"}
// detect running docker version before tagging
// flag `force` for docker tagging was removed after Docker 1.12.0
// to keep its backward compatibility, we are not going to remove `force`
// option, but to ignore it when Docker version >= 1.12.0
//
// for more detail, please refer to the following links:
// - https://docs.docker.com/engine/deprecated/#/f-flag-on-docker-tag
// - https://github.com/docker/docker/pull/23090
version_running, err := d.Version()
if err != nil {
return err
}
version_deprecated, err := version.NewVersion("1.12.0")
if err != nil {
// should never reach this line
return err
}
if force {
if version_running.LessThan(version_deprecated) {
args = append(args, "-f")
} else {
// do nothing if Docker version >= 1.12.0
log.Printf("[WARN] option: \"force\" will be ignored here")
log.Printf("since it was removed after Docker 1.12.0 released")
}
}
args = append(args, id, repo)
var stderr bytes.Buffer
cmd := exec.Command("docker", args...)
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
err = fmt.Errorf("Error tagging image: %s\nStderr: %s",
err, stderr.String())
return err
}
return nil
}
func (d *DockerDriver) Verify() error {
if _, err := exec.LookPath("docker"); err != nil {
return err
}
return nil
}
func (d *DockerDriver) Version() (*version.Version, error) {
output, err := exec.Command("docker", "-v").Output()
if err != nil {
return nil, err
}
match := regexp.MustCompile(version.VersionRegexpRaw).FindSubmatch(output)
if match == nil {
return nil, fmt.Errorf("unknown version: %s", output)
}
return version.NewVersion(string(match[0]))
}