-
Notifications
You must be signed in to change notification settings - Fork 618
/
Copy pathdocker_task_engine_test.go
2272 lines (2047 loc) · 87.7 KB
/
docker_task_engine_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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// +build unit
// Copyright 2014-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package engine
import (
"encoding/json"
"errors"
"fmt"
"net"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/aws/amazon-ecs-agent/agent/api"
apicontainer "github.com/aws/amazon-ecs-agent/agent/api/container"
apicontainerstatus "github.com/aws/amazon-ecs-agent/agent/api/container/status"
apieni "github.com/aws/amazon-ecs-agent/agent/api/eni"
apitask "github.com/aws/amazon-ecs-agent/agent/api/task"
apitaskstatus "github.com/aws/amazon-ecs-agent/agent/api/task/status"
"github.com/aws/amazon-ecs-agent/agent/asm"
"github.com/aws/amazon-ecs-agent/agent/asm/factory/mocks"
mock_secretsmanageriface "github.com/aws/amazon-ecs-agent/agent/asm/mocks"
"github.com/aws/amazon-ecs-agent/agent/config"
"github.com/aws/amazon-ecs-agent/agent/containermetadata/mocks"
"github.com/aws/amazon-ecs-agent/agent/credentials"
"github.com/aws/amazon-ecs-agent/agent/credentials/mocks"
"github.com/aws/amazon-ecs-agent/agent/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/dockerapi"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/dockerapi/mocks"
"github.com/aws/amazon-ecs-agent/agent/ecscni"
"github.com/aws/amazon-ecs-agent/agent/ecscni/mocks"
"github.com/aws/amazon-ecs-agent/agent/engine/dockerstate"
"github.com/aws/amazon-ecs-agent/agent/engine/image"
"github.com/aws/amazon-ecs-agent/agent/engine/mocks"
"github.com/aws/amazon-ecs-agent/agent/engine/testdata"
"github.com/aws/amazon-ecs-agent/agent/eventstream"
"github.com/aws/amazon-ecs-agent/agent/statemanager/mocks"
"github.com/aws/amazon-ecs-agent/agent/taskresource"
"github.com/aws/amazon-ecs-agent/agent/taskresource/asmauth"
"github.com/aws/amazon-ecs-agent/agent/taskresource/mocks"
taskresourcevolume "github.com/aws/amazon-ecs-agent/agent/taskresource/volume"
"github.com/aws/amazon-ecs-agent/agent/utils/ttime/mocks"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/secretsmanager"
"github.com/containernetworking/cni/pkg/types/current"
docker "github.com/fsouza/go-dockerclient"
"github.com/golang/mock/gomock"
"github.com/pborman/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"context"
)
const (
credentialsID = "credsid"
ipv4 = "10.0.0.1"
mac = "1.2.3.4"
ipv6 = "f0:234:23"
dockerContainerName = "docker-container-name"
containerPid = 123
taskIP = "169.254.170.3"
exitCode = 1
labelsTaskARN = "arn:aws:ecs:us-east-1:012345678910:task/c09f0188-7f87-4b0f-bfc3-16296622b6fe"
taskSteadyStatePollInterval = time.Millisecond
secretID = "meaning-of-life"
region = "us-west-2"
username = "irene"
password = "sher"
)
var (
defaultConfig config.Config
nsResult = mockSetupNSResult()
// createdContainerName is used to save the name of the created
// container from the validateContainerRunWorkflow method. This
// variable should never be accessed directly.
// The `getCreatedContainerName` and `setCreatedContainerName`
// methods should be used instead.
createdContainerName string
// createdContainerNameLock guards access to the createdContainerName
// var.
createdContainerNameLock sync.Mutex
)
func init() {
defaultConfig = config.DefaultConfig()
defaultConfig.TaskCPUMemLimit = config.ExplicitlyDisabled
}
func getCreatedContainerName() string {
createdContainerNameLock.Lock()
defer createdContainerNameLock.Unlock()
return createdContainerName
}
func setCreatedContainerName(name string) {
createdContainerNameLock.Lock()
defer createdContainerNameLock.Unlock()
createdContainerName = name
}
func mocks(t *testing.T, ctx context.Context, cfg *config.Config) (*gomock.Controller,
*mock_dockerapi.MockDockerClient, *mock_ttime.MockTime, TaskEngine,
*mock_credentials.MockManager, *mock_engine.MockImageManager, *mock_containermetadata.MockManager) {
ctrl := gomock.NewController(t)
client := mock_dockerapi.NewMockDockerClient(ctrl)
mockTime := mock_ttime.NewMockTime(ctrl)
credentialsManager := mock_credentials.NewMockManager(ctrl)
containerChangeEventStream := eventstream.NewEventStream("TESTTASKENGINE", ctx)
containerChangeEventStream.StartListening()
imageManager := mock_engine.NewMockImageManager(ctrl)
metadataManager := mock_containermetadata.NewMockManager(ctrl)
taskEngine := NewTaskEngine(cfg, client, credentialsManager, containerChangeEventStream,
imageManager, dockerstate.NewTaskEngineState(), metadataManager, nil)
taskEngine.(*DockerTaskEngine)._time = mockTime
taskEngine.(*DockerTaskEngine).ctx = ctx
return ctrl, client, mockTime, taskEngine, credentialsManager, imageManager, metadataManager
}
func mockSetupNSResult() *current.Result {
_, ip, _ := net.ParseCIDR(taskIP + "/32")
return ¤t.Result{
IPs: []*current.IPConfig{
{
Address: *ip,
},
},
}
}
func TestBatchContainerHappyPath(t *testing.T) {
testcases := []struct {
name string
metadataCreateError error
metadataUpdateError error
metadataCleanError error
taskCPULimit config.Conditional
}{
{
name: "Metadata Manager Succeeds",
metadataCreateError: nil,
metadataUpdateError: nil,
metadataCleanError: nil,
taskCPULimit: config.ExplicitlyDisabled,
},
{
name: "Metadata Manager Fails to Create, Update and Cleanup",
metadataCreateError: errors.New("create metadata error"),
metadataUpdateError: errors.New("update metadata error"),
metadataCleanError: errors.New("clean metadata error"),
taskCPULimit: config.ExplicitlyDisabled,
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
metadataConfig := defaultConfig
metadataConfig.TaskCPUMemLimit = tc.taskCPULimit
metadataConfig.ContainerMetadataEnabled = true
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, mockTime, taskEngine, credentialsManager, imageManager, metadataManager := mocks(
t, ctx, &metadataConfig)
defer ctrl.Finish()
roleCredentials := credentials.TaskIAMRoleCredentials{
IAMRoleCredentials: credentials.IAMRoleCredentials{CredentialsID: "credsid"},
}
credentialsManager.EXPECT().GetTaskCredentials(credentialsID).Return(roleCredentials, true).AnyTimes()
credentialsManager.EXPECT().RemoveCredentials(credentialsID)
sleepTask := testdata.LoadTask("sleep5")
sleepTask.SetCredentialsID(credentialsID)
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
// containerEventsWG is used to force the test to wait until the container created and started
// events are processed
containerEventsWG := sync.WaitGroup{}
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any()).Return("1.12.6", nil)
}
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
containerName := make(chan string)
go func() {
name := <-containerName
setCreatedContainerName(name)
}()
for _, container := range sleepTask.Containers {
validateContainerRunWorkflow(t, container, sleepTask, imageManager,
client, &roleCredentials, containerEventsWG,
eventStream, containerName, func() {
metadataManager.EXPECT().Create(gomock.Any(), gomock.Any(),
gomock.Any(), gomock.Any()).Return(tc.metadataCreateError)
metadataManager.EXPECT().Update(gomock.Any(), gomock.Any(), gomock.Any(),
gomock.Any()).Return(tc.metadataUpdateError)
})
}
addTaskToEngine(t, ctx, taskEngine, sleepTask, mockTime, containerEventsWG)
cleanup := make(chan time.Time, 1)
defer close(cleanup)
mockTime.EXPECT().After(gomock.Any()).Return(cleanup).MinTimes(1)
client.EXPECT().DescribeContainer(gomock.Any(), gomock.Any()).AnyTimes()
// Simulate a container stop event from docker
eventStream <- dockerapi.DockerContainerChangeEvent{
Status: apicontainerstatus.ContainerStopped,
DockerContainerMetadata: dockerapi.DockerContainerMetadata{
DockerID: containerID,
ExitCode: aws.Int(exitCode),
},
}
// StopContainer might be invoked if the test execution is slow, during
// the cleanup phase. Account for that.
client.EXPECT().StopContainer(gomock.Any(), gomock.Any(), gomock.Any()).Return(
dockerapi.DockerContainerMetadata{DockerID: containerID}).AnyTimes()
waitForStopEvents(t, taskEngine.StateChangeEvents(), true)
// This ensures that managedTask.waitForStopReported makes progress
sleepTask.SetSentStatus(apitaskstatus.TaskStopped)
// Extra events should not block forever; duplicate acs and docker events are possible
go func() { eventStream <- createDockerEvent(apicontainerstatus.ContainerStopped) }()
go func() { eventStream <- createDockerEvent(apicontainerstatus.ContainerStopped) }()
sleepTaskStop := testdata.LoadTask("sleep5")
sleepTaskStop.SetCredentialsID(credentialsID)
sleepTaskStop.SetDesiredStatus(apitaskstatus.TaskStopped)
taskEngine.AddTask(sleepTaskStop)
// As above, duplicate events should not be a problem
taskEngine.AddTask(sleepTaskStop)
taskEngine.AddTask(sleepTaskStop)
// Expect a bunch of steady state 'poll' describes when we trigger cleanup
client.EXPECT().RemoveContainer(gomock.Any(), gomock.Any(), gomock.Any()).Do(
func(ctx interface{}, removedContainerName string, timeout time.Duration) {
assert.Equal(t, getCreatedContainerName(), removedContainerName,
"Container name mismatch")
}).Return(nil)
imageManager.EXPECT().RemoveContainerReferenceFromImageState(gomock.Any())
metadataManager.EXPECT().Clean(gomock.Any()).Return(tc.metadataCleanError)
// trigger cleanup
cleanup <- time.Now()
go func() { eventStream <- createDockerEvent(apicontainerstatus.ContainerStopped) }()
// Wait for the task to actually be dead; if we just fallthrough immediately,
// the remove might not have happened (expectation failure)
for {
tasks, _ := taskEngine.(*DockerTaskEngine).ListTasks()
if len(tasks) == 0 {
break
}
time.Sleep(5 * time.Millisecond)
}
})
}
}
// TestTaskWithSteadyStateResourcesProvisioned tests container and task transitions
// when the steady state for the pause container is set to RESOURCES_PROVISIONED and
// the steady state for the normal container is set to RUNNING
func TestTaskWithSteadyStateResourcesProvisioned(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, mockTime, taskEngine, _, imageManager, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
mockCNIClient := mock_ecscni.NewMockCNIClient(ctrl)
taskEngine.(*DockerTaskEngine).cniClient = mockCNIClient
// sleep5 contains a single 'sleep' container, with DesiredStatus == RUNNING
sleepTask := testdata.LoadTask("sleep5")
sleepContainer := sleepTask.Containers[0]
sleepContainer.TransitionDependenciesMap = make(map[apicontainerstatus.ContainerStatus]apicontainer.TransitionDependencySet)
sleepContainer.BuildContainerDependency("pause", apicontainerstatus.ContainerResourcesProvisioned, apicontainerstatus.ContainerPulled)
// Add a second container with DesiredStatus == RESOURCES_PROVISIONED and
// steadyState == RESOURCES_PROVISIONED
pauseContainer := apicontainer.NewContainerWithSteadyState(apicontainerstatus.ContainerResourcesProvisioned)
pauseContainer.Name = "pause"
pauseContainer.Image = "pause"
pauseContainer.CPU = 10
pauseContainer.Memory = 10
pauseContainer.Essential = true
pauseContainer.Type = apicontainer.ContainerCNIPause
sleepTask.Containers = append(sleepTask.Containers, pauseContainer)
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
// containerEventsWG is used to force the test to wait until the container created and started
// events are processed
containerEventsWG := sync.WaitGroup{}
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any())
}
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
// We cannot rely on the order of pulls between images as they can still be downloaded in
// parallel. The dependency graph enforcement comes into effect for CREATED transitions.
// Hence, do not enforce the order of invocation of these calls
imageManager.EXPECT().AddAllImageStates(gomock.Any()).AnyTimes()
client.EXPECT().PullImage(sleepContainer.Image, nil).Return(dockerapi.DockerContainerMetadata{})
imageManager.EXPECT().RecordContainerReference(sleepContainer).Return(nil)
imageManager.EXPECT().GetImageStateFromImageName(sleepContainer.Image).Return(nil, false)
gomock.InOrder(
// Ensure that the pause container is created first
client.EXPECT().APIVersion().Return(defaultDockerClientAPIVersion, nil),
client.EXPECT().CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do(
func(ctx interface{}, config *docker.Config, hostConfig *docker.HostConfig, containerName string, z time.Duration) {
sleepTask.SetTaskENI(&apieni.ENI{
ID: "TestTaskWithSteadyStateResourcesProvisioned",
IPV4Addresses: []*apieni.ENIIPV4Address{
{
Primary: true,
Address: ipv4,
},
},
MacAddress: mac,
IPV6Addresses: []*apieni.ENIIPV6Address{
{
Address: ipv6,
},
},
})
assert.Equal(t, "none", hostConfig.NetworkMode)
assert.True(t, strings.Contains(containerName, pauseContainer.Name))
containerEventsWG.Add(1)
go func() {
eventStream <- createDockerEvent(apicontainerstatus.ContainerCreated)
containerEventsWG.Done()
}()
}).Return(dockerapi.DockerContainerMetadata{DockerID: containerID + ":" + pauseContainer.Name}),
// Ensure that the pause container is started after it's created
client.EXPECT().StartContainer(gomock.Any(), containerID+":"+pauseContainer.Name, defaultConfig.ContainerStartTimeout).Do(
func(ctx interface{}, id string, timeout time.Duration) {
containerEventsWG.Add(1)
go func() {
eventStream <- createDockerEvent(apicontainerstatus.ContainerRunning)
containerEventsWG.Done()
}()
}).Return(dockerapi.DockerContainerMetadata{DockerID: containerID + ":" + pauseContainer.Name}),
client.EXPECT().InspectContainer(gomock.Any(), gomock.Any(), gomock.Any()).Return(&docker.Container{
ID: containerID,
State: docker.State{Pid: 23},
}, nil),
// Then setting up the pause container network namespace
mockCNIClient.EXPECT().SetupNS(gomock.Any(), gomock.Any(), gomock.Any()).Return(nsResult, nil),
// Once the pause container is started, sleep container will be created
client.EXPECT().APIVersion().Return(defaultDockerClientAPIVersion, nil),
client.EXPECT().CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do(
func(ctx interface{}, config *docker.Config, hostConfig *docker.HostConfig, containerName string, z time.Duration) {
assert.True(t, strings.Contains(containerName, sleepContainer.Name))
assert.Equal(t, "container:"+containerID+":"+pauseContainer.Name, hostConfig.NetworkMode)
containerEventsWG.Add(1)
go func() {
eventStream <- createDockerEvent(apicontainerstatus.ContainerCreated)
containerEventsWG.Done()
}()
}).Return(dockerapi.DockerContainerMetadata{DockerID: containerID + ":" + sleepContainer.Name}),
// Next, the sleep container is started
client.EXPECT().StartContainer(gomock.Any(), containerID+":"+sleepContainer.Name, defaultConfig.ContainerStartTimeout).Do(
func(ctx interface{}, id string, timeout time.Duration) {
containerEventsWG.Add(1)
go func() {
eventStream <- createDockerEvent(apicontainerstatus.ContainerRunning)
containerEventsWG.Done()
}()
}).Return(dockerapi.DockerContainerMetadata{DockerID: containerID + ":" + sleepContainer.Name}),
)
addTaskToEngine(t, ctx, taskEngine, sleepTask, mockTime, containerEventsWG)
taskARNByIP, ok := taskEngine.(*DockerTaskEngine).state.GetTaskByIPAddress(taskIP)
assert.True(t, ok)
assert.Equal(t, sleepTask.Arn, taskARNByIP)
cleanup := make(chan time.Time, 1)
mockTime.EXPECT().After(gomock.Any()).Return(cleanup).AnyTimes()
client.EXPECT().InspectContainer(gomock.Any(), gomock.Any(), gomock.Any()).Return(&docker.Container{
ID: containerID,
State: docker.State{Pid: 23},
}, nil)
mockCNIClient.EXPECT().CleanupNS(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
client.EXPECT().StopContainer(gomock.Any(), containerID+":"+pauseContainer.Name, gomock.Any()).MinTimes(1)
mockCNIClient.EXPECT().ReleaseIPResource(gomock.Any()).Return(nil).MaxTimes(1)
// Simulate a container stop event from docker
eventStream <- dockerapi.DockerContainerChangeEvent{
Status: apicontainerstatus.ContainerStopped,
DockerContainerMetadata: dockerapi.DockerContainerMetadata{
DockerID: containerID + ":" + sleepContainer.Name,
ExitCode: aws.Int(exitCode),
},
}
waitForStopEvents(t, taskEngine.StateChangeEvents(), true)
}
// TestRemoveEvents tests if the task engine can handle task events while the task is being
// cleaned up. This test ensures that there's no regression in the task engine and ensures
// there's no deadlock as seen in #313
func TestRemoveEvents(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, mockTime, taskEngine, _, imageManager, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
sleepTask := testdata.LoadTask("sleep5")
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
// containerEventsWG is used to force the test to wait until the container created and started
// events are processed
containerEventsWG := sync.WaitGroup{}
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any())
}
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
client.EXPECT().StopContainer(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
containerName := make(chan string)
go func() {
name := <-containerName
setCreatedContainerName(name)
}()
for _, container := range sleepTask.Containers {
validateContainerRunWorkflow(t, container, sleepTask, imageManager,
client, nil, containerEventsWG,
eventStream, containerName, func() {
})
}
addTaskToEngine(t, ctx, taskEngine, sleepTask, mockTime, containerEventsWG)
cleanup := make(chan time.Time, 1)
defer close(cleanup)
mockTime.EXPECT().After(gomock.Any()).Return(cleanup).MinTimes(1)
client.EXPECT().DescribeContainer(gomock.Any(), gomock.Any()).AnyTimes()
// Simulate a container stop event from docker
eventStream <- dockerapi.DockerContainerChangeEvent{
Status: apicontainerstatus.ContainerStopped,
DockerContainerMetadata: dockerapi.DockerContainerMetadata{
DockerID: containerID,
ExitCode: aws.Int(exitCode),
},
}
waitForStopEvents(t, taskEngine.StateChangeEvents(), true)
sleepTaskStop := testdata.LoadTask("sleep5")
sleepTaskStop.SetDesiredStatus(apitaskstatus.TaskStopped)
taskEngine.AddTask(sleepTaskStop)
client.EXPECT().RemoveContainer(gomock.Any(), gomock.Any(), gomock.Any()).Do(
func(ctx interface{}, removedContainerName string, timeout time.Duration) {
assert.Equal(t, getCreatedContainerName(), removedContainerName,
"Container name mismatch")
// Emit a couple of events for the task before cleanup finishes. This forces
// discardEventsUntil to be invoked and should test the code path that
// caused the deadlock, which was fixed with #320
eventStream <- createDockerEvent(apicontainerstatus.ContainerStopped)
eventStream <- createDockerEvent(apicontainerstatus.ContainerStopped)
}).Return(nil)
imageManager.EXPECT().RemoveContainerReferenceFromImageState(gomock.Any())
// This ensures that managedTask.waitForStopReported makes progress
sleepTask.SetSentStatus(apitaskstatus.TaskStopped)
// trigger cleanup
cleanup <- time.Now()
// Wait for the task to actually be dead; if we just fallthrough immediately,
// the remove might not have happened (expectation failure)
for {
tasks, _ := taskEngine.(*DockerTaskEngine).ListTasks()
if len(tasks) == 0 {
break
}
time.Sleep(5 * time.Millisecond)
}
}
func TestStartTimeoutThenStart(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, testTime, taskEngine, _, imageManager, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
sleepTask := testdata.LoadTask("sleep5")
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
testTime.EXPECT().Now().Return(time.Now()).AnyTimes()
testTime.EXPECT().After(gomock.Any())
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any())
}
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
client.EXPECT().APIVersion().Return(defaultDockerClientAPIVersion, nil)
for _, container := range sleepTask.Containers {
imageManager.EXPECT().AddAllImageStates(gomock.Any()).AnyTimes()
client.EXPECT().PullImage(container.Image, nil).Return(dockerapi.DockerContainerMetadata{})
imageManager.EXPECT().RecordContainerReference(container)
imageManager.EXPECT().GetImageStateFromImageName(gomock.Any()).Return(nil, false)
client.EXPECT().CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do(
func(ctx interface{}, x, y, z, timeout interface{}) {
go func() { eventStream <- createDockerEvent(apicontainerstatus.ContainerCreated) }()
}).Return(dockerapi.DockerContainerMetadata{DockerID: containerID})
client.EXPECT().StartContainer(gomock.Any(), containerID, defaultConfig.ContainerStartTimeout).Return(dockerapi.DockerContainerMetadata{
Error: &dockerapi.DockerTimeoutError{},
})
}
// Start timeout triggers a container stop as we force stop containers
// when startcontainer times out. See #1043 for details
client.EXPECT().StopContainer(gomock.Any(), containerID, gomock.Any()).Return(dockerapi.DockerContainerMetadata{
Error: dockerapi.CannotStartContainerError{fmt.Errorf("cannot start container")},
}).AnyTimes()
err := taskEngine.Init(ctx)
assert.NoError(t, err)
stateChangeEvents := taskEngine.StateChangeEvents()
taskEngine.AddTask(sleepTask)
waitForStopEvents(t, taskEngine.StateChangeEvents(), false)
// Now surprise surprise, it actually did start!
eventStream <- createDockerEvent(apicontainerstatus.ContainerRunning)
// However, if it starts again, we should not see it be killed; no additional expect
eventStream <- createDockerEvent(apicontainerstatus.ContainerRunning)
eventStream <- createDockerEvent(apicontainerstatus.ContainerRunning)
select {
case <-stateChangeEvents:
t.Fatal("Should be out of events")
default:
}
}
func TestSteadyStatePoll(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, testTime, taskEngine, _, imageManager, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
taskEngine.(*DockerTaskEngine).taskSteadyStatePollInterval = taskSteadyStatePollInterval
containerEventsWG := sync.WaitGroup{}
sleepTask := testdata.LoadTask("sleep5")
sleepTask.Arn = uuid.New()
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any())
}
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
containerName := make(chan string)
go func() {
<-containerName
}()
// set up expectations for each container in the task calling create + start
for _, container := range sleepTask.Containers {
validateContainerRunWorkflow(t, container, sleepTask, imageManager,
client, nil, containerEventsWG,
eventStream, containerName, func() {
})
}
testTime.EXPECT().Now().Return(time.Now()).MinTimes(1)
var wg sync.WaitGroup
wg.Add(1)
client.EXPECT().DescribeContainer(gomock.Any(), containerID).Return(
apicontainerstatus.ContainerStopped,
dockerapi.DockerContainerMetadata{
DockerID: containerID,
}).Do(func(ctx interface{}, x interface{}) {
wg.Done()
})
client.EXPECT().DescribeContainer(gomock.Any(), containerID).Return(
apicontainerstatus.ContainerStopped,
dockerapi.DockerContainerMetadata{
DockerID: containerID,
}).AnyTimes()
client.EXPECT().StopContainer(gomock.Any(), containerID, dockerclient.StopContainerTimeout).AnyTimes()
err := taskEngine.Init(ctx) // start the task engine
assert.NoError(t, err)
taskEngine.AddTask(sleepTask) // actually add the task we created
waitForRunningEvents(t, taskEngine.StateChangeEvents())
containerMap, ok := taskEngine.(*DockerTaskEngine).State().ContainerMapByArn(sleepTask.Arn)
assert.True(t, ok)
dockerContainer, ok := containerMap[sleepTask.Containers[0].Name]
assert.True(t, ok)
// Wait for container create and start events to be processed
containerEventsWG.Wait()
wg.Wait()
cleanup := make(chan time.Time)
defer close(cleanup)
testTime.EXPECT().After(gomock.Any()).Return(cleanup).MinTimes(1)
client.EXPECT().RemoveContainer(gomock.Any(), dockerContainer.DockerName, dockerclient.RemoveContainerTimeout).Return(nil)
imageManager.EXPECT().RemoveContainerReferenceFromImageState(gomock.Any()).Return(nil)
waitForStopEvents(t, taskEngine.StateChangeEvents(), false)
// trigger cleanup, this ensures all the goroutines were finished
sleepTask.SetSentStatus(apitaskstatus.TaskStopped)
cleanup <- time.Now()
for {
tasks, _ := taskEngine.(*DockerTaskEngine).ListTasks()
if len(tasks) == 0 {
break
}
time.Sleep(5 * time.Millisecond)
}
}
func TestStopWithPendingStops(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, testTime, taskEngine, _, imageManager, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
testTime.EXPECT().Now().Return(time.Now()).AnyTimes()
testTime.EXPECT().After(gomock.Any()).AnyTimes()
sleepTask1 := testdata.LoadTask("sleep5")
sleepTask1.StartSequenceNumber = 5
sleepTask2 := testdata.LoadTask("sleep5")
sleepTask2.Arn = "arn2"
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any()).Return("1.7.0", nil)
}
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
err := taskEngine.Init(ctx)
assert.NoError(t, err)
stateChangeEvents := taskEngine.StateChangeEvents()
defer discardEvents(stateChangeEvents)()
pullDone := make(chan bool)
pullInvoked := make(chan bool)
client.EXPECT().PullImage(gomock.Any(), nil).Do(func(x, y interface{}) {
pullInvoked <- true
<-pullDone
}).MaxTimes(2)
imageManager.EXPECT().RecordContainerReference(gomock.Any()).AnyTimes()
imageManager.EXPECT().GetImageStateFromImageName(gomock.Any()).AnyTimes()
taskEngine.AddTask(sleepTask2)
<-pullInvoked
stopSleep2 := testdata.LoadTask("sleep5")
stopSleep2.Arn = "arn2"
stopSleep2.SetDesiredStatus(apitaskstatus.TaskStopped)
stopSleep2.StopSequenceNumber = 4
taskEngine.AddTask(stopSleep2)
taskEngine.AddTask(sleepTask1)
stopSleep1 := testdata.LoadTask("sleep5")
stopSleep1.SetDesiredStatus(apitaskstatus.TaskStopped)
stopSleep1.StopSequenceNumber = 5
taskEngine.AddTask(stopSleep1)
pullDone <- true
// this means the PullImage is only called once due to the task is stopped before it
// gets the pull image lock
}
func TestCreateContainerForceSave(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, _, privateTaskEngine, _, _, _ := mocks(t, ctx, &config.Config{})
saver := mock_statemanager.NewMockStateManager(ctrl)
defer ctrl.Finish()
taskEngine, _ := privateTaskEngine.(*DockerTaskEngine)
taskEngine.SetSaver(saver)
sleepTask := testdata.LoadTask("sleep5")
sleepContainer, _ := sleepTask.ContainerByName("sleep5")
client.EXPECT().APIVersion().Return(defaultDockerClientAPIVersion, nil).AnyTimes()
gomock.InOrder(
saver.EXPECT().ForceSave().Do(func() interface{} {
task, ok := taskEngine.state.TaskByArn(sleepTask.Arn)
assert.True(t, ok, "Expected task with ARN: ", sleepTask.Arn)
assert.NotNil(t, task, "Expected task with ARN: ", sleepTask.Arn)
_, ok = task.ContainerByName("sleep5")
assert.True(t, ok, "Expected container sleep5")
return nil
}),
client.EXPECT().CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()),
)
metadata := taskEngine.createContainer(sleepTask, sleepContainer)
if metadata.Error != nil {
t.Error("Unexpected error", metadata.Error)
}
}
func TestCreateContainerMergesLabels(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, _, taskEngine, _, _, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
testTask := &apitask.Task{
Arn: labelsTaskARN,
Family: "myFamily",
Version: "1",
Containers: []*apicontainer.Container{
{
Name: "c1",
DockerConfig: apicontainer.DockerConfig{
Config: aws.String(`{"Labels":{"key":"value"}}`),
},
},
},
}
expectedConfig, err := testTask.DockerConfig(testTask.Containers[0], defaultDockerClientAPIVersion)
if err != nil {
t.Fatal(err)
}
expectedConfig.Labels = map[string]string{
"com.amazonaws.ecs.task-arn": labelsTaskARN,
"com.amazonaws.ecs.container-name": "c1",
"com.amazonaws.ecs.task-definition-family": "myFamily",
"com.amazonaws.ecs.task-definition-version": "1",
"com.amazonaws.ecs.cluster": "",
"key": "value",
}
client.EXPECT().APIVersion().Return(defaultDockerClientAPIVersion, nil).AnyTimes()
client.EXPECT().CreateContainer(gomock.Any(), expectedConfig, gomock.Any(), gomock.Any(), gomock.Any())
taskEngine.(*DockerTaskEngine).createContainer(testTask, testTask.Containers[0])
}
// TestTaskTransitionWhenStopContainerTimesout tests that task transitions to stopped
// only when terminal events are received from docker event stream when
// StopContainer times out
func TestTaskTransitionWhenStopContainerTimesout(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, mockTime, taskEngine, _, imageManager, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
sleepTask := testdata.LoadTask("sleep5")
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any())
}
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
mockTime.EXPECT().Now().Return(time.Now()).AnyTimes()
mockTime.EXPECT().After(gomock.Any()).AnyTimes()
containerStopTimeoutError := dockerapi.DockerContainerMetadata{
Error: &dockerapi.DockerTimeoutError{
Transition: "stop",
Duration: dockerclient.StopContainerTimeout,
},
}
dockerEventSent := make(chan int)
for _, container := range sleepTask.Containers {
imageManager.EXPECT().AddAllImageStates(gomock.Any()).AnyTimes()
client.EXPECT().PullImage(container.Image, nil).Return(dockerapi.DockerContainerMetadata{})
imageManager.EXPECT().RecordContainerReference(container)
imageManager.EXPECT().GetImageStateFromImageName(gomock.Any()).Return(nil, false)
client.EXPECT().APIVersion().Return(defaultDockerClientAPIVersion, nil)
client.EXPECT().CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do(
func(ctx interface{}, x, y, z, timeout interface{}) {
go func() { eventStream <- createDockerEvent(apicontainerstatus.ContainerCreated) }()
}).Return(dockerapi.DockerContainerMetadata{DockerID: containerID})
gomock.InOrder(
client.EXPECT().StartContainer(gomock.Any(), containerID, defaultConfig.ContainerStartTimeout).Do(
func(ctx interface{}, id string, timeout time.Duration) {
go func() {
eventStream <- createDockerEvent(apicontainerstatus.ContainerRunning)
}()
}).Return(dockerapi.DockerContainerMetadata{DockerID: containerID}),
// StopContainer times out
client.EXPECT().StopContainer(gomock.Any(), containerID, gomock.Any()).Return(containerStopTimeoutError),
// Since task is not in steady state, progressContainers causes
// another invocation of StopContainer. Return a timeout error
// for that as well.
client.EXPECT().StopContainer(gomock.Any(), containerID, gomock.Any()).Do(
func(ctx interface{}, id string, timeout time.Duration) {
go func() {
dockerEventSent <- 1
// Emit 'ContainerStopped' event to the container event stream
// This should cause the container and the task to transition
// to 'STOPPED'
eventStream <- createDockerEvent(apicontainerstatus.ContainerStopped)
}()
}).Return(containerStopTimeoutError).MinTimes(1),
)
}
err := taskEngine.Init(ctx)
assert.NoError(t, err)
stateChangeEvents := taskEngine.StateChangeEvents()
go taskEngine.AddTask(sleepTask)
// wait for task running
waitForRunningEvents(t, taskEngine.StateChangeEvents())
// Set the task desired status to be stopped and StopContainer will be called
updateSleepTask := testdata.LoadTask("sleep5")
updateSleepTask.SetDesiredStatus(apitaskstatus.TaskStopped)
go taskEngine.AddTask(updateSleepTask)
// StopContainer timeout error shouldn't cause cantainer/task status change
// until receive stop event from docker event stream
select {
case <-stateChangeEvents:
t.Error("Should not get task events")
case <-dockerEventSent:
t.Logf("Send docker stop event")
go func() {
for {
select {
case <-dockerEventSent:
case <-ctx.Done():
return
}
}
}()
}
// StopContainer was called again and received stop event from docker event stream
// Expect it to go to stopped
waitForStopEvents(t, taskEngine.StateChangeEvents(), false)
}
// TestTaskTransitionWhenStopContainerReturnsUnretriableError tests if the task transitions
// to stopped without retrying stopping the container in the task when the initial
// stop container call returns an unretriable error from docker, specifically the
// ContainerNotRunning error
func TestTaskTransitionWhenStopContainerReturnsUnretriableError(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, mockTime, taskEngine, _, imageManager, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
sleepTask := testdata.LoadTask("sleep5")
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any())
}
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
mockTime.EXPECT().Now().Return(time.Now()).AnyTimes()
mockTime.EXPECT().After(gomock.Any()).AnyTimes()
containerEventsWG := sync.WaitGroup{}
for _, container := range sleepTask.Containers {
gomock.InOrder(
imageManager.EXPECT().AddAllImageStates(gomock.Any()).AnyTimes(),
client.EXPECT().PullImage(container.Image, nil).Return(dockerapi.DockerContainerMetadata{}),
imageManager.EXPECT().RecordContainerReference(container),
imageManager.EXPECT().GetImageStateFromImageName(gomock.Any()).Return(nil, false),
client.EXPECT().APIVersion().Return(defaultDockerClientAPIVersion, nil),
// Simulate successful create container
client.EXPECT().CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Do(
func(ctx interface{}, x, y, z, timeout interface{}) {
containerEventsWG.Add(1)
go func() {
eventStream <- createDockerEvent(apicontainerstatus.ContainerCreated)
containerEventsWG.Done()
}()
}).Return(dockerapi.DockerContainerMetadata{DockerID: containerID}),
// Simulate successful start container
client.EXPECT().StartContainer(gomock.Any(), containerID, defaultConfig.ContainerStartTimeout).Do(
func(ctx interface{}, id string, timeout time.Duration) {
containerEventsWG.Add(1)
go func() {
eventStream <- createDockerEvent(apicontainerstatus.ContainerRunning)
containerEventsWG.Done()
}()
}).Return(dockerapi.DockerContainerMetadata{DockerID: containerID}),
// StopContainer errors out. However, since this is a known unretriable error,
// the task engine should not retry stopping the container and move on.
// If there's a delay in task engine's processing of the ContainerRunning
// event, StopContainer will be invoked again as the engine considers it
// as a stopped container coming back. MinTimes() should guarantee that
// StopContainer is invoked at least once and in protecting agasint a test
// failure when there's a delay in task engine processing the ContainerRunning
// event.
client.EXPECT().StopContainer(gomock.Any(), containerID, gomock.Any()).Return(dockerapi.DockerContainerMetadata{
Error: dockerapi.CannotStopContainerError{&docker.ContainerNotRunning{}},
}).MinTimes(1),
)
}
err := taskEngine.Init(ctx)
assert.NoError(t, err)
go taskEngine.AddTask(sleepTask)
// wait for task running
waitForRunningEvents(t, taskEngine.StateChangeEvents())
containerEventsWG.Wait()
// Set the task desired status to be stopped and StopContainer will be called
updateSleepTask := testdata.LoadTask("sleep5")
updateSleepTask.SetDesiredStatus(apitaskstatus.TaskStopped)
go taskEngine.AddTask(updateSleepTask)
// StopContainer was called again and received stop event from docker event stream
// Expect it to go to stopped
waitForStopEvents(t, taskEngine.StateChangeEvents(), false)
}
// TestTaskTransitionWhenStopContainerReturnsTransientErrorBeforeSucceeding tests if the task
// transitions to stopped only after receiving the container stopped event from docker when
// the initial stop container call fails with an unknown error.
func TestTaskTransitionWhenStopContainerReturnsTransientErrorBeforeSucceeding(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctrl, client, mockTime, taskEngine, _, imageManager, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
sleepTask := testdata.LoadTask("sleep5")
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any())
}
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
mockTime.EXPECT().Now().Return(time.Now()).AnyTimes()
mockTime.EXPECT().After(gomock.Any()).AnyTimes()
containerStoppingError := dockerapi.DockerContainerMetadata{
Error: dockerapi.CannotStopContainerError{errors.New("Error stopping container")},
}
for _, container := range sleepTask.Containers {
gomock.InOrder(
imageManager.EXPECT().AddAllImageStates(gomock.Any()).AnyTimes(),
client.EXPECT().PullImage(container.Image, nil).Return(dockerapi.DockerContainerMetadata{}),
imageManager.EXPECT().RecordContainerReference(container),
imageManager.EXPECT().GetImageStateFromImageName(gomock.Any()).Return(nil, false),
// Simulate successful create container
client.EXPECT().APIVersion().Return(defaultDockerClientAPIVersion, nil),
client.EXPECT().CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(
dockerapi.DockerContainerMetadata{DockerID: containerID}),
// Simulate successful start container
client.EXPECT().StartContainer(gomock.Any(), containerID, defaultConfig.ContainerStartTimeout).Return(
dockerapi.DockerContainerMetadata{DockerID: containerID}),
// StopContainer errors out a couple of times
client.EXPECT().StopContainer(gomock.Any(), containerID, gomock.Any()).Return(containerStoppingError).Times(2),
// Since task is not in steady state, progressContainers causes
// another invocation of StopContainer. Return the 'succeed' response,
// which should cause the task engine to stop invoking this again and
// transition the task to stopped.
client.EXPECT().StopContainer(gomock.Any(), containerID, gomock.Any()).Return(dockerapi.DockerContainerMetadata{}),
)
}
err := taskEngine.Init(ctx)
assert.NoError(t, err)
go taskEngine.AddTask(sleepTask)
// wait for task running
waitForRunningEvents(t, taskEngine.StateChangeEvents())
// Set the task desired status to be stopped and StopContainer will be called
updateSleepTask := testdata.LoadTask("sleep5")
updateSleepTask.SetDesiredStatus(apitaskstatus.TaskStopped)
go taskEngine.AddTask(updateSleepTask)
// StopContainer invocation should have caused it to stop eventually.
waitForStopEvents(t, taskEngine.StateChangeEvents(), false)
}
func TestGetTaskByArn(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
// Need a mock client as AddTask not only adds a task to the engine, but
// also causes the engine to progress the task.
ctrl, client, mockTime, taskEngine, _, imageManager, _ := mocks(t, ctx, &defaultConfig)
defer ctrl.Finish()
mockTime.EXPECT().Now().Return(time.Now()).AnyTimes()
if dockerVersionCheckDuringInit {
client.EXPECT().Version(gomock.Any(), gomock.Any())
}
eventStream := make(chan dockerapi.DockerContainerChangeEvent)
client.EXPECT().ContainerEvents(gomock.Any()).Return(eventStream, nil)
imageManager.EXPECT().AddAllImageStates(gomock.Any()).AnyTimes()
imageManager.EXPECT().RecordContainerReference(gomock.Any()).AnyTimes()
imageManager.EXPECT().GetImageStateFromImageName(gomock.Any()).AnyTimes()
err := taskEngine.Init(ctx)
assert.NoError(t, err)
defer taskEngine.Disable()
sleepTask := testdata.LoadTask("sleep5")
sleepTask.SetDesiredStatus(apitaskstatus.TaskStopped)
sleepTaskArn := sleepTask.Arn
sleepTask.SetDesiredStatus(apitaskstatus.TaskStopped)