-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathapplication-load-balanced-fargate-service.ts
202 lines (181 loc) · 7.96 KB
/
application-load-balanced-fargate-service.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
import { Construct } from 'constructs';
import { ISecurityGroup, SubnetSelection } from '../../../aws-ec2';
import { FargateService, FargateTaskDefinition, HealthCheck } from '../../../aws-ecs';
import { FeatureFlags, Token } from '../../../core';
import * as cxapi from '../../../cx-api';
import { ApplicationLoadBalancedServiceBase, ApplicationLoadBalancedServiceBaseProps } from '../base/application-load-balanced-service-base';
import { FargateServiceBaseProps } from '../base/fargate-service-base';
/**
* The properties for the ApplicationLoadBalancedFargateService service.
*/
export interface ApplicationLoadBalancedFargateServiceProps extends ApplicationLoadBalancedServiceBaseProps, FargateServiceBaseProps {
/**
* Determines whether the service will be assigned a public IP address.
*
* @default false
*/
readonly assignPublicIp?: boolean;
/**
* The subnets to associate with the service.
*
* @default - Public subnets if `assignPublicIp` is set, otherwise the first available one of Private, Isolated, Public, in that order.
*/
readonly taskSubnets?: SubnetSelection;
/**
* The security groups to associate with the service. If you do not specify a security group, a new security group is created.
*
* @default - A new security group is created.
*/
readonly securityGroups?: ISecurityGroup[];
/**
* The health check command and associated configuration parameters for the container.
*
* @default - Health check configuration from container.
*/
readonly healthCheck?: HealthCheck;
/**
* The minimum number of CPU units to reserve for the container.
*
* @default - No minimum CPU units reserved.
*/
readonly containerCpu?: number;
/**
* The amount (in MiB) of memory to present to the container.
*
* If your container attempts to exceed the allocated memory, the container
* is terminated.
*
* @default - No memory limit.
*/
readonly containerMemoryLimitMiB?: number;
}
/**
* A Fargate service running on an ECS cluster fronted by an application load balancer.
*/
export class ApplicationLoadBalancedFargateService extends ApplicationLoadBalancedServiceBase {
/**
* Determines whether the service will be assigned a public IP address.
*/
public readonly assignPublicIp: boolean;
/**
* The Fargate service in this construct.
*/
public readonly service: FargateService;
/**
* The Fargate task definition in this construct.
*/
public readonly taskDefinition: FargateTaskDefinition;
/**
* Constructs a new instance of the ApplicationLoadBalancedFargateService class.
*/
constructor(scope: Construct, id: string, props: ApplicationLoadBalancedFargateServiceProps = {}) {
super(scope, id, props);
this.assignPublicIp = props.assignPublicIp ?? false;
if (props.taskDefinition && props.taskImageOptions) {
throw new Error('You must specify either a taskDefinition or an image, not both.');
} else if (props.taskDefinition) {
this.taskDefinition = props.taskDefinition;
} else if (props.taskImageOptions) {
const taskImageOptions = props.taskImageOptions;
this.taskDefinition = new FargateTaskDefinition(this, 'TaskDef', {
memoryLimitMiB: props.memoryLimitMiB,
cpu: props.cpu,
ephemeralStorageGiB: props.ephemeralStorageGiB,
executionRole: taskImageOptions.executionRole,
taskRole: taskImageOptions.taskRole,
family: taskImageOptions.family,
runtimePlatform: props.runtimePlatform,
});
// Create log driver if logging is enabled
const enableLogging = taskImageOptions.enableLogging ?? true;
const logDriver = taskImageOptions.logDriver !== undefined
? taskImageOptions.logDriver : enableLogging
? this.createAWSLogDriver(this.node.id) : undefined;
this.validateContainerCpu(props.containerCpu, props.cpu);
this.validateContainerMemoryLimitMiB(props.containerMemoryLimitMiB, props.memoryLimitMiB);
const containerName = taskImageOptions.containerName ?? 'web';
const container = this.taskDefinition.addContainer(containerName, {
image: taskImageOptions.image,
healthCheck: props.healthCheck,
logging: logDriver,
environment: taskImageOptions.environment,
secrets: taskImageOptions.secrets,
dockerLabels: taskImageOptions.dockerLabels,
command: taskImageOptions.command,
entryPoint: taskImageOptions.entryPoint,
cpu: props.containerCpu,
memoryLimitMiB: props.containerMemoryLimitMiB,
});
container.addPortMappings({
containerPort: taskImageOptions.containerPort || 80,
});
} else {
throw new Error('You must specify one of: taskDefinition or image');
}
this.validateHealthyPercentage('minHealthyPercent', props.minHealthyPercent);
this.validateHealthyPercentage('maxHealthyPercent', props.maxHealthyPercent);
if (
props.minHealthyPercent &&
!Token.isUnresolved(props.minHealthyPercent) &&
props.maxHealthyPercent &&
!Token.isUnresolved(props.maxHealthyPercent) &&
props.minHealthyPercent >= props.maxHealthyPercent
) {
throw new Error('Minimum healthy percent must be less than maximum healthy percent.');
}
const desiredCount = FeatureFlags.of(this).isEnabled(cxapi.ECS_REMOVE_DEFAULT_DESIRED_COUNT) ? this.internalDesiredCount : this.desiredCount;
this.service = new FargateService(this, 'Service', {
cluster: this.cluster,
desiredCount: desiredCount,
taskDefinition: this.taskDefinition,
assignPublicIp: this.assignPublicIp,
serviceName: props.serviceName,
healthCheckGracePeriod: props.healthCheckGracePeriod,
minHealthyPercent: props.minHealthyPercent,
maxHealthyPercent: props.maxHealthyPercent,
propagateTags: props.propagateTags,
enableECSManagedTags: props.enableECSManagedTags,
cloudMapOptions: props.cloudMapOptions,
platformVersion: props.platformVersion,
deploymentController: props.deploymentController,
circuitBreaker: props.circuitBreaker,
securityGroups: props.securityGroups,
vpcSubnets: props.taskSubnets,
enableExecuteCommand: props.enableExecuteCommand,
capacityProviderStrategies: props.capacityProviderStrategies,
});
this.addServiceAsTarget(this.service);
}
/**
* Throws an error if the specified percent is not an integer or negative.
*/
private validateHealthyPercentage(name: string, value?: number) {
if (value === undefined || Token.isUnresolved(value)) { return; }
if (!Number.isInteger(value) || value < 0) {
throw new Error(`${name}: Must be a non-negative integer; received ${value}`);
}
}
private validateContainerCpu(containerCpu?: number, cpu: number = 256) { // default value for cpu is 256
if (containerCpu === undefined || Token.isUnresolved(containerCpu) || Token.isUnresolved(cpu)) {
return;
}
if (containerCpu > cpu) {
throw new Error(`containerCpu must be less than to cpu; received containerCpu: ${containerCpu}, cpu: ${cpu}`);
}
// If containerCPU is 0, it is not an error.
if (containerCpu < 0 || !Number.isInteger(containerCpu)) {
throw new Error(`containerCpu must be a non-negative integer; received ${containerCpu}`);
}
}
private validateContainerMemoryLimitMiB(containerMemoryLimitMiB?: number, memoryLimitMiB: number = 512) { // default value for memoryLimitMiB is 512
if (containerMemoryLimitMiB === undefined || Token.isUnresolved(containerMemoryLimitMiB) || Token.isUnresolved(memoryLimitMiB)) {
return;
}
if (containerMemoryLimitMiB > memoryLimitMiB) {
throw new Error(`containerMemoryLimitMiB must be less than to memoryLimitMiB; received containerMemoryLimitMiB: ${containerMemoryLimitMiB}, memoryLimitMiB: ${memoryLimitMiB}`);
}
if (containerMemoryLimitMiB <= 0 || !Number.isInteger(containerMemoryLimitMiB)) {
throw new Error(`containerMemoryLimitMiB must be a positive integer; received ${containerMemoryLimitMiB}`);
}
}
}