-
Notifications
You must be signed in to change notification settings - Fork 612
/
task.go
3812 lines (3335 loc) · 145 KB
/
task.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 task
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"time"
apicontainer "github.com/aws/amazon-ecs-agent/agent/api/container"
"github.com/aws/amazon-ecs-agent/agent/api/serviceconnect"
"github.com/aws/amazon-ecs-agent/agent/config"
"github.com/aws/amazon-ecs-agent/agent/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/dockerapi"
"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/asmsecret"
"github.com/aws/amazon-ecs-agent/agent/taskresource/credentialspec"
"github.com/aws/amazon-ecs-agent/agent/taskresource/envFiles"
"github.com/aws/amazon-ecs-agent/agent/taskresource/firelens"
"github.com/aws/amazon-ecs-agent/agent/taskresource/ssmsecret"
resourcestatus "github.com/aws/amazon-ecs-agent/agent/taskresource/status"
resourcetype "github.com/aws/amazon-ecs-agent/agent/taskresource/types"
taskresourcevolume "github.com/aws/amazon-ecs-agent/agent/taskresource/volume"
"github.com/aws/amazon-ecs-agent/agent/utils"
"github.com/aws/amazon-ecs-agent/ecs-agent/acs/model/ecsacs"
"github.com/aws/amazon-ecs-agent/ecs-agent/api/container/restart"
apicontainerstatus "github.com/aws/amazon-ecs-agent/ecs-agent/api/container/status"
"github.com/aws/amazon-ecs-agent/ecs-agent/api/ecs/model/ecs"
apierrors "github.com/aws/amazon-ecs-agent/ecs-agent/api/errors"
apitaskstatus "github.com/aws/amazon-ecs-agent/ecs-agent/api/task/status"
"github.com/aws/amazon-ecs-agent/ecs-agent/credentials"
"github.com/aws/amazon-ecs-agent/ecs-agent/logger"
"github.com/aws/amazon-ecs-agent/ecs-agent/logger/field"
nlappmesh "github.com/aws/amazon-ecs-agent/ecs-agent/netlib/model/appmesh"
ni "github.com/aws/amazon-ecs-agent/ecs-agent/netlib/model/networkinterface"
commonutils "github.com/aws/amazon-ecs-agent/ecs-agent/utils"
"github.com/aws/amazon-ecs-agent/ecs-agent/utils/arn"
"github.com/aws/amazon-ecs-agent/ecs-agent/utils/ttime"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
"github.com/docker/docker/api/types"
dockercontainer "github.com/docker/docker/api/types/container"
"github.com/docker/go-connections/nat"
"github.com/pkg/errors"
)
const (
// NetworkPauseContainerName is the internal name for the pause container
NetworkPauseContainerName = "~internal~ecs~pause"
// ServiceConnectPauseContainerNameFormat is the naming format for SC pause containers
ServiceConnectPauseContainerNameFormat = "~internal~ecs~pause-%s"
// NamespacePauseContainerName is the internal name for the IPC resource namespace and/or
// PID namespace sharing pause container
NamespacePauseContainerName = "~internal~ecs~pause~namespace"
emptyHostVolumeName = "~internal~ecs-emptyvolume-source"
// awsSDKCredentialsRelativeURIPathEnvironmentVariableName defines the name of the environment
// variable in containers' config, which will be used by the AWS SDK to fetch
// credentials.
awsSDKCredentialsRelativeURIPathEnvironmentVariableName = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"
NvidiaVisibleDevicesEnvVar = "NVIDIA_VISIBLE_DEVICES"
GPUAssociationType = "gpu"
// neuronRuntime is the name of the neuron docker runtime.
neuronRuntime = "neuron"
ContainerOrderingCreateCondition = "CREATE"
ContainerOrderingStartCondition = "START"
ContainerOrderingHealthyCondition = "HEALTHY"
// networkModeNone specifies the string used to define the `none` docker networking mode
networkModeNone = "none"
// dockerMappingContainerPrefix specifies the prefix string used for setting the
// container's option (network, ipc, or pid) to that of another existing container
dockerMappingContainerPrefix = "container:"
// awslogsCredsEndpointOpt is the awslogs option that is used to pass in a
// http endpoint for authentication
awslogsCredsEndpointOpt = "awslogs-credentials-endpoint"
// These contants identify the docker flag options
pidModeHost = "host"
pidModeTask = "task"
ipcModeHost = "host"
ipcModeTask = "task"
ipcModeSharable = "shareable"
ipcModeNone = "none"
// firelensConfigBindFormatFluentd and firelensConfigBindFormatFluentbit specify the format of the firelens
// config file bind mount for fluentd and fluentbit firelens container respectively.
// First placeholder is host data dir, second placeholder is taskID.
firelensConfigBindFormatFluentd = "%s/data/firelens/%s/config/fluent.conf:/fluentd/etc/fluent.conf"
firelensConfigBindFormatFluentbit = "%s/data/firelens/%s/config/fluent.conf:/fluent-bit/etc/fluent-bit.conf"
// firelensS3ConfigBindFormat specifies the format of the bind mount for the firelens config file downloaded from S3.
// First placeholder is host data dir, second placeholder is taskID, third placeholder is the s3 config path inside
// the firelens container.
firelensS3ConfigBindFormat = "%s/data/firelens/%s/config/external.conf:%s"
// firelensSocketBindFormat specifies the format for firelens container's socket directory bind mount.
// First placeholder is host data dir, second placeholder is taskID.
firelensSocketBindFormat = "%s/data/firelens/%s/socket/:/var/run/"
// firelensDriverName is the log driver name for containers that want to use the firelens container to send logs.
firelensDriverName = "awsfirelens"
// FirelensLogDriverBufferLimitOption is the option for customers who want to specify the buffer limit size in FireLens.
FirelensLogDriverBufferLimitOption = "log-driver-buffer-limit"
// firelensConfigVarFmt specifies the format for firelens config variable name. The first placeholder
// is option name. The second placeholder is the index of the container in the task's container list, appended
// for the purpose of avoiding config vars from different containers within a task collide (note: can't append
// container name here because it may contain hyphen which will break the config var resolution (see PR 2164 for
// details), and can't append container ID either because we need the config var in PostUnmarshalTask, which is
// before all the containers being created).
firelensConfigVarFmt = "%s_%d"
// firelensConfigVarPlaceholderFmtFluentd and firelensConfigVarPlaceholderFmtFluentbit specify the config var
// placeholder format expected by fluentd and fluentbit respectively.
firelensConfigVarPlaceholderFmtFluentd = "\"#{ENV['%s']}\""
firelensConfigVarPlaceholderFmtFluentbit = "${%s}"
// awsExecutionEnvKey is the key of the env specifying the execution environment.
awsExecutionEnvKey = "AWS_EXECUTION_ENV"
// ec2ExecutionEnv specifies the ec2 execution environment.
ec2ExecutionEnv = "AWS_ECS_EC2"
// BridgeNetworkMode specifies bridge type mode for a task
BridgeNetworkMode = "bridge"
// AWSVPCNetworkMode specifies awsvpc type mode for a task
AWSVPCNetworkMode = "awsvpc"
// HostNetworkMode specifies host type mode for a task
HostNetworkMode = "host"
// disableIPv6SysctlKey specifies the setting that controls whether ipv6 is disabled.
disableIPv6SysctlKey = "net.ipv6.conf.all.disable_ipv6"
// sysctlValueOff specifies the value to use to turn off a sysctl setting.
sysctlValueOff = "0"
serviceConnectListenerPortMappingEnvVar = "APPNET_LISTENER_PORT_MAPPING"
serviceConnectContainerMappingEnvVar = "APPNET_CONTAINER_IP_MAPPING"
// ServiceConnectAttachmentType specifies attachment type for service connect
serviceConnectAttachmentType = "serviceconnectdetail"
)
// TaskOverrides are the overrides applied to a task
type TaskOverrides struct{}
// Task is the internal representation of a task in the ECS agent
type Task struct {
// Arn is the unique identifier for the task
Arn string
// id is the id section of the task ARN
id string
// Overrides are the overrides applied to a task
Overrides TaskOverrides `json:"-"`
// Family is the name of the task definition family
Family string
// Version is the version of the task definition
Version string
// ServiceName is the name of the service to which the task belongs.
// It is empty if the task does not belong to any service.
ServiceName string
// Containers are the containers for the task
Containers []*apicontainer.Container
// Associations are the available associations for the task.
Associations []Association `json:"associations"`
// ResourcesMapUnsafe is the map of resource type to corresponding resources
ResourcesMapUnsafe resourcetype.ResourcesMap `json:"resources"`
// Volumes are the volumes for the task
Volumes []TaskVolume `json:"volumes"`
// CPU is a task-level limit for compute resources. A value of 1 means that
// the task may access 100% of 1 vCPU on the instance
CPU float64 `json:"Cpu,omitempty"`
// Memory is a task-level limit for memory resources in bytes
Memory int64 `json:"Memory,omitempty"`
// DesiredStatusUnsafe represents the state where the task should go. Generally,
// the desired status is informed by the ECS backend as a result of either
// API calls made to ECS or decisions made by the ECS service scheduler.
// The DesiredStatusUnsafe is almost always either apitaskstatus.TaskRunning or apitaskstatus.TaskStopped.
// NOTE: Do not access DesiredStatusUnsafe directly.
// Instead, use `UpdateStatus`, `UpdateDesiredStatus`, and `SetDesiredStatus`.
// TODO DesiredStatusUnsafe should probably be private with appropriately written
// setter/getter. When this is done, we need to ensure that the UnmarshalJSON
// is handled properly so that the state storage continues to work.
DesiredStatusUnsafe apitaskstatus.TaskStatus `json:"DesiredStatus"`
// KnownStatusUnsafe represents the state where the task is. This is generally
// the minimum of equivalent status types for the containers in the task;
// if one container is at ContainerRunning and another is at ContainerPulled,
// the task KnownStatusUnsafe would be TaskPulled.
// NOTE: Do not access KnownStatusUnsafe directly. Instead, use `UpdateStatus`,
// and `GetKnownStatus`.
// TODO KnownStatusUnsafe should probably be private with appropriately written
// setter/getter. When this is done, we need to ensure that the UnmarshalJSON
// is handled properly so that the state storage continues to work.
KnownStatusUnsafe apitaskstatus.TaskStatus `json:"KnownStatus"`
// KnownStatusTimeUnsafe captures the time when the KnownStatusUnsafe was last updated.
// NOTE: Do not access KnownStatusTime directly, instead use `GetKnownStatusTime`.
KnownStatusTimeUnsafe time.Time `json:"KnownTime"`
// PullStartedAtUnsafe is the timestamp when the task start pulling the first container,
// it won't be set if the pull never happens
PullStartedAtUnsafe time.Time `json:"PullStartedAt"`
// PullStoppedAtUnsafe is the timestamp when the task finished pulling the last container,
// it won't be set if the pull never happens
PullStoppedAtUnsafe time.Time `json:"PullStoppedAt"`
// ExecutionStoppedAtUnsafe is the timestamp when the task desired status moved to stopped,
// which is when any of the essential containers stopped
ExecutionStoppedAtUnsafe time.Time `json:"ExecutionStoppedAt"`
// SentStatusUnsafe represents the last KnownStatusUnsafe that was sent to the ECS SubmitTaskStateChange API.
// TODO SentStatusUnsafe should probably be private with appropriately written
// setter/getter. When this is done, we need to ensure that the UnmarshalJSON
// is handled properly so that the state storage continues to work.
SentStatusUnsafe apitaskstatus.TaskStatus `json:"SentStatus"`
// ExecutionCredentialsID is the ID of credentials that are used by agent to
// perform some action at the task level, such as pulling image from ECR
ExecutionCredentialsID string `json:"executionCredentialsID"`
// credentialsID is used to set the CredentialsId field for the
// IAMRoleCredentials object associated with the task. This id can be
// used to look up the credentials for task in the credentials manager
credentialsID string
credentialsRelativeURIUnsafe string
// ENIs is the list of Elastic Network Interfaces assigned to this task. The
// TaskENIs type is helpful when decoding state files which might have stored
// ENIs as a single ENI object instead of a list.
ENIs TaskENIs `json:"ENI"`
// AppMesh is the service mesh specified by the task
AppMesh *nlappmesh.AppMesh
// MemoryCPULimitsEnabled to determine if task supports CPU, memory limits
MemoryCPULimitsEnabled bool `json:"MemoryCPULimitsEnabled,omitempty"`
// PlatformFields consists of fields specific to linux/windows for a task
PlatformFields PlatformFields `json:"PlatformFields,omitempty"`
// terminalReason should be used when we explicitly move a task to stopped.
// This ensures the task object carries some context for why it was explicitly stopped.
terminalReason string
terminalReasonOnce sync.Once
// PIDMode is used to determine how PID namespaces are organized between
// containers of the Task
PIDMode string `json:"PidMode,omitempty"`
// IPCMode is used to determine how IPC resources should be shared among
// containers of the Task
IPCMode string `json:"IpcMode,omitempty"`
// NvidiaRuntime is the runtime to pass Nvidia GPU devices to containers
NvidiaRuntime string `json:"NvidiaRuntime,omitempty"`
// LocalIPAddressUnsafe stores the local IP address allocated to the bridge that connects the task network
// namespace and the host network namespace, for tasks in awsvpc network mode (tasks in other network mode won't
// have a value for this). This field should be accessed via GetLocalIPAddress and SetLocalIPAddress.
LocalIPAddressUnsafe string `json:"LocalIPAddress,omitempty"`
// LaunchType is the launch type of this task.
LaunchType string `json:"LaunchType,omitempty"`
// lock is for protecting all fields in the task struct
lock sync.RWMutex
// setIdOnce is used to set the value of this task's id only the first time GetID is invoked
setIdOnce sync.Once
ServiceConnectConfig *serviceconnect.Config `json:"ServiceConnectConfig,omitempty"`
ServiceConnectConnectionDrainingUnsafe bool `json:"ServiceConnectConnectionDraining,omitempty"`
NetworkMode string `json:"NetworkMode,omitempty"`
IsInternal bool `json:"IsInternal,omitempty"`
NetworkNamespace string `json:"NetworkNamespace,omitempty"`
EnableFaultInjection bool `json:"enableFaultInjection,omitempty"`
// DefaultIfname is used to reference the default network interface name on the task network namespace
// For AWSVPC mode, it can be eth0 which corresponds to the interface name on the task ENI
// For Host mode, it can vary based on the hardware/network config on the host instance (e.g. eth0, ens5, etc.) and will need to be obtained on the host.
// For all other network modes (i.e. bridge, none, etc.), DefaultIfname is currently not being initialized/set. In order to use this task field for these
// network modes, changes will need to be made in the corresponding task provisioning workflows.
DefaultIfname string `json:"DefaultIfname,omitempty"`
}
// TaskFromACS translates ecsacs.Task to apitask.Task by first marshaling the received
// ecsacs.Task to json and unmarshalling it as apitask.Task
func TaskFromACS(acsTask *ecsacs.Task, envelope *ecsacs.PayloadMessage) (*Task, error) {
data, err := jsonutil.BuildJSON(acsTask)
if err != nil {
return nil, err
}
task := &Task{}
if err := json.Unmarshal(data, task); err != nil {
return nil, err
}
// Set the EnableFaultInjection field if present
task.EnableFaultInjection = aws.BoolValue(acsTask.EnableFaultInjection)
// Overrides the container command if it's set
for _, container := range task.Containers {
if (container.Overrides != apicontainer.ContainerOverrides{}) && container.Overrides.Command != nil {
container.Command = *container.Overrides.Command
}
container.TransitionDependenciesMap = make(map[apicontainerstatus.ContainerStatus]apicontainer.TransitionDependencySet)
}
//initialize resources map for task
task.ResourcesMapUnsafe = make(map[string][]taskresource.TaskResource)
task.initNetworkMode(acsTask.NetworkMode)
// extract and validate attachments
if err := handleTaskAttachments(acsTask, task); err != nil {
return nil, err
}
return task, nil
}
func (task *Task) RemoveVolume(index int) {
task.lock.Lock()
defer task.lock.Unlock()
task.removeVolumeUnsafe(index)
}
func (task *Task) removeVolumeUnsafe(index int) {
if index < 0 || index >= len(task.Volumes) {
return
}
out := make([]TaskVolume, 0)
out = append(out, task.Volumes[:index]...)
out = append(out, task.Volumes[index+1:]...)
task.Volumes = out
}
func (task *Task) initializeVolumes(cfg *config.Config, dockerClient dockerapi.DockerClient, ctx context.Context) error {
// TODO: Have EBS volumes use the DockerVolumeConfig to create the mountpoint
err := task.initializeDockerLocalVolumes(dockerClient, ctx)
if err != nil {
return apierrors.NewResourceInitError(task.Arn, err)
}
err = task.initializeDockerVolumes(cfg.SharedVolumeMatchFullConfig.Enabled(), dockerClient, ctx)
if err != nil {
return apierrors.NewResourceInitError(task.Arn, err)
}
err = task.initializeEFSVolumes(cfg, dockerClient, ctx)
if err != nil {
return apierrors.NewResourceInitError(task.Arn, err)
}
return nil
}
// PostUnmarshalTask is run after a task has been unmarshalled, but before it has been
// run. It is possible it will be subsequently called after that and should be
// able to handle such an occurrence appropriately (e.g. behave idempotently).
func (task *Task) PostUnmarshalTask(cfg *config.Config,
credentialsManager credentials.Manager, resourceFields *taskresource.ResourceFields,
dockerClient dockerapi.DockerClient, ctx context.Context, options ...Option) error {
task.adjustForPlatform(cfg)
// Initialize cgroup resource spec definition for later cgroup resource creation.
// This sets up the cgroup spec for cpu, memory, and pids limits for the task.
// Actual cgroup creation happens later.
if err := task.initializeCgroupResourceSpec(cfg.CgroupPath, cfg.CgroupCPUPeriod, cfg.TaskPidsLimit, resourceFields); err != nil {
logger.Error("Could not initialize resource", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
return apierrors.NewResourceInitError(task.Arn, err)
}
if err := task.initServiceConnectResources(); err != nil {
logger.Error("Could not initialize Service Connect resources", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
return apierrors.NewResourceInitError(task.Arn, err)
}
if err := task.initializeContainerOrdering(); err != nil {
logger.Error("Could not initialize dependency for container", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
return apierrors.NewResourceInitError(task.Arn, err)
}
task.initSecretResources(credentialsManager, resourceFields)
task.initializeCredentialsEndpoint(credentialsManager)
// NOTE: initializeVolumes needs to be after initializeCredentialsEndpoint, because EFS volume might
// need the credentials endpoint constructed by it.
if err := task.initializeVolumes(cfg, dockerClient, ctx); err != nil {
return err
}
if err := task.addGPUResource(cfg); err != nil {
logger.Error("Could not initialize GPU associations", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
return apierrors.NewResourceInitError(task.Arn, err)
}
task.initializeContainersV3MetadataEndpoint(utils.NewDynamicUUIDProvider())
task.initializeContainersV4MetadataEndpoint(utils.NewDynamicUUIDProvider())
task.initializeContainersV1AgentAPIEndpoint(utils.NewDynamicUUIDProvider())
if err := task.addNetworkResourceProvisioningDependency(cfg); err != nil {
logger.Error("Could not provision network resource", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
return apierrors.NewResourceInitError(task.Arn, err)
}
// Adds necessary Pause containers for sharing PID or IPC namespaces
task.addNamespaceSharingProvisioningDependency(cfg)
if err := task.applyFirelensSetup(cfg, resourceFields, credentialsManager); err != nil {
return err
}
if task.requiresAnyCredentialSpecResource() {
if err := task.initializeCredentialSpecResource(cfg, credentialsManager, resourceFields); err != nil {
logger.Error("Could not initialize credentialspec resource", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
return apierrors.NewResourceInitError(task.Arn, err)
}
}
if err := task.initializeEnvfilesResource(cfg, credentialsManager); err != nil {
logger.Error("Could not initialize environment files resource", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
return apierrors.NewResourceInitError(task.Arn, err)
}
task.populateTaskARN()
// fsxWindowsFileserver is the product type -- it is technically "agnostic" ie it should apply to both Windows and Linux tasks
if task.requiresFSxWindowsFileServerResource() {
if err := task.initializeFSxWindowsFileServerResource(cfg, credentialsManager, resourceFields); err != nil {
logger.Error("Could not initialize FSx for Windows File Server resource", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
return apierrors.NewResourceInitError(task.Arn, err)
}
}
task.initRestartTrackers()
for _, opt := range options {
if err := opt(task); err != nil {
logger.Error("Could not apply task option", logger.Fields{
field.TaskID: task.GetID(),
field.Error: err,
})
return err
}
}
return nil
}
// initializeCredentialSpecResource builds the resource dependency map for the credentialspec resource
func (task *Task) initializeCredentialSpecResource(config *config.Config, credentialsManager credentials.Manager,
resourceFields *taskresource.ResourceFields) error {
credspecContainerMapping := task.GetAllCredentialSpecRequirements()
credentialspecResource, err := credentialspec.NewCredentialSpecResource(task.Arn, config.AWSRegion, task.ExecutionCredentialsID,
credentialsManager, resourceFields.SSMClientCreator, resourceFields.S3ClientCreator, resourceFields.ASMClientCreator, credspecContainerMapping)
if err != nil {
return err
}
task.AddResource(credentialspec.ResourceName, credentialspecResource)
// for every container that needs credential spec vending, it needs to wait for all credential spec resources
for _, container := range task.Containers {
if container.RequiresAnyCredentialSpec() {
container.BuildResourceDependency(credentialspecResource.GetName(),
resourcestatus.ResourceStatus(credentialspec.CredentialSpecCreated),
apicontainerstatus.ContainerCreated)
}
}
return nil
}
// initNetworkMode initializes/infers the network mode for the task and assigns the result to this task's NetworkMode field.
// ACS is streaming down this value with task payload. In case of docker bridge mode task, this value might be left empty
// as it's the default task network mode.
func (task *Task) initNetworkMode(acsTaskNetworkMode *string) {
switch aws.StringValue(acsTaskNetworkMode) {
case AWSVPCNetworkMode:
task.NetworkMode = AWSVPCNetworkMode
case HostNetworkMode:
task.NetworkMode = HostNetworkMode
case BridgeNetworkMode, "":
task.NetworkMode = BridgeNetworkMode
case networkModeNone:
task.NetworkMode = networkModeNone
default:
logger.Warn("Unmapped task network mode", logger.Fields{
field.TaskID: task.GetID(),
field.NetworkMode: aws.StringValue(acsTaskNetworkMode),
})
}
}
// initRestartTrackers initializes the restart policy tracker for each container
// that has a restart policy configured and enabled.
func (task *Task) initRestartTrackers() {
for _, c := range task.Containers {
if c.RestartPolicyEnabled() {
c.RestartTracker = restart.NewRestartTracker(*c.RestartPolicy)
}
}
}
func (task *Task) initServiceConnectResources() error {
// TODO [SC]: ServiceConnectConfig will come from ACS. Adding this here for dev/testing purposes only Remove when
// ACS model is integrated
if task.ServiceConnectConfig == nil {
task.ServiceConnectConfig = &serviceconnect.Config{
ContainerName: "service-connect",
}
}
if task.IsServiceConnectEnabled() {
// TODO [SC]: initDummyServiceConnectConfig is for dev testing only, remove it when final SC model from ACS is in place
task.initDummyServiceConnectConfig()
if err := task.initServiceConnectEphemeralPorts(); err != nil {
return err
}
}
return nil
}
// TODO [SC]: This is for dev testing only, remove it when final SC model from ACS is in place
func (task *Task) initDummyServiceConnectConfig() {
scContainer := task.GetServiceConnectContainer()
if _, ok := scContainer.Environment["SC_CONFIG"]; !ok {
// no SC_CONFIG :(
return
}
if err := json.Unmarshal([]byte(scContainer.Environment["SC_CONFIG"]), task.ServiceConnectConfig); err != nil {
logger.Error("Error parsing SC_CONFIG", logger.Fields{
field.Error: err,
})
return
}
}
func (task *Task) initServiceConnectEphemeralPorts() error {
var utilizedPorts []uint16
// First determine how many ephemeral ports we need
var numEphemeralPortsNeeded int
for _, ic := range task.ServiceConnectConfig.IngressConfig {
if ic.ListenerPort == 0 { // This means listener port was not sent to us by ACS, signaling the port needs to be ephemeral
numEphemeralPortsNeeded++
} else {
utilizedPorts = append(utilizedPorts, ic.ListenerPort)
}
}
// Presently, SC egress port is always ephemeral, but adding this for future-proofing
if task.ServiceConnectConfig.EgressConfig != nil {
if task.ServiceConnectConfig.EgressConfig.ListenerPort == 0 {
numEphemeralPortsNeeded++
} else {
utilizedPorts = append(utilizedPorts, task.ServiceConnectConfig.EgressConfig.ListenerPort)
}
}
// Get all exposed ports in the task so that the ephemeral port generator doesn't take those into account in order
// to avoid port conflicts.
for _, c := range task.Containers {
for _, p := range c.Ports {
utilizedPorts = append(utilizedPorts, p.ContainerPort)
}
}
ephemeralPorts, err := utils.GenerateEphemeralPortNumbers(numEphemeralPortsNeeded, utilizedPorts)
if err != nil {
return fmt.Errorf("error initializing ports for Service Connect: %w", err)
}
// Assign ephemeral ports
portMapping := make(map[string]uint16)
var curEphemeralIndex int
for i, ic := range task.ServiceConnectConfig.IngressConfig {
if ic.ListenerPort == 0 {
portMapping[ic.ListenerName] = ephemeralPorts[curEphemeralIndex]
task.ServiceConnectConfig.IngressConfig[i].ListenerPort = ephemeralPorts[curEphemeralIndex]
curEphemeralIndex++
}
}
if task.ServiceConnectConfig.EgressConfig != nil && task.ServiceConnectConfig.EgressConfig.ListenerPort == 0 {
portMapping[task.ServiceConnectConfig.EgressConfig.ListenerName] = ephemeralPorts[curEphemeralIndex]
task.ServiceConnectConfig.EgressConfig.ListenerPort = ephemeralPorts[curEphemeralIndex]
}
// Add the APPNET_LISTENER_PORT_MAPPING env var for listeners that require it
envVars := make(map[string]string)
portMappingJson, err := json.Marshal(portMapping)
if err != nil {
return fmt.Errorf("error injecting required env vars to Service Connect container: %w", err)
}
envVars[serviceConnectListenerPortMappingEnvVar] = string(portMappingJson)
task.GetServiceConnectContainer().MergeEnvironmentVariables(envVars)
return nil
}
// populateTaskARN populates the arn of the task to the containers.
func (task *Task) populateTaskARN() {
for _, c := range task.Containers {
c.SetTaskARN(task.Arn)
}
}
func (task *Task) initSecretResources(credentialsManager credentials.Manager,
resourceFields *taskresource.ResourceFields) {
if task.requiresASMDockerAuthData() {
task.initializeASMAuthResource(credentialsManager, resourceFields)
}
if task.requiresSSMSecret() {
task.initializeSSMSecretResource(credentialsManager, resourceFields)
}
if task.requiresASMSecret() {
task.initializeASMSecretResource(credentialsManager, resourceFields)
}
}
func (task *Task) applyFirelensSetup(cfg *config.Config, resourceFields *taskresource.ResourceFields,
credentialsManager credentials.Manager) error {
firelensContainer := task.GetFirelensContainer()
if firelensContainer != nil {
if err := task.initializeFirelensResource(cfg, resourceFields, firelensContainer, credentialsManager); err != nil {
return apierrors.NewResourceInitError(task.Arn, err)
}
if err := task.addFirelensContainerDependency(); err != nil {
return errors.New("unable to add firelens container dependency")
}
}
return nil
}
func (task *Task) addGPUResource(cfg *config.Config) error {
if cfg.GPUSupportEnabled {
for _, association := range task.Associations {
// One GPU can be associated with only one container
// That is why validating if association.Containers is of length 1
if association.Type == GPUAssociationType {
if len(association.Containers) != 1 {
return fmt.Errorf("could not associate multiple containers to GPU %s", association.Name)
}
container, ok := task.ContainerByName(association.Containers[0])
if !ok {
return fmt.Errorf("could not find container with name %s for associating GPU %s",
association.Containers[0], association.Name)
}
container.GPUIDs = append(container.GPUIDs, association.Name)
}
}
// For external instances, GPU IDs are handled by resources struct
// For internal instances, GPU IDs are handled by env var
if !cfg.External.Enabled() {
task.populateGPUEnvironmentVariables()
task.NvidiaRuntime = cfg.NvidiaRuntime
}
}
return nil
}
func (task *Task) isGPUEnabled() bool {
for _, association := range task.Associations {
if association.Type == GPUAssociationType {
return true
}
}
return false
}
func (task *Task) populateGPUEnvironmentVariables() {
for _, container := range task.Containers {
if len(container.GPUIDs) > 0 {
gpuList := strings.Join(container.GPUIDs, ",")
envVars := make(map[string]string)
envVars[NvidiaVisibleDevicesEnvVar] = gpuList
container.MergeEnvironmentVariables(envVars)
}
}
}
func (task *Task) shouldRequireNvidiaRuntime(container *apicontainer.Container) bool {
_, ok := container.Environment[NvidiaVisibleDevicesEnvVar]
return ok
}
func (task *Task) initializeDockerLocalVolumes(dockerClient dockerapi.DockerClient, ctx context.Context) error {
var requiredLocalVolumes []string
for _, container := range task.Containers {
for _, mountPoint := range container.MountPoints {
vol, ok := task.HostVolumeByName(mountPoint.SourceVolume)
if !ok {
continue
}
if localVolume, ok := vol.(*taskresourcevolume.LocalDockerVolume); ok {
localVolume.HostPath = task.volumeName(mountPoint.SourceVolume)
container.BuildResourceDependency(mountPoint.SourceVolume,
resourcestatus.ResourceStatus(taskresourcevolume.VolumeCreated),
apicontainerstatus.ContainerPulled)
requiredLocalVolumes = append(requiredLocalVolumes, mountPoint.SourceVolume)
}
}
}
if len(requiredLocalVolumes) == 0 {
// No need to create the auxiliary local driver volumes
return nil
}
// if we have required local volumes, create one with default local drive
for _, volumeName := range requiredLocalVolumes {
vol, _ := task.HostVolumeByName(volumeName)
// BUG(samuelkarp) On Windows, volumes with names that differ only by case will collide
scope := taskresourcevolume.TaskScope
localVolume, err := taskresourcevolume.NewVolumeResource(ctx, volumeName, HostVolumeType,
vol.Source(), scope, false,
taskresourcevolume.DockerLocalVolumeDriver,
make(map[string]string), make(map[string]string), dockerClient)
if err != nil {
return err
}
task.AddResource(resourcetype.DockerVolumeKey, localVolume)
}
return nil
}
func (task *Task) volumeName(name string) string {
return "ecs-" + task.Family + "-" + task.Version + "-" + name + "-" + utils.RandHex()
}
// initializeDockerVolumes checks the volume resource in the task to determine if the agent
// should create the volume before creating the container
func (task *Task) initializeDockerVolumes(sharedVolumeMatchFullConfig bool, dockerClient dockerapi.DockerClient, ctx context.Context) error {
for i, vol := range task.Volumes {
// No need to do this for non-docker volume, eg: host bind/empty volume
if vol.Type != DockerVolumeType {
continue
}
dockerVolume, ok := vol.Volume.(*taskresourcevolume.DockerVolumeConfig)
if !ok {
return errors.New("task volume: volume configuration does not match the type 'docker'")
}
// Agent needs to create task-scoped volume
if dockerVolume.Scope == taskresourcevolume.TaskScope {
if err := task.addTaskScopedVolumes(ctx, dockerClient, &task.Volumes[i]); err != nil {
return err
}
} else {
// Agent needs to create shared volume if that's auto provisioned
if err := task.addSharedVolumes(sharedVolumeMatchFullConfig, ctx, dockerClient, &task.Volumes[i]); err != nil {
return err
}
}
}
return nil
}
// initializeEFSVolumes inspects the volume definitions in the task definition.
// If it finds EFS volumes in the task definition, then it converts it to a docker
// volume definition.
func (task *Task) initializeEFSVolumes(cfg *config.Config, dockerClient dockerapi.DockerClient, ctx context.Context) error {
for i, vol := range task.Volumes {
// No need to do this for non-efs volume, eg: host bind/empty volume
if vol.Type != EFSVolumeType {
continue
}
efsvol, ok := vol.Volume.(*taskresourcevolume.EFSVolumeConfig)
if !ok {
return errors.New("task volume: volume configuration does not match the type 'efs'")
}
err := task.addEFSVolumes(ctx, cfg, dockerClient, &task.Volumes[i], efsvol)
if err != nil {
return err
}
}
return nil
}
// addEFSVolumes converts the EFS task definition into an internal docker 'local' volume
// mounted with NFS struct and updates container dependency
func (task *Task) addEFSVolumes(
ctx context.Context,
cfg *config.Config,
dockerClient dockerapi.DockerClient,
vol *TaskVolume,
efsvol *taskresourcevolume.EFSVolumeConfig,
) error {
driverOpts := taskresourcevolume.GetDriverOptions(cfg, efsvol, task.GetCredentialsRelativeURI())
driverName := getEFSVolumeDriverName(cfg)
volumeResource, err := taskresourcevolume.NewVolumeResource(
ctx,
vol.Name,
EFSVolumeType,
task.volumeName(vol.Name),
"task",
false,
driverName,
driverOpts,
map[string]string{},
dockerClient,
)
if err != nil {
return err
}
vol.Volume = &volumeResource.VolumeConfig
task.AddResource(resourcetype.DockerVolumeKey, volumeResource)
task.updateContainerVolumeDependency(vol.Name)
return nil
}
// addTaskScopedVolumes adds the task scoped volume into task resources and updates container dependency
func (task *Task) addTaskScopedVolumes(ctx context.Context, dockerClient dockerapi.DockerClient,
vol *TaskVolume) error {
volumeConfig := vol.Volume.(*taskresourcevolume.DockerVolumeConfig)
volumeResource, err := taskresourcevolume.NewVolumeResource(
ctx,
vol.Name,
DockerVolumeType,
task.volumeName(vol.Name),
volumeConfig.Scope, volumeConfig.Autoprovision,
volumeConfig.Driver, volumeConfig.DriverOpts,
volumeConfig.Labels, dockerClient)
if err != nil {
return err
}
vol.Volume = &volumeResource.VolumeConfig
task.AddResource(resourcetype.DockerVolumeKey, volumeResource)
task.updateContainerVolumeDependency(vol.Name)
return nil
}
// addSharedVolumes adds shared volume into task resources and updates container dependency
func (task *Task) addSharedVolumes(SharedVolumeMatchFullConfig bool, ctx context.Context, dockerClient dockerapi.DockerClient,
vol *TaskVolume) error {
volumeConfig := vol.Volume.(*taskresourcevolume.DockerVolumeConfig)
volumeConfig.DockerVolumeName = vol.Name
// if autoprovision == true, we will auto-provision the volume if it does not exist already
// else the named volume must exist
if !volumeConfig.Autoprovision {
volumeMetadata := dockerClient.InspectVolume(ctx, vol.Name, dockerclient.InspectVolumeTimeout)
if volumeMetadata.Error != nil {
return errors.Wrapf(volumeMetadata.Error, "initialize volume: volume detection failed, volume '%s' does not exist and autoprovision is set to false", vol.Name)
}
return nil
}
// at this point we know autoprovision = true
// check if the volume configuration matches the one exists on the instance
volumeMetadata := dockerClient.InspectVolume(ctx, volumeConfig.DockerVolumeName, dockerclient.InspectVolumeTimeout)
if volumeMetadata.Error != nil {
// Inspect the volume timed out, fail the task
if _, ok := volumeMetadata.Error.(*dockerapi.DockerTimeoutError); ok {
return volumeMetadata.Error
}
logger.Error("Failed to initialize non-autoprovisioned volume", logger.Fields{
field.TaskID: task.GetID(),
field.Volume: vol.Name,
field.Error: volumeMetadata.Error,
})
// this resource should be created by agent
volumeResource, err := taskresourcevolume.NewVolumeResource(
ctx,
vol.Name,
DockerVolumeType,
vol.Name,
volumeConfig.Scope, volumeConfig.Autoprovision,
volumeConfig.Driver, volumeConfig.DriverOpts,
volumeConfig.Labels, dockerClient)
if err != nil {
return err
}
task.AddResource(resourcetype.DockerVolumeKey, volumeResource)
task.updateContainerVolumeDependency(vol.Name)
return nil
}
logger.Debug("Volume already exists", logger.Fields{
field.TaskID: task.GetID(),
field.Volume: volumeConfig.DockerVolumeName,
})
if !SharedVolumeMatchFullConfig {
logger.Info("ECS_SHARED_VOLUME_MATCH_FULL_CONFIG is set to false and volume was found", logger.Fields{
field.TaskID: task.GetID(),
field.Volume: volumeConfig.DockerVolumeName,
})
return nil
}
// validate all the volume metadata fields match to the configuration
if len(volumeMetadata.DockerVolume.Labels) == 0 && len(volumeMetadata.DockerVolume.Labels) == len(volumeConfig.Labels) {
logger.Info("Volume labels are both empty or null", logger.Fields{
field.TaskID: task.GetID(),
field.Volume: volumeConfig.DockerVolumeName,
})
} else if !reflect.DeepEqual(volumeMetadata.DockerVolume.Labels, volumeConfig.Labels) {
return errors.Errorf("intialize volume: non-autoprovisioned volume does not match existing volume labels: existing: %v, expected: %v",
volumeMetadata.DockerVolume.Labels, volumeConfig.Labels)
}
if len(volumeMetadata.DockerVolume.Options) == 0 && len(volumeMetadata.DockerVolume.Options) == len(volumeConfig.DriverOpts) {
logger.Info("Volume driver options are both empty or null", logger.Fields{
field.TaskID: task.GetID(),
field.Volume: volumeConfig.DockerVolumeName,
})
} else if !reflect.DeepEqual(volumeMetadata.DockerVolume.Options, volumeConfig.DriverOpts) {
return errors.Errorf("initialize volume: non-autoprovisioned volume does not match existing volume options: existing: %v, expected: %v",
volumeMetadata.DockerVolume.Options, volumeConfig.DriverOpts)
}
// Right now we are not adding shared, autoprovision = true volume to task as resource if it already exists (i.e. when this task didn't create the volume).
// if we need to change that, make a call to task.AddResource here.
return nil
}
// updateContainerVolumeDependency adds the volume resource to container dependency
func (task *Task) updateContainerVolumeDependency(name string) {
// Find all the container that depends on the volume
for _, container := range task.Containers {
for _, mountpoint := range container.MountPoints {
if mountpoint.SourceVolume == name {
container.BuildResourceDependency(name,
resourcestatus.ResourceCreated,
apicontainerstatus.ContainerPulled)
}
}
}
}
// initializeCredentialsEndpoint sets the credentials endpoint for all containers in a task if needed.
func (task *Task) initializeCredentialsEndpoint(credentialsManager credentials.Manager) {
id := task.GetCredentialsID()
if id == "" {
// No credentials set for the task. Do not inject the endpoint environment variable.
return
}
taskCredentials, ok := credentialsManager.GetTaskCredentials(id)
if !ok {
// Task has credentials id set, but credentials manager is unaware of
// the id. This should never happen as the payload handler sets
// credentialsId for the task after adding credentials to the
// credentials manager
logger.Error("Unable to get credentials for task", logger.Fields{
field.TaskID: task.GetID(),