-
Notifications
You must be signed in to change notification settings - Fork 6
/
docker.go
118 lines (103 loc) · 2.46 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
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"sync"
"time"
"github.com/fsouza/go-dockerclient"
"golang.org/x/net/context"
)
func getDockerClient() (*docker.Client, error) {
endpoint := "unix:///var/run/docker.sock"
return docker.NewClient(endpoint)
}
func pullDockerImage(client *docker.Client, image, tag string, auth docker.AuthConfiguration) (result string, err error) {
var wg sync.WaitGroup
wg.Add(2) // Wait for the puller and collector goroutines.
// A pipe connecting the puller and the collector.
r, w := io.Pipe()
// Pull the image.
go func() {
defer wg.Done()
defer w.Close()
err = client.PullImage(
docker.PullImageOptions{
Repository: image,
Tag: tag,
OutputStream: w,
RawJSONStream: false,
InactivityTimeout: 30 * time.Second,
Context: context.Background(),
},
auth,
)
}()
// Collect the output.
go func() {
defer wg.Done()
defer r.Close()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
result = scanner.Text()
}
if err == nil {
err = scanner.Err()
}
}()
// Wait for the puller and collector to finish.
wg.Wait()
return
}
func runDockerCommand(client *docker.Client, image, tag string, args, env []string) (exit int, output []byte, err error) {
// Set the timeout.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
var fullImage string = image
if tag != "" {
fullImage += fmt.Sprintf(":%s", tag)
}
// Create the container.
var cont *docker.Container
if cont, err = client.CreateContainer(docker.CreateContainerOptions{
"",
&docker.Config{
Image: fullImage,
Cmd: args,
Env: env,
},
&docker.HostConfig{
AutoRemove: true,
},
nil,
ctx,
}); err != nil {
return
}
// Capture all output from the container. This blocks so run it in parallel
// to enable us to start the container.
var buf bytes.Buffer
go func() {
if err = client.AttachToContainer(docker.AttachToContainerOptions{
Container: cont.ID,
OutputStream: &buf,
Logs: true,
Stdout: true,
Stderr: true,
Stream: true,
}); err != nil {
return
}
}()
// Start the container and begin capturing the output.
if err = client.StartContainer(cont.ID, nil); err != nil {
return
}
// Wait for the container to exit, by which time all output should be complete.
if exit, err = client.WaitContainer(cont.ID); err != nil {
return
}
output = buf.Bytes()
return
}