forked from flynn/flynn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker_test.go
346 lines (301 loc) · 8.51 KB
/
docker_test.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
package main
import (
"errors"
"strings"
"sync"
"testing"
"github.com/flynn/flynn/Godeps/_workspace/src/github.com/fsouza/go-dockerclient"
"github.com/flynn/flynn/Godeps/_workspace/src/github.com/technoweenie/grohl"
"github.com/flynn/flynn/host/ports"
"github.com/flynn/flynn/host/types"
)
type nullLogger struct{}
func (nullLogger) Log(grohl.Data) error { return nil }
func init() { grohl.SetLogger(nullLogger{}) }
func NewFakeDockerClient() *fakeDockerClient {
return &fakeDockerClient{
listeners: make(map[chan<- *docker.APIEvents]struct{}),
}
}
type fakeDockerClient struct {
createErr error
startErr error
pullErr error
created docker.CreateContainerOptions
pulled string
started bool
hostConf *docker.HostConfig
listeners map[chan<- *docker.APIEvents]struct{}
mtx sync.RWMutex
newListener chan struct{}
}
func (c *fakeDockerClient) CreateContainer(config docker.CreateContainerOptions) (*docker.Container, error) {
if c.createErr != nil {
err := c.createErr
c.createErr = nil
return nil, err
}
c.created = config
return &docker.Container{ID: "asdf"}, nil
}
func (c *fakeDockerClient) StartContainer(id string, config *docker.HostConfig) error {
if id != "asdf" {
return errors.New("Invalid ID")
}
if c.startErr != nil {
return c.startErr
}
c.started = true
c.hostConf = config
return nil
}
func (c *fakeDockerClient) InspectContainer(id string) (*docker.Container, error) {
if id == "1" {
return &docker.Container{State: docker.State{ExitCode: 1}}, nil
}
container := &docker.Container{Volumes: make(map[string]string), NetworkSettings: &docker.NetworkSettings{}}
for v := range c.created.Config.Volumes {
container.Volumes[v] = "/var/lib/docker/vfs/dir/" + strings.Replace(v, "/", "-", -1)
}
return container, nil
}
func (c *fakeDockerClient) PullImage(opts docker.PullImageOptions, auth docker.AuthConfiguration) error {
if c.pullErr != nil {
return c.pullErr
}
c.pulled = opts.Repository
return nil
}
func (c *fakeDockerClient) AddEventListener(ch chan<- *docker.APIEvents) error {
c.mtx.Lock()
defer c.mtx.Unlock()
c.listeners[ch] = struct{}{}
if c.newListener != nil {
c.newListener <- struct{}{}
}
return nil
}
func (c *fakeDockerClient) RemoveEventListener(ch chan *docker.APIEvents) error {
c.mtx.Lock()
delete(c.listeners, ch)
c.mtx.Unlock()
return nil
}
func (c *fakeDockerClient) sendEvent(data *docker.APIEvents) {
c.mtx.RLock()
defer c.mtx.RUnlock()
for ch := range c.listeners {
ch <- data
}
}
func (c *fakeDockerClient) closeListeners() {
c.mtx.Lock()
defer c.mtx.Unlock()
for ch := range c.listeners {
close(ch)
}
}
func (c *fakeDockerClient) StopContainer(string, uint) error {
return nil
}
func (c *fakeDockerClient) ResizeContainerTTY(string, int, int) error {
return nil
}
func (c *fakeDockerClient) AttachToContainer(docker.AttachToContainerOptions) error {
return nil
}
func (c *fakeDockerClient) KillContainer(docker.KillContainerOptions) error {
return nil
}
func (c *fakeDockerClient) ListContainers(docker.ListContainersOptions) ([]docker.APIContainers, error) {
return nil, nil
}
func testDockerRun(job *host.Job, t *testing.T) (*State, *fakeDockerClient) {
client := NewFakeDockerClient()
return testDockerRunWithOpts(job, "", client, t), client
}
func testDockerRunWithOpts(job *host.Job, bindAddr string, client *fakeDockerClient, t *testing.T) *State {
if job.Artifact.URI == "" {
job.Artifact = host.Artifact{Type: "docker", URI: "https://registry.hub.docker.com/test/foo"}
}
if client == nil {
client = NewFakeDockerClient()
}
state, err := dockerRunWithOpts(job, bindAddr, client)
if err != nil {
t.Errorf("run error: %s", err)
}
if client.created.Config == nil {
t.Error("job not created")
}
if !client.started {
t.Error("job not started")
}
sjob := state.GetJob("a")
if sjob == nil || sjob.StartedAt.IsZero() || sjob.Status != host.StatusRunning || sjob.ContainerID != "asdf" {
t.Error("incorrect state")
}
return state
}
func testProcessWithError(job *host.Job, client *fakeDockerClient, expected error, t *testing.T) {
if job.Artifact.URI == "" {
job.Artifact = host.Artifact{Type: "docker", URI: "https://registry.hub.docker.com/test/foo"}
}
_, err := dockerRunWithOpts(job, "", client)
if err != expected {
t.Errorf("expected %s, got %s", expected, err)
}
}
func dockerRunWithOpts(job *host.Job, bindAddr string, client *fakeDockerClient) (*State, error) {
state := NewState("")
err := (&DockerBackend{
bindAddr: bindAddr,
docker: client,
state: state,
ports: map[string]*ports.Allocator{"tcp": ports.NewAllocator(500, 550)},
}).Run(job)
return state, err
}
func TestProcessJob(t *testing.T) {
testDockerRun(&host.Job{ID: "a"}, t)
}
func TestProcessJobWithImplicitPorts(t *testing.T) {
job := &host.Job{
ID: "a",
Config: host.ContainerConfig{
Ports: []host.Port{{Proto: "tcp"}, {Proto: "tcp"}},
},
}
_, client := testDockerRun(job, t)
if len(client.created.Config.Env) == 0 || !sliceHasString(client.created.Config.Env, "PORT=500") {
t.Fatal("PORT env not set")
}
if !sliceHasString(client.created.Config.Env, "PORT_0=500") {
t.Error("PORT_0 env not set")
}
if !sliceHasString(client.created.Config.Env, "PORT_1=501") {
t.Error("PORT_1 env not set")
}
if _, ok := client.created.Config.ExposedPorts["500/tcp"]; !ok {
t.Error("exposed port 500 not set")
}
if _, ok := client.created.Config.ExposedPorts["501/tcp"]; !ok {
t.Error("exposed port 501 not set")
}
if b := client.hostConf.PortBindings["500/tcp"]; len(b) == 0 || b[0].HostPort != "500" {
t.Error("port 500 binding not set")
}
if b := client.hostConf.PortBindings["501/tcp"]; len(b) == 0 || b[0].HostPort != "501" {
t.Error("port 501 binding not set")
}
}
func TestProcessWithImplicitPortsAndIP(t *testing.T) {
job := &host.Job{
ID: "a",
Config: host.ContainerConfig{
Ports: []host.Port{{Proto: "tcp"}, {Proto: "tcp"}},
},
}
client := NewFakeDockerClient()
testDockerRunWithOpts(job, "127.0.42.1", client, t)
b := client.hostConf.PortBindings["500/tcp"]
if b[0].HostIp != "127.0.42.1" {
t.Error("host ip not 127.0.42.1")
}
if len(b) == 0 || b[0].HostPort != "500" {
t.Error("port 8080 binding not set")
}
}
func sliceHasString(slice []string, str string) bool {
for _, s := range slice {
if s == str {
return true
}
}
return false
}
func TestProcessWithPull(t *testing.T) {
job := &host.Job{ID: "a"}
client := NewFakeDockerClient()
client.createErr = docker.ErrNoSuchImage
testDockerRunWithOpts(job, "", client, t)
if client.pulled != "test/foo" {
t.Error("image not pulled")
}
}
func TestProcessWithCreateFailure(t *testing.T) {
job := &host.Job{ID: "a"}
err := errors.New("undefined failure")
client := NewFakeDockerClient()
client.createErr = err
testProcessWithError(job, client, err, t)
}
func TestProcessWithPullFailure(t *testing.T) {
job := &host.Job{ID: "a"}
err := errors.New("undefined failure")
client := NewFakeDockerClient()
client.createErr = docker.ErrNoSuchImage
client.pullErr = err
testProcessWithError(job, client, err, t)
}
func TestProcessWithStartFailure(t *testing.T) {
job := &host.Job{ID: "a"}
err := errors.New("undefined failure")
client := NewFakeDockerClient()
client.startErr = err
testProcessWithError(job, client, err, t)
}
type schedulerSyncClient struct {
removeErr error
removed []string
}
func (s *schedulerSyncClient) RemoveJobs(jobs []string) error {
if s.removeErr != nil {
return s.removeErr
}
s.removed = append(s.removed, jobs...)
return nil
}
func TestSyncScheduler(t *testing.T) {
events := make(chan host.Event)
client := &schedulerSyncClient{}
done := make(chan struct{})
go func() {
syncScheduler(client, events)
close(done)
}()
events <- host.Event{Event: "stop", JobID: "a"}
close(events)
<-done
if len(client.removed) != 1 && client.removed[0] != "a" {
t.Error("job not removed")
}
}
func TestStreamEvents(t *testing.T) {
client := NewFakeDockerClient()
client.newListener = make(chan struct{})
state := NewState("")
state.AddJob(&host.Job{ID: "a"})
state.SetContainerID("a", "1")
state.SetStatusRunning("a")
done := make(chan struct{})
go func() {
(&DockerBackend{
docker: client,
state: state,
ports: map[string]*ports.Allocator{"tcp": ports.NewAllocator(500, 550)},
}).handleEvents()
close(done)
}()
<-client.newListener
client.sendEvent(&docker.APIEvents{Status: "die", ID: "1"})
client.closeListeners()
<-done
job := state.GetJob("a")
if job.Status != host.StatusCrashed {
t.Error("incorrect status")
}
if job.ExitStatus != 1 {
t.Error("incorrect exit status")
}
}