-
Notifications
You must be signed in to change notification settings - Fork 8
/
executor_test.go
449 lines (365 loc) · 11.7 KB
/
executor_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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package main
import (
"bytes"
"errors"
"io"
"io/ioutil"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/Nitro/sidecar-executor/container"
"github.com/fsouza/go-dockerclient"
mesos "github.com/mesos/mesos-go/api/v1/lib"
"github.com/pborman/uuid"
"github.com/relistan/go-director"
log "github.com/sirupsen/logrus"
. "github.com/smartystreets/goconvey/convey"
)
// mockDriver ---
type mockDriver struct {
lastStatus mesos.TaskStatus
}
func (m *mockDriver) NewStatus(id mesos.TaskID) mesos.TaskStatus {
return mesos.TaskStatus{
TaskID: id,
Source: mesos.SOURCE_EXECUTOR.Enum(),
ExecutorID: &mesos.ExecutorID{Value: "Beowulf-executor"},
UUID: []byte(uuid.NewRandom()),
}
}
func (m *mockDriver) SendStatusUpdate(status mesos.TaskStatus) error {
m.lastStatus = status
return nil
}
func (m *mockDriver) Stop() {}
func (m *mockDriver) Run() error { return nil }
// mockFetcher ---
type mockFetcher struct {
ShouldFail bool
ShouldError bool
ShouldBadJson bool
callCount int
}
func (m *mockFetcher) Get(url string) (*http.Response, error) {
m.callCount += 1
if m.ShouldBadJson {
return m.badJson()
}
if m.ShouldError {
return nil, errors.New("OMG something went horribly wrong!")
}
// Mesos master
if strings.Contains(url, "mesos-master") {
return httpResponse(200,
`{"slaves":[{"hostname": "bede"},{"hostname":"chaucer"}]}`,
), nil
}
// Mesos worker
if strings.Contains(url, "mesos-worker") {
return httpResponse(200,
`{"master_hostname":"mesos-master"}`,
), nil
}
// Sidecar
if m.ShouldFail {
return m.failedRequest()
} else {
return m.successRequest()
}
}
func (m *mockFetcher) Post(url string, contentType string, body io.Reader) (*http.Response, error) {
return nil, nil
}
func (m *mockFetcher) successRequest() (*http.Response, error) {
return httpResponse(200, `
{
"Servers": {
"roncevalles": {
"Services": {
"deadbeef0010": {
"ID": "deadbeef0010",
"Status": 0
}
}
}
}
}
`), nil
}
func (m *mockFetcher) badJson() (*http.Response, error) {
return httpResponse(200, `OMG invalid JSON`), nil
}
func (m *mockFetcher) failedRequest() (*http.Response, error) {
return httpResponse(500, `
{
"Servers": {
"roncevalles": {
"Services": {
"deadbeef0010": {
"ID": "deadbeef0010",
"Status": 1
},
"running00010": {
"ID": "running00010",
"Status": 1
}
}
}
}
}
`), nil
}
func httpResponse(status int, bodyStr string) *http.Response {
body := bytes.NewBuffer([]byte(bodyStr))
return &http.Response{
Status: strconv.Itoa(status),
StatusCode: status,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Body: ioutil.NopCloser(body),
ContentLength: int64(body.Len()),
}
}
func Test_sidecarStatus(t *testing.T) {
Convey("When handling Sidecar status", t, func() {
log.SetOutput(ioutil.Discard) // Don't show logged errors/warnings/etc
os.Setenv("TASK_HOST", "roncevalles")
fetcher := &mockFetcher{}
client := &container.MockDockerClient{}
exec := newSidecarExecutor(client, &docker.AuthConfiguration{}, Config{})
exec.fetcher = fetcher
Convey("return healthy on HTTP request errors", func() {
fetcher.ShouldError = true
So(exec.sidecarStatus("deadbeef0010"), ShouldBeNil)
So(exec.failCount, ShouldEqual, 0)
})
Convey("retries as expected", func() {
fetcher.ShouldError = true
exec.config.SidecarRetryCount = 5
So(exec.sidecarStatus("deadbeef0010"), ShouldBeNil)
So(fetcher.callCount, ShouldEqual, 6) // 1 try + (5 retries)
})
Convey("healthy on JSON parse errors", func() {
fetcher.ShouldBadJson = true
So(exec.sidecarStatus("deadbeef0010"), ShouldBeNil)
So(exec.failCount, ShouldEqual, 0)
})
Convey("errors when it can talk to Sidecar and fail count is exceeded", func() {
fetcher.ShouldFail = true
exec.config.SidecarMaxFails = 3
exec.failCount = 3
result := exec.sidecarStatus("deadbeef0010")
So(result, ShouldNotBeNil)
So(result.Error(), ShouldContainSubstring, "deadbeef0010 failing task!")
So(exec.failCount, ShouldEqual, 0) // Gets reset!
})
Convey("healthy when it can talk to Sidecar and fail count is below limit", func() {
fetcher.ShouldFail = true
exec.config.SidecarMaxFails = 3
exec.failCount = 1
result := exec.sidecarStatus("deadbeef0010")
So(result, ShouldBeNil)
So(exec.failCount, ShouldEqual, 2)
})
Convey("resets failCount on first healthy response", func() {
fetcher.ShouldFail = true
exec.config.SidecarMaxFails = 3
exec.failCount = 1
result := exec.sidecarStatus("deadbeef0010")
So(result, ShouldBeNil)
So(exec.failCount, ShouldEqual, 2)
// Get a healthy response, reset the counter
fetcher.ShouldFail = false
result = exec.sidecarStatus("deadbeef0010")
So(result, ShouldBeNil)
So(exec.failCount, ShouldEqual, 0)
})
Convey("healthy when the host doesn't exist in Sidecar", func() {
os.Setenv("TASK_HOST", "zaragoza")
fetcher.ShouldError = false
So(exec.sidecarStatus("deadbeef0010"), ShouldBeNil)
So(exec.failCount, ShouldEqual, 0)
})
})
}
func Test_logConfig(t *testing.T) {
// We want to make sure we don't forget to print settings when they get added
Convey("Logs all the config settings", t, func() {
output := bytes.NewBuffer([]byte{})
os.Setenv("MESOS_LEGEND", "roncevalles")
config, err := initConfig()
So(err, ShouldBeNil)
log.SetOutput(output) // Capture the output
logConfig(config)
v := reflect.ValueOf(config)
for i := 0; i < v.NumField(); i++ {
So(output.String(), ShouldContainSubstring, v.Type().Field(i).Name)
}
So(output.String(), ShouldContainSubstring, "roncevalles")
})
}
func Test_logTaskEnv(t *testing.T) {
Convey("Logging Docker task env vars", t, func() {
output := bytes.NewBuffer([]byte{})
log.SetOutput(output) // Capture the output
fetcher := &mockFetcher{}
client := &container.MockDockerClient{}
exec := newSidecarExecutor(client, &docker.AuthConfiguration{}, Config{})
exec.fetcher = fetcher
taskInfo := &mesos.TaskInfo{
TaskID: mesos.TaskID{Value: "my-task-id"},
Container: &mesos.ContainerInfo{
Docker: &mesos.ContainerInfo_DockerInfo{
Parameters: []mesos.Parameter{
{
Key: "env",
Value: "BOCACCIO=author",
},
},
},
},
}
Convey("dumps the vars it finds", func() {
exec.logTaskEnv(taskInfo, container.LabelsForTask(taskInfo), []string{})
So(output.String(), ShouldContainSubstring, "--------")
So(output.String(), ShouldContainSubstring, "BOCACCIO=author")
})
Convey("has environment and service name if defined", func() {
taskInfo.Container.Docker.Parameters = []mesos.Parameter{
{
Key: "label",
Value: "ServiceName=test-service",
},
{
Key: "label",
Value: "Environment=dev",
},
}
exec.logTaskEnv(taskInfo, container.LabelsForTask(taskInfo), []string{})
So(output.String(), ShouldContainSubstring, "SERVICE_NAME=test-service")
So(output.String(), ShouldContainSubstring, "ENVIRONMENT=dev")
})
Convey("leaves environment and service undefined if no labels are set", func() {
taskInfo.Container.Docker.Parameters = []mesos.Parameter{}
exec.logTaskEnv(taskInfo, container.LabelsForTask(taskInfo), []string{})
So(output.String(), ShouldNotContainSubstring, "SERVICE_NAME=")
So(output.String(), ShouldNotContainSubstring, "ENVIRONMENT=")
})
Convey("leaves version unset if it can't be parsed", func() {
taskInfo.Container.Docker.Image = "test-service"
exec.logTaskEnv(taskInfo, container.LabelsForTask(taskInfo), []string{})
So(output.String(), ShouldNotContainSubstring, "SERVICE_VERSION=")
})
Convey("shows added env vars", func() {
exec.logTaskEnv(taskInfo, container.LabelsForTask(taskInfo), []string{"ADDED_VAR=true"})
So(output.String(), ShouldContainSubstring, "ADDED_VAR=")
})
Convey("adds Sidecar seeds", func() {
os.Setenv("MESOS_AGENT_ENDPOINT", "mesos-worker:5050")
exec.config.SeedSidecar = true
addEnvVars := exec.addSidecarSeeds([]string{})
exec.logTaskEnv(taskInfo, container.LabelsForTask(taskInfo), addEnvVars)
So(output.String(), ShouldContainSubstring, "SIDECAR_SEEDS=bede,chaucer")
})
Convey("redacts secrets", func() {
exec.logTaskEnv(taskInfo, container.LabelsForTask(taskInfo), []string{"AWS_SECRET_ACCESS_KEY=1234567890abbacafe12345"})
So(output.String(), ShouldContainSubstring, "AWS_SECRET_ACCESS_KEY=123[REDACTED]acafe...")
})
})
}
func Test_monitorTask(t *testing.T) {
Convey("When monitoring the task", t, func() {
client := &container.MockDockerClient{}
config, err := initConfig()
So(err, ShouldBeNil)
config.SidecarBackoff = time.Duration(0) // Don't wait to start health checking
config.SidecarRetryDelay = time.Duration(0) // Sidecar status should fail if ever checked
// Capture logs
var captured bytes.Buffer
log.SetOutput(&captured)
driver := &mockDriver{}
exec := newSidecarExecutor(client, &docker.AuthConfiguration{}, config)
exec.driver = driver
exec.statusSleepTime = 0
resultChan := make(chan error, 5)
exec.watchLooper = director.NewFreeLooper(1, resultChan)
exec.failCount = exec.config.SidecarMaxFails
os.Setenv("TASK_HOST", "roncevalles")
exec.fetcher = &mockFetcher{
ShouldFail: true,
}
taskInfo := &mesos.TaskInfo{
TaskID: mesos.TaskID{Value: "my-task-id"},
Container: &mesos.ContainerInfo{
Docker: &mesos.ContainerInfo_DockerInfo{
Parameters: []mesos.Parameter{
{
Key: "env",
Value: "BOCACCIO=author",
},
},
},
},
}
client.ListContainersContainers = []docker.APIContainers{
{
ID: "deadbeef0010",
State: "exited",
},
{
ID: "running00010",
State: "running",
},
}
client.Container = &docker.Container{
State: docker.State{
Status: "exited",
},
}
Convey("returns an error when ListContainers fails", func() {
client.ListContainersShouldError = true
exec.monitorTask("deadbeef0010", taskInfo, true)
So(driver.lastStatus.State, ShouldResemble, mesos.TASK_FAILED.Enum())
So(captured.String(), ShouldContainSubstring, "[ListContainers()]")
})
Convey("returns an error when the container doesn't exist", func() {
client.Container = nil
exec.monitorTask("missingbeef0010", taskInfo, true)
So(driver.lastStatus.State, ShouldResemble, mesos.TASK_FAILED.Enum())
So(captured.String(), ShouldContainSubstring,
"Container missingbeef0010 not found!",
)
})
Convey("returns an error when the container exists but has exited with errors", func() {
client.Container.State.ExitCode = 1
exec.monitorTask("deadbeef0010", taskInfo, true)
So(driver.lastStatus.State, ShouldResemble, mesos.TASK_FAILED.Enum())
So(captured.String(), ShouldContainSubstring,
"Container deadbeef0010 not running!",
)
})
Convey("returns without errors when the container exists and has exited without errors", func() {
client.Container.State.ExitCode = 0
exec.monitorTask("deadbeef0010", taskInfo, true)
So(driver.lastStatus.State, ShouldResemble, mesos.TASK_FINISHED.Enum())
So(captured.String(), ShouldContainSubstring, "Task completed")
})
Convey("check Sidecar status for a running container with SidecarDiscover: true", func() {
exec.monitorTask("running00010", taskInfo, true)
So(driver.lastStatus.State, ShouldResemble, mesos.TASK_FAILED.Enum())
So(captured.String(), ShouldContainSubstring,
"Unhealthy container: running00010 failing task!",
)
})
Convey("don't check Sidecar for a running container with SidecarDiscover: false", func() {
exec.monitorTask("running00010", taskInfo, false)
So(err, ShouldBeNil) // Container running, Sidecar no checked.
So(captured.String(), ShouldContainSubstring, "[checkSidecar: false]")
})
})
}