This repository has been archived by the owner on Jun 28, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 326
/
docker.go
254 lines (219 loc) · 5.64 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
// Package testing is used in driver tests.
package testing
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"math/rand"
"strconv"
"strings"
"testing"
"time"
dockertypes "github.com/docker/docker/api/types"
dockercontainer "github.com/docker/docker/api/types/container"
dockernetwork "github.com/docker/docker/api/types/network"
dockerclient "github.com/docker/docker/client"
)
func NewDockerContainer(t testing.TB, image string, env []string, cmd []string) (*DockerContainer, error) {
c, err := dockerclient.NewEnvClient()
if err != nil {
return nil, err
}
if cmd == nil {
cmd = make([]string, 0)
}
contr := &DockerContainer{
t: t,
client: c,
ImageName: image,
ENV: env,
Cmd: cmd,
}
if err := contr.PullImage(); err != nil {
return nil, err
}
if err := contr.Start(); err != nil {
return nil, err
}
return contr, nil
}
// DockerContainer implements Instance interface
type DockerContainer struct {
t testing.TB
client *dockerclient.Client
ImageName string
ENV []string
Cmd []string
ContainerId string
ContainerName string
ContainerJSON dockertypes.ContainerJSON
containerInspected bool
keepForDebugging bool
}
func (d *DockerContainer) PullImage() error {
d.t.Logf("Docker: Pull image %v", d.ImageName)
r, err := d.client.ImagePull(context.Background(), d.ImageName, dockertypes.ImagePullOptions{})
if err != nil {
return err
}
defer r.Close()
// read output and log relevant lines
bf := bufio.NewScanner(r)
for bf.Scan() {
var resp dockerImagePullOutput
if err := json.Unmarshal(bf.Bytes(), &resp); err != nil {
return err
}
if strings.HasPrefix(resp.Status, "Status: ") {
d.t.Logf("Docker: %v", resp.Status)
}
}
return bf.Err()
}
func (d *DockerContainer) Start() error {
containerName := fmt.Sprintf("migrate_test_%v", pseudoRandStr(10))
// create container first
resp, err := d.client.ContainerCreate(context.Background(),
&dockercontainer.Config{
Image: d.ImageName,
Labels: map[string]string{"migrate_test": "true"},
Env: d.ENV,
Cmd: d.Cmd,
},
&dockercontainer.HostConfig{
PublishAllPorts: true,
},
&dockernetwork.NetworkingConfig{},
containerName)
if err != nil {
return err
}
d.ContainerId = resp.ID
d.ContainerName = containerName
// then start it
if err := d.client.ContainerStart(context.Background(), resp.ID, dockertypes.ContainerStartOptions{}); err != nil {
return err
}
d.t.Logf("Docker: Started container %v (%v) for image %v listening at %v:%v", resp.ID[0:12], containerName, d.ImageName, d.Host(), d.Port())
for _, v := range resp.Warnings {
d.t.Logf("Docker: Warning: %v", v)
}
return nil
}
func (d *DockerContainer) KeepForDebugging() {
d.keepForDebugging = true
}
func (d *DockerContainer) Remove() error {
if d.keepForDebugging {
return nil
}
if len(d.ContainerId) == 0 {
return fmt.Errorf("missing containerId")
}
if err := d.client.ContainerRemove(context.Background(), d.ContainerId,
dockertypes.ContainerRemoveOptions{
Force: true,
}); err != nil {
d.t.Log(err)
return err
}
d.t.Logf("Docker: Removed %v", d.ContainerName)
return nil
}
func (d *DockerContainer) Inspect() error {
if len(d.ContainerId) == 0 {
return fmt.Errorf("missing containerId")
}
resp, err := d.client.ContainerInspect(context.Background(), d.ContainerId)
if err != nil {
return err
}
d.ContainerJSON = resp
d.containerInspected = true
return nil
}
func (d *DockerContainer) Logs() (io.ReadCloser, error) {
if len(d.ContainerId) == 0 {
return nil, fmt.Errorf("missing containerId")
}
return d.client.ContainerLogs(context.Background(), d.ContainerId, dockertypes.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
})
}
func (d *DockerContainer) portMapping(selectFirst bool, cPort int) (containerPort uint, hostIP string, hostPort uint, err error) {
if !d.containerInspected {
if err := d.Inspect(); err != nil {
d.t.Fatal(err)
}
}
for port, bindings := range d.ContainerJSON.NetworkSettings.Ports {
if !selectFirst && port.Int() != cPort {
// Skip ahead until we find the port we want
continue
}
for _, binding := range bindings {
hostPortUint, err := strconv.ParseUint(binding.HostPort, 10, 64)
if err != nil {
return 0, "", 0, err
}
return uint(port.Int()), binding.HostIP, uint(hostPortUint), nil
}
}
if selectFirst {
return 0, "", 0, fmt.Errorf("no port binding")
} else {
return 0, "", 0, fmt.Errorf("specified port not bound")
}
}
func (d *DockerContainer) Host() string {
_, hostIP, _, err := d.portMapping(true, -1)
if err != nil {
d.t.Fatal(err)
}
if hostIP == "0.0.0.0" {
return "127.0.0.1"
} else {
return hostIP
}
}
func (d *DockerContainer) Port() uint {
_, _, port, err := d.portMapping(true, -1)
if err != nil {
d.t.Fatal(err)
}
return port
}
func (d *DockerContainer) PortFor(cPort int) uint {
_, _, port, err := d.portMapping(false, cPort)
if err != nil {
d.t.Fatal(err)
}
return port
}
func (d *DockerContainer) NetworkSettings() dockertypes.NetworkSettings {
netSettings := d.ContainerJSON.NetworkSettings
return *netSettings
}
type dockerImagePullOutput struct {
Status string `json:"status"`
ProgressDetails struct {
Current int `json:"current"`
Total int `json:"total"`
} `json:"progressDetail"`
Id string `json:"id"`
Progress string `json:"progress"`
}
func init() {
rand.Seed(time.Now().UnixNano())
}
func pseudoRandStr(n int) string {
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz0123456789")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}