-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
container-definition.ts
1240 lines (1095 loc) · 38.1 KB
/
container-definition.ts
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
import * as iam from '@aws-cdk/aws-iam';
import * as secretsmanager from '@aws-cdk/aws-secretsmanager';
import * as ssm from '@aws-cdk/aws-ssm';
import * as cdk from '@aws-cdk/core';
import { Construct } from 'constructs';
import { NetworkMode, TaskDefinition } from './base/task-definition';
import { ContainerImage, ContainerImageConfig } from './container-image';
import { CfnTaskDefinition } from './ecs.generated';
import { EnvironmentFile, EnvironmentFileConfig } from './environment-file';
import { LinuxParameters } from './linux-parameters';
import { LogDriver, LogDriverConfig } from './log-drivers/log-driver';
/**
* Specify the secret's version id or version stage
*/
export interface SecretVersionInfo {
/**
* version id of the secret
*
* @default - use default version id
*/
readonly versionId?: string;
/**
* version stage of the secret
*
* @default - use default version stage
*/
readonly versionStage?: string;
}
/**
* A secret environment variable.
*/
export abstract class Secret {
/**
* Creates an environment variable value from a parameter stored in AWS
* Systems Manager Parameter Store.
*/
public static fromSsmParameter(parameter: ssm.IParameter): Secret {
return {
arn: parameter.parameterArn,
grantRead: grantee => parameter.grantRead(grantee),
};
}
/**
* Creates a environment variable value from a secret stored in AWS Secrets
* Manager.
*
* @param secret the secret stored in AWS Secrets Manager
* @param field the name of the field with the value that you want to set as
* the environment variable value. Only values in JSON format are supported.
* If you do not specify a JSON field, then the full content of the secret is
* used.
*/
public static fromSecretsManager(secret: secretsmanager.ISecret, field?: string): Secret {
return {
arn: field ? `${secret.secretArn}:${field}::` : secret.secretArn,
hasField: !!field,
grantRead: grantee => secret.grantRead(grantee),
};
}
/**
* Creates a environment variable value from a secret stored in AWS Secrets
* Manager.
*
* @param secret the secret stored in AWS Secrets Manager
* @param versionInfo the version information to reference the secret
* @param field the name of the field with the value that you want to set as
* the environment variable value. Only values in JSON format are supported.
* If you do not specify a JSON field, then the full content of the secret is
* used.
*/
public static fromSecretsManagerVersion(secret: secretsmanager.ISecret, versionInfo: SecretVersionInfo, field?: string): Secret {
return {
arn: `${secret.secretArn}:${field ?? ''}:${versionInfo.versionStage ?? ''}:${versionInfo.versionId ?? ''}`,
hasField: !!field,
grantRead: grantee => secret.grantRead(grantee),
};
}
/**
* The ARN of the secret
*/
public abstract readonly arn: string;
/**
* Whether this secret uses a specific JSON field
*/
public abstract readonly hasField?: boolean;
/**
* Grants reading the secret to a principal
*/
public abstract grantRead(grantee: iam.IGrantable): iam.Grant;
}
/*
* The options for creating a container definition.
*/
export interface ContainerDefinitionOptions {
/**
* The image used to start a container.
*
* This string is passed directly to the Docker daemon.
* Images in the Docker Hub registry are available by default.
* Other repositories are specified with either repository-url/image:tag or repository-url/image@digest.
* TODO: Update these to specify using classes of IContainerImage
*/
readonly image: ContainerImage;
/**
* The name of the container.
*
* @default - id of node associated with ContainerDefinition.
*/
readonly containerName?: string;
/**
* The command that is passed to the container.
*
* If you provide a shell command as a single string, you have to quote command-line arguments.
*
* @default - CMD value built into container image.
*/
readonly command?: string[];
/**
* The minimum number of CPU units to reserve for the container.
*
* @default - No minimum CPU units reserved.
*/
readonly cpu?: number;
/**
* Specifies whether networking is disabled within the container.
*
* When this parameter is true, networking is disabled within the container.
*
* @default false
*/
readonly disableNetworking?: boolean;
/**
* A list of DNS search domains that are presented to the container.
*
* @default - No search domains.
*/
readonly dnsSearchDomains?: string[];
/**
* A list of DNS servers that are presented to the container.
*
* @default - Default DNS servers.
*/
readonly dnsServers?: string[];
/**
* A key/value map of labels to add to the container.
*
* @default - No labels.
*/
readonly dockerLabels?: { [key: string]: string };
/**
* A list of strings to provide custom labels for SELinux and AppArmor multi-level security systems.
*
* @default - No security labels.
*/
readonly dockerSecurityOptions?: string[];
/**
* The ENTRYPOINT value to pass to the container.
*
* @see https://docs.docker.com/engine/reference/builder/#entrypoint
*
* @default - Entry point configured in container.
*/
readonly entryPoint?: string[];
/**
* The environment variables to pass to the container.
*
* @default - No environment variables.
*/
readonly environment?: { [key: string]: string };
/**
* The environment files to pass to the container.
*
* @see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/taskdef-envfiles.html
*
* @default - No environment files.
*/
readonly environmentFiles?: EnvironmentFile[];
/**
* The secret environment variables to pass to the container.
*
* @default - No secret environment variables.
*/
readonly secrets?: { [key: string]: Secret };
/**
* Time duration (in seconds) to wait before giving up on resolving dependencies for a container.
*
* @default - none
*/
readonly startTimeout?: cdk.Duration;
/**
* Time duration (in seconds) to wait before the container is forcefully killed if it doesn't exit normally on its own.
*
* @default - none
*/
readonly stopTimeout?: cdk.Duration;
/**
* Specifies whether the container is marked essential.
*
* If the essential parameter of a container is marked as true, and that container fails
* or stops for any reason, all other containers that are part of the task are stopped.
* If the essential parameter of a container is marked as false, then its failure does not
* affect the rest of the containers in a task. All tasks must have at least one essential container.
*
* If this parameter is omitted, a container is assumed to be essential.
*
* @default true
*/
readonly essential?: boolean;
/**
* A list of hostnames and IP address mappings to append to the /etc/hosts file on the container.
*
* @default - No extra hosts.
*/
readonly extraHosts?: { [name: string]: string };
/**
* The health check command and associated configuration parameters for the container.
*
* @default - Health check configuration from container.
*/
readonly healthCheck?: HealthCheck;
/**
* The hostname to use for your container.
*
* @default - Automatic hostname.
*/
readonly hostname?: string;
/**
* The amount (in MiB) of memory to present to the container.
*
* If your container attempts to exceed the allocated memory, the container
* is terminated.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required for non-Fargate services.
*
* @default - No memory limit.
*/
readonly memoryLimitMiB?: number;
/**
* The soft limit (in MiB) of memory to reserve for the container.
*
* When system memory is under heavy contention, Docker attempts to keep the
* container memory to this soft limit. However, your container can consume more
* memory when it needs to, up to either the hard limit specified with the memory
* parameter (if applicable), or all of the available memory on the container
* instance, whichever comes first.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required for non-Fargate services.
*
* @default - No memory reserved.
*/
readonly memoryReservationMiB?: number;
/**
* Specifies whether the container is marked as privileged.
* When this parameter is true, the container is given elevated privileges on the host container instance (similar to the root user).
*
* @default false
*/
readonly privileged?: boolean;
/**
* When this parameter is true, the container is given read-only access to its root file system.
*
* @default false
*/
readonly readonlyRootFilesystem?: boolean;
/**
* The user name to use inside the container.
*
* @default root
*/
readonly user?: string;
/**
* The working directory in which to run commands inside the container.
*
* @default /
*/
readonly workingDirectory?: string;
/**
* The log configuration specification for the container.
*
* @default - Containers use the same logging driver that the Docker daemon uses.
*/
readonly logging?: LogDriver;
/**
* Linux-specific modifications that are applied to the container, such as Linux kernel capabilities.
* For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html).
*
* @default - No Linux parameters.
*/
readonly linuxParameters?: LinuxParameters;
/**
* The number of GPUs assigned to the container.
*
* @default - No GPUs assigned.
*/
readonly gpuCount?: number;
/**
* The port mappings to add to the container definition.
* @default - No ports are mapped.
*/
readonly portMappings?: PortMapping[];
/**
* The inference accelerators referenced by the container.
* @default - No inference accelerators assigned.
*/
readonly inferenceAcceleratorResources?: string[];
/**
* A list of namespaced kernel parameters to set in the container.
*
* @default - No system controls are set.
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-systemcontrol.html
* @see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definition_systemcontrols
*/
readonly systemControls?: SystemControl[];
}
/**
* The properties in a container definition.
*/
export interface ContainerDefinitionProps extends ContainerDefinitionOptions {
/**
* The name of the task definition that includes this container definition.
*
* [disable-awslint:ref-via-interface]
*/
readonly taskDefinition: TaskDefinition;
}
/**
* A container definition is used in a task definition to describe the containers that are launched as part of a task.
*/
export class ContainerDefinition extends Construct {
/**
* The Linux-specific modifications that are applied to the container, such as Linux kernel capabilities.
*/
public readonly linuxParameters?: LinuxParameters;
/**
* The mount points for data volumes in your container.
*/
public readonly mountPoints = new Array<MountPoint>();
/**
* The list of port mappings for the container. Port mappings allow containers to access ports
* on the host container instance to send or receive traffic.
*/
public readonly portMappings = new Array<PortMapping>();
/**
* The data volumes to mount from another container in the same task definition.
*/
public readonly volumesFrom = new Array<VolumeFrom>();
/**
* An array of ulimits to set in the container.
*/
public readonly ulimits = new Array<Ulimit>();
/**
* An array dependencies defined for container startup and shutdown.
*/
public readonly containerDependencies = new Array<ContainerDependency>();
/**
* Specifies whether the container will be marked essential.
*
* If the essential parameter of a container is marked as true, and that container
* fails or stops for any reason, all other containers that are part of the task are
* stopped. If the essential parameter of a container is marked as false, then its
* failure does not affect the rest of the containers in a task.
*
* If this parameter is omitted, a container is assumed to be essential.
*/
public readonly essential: boolean;
/**
* The name of this container
*/
public readonly containerName: string;
/**
* Whether there was at least one memory limit specified in this definition
*/
public readonly memoryLimitSpecified: boolean;
/**
* The name of the task definition that includes this container definition.
*/
public readonly taskDefinition: TaskDefinition;
/**
* The environment files for this container
*/
public readonly environmentFiles?: EnvironmentFileConfig[];
/**
* The log configuration specification for the container.
*/
public readonly logDriverConfig?: LogDriverConfig;
/**
* The name of the image referenced by this container.
*/
public readonly imageName: string;
/**
* The inference accelerators referenced by this container.
*/
private readonly inferenceAcceleratorResources: string[] = [];
/**
* The configured container links
*/
private readonly links = new Array<string>();
private readonly imageConfig: ContainerImageConfig;
private readonly secrets: CfnTaskDefinition.SecretProperty[] = [];
private readonly environment: { [key: string]: string };
private _namedPorts: Map<string, PortMapping>;
/**
* Constructs a new instance of the ContainerDefinition class.
*/
constructor(scope: Construct, id: string, private readonly props: ContainerDefinitionProps) {
super(scope, id);
if (props.memoryLimitMiB !== undefined && props.memoryReservationMiB !== undefined) {
if (props.memoryLimitMiB < props.memoryReservationMiB) {
throw new Error('MemoryLimitMiB should not be less than MemoryReservationMiB.');
}
}
this.essential = props.essential ?? true;
this.taskDefinition = props.taskDefinition;
this.memoryLimitSpecified = props.memoryLimitMiB !== undefined || props.memoryReservationMiB !== undefined;
this.linuxParameters = props.linuxParameters;
this.containerName = props.containerName ?? this.node.id;
this.imageConfig = props.image.bind(this, this);
this.imageName = this.imageConfig.imageName;
this._namedPorts = new Map<string, PortMapping>();
if (props.logging) {
this.logDriverConfig = props.logging.bind(this, this);
}
if (props.secrets) {
for (const [name, secret] of Object.entries(props.secrets)) {
this.addSecret(name, secret);
}
}
if (props.environment) {
this.environment = { ...props.environment };
} else {
this.environment = {};
}
if (props.environmentFiles) {
this.environmentFiles = [];
for (const environmentFile of props.environmentFiles) {
this.environmentFiles.push(environmentFile.bind(this));
}
}
props.taskDefinition._linkContainer(this);
if (props.portMappings) {
this.addPortMappings(...props.portMappings);
}
if (props.inferenceAcceleratorResources) {
this.addInferenceAcceleratorResource(...props.inferenceAcceleratorResources);
}
}
/**
* This method adds a link which allows containers to communicate with each other without the need for port mappings.
*
* This parameter is only supported if the task definition is using the bridge network mode.
* Warning: The --link flag is a legacy feature of Docker. It may eventually be removed.
*/
public addLink(container: ContainerDefinition, alias?: string) {
if (this.taskDefinition.networkMode !== NetworkMode.BRIDGE) {
throw new Error('You must use network mode Bridge to add container links.');
}
if (alias !== undefined) {
this.links.push(`${container.containerName}:${alias}`);
} else {
this.links.push(`${container.containerName}`);
}
}
/**
* This method adds one or more mount points for data volumes to the container.
*/
public addMountPoints(...mountPoints: MountPoint[]) {
this.mountPoints.push(...mountPoints);
}
/**
* This method mounts temporary disk space to the container.
*
* This adds the correct container mountPoint and task definition volume.
*/
public addScratch(scratch: ScratchSpace) {
const mountPoint = {
containerPath: scratch.containerPath,
readOnly: scratch.readOnly,
sourceVolume: scratch.name,
};
const volume = {
host: {
sourcePath: scratch.sourcePath,
},
name: scratch.name,
};
this.taskDefinition.addVolume(volume);
this.addMountPoints(mountPoint);
}
/**
* This method adds one or more port mappings to the container.
*/
public addPortMappings(...portMappings: PortMapping[]) {
this.portMappings.push(...portMappings.map(pm => {
if (this.taskDefinition.networkMode === NetworkMode.AWS_VPC || this.taskDefinition.networkMode === NetworkMode.HOST) {
if (pm.containerPort !== pm.hostPort && pm.hostPort !== undefined) {
throw new Error(`Host port (${pm.hostPort}) must be left out or equal to container port ${pm.containerPort} for network mode ${this.taskDefinition.networkMode}`);
}
}
// No empty strings as port mapping names.
if (pm.name === '') {
throw new Error('Port mapping name cannot be an empty string.');
}
// Service connect logic.
if (pm.name || pm.appProtocol) {
// Service connect only supports Awsvpc and Bridge network modes.
if (![NetworkMode.BRIDGE, NetworkMode.AWS_VPC].includes(this.taskDefinition.networkMode)) {
throw new Error(`Service connect related port mapping fields 'name' and 'appProtocol' are not supported for network mode ${this.taskDefinition.networkMode}`);
}
// Name is not set but App Protocol is; this config is meaningless and we should throw.
if (!pm.name) {
throw new Error('Service connect-related port mapping field \'appProtocol\' cannot be set without \'name\'');
}
if (this._namedPorts.has(pm.name)) {
throw new Error(`Port mapping name '${pm.name}' already exists on this container`);
}
this._namedPorts.set(pm.name, pm);
}
if (this.taskDefinition.networkMode === NetworkMode.BRIDGE) {
if (pm.hostPort === undefined) {
pm = {
...pm,
hostPort: 0,
};
}
}
return pm;
}));
}
/**
* This method adds an environment variable to the container.
*/
public addEnvironment(name: string, value: string) {
this.environment[name] = value;
}
/**
* This method adds a secret as environment variable to the container.
*/
public addSecret(name: string, secret: Secret) {
secret.grantRead(this.taskDefinition.obtainExecutionRole());
this.secrets.push({
name,
valueFrom: secret.arn,
});
}
/**
* This method adds one or more resources to the container.
*/
public addInferenceAcceleratorResource(...inferenceAcceleratorResources: string[]) {
this.inferenceAcceleratorResources.push(...inferenceAcceleratorResources.map(resource => {
for (const inferenceAccelerator of this.taskDefinition.inferenceAccelerators) {
if (resource === inferenceAccelerator.deviceName) {
return resource;
}
}
throw new Error(`Resource value ${resource} in container definition doesn't match any inference accelerator device name in the task definition.`);
}));
}
/**
* This method adds one or more ulimits to the container.
*/
public addUlimits(...ulimits: Ulimit[]) {
this.ulimits.push(...ulimits);
}
/**
* This method adds one or more container dependencies to the container.
*/
public addContainerDependencies(...containerDependencies: ContainerDependency[]) {
this.containerDependencies.push(...containerDependencies);
}
/**
* This method adds one or more volumes to the container.
*/
public addVolumesFrom(...volumesFrom: VolumeFrom[]) {
this.volumesFrom.push(...volumesFrom);
}
/**
* This method adds the specified statement to the IAM task execution policy in the task definition.
*/
public addToExecutionPolicy(statement: iam.PolicyStatement) {
this.taskDefinition.addToExecutionRolePolicy(statement);
}
/**
* Returns the host port for the requested container port if it exists
*/
public findPortMapping(containerPort: number, protocol: Protocol): PortMapping | undefined {
for (const portMapping of this.portMappings) {
const p = portMapping.protocol || Protocol.TCP;
const c = portMapping.containerPort;
if (c === containerPort && p === protocol) {
return portMapping;
}
}
return undefined;
}
/**
* Returns the port mapping with the given name, if it exists.
*/
public findPortMappingByName(name: string): PortMapping | undefined {
return this._namedPorts.get(name);
}
/**
* Whether this container definition references a specific JSON field of a secret
* stored in Secrets Manager.
*/
public get referencesSecretJsonField(): boolean | undefined {
for (const secret of this.secrets) {
if (secret.valueFrom.endsWith('::')) {
return true;
}
}
return false;
}
/**
* The inbound rules associated with the security group the task or service will use.
*
* This property is only used for tasks that use the awsvpc network mode.
*/
public get ingressPort(): number {
if (this.portMappings.length === 0) {
throw new Error(`Container ${this.containerName} hasn't defined any ports. Call addPortMappings().`);
}
const defaultPortMapping = this.portMappings[0];
if (defaultPortMapping.hostPort !== undefined && defaultPortMapping.hostPort !== 0) {
return defaultPortMapping.hostPort;
}
if (this.taskDefinition.networkMode === NetworkMode.BRIDGE) {
return 0;
}
return defaultPortMapping.containerPort;
}
/**
* The port the container will listen on.
*/
public get containerPort(): number {
if (this.portMappings.length === 0) {
throw new Error(`Container ${this.containerName} hasn't defined any ports. Call addPortMappings().`);
}
const defaultPortMapping = this.portMappings[0];
return defaultPortMapping.containerPort;
}
/**
* Render this container definition to a CloudFormation object
*
* @param _taskDefinition [disable-awslint:ref-via-interface] (unused but kept to avoid breaking change)
*/
public renderContainerDefinition(_taskDefinition?: TaskDefinition): CfnTaskDefinition.ContainerDefinitionProperty {
return {
command: this.props.command,
cpu: this.props.cpu,
disableNetworking: this.props.disableNetworking,
dependsOn: cdk.Lazy.any({ produce: () => this.containerDependencies.map(renderContainerDependency) }, { omitEmptyArray: true }),
dnsSearchDomains: this.props.dnsSearchDomains,
dnsServers: this.props.dnsServers,
dockerLabels: this.props.dockerLabels,
dockerSecurityOptions: this.props.dockerSecurityOptions,
entryPoint: this.props.entryPoint,
essential: this.essential,
hostname: this.props.hostname,
image: this.imageConfig.imageName,
memory: this.props.memoryLimitMiB,
memoryReservation: this.props.memoryReservationMiB,
mountPoints: cdk.Lazy.any({ produce: () => this.mountPoints.map(renderMountPoint) }, { omitEmptyArray: true }),
name: this.containerName,
portMappings: cdk.Lazy.any({ produce: () => this.portMappings.map(renderPortMapping) }, { omitEmptyArray: true }),
privileged: this.props.privileged,
readonlyRootFilesystem: this.props.readonlyRootFilesystem,
repositoryCredentials: this.imageConfig.repositoryCredentials,
startTimeout: this.props.startTimeout && this.props.startTimeout.toSeconds(),
stopTimeout: this.props.stopTimeout && this.props.stopTimeout.toSeconds(),
ulimits: cdk.Lazy.any({ produce: () => this.ulimits.map(renderUlimit) }, { omitEmptyArray: true }),
user: this.props.user,
volumesFrom: cdk.Lazy.any({ produce: () => this.volumesFrom.map(renderVolumeFrom) }, { omitEmptyArray: true }),
workingDirectory: this.props.workingDirectory,
logConfiguration: this.logDriverConfig,
environment: this.environment && Object.keys(this.environment).length ? renderKV(this.environment, 'name', 'value') : undefined,
environmentFiles: this.environmentFiles && renderEnvironmentFiles(cdk.Stack.of(this).partition, this.environmentFiles),
secrets: this.secrets.length ? this.secrets : undefined,
extraHosts: this.props.extraHosts && renderKV(this.props.extraHosts, 'hostname', 'ipAddress'),
healthCheck: this.props.healthCheck && renderHealthCheck(this.props.healthCheck),
links: cdk.Lazy.list({ produce: () => this.links }, { omitEmpty: true }),
linuxParameters: this.linuxParameters && this.linuxParameters.renderLinuxParameters(),
resourceRequirements: (!this.props.gpuCount && this.inferenceAcceleratorResources.length == 0 ) ? undefined :
renderResourceRequirements(this.props.gpuCount, this.inferenceAcceleratorResources),
systemControls: this.props.systemControls && renderSystemControls(this.props.systemControls),
};
}
}
/**
* The health check command and associated configuration parameters for the container.
*/
export interface HealthCheck {
/**
* A string array representing the command that the container runs to determine if it is healthy.
* The string array must start with CMD to execute the command arguments directly, or
* CMD-SHELL to run the command with the container's default shell.
*
* For example: [ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]
*/
readonly command: string[];
/**
* The time period in seconds between each health check execution.
*
* You may specify between 5 and 300 seconds.
*
* @default Duration.seconds(30)
*/
readonly interval?: cdk.Duration;
/**
* The number of times to retry a failed health check before the container is considered unhealthy.
*
* You may specify between 1 and 10 retries.
*
* @default 3
*/
readonly retries?: number;
/**
* The optional grace period within which to provide containers time to bootstrap before
* failed health checks count towards the maximum number of retries.
*
* You may specify between 0 and 300 seconds.
*
* @default No start period
*/
readonly startPeriod?: cdk.Duration;
/**
* The time period in seconds to wait for a health check to succeed before it is considered a failure.
*
* You may specify between 2 and 60 seconds.
*
* @default Duration.seconds(5)
*/
readonly timeout?: cdk.Duration;
}
function renderKV(env: { [key: string]: string }, keyName: string, valueName: string): any[] {
const ret = [];
for (const [key, value] of Object.entries(env)) {
ret.push({ [keyName]: key, [valueName]: value });
}
return ret;
}
function renderEnvironmentFiles(partition: string, environmentFiles: EnvironmentFileConfig[]): any[] {
const ret = [];
for (const environmentFile of environmentFiles) {
const s3Location = environmentFile.s3Location;
if (!s3Location) {
throw Error('Environment file must specify an S3 location');
}
ret.push({
type: environmentFile.fileType,
value: `arn:${partition}:s3:::${s3Location.bucketName}/${s3Location.objectKey}`,
});
}
return ret;
}
function renderHealthCheck(hc: HealthCheck): CfnTaskDefinition.HealthCheckProperty {
if (hc.interval?.toSeconds() !== undefined) {
if (5 > hc.interval?.toSeconds() || hc.interval?.toSeconds() > 300) {
throw new Error('Interval must be between 5 seconds and 300 seconds.');
}
}
if (hc.timeout?.toSeconds() !== undefined) {
if (2 > hc.timeout?.toSeconds() || hc.timeout?.toSeconds() > 120) {
throw new Error('Timeout must be between 2 seconds and 120 seconds.');
}
}
if (hc.interval?.toSeconds() !== undefined && hc.timeout?.toSeconds() !== undefined) {
if (hc.interval?.toSeconds() < hc.timeout?.toSeconds()) {
throw new Error('Health check interval should be longer than timeout.');
}
}
return {
command: getHealthCheckCommand(hc),
interval: hc.interval?.toSeconds() ?? 30,
retries: hc.retries ?? 3,
startPeriod: hc.startPeriod?.toSeconds(),
timeout: hc.timeout?.toSeconds() ?? 5,
};
}
function getHealthCheckCommand(hc: HealthCheck): string[] {
const cmd = hc.command;
const hcCommand = new Array<string>();
if (cmd.length === 0) {
throw new Error('At least one argument must be supplied for health check command.');
}
if (cmd.length === 1) {
hcCommand.push('CMD-SHELL', cmd[0]);
return hcCommand;
}
if (cmd[0] !== 'CMD' && cmd[0] !== 'CMD-SHELL') {
hcCommand.push('CMD');
}
return hcCommand.concat(cmd);
}
function renderResourceRequirements(gpuCount: number = 0, inferenceAcceleratorResources: string[] = []):
CfnTaskDefinition.ResourceRequirementProperty[] | undefined {
const ret = [];
for (const resource of inferenceAcceleratorResources) {
ret.push({
type: 'InferenceAccelerator',
value: resource,
});
}
if (gpuCount > 0) {
ret.push({
type: 'GPU',
value: gpuCount.toString(),
});
}
return ret;
}
/**
* The ulimit settings to pass to the container.
*
* NOTE: Does not work for Windows containers.
*/
export interface Ulimit {
/**
* The type of the ulimit.
*
* For more information, see [UlimitName](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ecs/ulimitname.html#aws_ecs_UlimitName).
*/
readonly name: UlimitName,
/**
* The soft limit for the ulimit type.
*/
readonly softLimit: number,
/**
* The hard limit for the ulimit type.
*/
readonly hardLimit: number,
}
/**
* Type of resource to set a limit on
*/
export enum UlimitName {
CORE = 'core',
CPU = 'cpu',
DATA = 'data',
FSIZE = 'fsize',
LOCKS = 'locks',
MEMLOCK = 'memlock',
MSGQUEUE = 'msgqueue',
NICE = 'nice',
NOFILE = 'nofile',
NPROC = 'nproc',
RSS = 'rss',
RTPRIO = 'rtprio',
RTTIME = 'rttime',
SIGPENDING = 'sigpending',
STACK = 'stack'
}
function renderUlimit(ulimit: Ulimit): CfnTaskDefinition.UlimitProperty {
return {
name: ulimit.name,
softLimit: ulimit.softLimit,
hardLimit: ulimit.hardLimit,
};
}
/**
* The details of a dependency on another container in the task definition.
*
* @see https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ContainerDependency.html
*/
export interface ContainerDependency {
/**
* The container to depend on.
*/
readonly container: ContainerDefinition;
/**
* The state the container needs to be in to satisfy the dependency and proceed with startup.
* Valid values are ContainerDependencyCondition.START, ContainerDependencyCondition.COMPLETE,
* ContainerDependencyCondition.SUCCESS and ContainerDependencyCondition.HEALTHY.
*
* @default ContainerDependencyCondition.HEALTHY
*/
readonly condition?: ContainerDependencyCondition;
}
export enum ContainerDependencyCondition {
/**
* This condition emulates the behavior of links and volumes today.