-
Notifications
You must be signed in to change notification settings - Fork 612
/
docker_task_engine.go
2265 lines (2057 loc) · 85.6 KB
/
docker_task_engine.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
// Copyright 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 contains the core logic for managing tasks
package engine
import (
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/amazon-ecs-agent/agent/api"
"github.com/aws/amazon-ecs-agent/agent/api/appnet"
apicontainer "github.com/aws/amazon-ecs-agent/agent/api/container"
apicontainerstatus "github.com/aws/amazon-ecs-agent/agent/api/container/status"
apierrors "github.com/aws/amazon-ecs-agent/agent/api/errors"
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/config"
"github.com/aws/amazon-ecs-agent/agent/containermetadata"
"github.com/aws/amazon-ecs-agent/agent/credentials"
"github.com/aws/amazon-ecs-agent/agent/data"
"github.com/aws/amazon-ecs-agent/agent/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/dockerapi"
"github.com/aws/amazon-ecs-agent/agent/ecscni"
"github.com/aws/amazon-ecs-agent/agent/engine/dependencygraph"
"github.com/aws/amazon-ecs-agent/agent/engine/dockerstate"
"github.com/aws/amazon-ecs-agent/agent/engine/execcmd"
"github.com/aws/amazon-ecs-agent/agent/engine/serviceconnect"
"github.com/aws/amazon-ecs-agent/agent/eventstream"
"github.com/aws/amazon-ecs-agent/agent/logger"
"github.com/aws/amazon-ecs-agent/agent/logger/field"
"github.com/aws/amazon-ecs-agent/agent/metrics"
"github.com/aws/amazon-ecs-agent/agent/statechange"
"github.com/aws/amazon-ecs-agent/agent/taskresource"
"github.com/aws/amazon-ecs-agent/agent/taskresource/credentialspec"
"github.com/aws/amazon-ecs-agent/agent/taskresource/firelens"
"github.com/aws/amazon-ecs-agent/agent/utils"
"github.com/aws/amazon-ecs-agent/agent/utils/retry"
utilsync "github.com/aws/amazon-ecs-agent/agent/utils/sync"
"github.com/aws/amazon-ecs-agent/agent/utils/ttime"
"github.com/aws/aws-sdk-go/aws"
"github.com/docker/docker/api/types"
dockercontainer "github.com/docker/docker/api/types/container"
"github.com/pkg/errors"
)
const (
//DockerEndpointEnvVariable is the environment variable that can override the Docker endpoint
DockerEndpointEnvVariable = "DOCKER_HOST"
// DockerDefaultEndpoint is the default value for the Docker endpoint
DockerDefaultEndpoint = "unix:///var/run/docker.sock"
labelPrefix = "com.amazonaws.ecs."
labelTaskARN = labelPrefix + "task-arn"
labelContainerName = labelPrefix + "container-name"
labelTaskDefinitionFamily = labelPrefix + "task-definition-family"
labelTaskDefinitionVersion = labelPrefix + "task-definition-version"
labelCluster = labelPrefix + "cluster"
minGetIPBridgeTimeout = time.Second
maxGetIPBridgeTimeout = 10 * time.Second
getIPBridgeRetryJitterMultiplier = 0.2
getIPBridgeRetryDelayMultiplier = 2
ipamCleanupTmeout = 5 * time.Second
minEngineConnectRetryDelay = 2 * time.Second
maxEngineConnectRetryDelay = 200 * time.Second
engineConnectRetryJitterMultiplier = 0.20
engineConnectRetryDelayMultiplier = 1.5
// logDriverTypeFirelens is the log driver type for containers that want to use the firelens container to send logs.
logDriverTypeFirelens = "awsfirelens"
logDriverTypeFluentd = "fluentd"
logDriverTag = "tag"
logDriverFluentdAddress = "fluentd-address"
dataLogDriverPath = "/data/firelens/"
logDriverAsyncConnect = "fluentd-async-connect"
logDriverSubSecondPrecision = "fluentd-sub-second-precision"
logDriverBufferLimit = "fluentd-buffer-limit"
dataLogDriverSocketPath = "/socket/fluent.sock"
socketPathPrefix = "unix://"
// fluentTagDockerFormat is the format for the log tag, which is "containerName-firelens-taskID"
fluentTagDockerFormat = "%s-firelens-%s"
// Environment variables are needed for firelens
fluentNetworkHost = "FLUENT_HOST"
fluentNetworkPort = "FLUENT_PORT"
FluentNetworkPortValue = "24224"
FluentAWSVPCHostValue = "127.0.0.1"
defaultMonitorExecAgentsInterval = 15 * time.Minute
defaultStopContainerBackoffMin = time.Second
defaultStopContainerBackoffMax = time.Second * 5
stopContainerBackoffJitter = 0.2
stopContainerBackoffMultiplier = 1.3
stopContainerMaxRetryCount = 5
)
var newExponentialBackoff = retry.NewExponentialBackoff
// DockerTaskEngine is a state machine for managing a task and its containers
// in ECS.
//
// DockerTaskEngine implements an abstraction over the DockerGoClient so that
// it does not have to know about tasks, only containers
// The DockerTaskEngine interacts with Docker to implement a TaskEngine
type DockerTaskEngine struct {
// implements TaskEngine
cfg *config.Config
ctx context.Context
initialized bool
mustInitLock sync.Mutex
// state stores all tasks this task engine is aware of, including their
// current state and mappings to/from dockerId and name.
// This is used to checkpoint state to disk so tasks may survive agent
// failures or updates
state dockerstate.TaskEngineState
managedTasks map[string]*managedTask
taskStopGroup *utilsync.SequentialWaitGroup
events <-chan dockerapi.DockerContainerChangeEvent
stateChangeEvents chan statechange.Event
client dockerapi.DockerClient
dataClient data.Client
cniClient ecscni.CNIClient
appnetClient api.AppnetClient
containerChangeEventStream *eventstream.EventStream
stopEngine context.CancelFunc
// tasksLock is a mutex that the task engine must acquire before changing
// any task's state which it manages. Since this is a lock that encompasses
// all tasks, it must not acquire it for any significant duration
// The write mutex should be taken when adding and removing tasks from managedTasks.
tasksLock sync.RWMutex
credentialsManager credentials.Manager
_time ttime.Time
_timeOnce sync.Once
imageManager ImageManager
containerStatusToTransitionFunction map[apicontainerstatus.ContainerStatus]transitionApplyFunc
metadataManager containermetadata.Manager
serviceconnectManager serviceconnect.Manager
serviceconnectRelay *apitask.Task
// taskSteadyStatePollInterval is the duration that a managed task waits
// once the task gets into steady state before polling the state of all of
// the task's containers to re-evaluate if the task is still in steady state
// This is set to defaultTaskSteadyStatePollInterval in production code.
// This can be used by tests that are looking to ensure that the steady state
// verification logic gets executed to set it to a low interval
taskSteadyStatePollInterval time.Duration
taskSteadyStatePollIntervalJitter time.Duration
resourceFields *taskresource.ResourceFields
// handleDelay is a function used to delay cleanup. Implementation is
// swappable for testing
handleDelay func(duration time.Duration)
monitorExecAgentsTicker *time.Ticker
execCmdMgr execcmd.Manager
monitorExecAgentsInterval time.Duration
stopContainerBackoffMin time.Duration
stopContainerBackoffMax time.Duration
namespaceHelper ecscni.NamespaceHelper
}
// NewDockerTaskEngine returns a created, but uninitialized, DockerTaskEngine.
// The distinction between created and initialized is that when created it may
// be serialized/deserialized, but it will not communicate with docker until it
// is also initialized.
func NewDockerTaskEngine(cfg *config.Config,
client dockerapi.DockerClient,
credentialsManager credentials.Manager,
containerChangeEventStream *eventstream.EventStream,
imageManager ImageManager,
state dockerstate.TaskEngineState,
metadataManager containermetadata.Manager,
resourceFields *taskresource.ResourceFields,
execCmdMgr execcmd.Manager,
serviceConnectManager serviceconnect.Manager) *DockerTaskEngine {
dockerTaskEngine := &DockerTaskEngine{
cfg: cfg,
client: client,
dataClient: data.NewNoopClient(),
state: state,
managedTasks: make(map[string]*managedTask),
taskStopGroup: utilsync.NewSequentialWaitGroup(),
stateChangeEvents: make(chan statechange.Event),
credentialsManager: credentialsManager,
containerChangeEventStream: containerChangeEventStream,
imageManager: imageManager,
cniClient: ecscni.NewClient(cfg.CNIPluginsPath),
appnetClient: appnet.Client(),
metadataManager: metadataManager,
serviceconnectManager: serviceConnectManager,
taskSteadyStatePollInterval: defaultTaskSteadyStatePollInterval,
taskSteadyStatePollIntervalJitter: defaultTaskSteadyStatePollIntervalJitter,
resourceFields: resourceFields,
handleDelay: time.Sleep,
execCmdMgr: execCmdMgr,
monitorExecAgentsInterval: defaultMonitorExecAgentsInterval,
stopContainerBackoffMin: defaultStopContainerBackoffMin,
stopContainerBackoffMax: defaultStopContainerBackoffMax,
namespaceHelper: ecscni.NewNamespaceHelper(client),
}
dockerTaskEngine.initializeContainerStatusToTransitionFunction()
return dockerTaskEngine
}
func (engine *DockerTaskEngine) initializeContainerStatusToTransitionFunction() {
containerStatusToTransitionFunction := map[apicontainerstatus.ContainerStatus]transitionApplyFunc{
apicontainerstatus.ContainerPulled: engine.pullContainer,
apicontainerstatus.ContainerCreated: engine.createContainer,
apicontainerstatus.ContainerRunning: engine.startContainer,
apicontainerstatus.ContainerResourcesProvisioned: engine.provisionContainerResources,
apicontainerstatus.ContainerStopped: engine.stopContainer,
}
engine.containerStatusToTransitionFunction = containerStatusToTransitionFunction
}
// ImagePullDeleteLock ensures that pulls and deletes do not run at the same time and pulls can be run at the same time for docker >= 1.11.1
// Pulls are serialized as a temporary workaround for a devicemapper issue. (see https://github.com/docker/docker/issues/9718)
// Deletes must not run at the same time as pulls to prevent deletion of images that are being used to launch new tasks.
var ImagePullDeleteLock sync.RWMutex
// UnmarshalJSON restores a previously marshaled task-engine state from json
func (engine *DockerTaskEngine) UnmarshalJSON(data []byte) error {
return engine.state.UnmarshalJSON(data)
}
// MarshalJSON marshals into state directly
func (engine *DockerTaskEngine) MarshalJSON() ([]byte, error) {
return engine.state.MarshalJSON()
}
// Init initializes a DockerTaskEngine such that it may communicate with docker
// and operate normally.
// This function must be called before any other function, except serializing and deserializing, can succeed without error.
func (engine *DockerTaskEngine) Init(ctx context.Context) error {
derivedCtx, cancel := context.WithCancel(ctx)
engine.stopEngine = cancel
engine.ctx = derivedCtx
// Open the event stream before we sync state so that e.g. if a container
// goes from running to stopped after we sync with it as "running" we still
// have the "went to stopped" event pending so we can be up to date.
err := engine.openEventstream(derivedCtx)
if err != nil {
return err
}
engine.synchronizeState()
// Now catch up and start processing new events per normal
go engine.handleDockerEvents(derivedCtx)
engine.initialized = true
go engine.startPeriodicExecAgentsMonitoring(derivedCtx)
go engine.watchAppNetImage(derivedCtx)
return nil
}
func (engine *DockerTaskEngine) startPeriodicExecAgentsMonitoring(ctx context.Context) {
engine.monitorExecAgentsTicker = time.NewTicker(engine.monitorExecAgentsInterval)
for {
select {
case <-engine.monitorExecAgentsTicker.C:
go engine.monitorExecAgentProcesses(ctx)
case <-ctx.Done():
engine.monitorExecAgentsTicker.Stop()
return
}
}
}
func (engine *DockerTaskEngine) monitorExecAgentProcesses(ctx context.Context) {
// TODO: [ecs-exec]add jitter between containers to not overload docker with top calls
engine.tasksLock.RLock()
defer engine.tasksLock.RUnlock()
for _, mTask := range engine.managedTasks {
task := mTask.Task
if task.GetKnownStatus() != apitaskstatus.TaskRunning {
continue
}
for _, c := range task.Containers {
if execcmd.IsExecEnabledContainer(c) {
if ma, _ := c.GetManagedAgentByName(execcmd.ExecuteCommandAgentName); !ma.InitFailed {
go engine.monitorExecAgentRunning(ctx, mTask, c)
}
}
}
}
}
func (engine *DockerTaskEngine) monitorExecAgentRunning(ctx context.Context,
mTask *managedTask, c *apicontainer.Container) {
if !c.IsRunning() {
return
}
task := mTask.Task
dockerID, err := engine.getDockerID(task, c)
if err != nil {
logger.Error("Could not retrieve docker id for container", logger.Fields{
field.TaskID: task.GetID(),
field.Container: c.Name,
})
return
}
// Sleeping here so that all the containers do not call inspect/start exec agent process
// at the same time.
// The max sleep is 50% of the monitor interval to allow enough buffer time
// to finish monitoring.
// This is inspired from containers streaming stats from Docker.
time.Sleep(retry.AddJitter(time.Nanosecond, engine.monitorExecAgentsInterval/2))
status, err := engine.execCmdMgr.RestartAgentIfStopped(ctx, engine.client, task, c, dockerID)
if err != nil {
logger.Error("Failed to restart ExecCommandAgent Process for container", logger.Fields{
field.TaskID: task.GetID(),
field.Container: c.Name,
field.DockerId: dockerID,
field.Error: err,
})
mTask.emitManagedAgentEvent(mTask.Task, c, execcmd.ExecuteCommandAgentName, "ExecuteCommandAgent cannot be restarted")
}
if status == execcmd.Restarted {
mTask.emitManagedAgentEvent(mTask.Task, c, execcmd.ExecuteCommandAgentName, "ExecuteCommandAgent restarted")
}
}
// MustInit blocks and retries until an engine can be initialized.
func (engine *DockerTaskEngine) MustInit(ctx context.Context) {
if engine.initialized {
return
}
engine.mustInitLock.Lock()
defer engine.mustInitLock.Unlock()
errorOnce := sync.Once{}
taskEngineConnectBackoff := retry.NewExponentialBackoff(minEngineConnectRetryDelay, maxEngineConnectRetryDelay,
engineConnectRetryJitterMultiplier, engineConnectRetryDelayMultiplier)
retry.RetryWithBackoff(taskEngineConnectBackoff, func() error {
if engine.initialized {
return nil
}
err := engine.Init(ctx)
if err != nil {
errorOnce.Do(func() {
logger.Error("Could not connect to docker daemon", logger.Fields{
field.Error: err,
})
})
}
return err
})
}
// SetDataClient sets the saver that is used by the DockerTaskEngine.
func (engine *DockerTaskEngine) SetDataClient(client data.Client) {
engine.dataClient = client
}
func (engine *DockerTaskEngine) Context() context.Context {
return engine.ctx
}
// Shutdown makes a best-effort attempt to cleanup after the task engine.
// This should not be relied on for anything more complicated than testing.
func (engine *DockerTaskEngine) Shutdown() {
engine.stopEngine()
engine.Disable()
}
// Disable prevents this engine from managing any additional tasks.
func (engine *DockerTaskEngine) Disable() {
engine.tasksLock.Lock()
}
// isTaskManaged checks if task for the corresponding arn is present
func (engine *DockerTaskEngine) isTaskManaged(arn string) bool {
engine.tasksLock.RLock()
defer engine.tasksLock.RUnlock()
_, ok := engine.managedTasks[arn]
return ok
}
// synchronizeState explicitly goes through each docker container stored in
// "state" and updates its KnownStatus appropriately, as well as queueing up
// events to push upstream. It also initializes some fields of task resources and eni attachments that won't be populated
// from loading state file.
func (engine *DockerTaskEngine) synchronizeState() {
engine.tasksLock.Lock()
defer engine.tasksLock.Unlock()
imageStates := engine.state.AllImageStates()
if len(imageStates) != 0 {
engine.imageManager.AddAllImageStates(imageStates)
}
eniAttachments := engine.state.AllENIAttachments()
for _, eniAttachment := range eniAttachments {
timeoutFunc := func() {
eniAttachment, ok := engine.state.ENIByMac(eniAttachment.MACAddress)
if !ok {
logger.Warn("Ignoring unmanaged ENI attachment", logger.Fields{
"macAddress": eniAttachment.MACAddress,
})
return
}
if !eniAttachment.IsSent() {
logger.Warn("Timed out waiting for ENI ack; removing ENI attachment record", logger.Fields{
field.TaskARN: eniAttachment.TaskARN,
field.Status: eniAttachment.Status.String(),
"attachmentArn": eniAttachment.AttachmentARN,
"expiresAt": eniAttachment.ExpiresAt.Format(time.RFC3339),
"type": eniAttachment.AttachmentType,
})
engine.removeENIAttachmentData(eniAttachment.MACAddress)
engine.state.RemoveENIAttachment(eniAttachment.MACAddress)
}
}
err := eniAttachment.Initialize(timeoutFunc)
if err != nil {
// The only case where we get an error from Initialize is that the attachment has expired. In that case, remove the expired
// attachment from state.
logger.Warn("ENI attachment has expired; removing it from state", logger.Fields{
field.TaskARN: eniAttachment.TaskARN,
field.Status: eniAttachment.Status.String(),
"attachmentArn": eniAttachment.AttachmentARN,
"expiresAt": eniAttachment.ExpiresAt.Format(time.RFC3339),
"type": eniAttachment.AttachmentType,
})
engine.removeENIAttachmentData(eniAttachment.MACAddress)
engine.state.RemoveENIAttachment(eniAttachment.MACAddress)
}
}
tasks := engine.state.AllTasks()
tasksToStart := engine.filterTasksToStartUnsafe(tasks)
for _, task := range tasks {
task.InitializeResources(engine.resourceFields)
engine.saveTaskData(task)
}
for _, task := range tasksToStart {
engine.startTask(task)
}
}
// filterTasksToStartUnsafe filters only the tasks that need to be started after
// the agent has been restarted. It also synchronizes states of all of the containers
// in tasks that need to be started.
func (engine *DockerTaskEngine) filterTasksToStartUnsafe(tasks []*apitask.Task) []*apitask.Task {
var tasksToStart []*apitask.Task
for _, task := range tasks {
conts, ok := engine.state.ContainerMapByArn(task.Arn)
if !ok {
// task hasn't started processing, no need to check container status
tasksToStart = append(tasksToStart, task)
continue
}
for _, cont := range conts {
engine.synchronizeContainerStatus(cont, task)
engine.saveDockerContainerData(cont) // persist the container with the updated information.
}
tasksToStart = append(tasksToStart, task)
// Put tasks that are stopped by acs but hasn't been stopped in wait group
if task.GetDesiredStatus().Terminal() && task.GetStopSequenceNumber() != 0 {
engine.taskStopGroup.Add(task.GetStopSequenceNumber(), 1)
}
}
return tasksToStart
}
// updateContainerMetadata sets the container metadata from the docker inspect,
// and update port mappings for bridge mode containers with service connect enabled
func updateContainerMetadata(metadata *dockerapi.DockerContainerMetadata, container *apicontainer.Container, task *apitask.Task) {
container.SetCreatedAt(metadata.CreatedAt)
container.SetStartedAt(metadata.StartedAt)
container.SetFinishedAt(metadata.FinishedAt)
// Set the labels if it's not set
if len(metadata.Labels) != 0 && len(container.GetLabels()) == 0 {
container.SetLabels(metadata.Labels)
}
// Update volume for empty volume container
if metadata.Volumes != nil {
if container.IsInternal() {
task.UpdateMountPoints(container, metadata.Volumes)
} else {
container.SetVolumes(metadata.Volumes)
}
}
// Set Exitcode if it's not set
if metadata.ExitCode != nil {
container.SetKnownExitCode(metadata.ExitCode)
}
// Set port mappings
if len(metadata.PortBindings) != 0 && len(container.GetKnownPortBindings()) == 0 {
container.SetKnownPortBindings(metadata.PortBindings)
}
// update port mappings for service connect bridge mode.
// For the bridge-mode ServiceConnect-enabled task, port mappings are applied to the pause container
// (~internal-ecs-pause-<$APP_CONTAINER>) instead of the application container (<$APP_CONTAINER>); therefore,
// we need to remap the port mappings from the associated pause container (~internal-ecs-pause-<$APP_CONTAINER>)
// to the application container (<$APP_CONTAINER>).
if task.IsServiceConnectEnabled() && task.IsNetworkModeBridge() &&
!container.IsInternal() && len(container.Name) > 0 {
pauseContainer, err := task.GetBridgeModePauseContainerForTaskContainer(container)
if err != nil {
logger.Error("Error resolving pause container for bridge mode SC container", logger.Fields{
field.Container: container.Name,
field.Error: err,
})
} else {
container.SetKnownPortBindings(pauseContainer.GetKnownPortBindings())
}
}
// update the container health information
if container.HealthStatusShouldBeReported() {
container.SetHealthStatus(metadata.Health)
}
container.SetNetworkMode(metadata.NetworkMode)
container.SetNetworkSettings(metadata.NetworkSettings)
}
// synchronizeContainerStatus checks and updates the container status with docker
func (engine *DockerTaskEngine) synchronizeContainerStatus(container *apicontainer.DockerContainer, task *apitask.Task) {
if container.DockerID == "" {
logger.Debug("Found container potentially created while we were down", logger.Fields{
field.TaskID: task.GetID(),
field.Container: container.DockerName,
})
// Figure out the dockerid
describedContainer, err := engine.client.InspectContainer(engine.ctx,
container.DockerName, dockerclient.InspectContainerTimeout)
if err != nil {
logger.Warn("Error getting container with name", logger.Fields{
field.TaskID: task.GetID(),
field.Container: container.DockerName,
field.Error: err,
})
} else {
// update the container metadata in case the container was created during agent restart
metadata := dockerapi.MetadataFromContainer(describedContainer)
updateContainerMetadata(&metadata, container.Container, task)
container.DockerID = describedContainer.ID
container.Container.SetKnownStatus(dockerapi.DockerStateToState(describedContainer.State))
// update mappings that need dockerid
engine.state.AddContainer(container, task)
err := engine.imageManager.RecordContainerReference(container.Container)
if err != nil {
logger.Warn("Unable to add container reference to image state", logger.Fields{
field.TaskID: task.GetID(),
field.Container: container.DockerName,
field.Error: err,
})
}
}
return
}
currentState, metadata := engine.client.DescribeContainer(engine.ctx, container.DockerID)
if metadata.Error != nil {
currentState = apicontainerstatus.ContainerStopped
// If this is a Docker API error
if metadata.Error.ErrorName() == dockerapi.CannotDescribeContainerErrorName {
logger.Warn("Could not describe previously known container; assuming dead", logger.Fields{
field.TaskID: task.GetID(),
field.Container: container.DockerName,
field.DockerId: container.DockerID,
field.Error: metadata.Error,
})
if !container.Container.KnownTerminal() {
container.Container.ApplyingError = apierrors.NewNamedError(&ContainerVanishedError{})
err := engine.imageManager.RemoveContainerReferenceFromImageState(container.Container)
if err != nil {
logger.Warn("Could not remove container reference from image state", logger.Fields{
field.TaskID: task.GetID(),
field.Container: container.DockerName,
"image": container.Container.Image,
field.Error: err,
})
}
}
} else {
// If this is a container state error
updateContainerMetadata(&metadata, container.Container, task)
container.Container.ApplyingError = apierrors.NewNamedError(metadata.Error)
}
} else {
// update the container metadata in case the container status/metadata changed during agent restart
updateContainerMetadata(&metadata, container.Container, task)
err := engine.imageManager.RecordContainerReference(container.Container)
if err != nil {
logger.Warn("Unable to add container reference to image state", logger.Fields{
field.TaskID: task.GetID(),
field.Container: container.DockerName,
field.Error: err,
})
}
if engine.cfg.ContainerMetadataEnabled.Enabled() && !container.Container.IsMetadataFileUpdated() {
go engine.updateMetadataFile(task, container)
}
}
if currentState > container.Container.GetKnownStatus() {
// update the container known status
container.Container.SetKnownStatus(currentState)
}
// Update task ExecutionStoppedAt timestamp
task.RecordExecutionStoppedAt(container.Container)
}
// checkTaskState inspects the state of all containers within a task and writes
// their state to the managed task's container channel.
func (engine *DockerTaskEngine) checkTaskState(task *apitask.Task) {
defer metrics.MetricsEngineGlobal.RecordTaskEngineMetric("CHECK_TASK_STATE")()
for _, container := range task.Containers {
dockerID, err := engine.getDockerID(task, container)
if err != nil {
continue
}
status, metadata := engine.client.DescribeContainer(engine.ctx, dockerID)
engine.tasksLock.RLock()
managedTask, ok := engine.managedTasks[task.Arn]
engine.tasksLock.RUnlock()
if ok {
managedTask.emitDockerContainerChange(dockerContainerChange{
container: container,
event: dockerapi.DockerContainerChangeEvent{
Status: status,
DockerContainerMetadata: metadata,
},
})
}
}
}
// sweepTask deletes all the containers associated with a task
func (engine *DockerTaskEngine) sweepTask(task *apitask.Task) {
for _, cont := range task.Containers {
err := engine.removeContainer(task, cont)
if err != nil {
logger.Error("Unable to remove old container", logger.Fields{
field.TaskID: task.GetID(),
field.Container: cont.Name,
field.Error: err,
})
}
// Internal container(created by ecs-agent) state isn't recorded
if cont.IsInternal() {
continue
}
err = engine.imageManager.RemoveContainerReferenceFromImageState(cont)
if err != nil {
logger.Error("Unable to remove container reference from image state", logger.Fields{
field.TaskID: task.GetID(),
field.Container: cont.Name,
field.Error: err,
})
}
}
// Clean metadata directory for task
if engine.cfg.ContainerMetadataEnabled.Enabled() {
err := engine.metadataManager.Clean(task.Arn)
if err != nil {
logger.Warn("Error cleaning task metadata", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
}
}
}
var removeAll = os.RemoveAll
func (engine *DockerTaskEngine) deleteTask(task *apitask.Task) {
for _, resource := range task.GetResources() {
err := resource.Cleanup()
if err != nil {
logger.Warn("Unable to cleanup resource", logger.Fields{
field.TaskID: task.GetID(),
field.Resource: resource.GetName(),
field.Error: err,
})
} else {
logger.Info("Resource cleanup complete", logger.Fields{
field.TaskID: task.GetID(),
field.Resource: resource.GetName(),
})
}
}
tID := task.GetID()
if execcmd.IsExecEnabledTask(task) {
// cleanup host exec agent log dirs
if err := removeAll(filepath.Join(execcmd.ECSAgentExecLogDir, tID)); err != nil {
logger.Warn("Unable to remove ExecAgent host logs for task", logger.Fields{
field.TaskID: tID,
field.Error: err,
})
}
}
if task.IsServiceConnectEnabled() {
serviceconnectConfig := task.GetServiceConnectRuntimeConfig()
if err := removeAll(filepath.Dir(serviceconnectConfig.AdminSocketPath)); err != nil {
logger.Warn("Unable to remove service-connect UDS bind mount path for task", logger.Fields{
field.TaskID: tID,
field.Error: err,
})
}
}
// Now remove ourselves from the global state and cleanup channels
engine.tasksLock.Lock()
engine.state.RemoveTask(task)
taskENIs := task.GetTaskENIs()
for _, taskENI := range taskENIs {
// ENIs that exist only as logical associations on another interface do not have
// attachments that need to be removed.
if taskENI.IsStandardENI() {
logger.Debug("Removing ENI from agent state", logger.Fields{
field.TaskID: task.GetID(),
"eni": taskENI.ID,
})
engine.removeENIAttachmentData(taskENI.MacAddress)
engine.state.RemoveENIAttachment(taskENI.MacAddress)
} else {
logger.Debug("Skipping removing logical ENI from agent state because it's not a standard ENI", logger.Fields{
field.TaskID: task.GetID(),
"eni": taskENI.ID,
})
}
}
// Remove task and container data from database.
engine.removeTaskData(task)
logger.Info("Finished removing task data, removing task from managed tasks", logger.Fields{
field.TaskID: task.GetID(),
})
delete(engine.managedTasks, task.Arn)
engine.tasksLock.Unlock()
}
func (engine *DockerTaskEngine) emitTaskEvent(task *apitask.Task, reason string) {
event, err := api.NewTaskStateChangeEvent(task, reason)
if err != nil {
if _, ok := err.(api.ErrShouldNotSendEvent); ok {
logger.Debug(err.Error())
} else {
logger.Error("Unable to create task state change event", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
}
return
}
logger.Info("Preparing to send change event", logger.Fields{
field.TaskID: task.GetID(),
field.Status: event.Status.String(),
field.Reason: event.Reason,
})
engine.stateChangeEvents <- event
}
// startTask creates a managedTask construct to track the task and then begins
// pushing it towards its desired state when allowed startTask is protected by
// the tasksLock lock of 'AddTask'. It should not be called from anywhere
// else and should exit quickly to allow AddTask to do more work.
func (engine *DockerTaskEngine) startTask(task *apitask.Task) {
// Create a channel that may be used to communicate with this task, survey
// what tasks need to be waited for for this one to start, and then spin off
// a goroutine to oversee this task
thisTask := engine.newManagedTask(task)
thisTask._time = engine.time()
go thisTask.overseeTask()
}
func (engine *DockerTaskEngine) time() ttime.Time {
engine._timeOnce.Do(func() {
if engine._time == nil {
engine._time = &ttime.DefaultTime{}
}
})
return engine._time
}
// openEventstream opens, but does not consume, the docker event stream
func (engine *DockerTaskEngine) openEventstream(ctx context.Context) error {
events, err := engine.client.ContainerEvents(ctx)
if err != nil {
return err
}
engine.events = events
return nil
}
// handleDockerEvents must be called after openEventstream; it processes each
// event that it reads from the docker eventstream
func (engine *DockerTaskEngine) handleDockerEvents(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case event := <-engine.events:
engine.handleDockerEvent(event)
}
}
}
// handleDockerEvent is the entrypoint for task modifications originating with
// events occurring through Docker, outside the task engine itself.
// handleDockerEvent is responsible for taking an event that correlates to a
// container and placing it in the context of the task to which that container
// belongs.
func (engine *DockerTaskEngine) handleDockerEvent(event dockerapi.DockerContainerChangeEvent) {
eventFields := logger.Fields{
field.DockerId: event.DockerID,
field.Status: event.Status.String(),
"health": event.Health.Status.String(),
}
if event.ExitCode != nil {
eventFields["exitCode"] = aws.IntValue(event.ExitCode)
}
if len(event.PortBindings) != 0 {
eventFields["portBindings"] = event.PortBindings
}
if event.Error != nil {
eventFields[field.Error] = event.Error
}
if len(event.Volumes) != 0 {
eventFields["volumes"] = event.Volumes
}
if len(event.Labels) != 0 {
eventFields["labels"] = event.Labels
}
if !event.CreatedAt.IsZero() {
eventFields["createdAt"] = event.CreatedAt.String()
}
if !event.StartedAt.IsZero() {
eventFields["startedAt"] = event.StartedAt.String()
}
if !event.FinishedAt.IsZero() {
eventFields["finishedAt"] = event.FinishedAt.String()
}
logger.Debug("Handling a docker event", eventFields)
task, ok := engine.state.TaskByID(event.DockerID)
if !ok {
logger.Debug("Unable to map container event to task", eventFields)
return
}
cont, ok := engine.state.ContainerByID(event.DockerID)
if !ok {
logger.Debug("Unable to map container id to container", logger.Fields{
field.TaskID: task.GetID(),
}, eventFields)
return
}
// Container health status change does not affect the container status
// no need to process this in task manager
if event.Type == apicontainer.ContainerHealthEvent {
if cont.Container.HealthStatusShouldBeReported() {
logger.Debug("Updating container health status", logger.Fields{
field.TaskID: task.GetID(),
field.Container: cont.Container.Name,
field.DockerId: cont.DockerID,
"status": event.DockerContainerMetadata.Health.Status.String(),
"exitCode": event.DockerContainerMetadata.Health.ExitCode,
"output": event.DockerContainerMetadata.Health.Output,
})
cont.Container.SetHealthStatus(event.DockerContainerMetadata.Health)
}
return
}
engine.tasksLock.RLock()
managedTask, ok := engine.managedTasks[task.Arn]
engine.tasksLock.RUnlock()
if !ok {
logger.Critical("Could not find managed task for docker event", logger.Fields{
field.TaskID: task.GetID(),
}, eventFields)
return
}
logger.Debug("Writing docker event to the task", logger.Fields{
field.TaskID: task.GetID(),
}, eventFields)
managedTask.emitDockerContainerChange(dockerContainerChange{container: cont.Container, event: event})
logger.Debug("Wrote docker event to the task", logger.Fields{
field.TaskID: task.GetID(),
}, eventFields)
}
// StateChangeEvents returns channels to read task and container state changes. These
// changes should be read as soon as possible as them not being read will block
// processing the task referenced by the event.
func (engine *DockerTaskEngine) StateChangeEvents() chan statechange.Event {
return engine.stateChangeEvents
}
// AddTask starts tracking a task
func (engine *DockerTaskEngine) AddTask(task *apitask.Task) {
defer metrics.MetricsEngineGlobal.RecordTaskEngineMetric("ADD_TASK")()
err := task.PostUnmarshalTask(engine.cfg, engine.credentialsManager,
engine.resourceFields, engine.client, engine.ctx)
if err != nil {
logger.Error("Unable to add task to the engine", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
task.SetKnownStatus(apitaskstatus.TaskStopped)
task.SetDesiredStatus(apitaskstatus.TaskStopped)
engine.emitTaskEvent(task, err.Error())
return
}
// Check if ServiceConnect is Needed
if task.IsServiceConnectEnabled() {
if engine.serviceconnectRelay == nil {
engine.serviceconnectRelay, err = engine.serviceconnectManager.CreateInstanceTask(engine.cfg)
if err != nil {
logger.Error("Unable to start relay for task in the engine", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
task.SetKnownStatus(apitaskstatus.TaskStopped)
task.SetDesiredStatus(apitaskstatus.TaskStopped)
engine.emitTaskEvent(task, err.Error())
return
}
engine.AddTask(engine.serviceconnectRelay)
logger.Info("docker_task_engine: Added AppNet Relay task to engine")
}
}
engine.tasksLock.Lock()
defer engine.tasksLock.Unlock()
existingTask, exists := engine.state.TaskByArn(task.Arn)
if !exists {
// This will update the container desired status
task.UpdateDesiredStatus()
// This will update any dependencies for awsvpc network mode before the task is started.
engine.updateTaskENIDependencies(task)
engine.state.AddTask(task)
if dependencygraph.ValidDependencies(task, engine.cfg) {
engine.startTask(task)
} else {
logger.Error("Task has circular dependencies; unable to start", logger.Fields{
field.TaskID: task.GetID(),
})
task.SetKnownStatus(apitaskstatus.TaskStopped)