-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathbase-service.ts
538 lines (467 loc) · 18 KB
/
base-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
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
import appscaling = require('@aws-cdk/aws-applicationautoscaling');
import cloudwatch = require('@aws-cdk/aws-cloudwatch');
import ec2 = require('@aws-cdk/aws-ec2');
import elbv2 = require('@aws-cdk/aws-elasticloadbalancingv2');
import iam = require('@aws-cdk/aws-iam');
import cloudmap = require('@aws-cdk/aws-servicediscovery');
import { Construct, Duration, IResolvable, IResource, Lazy, Resource, Stack } from '@aws-cdk/core';
import { NetworkMode, TaskDefinition } from '../base/task-definition';
import { ICluster } from '../cluster';
import { CfnService } from '../ecs.generated';
import { ScalableTaskCount } from './scalable-task-count';
/**
* The interface for a service.
*/
export interface IService extends IResource {
/**
* The Amazon Resource Name (ARN) of the service.
*
* @attribute
*/
readonly serviceArn: string;
}
/**
* The properties for the base Ec2Service or FargateService service.
*/
export interface BaseServiceOptions {
/**
* The name of the cluster that hosts the service.
*/
readonly cluster: ICluster;
/**
* The desired number of instantiations of the task definition to keep running on the service.
*
* @default 1
*/
readonly desiredCount?: number;
/**
* The name of the service.
*
* @default - CloudFormation-generated name.
*/
readonly serviceName?: string;
/**
* The maximum number of tasks, specified as a percentage of the Amazon ECS
* service's DesiredCount value, that can run in a service during a
* deployment.
*
* @default - 100 if daemon, otherwise 200
*/
readonly maxHealthyPercent?: number;
/**
* The minimum number of tasks, specified as a percentage of
* the Amazon ECS service's DesiredCount value, that must
* continue to run and remain healthy during a deployment.
*
* @default - 0 if daemon, otherwise 50
*/
readonly minHealthyPercent?: number;
/**
* The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy
* Elastic Load Balancing target health checks after a task has first started.
*
* @default - defaults to 60 seconds if at least one load balancer is in-use and it is not already set
*/
readonly healthCheckGracePeriod?: Duration;
/**
* The options for configuring an Amazon ECS service to use service discovery.
*
* @default - AWS Cloud Map service discovery is not enabled.
*/
readonly cloudMapOptions?: CloudMapOptions;
/**
* Specifies whether to propagate the tags from the task definition or the service to the tasks in the service
*
* Valid values are: PropagatedTagSource.SERVICE, PropagatedTagSource.TASK_DEFINITION or PropagatedTagSource.NONE
*
* @default PropagatedTagSource.NONE
*/
readonly propagateTags?: PropagatedTagSource;
/**
* Specifies whether to enable Amazon ECS managed tags for the tasks within the service. For more information, see
* [Tagging Your Amazon ECS Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html)
*
* @default false
*/
readonly enableECSManagedTags?: boolean;
}
/**
* Complete base service properties that are required to be supplied by the implementation
* of the BaseService class.
*/
export interface BaseServiceProps extends BaseServiceOptions {
/**
* The launch type on which to run your service.
*
* Valid values are: LaunchType.ECS or LaunchType.FARGATE
*/
readonly launchType: LaunchType;
}
/**
* The base class for Ec2Service and FargateService services.
*/
export abstract class BaseService extends Resource
implements IService, elbv2.IApplicationLoadBalancerTarget, elbv2.INetworkLoadBalancerTarget {
/**
* The security groups which manage the allowed network traffic for the service.
*/
public readonly connections: ec2.Connections = new ec2.Connections();
/**
* The Amazon Resource Name (ARN) of the service.
*/
public readonly serviceArn: string;
/**
* The name of the service.
*
* @attribute
*/
public readonly serviceName: string;
/**
* The task definition to use for tasks in the service.
*/
public readonly taskDefinition: TaskDefinition;
/**
* The cluster that hosts the service.
*/
public readonly cluster: ICluster;
/**
* The details of the AWS Cloud Map service.
*/
protected cloudmapService?: cloudmap.Service;
/**
* A list of Elastic Load Balancing load balancer objects, containing the load balancer name, the container
* name (as it appears in a container definition), and the container port to access from the load balancer.
*/
protected loadBalancers = new Array<CfnService.LoadBalancerProperty>();
/**
* A list of Elastic Load Balancing load balancer objects, containing the load balancer name, the container
* name (as it appears in a container definition), and the container port to access from the load balancer.
*/
protected networkConfiguration?: CfnService.NetworkConfigurationProperty;
/**
* The details of the service discovery registries to assign to this service.
* For more information, see Service Discovery.
*/
protected serviceRegistries = new Array<CfnService.ServiceRegistryProperty>();
private readonly resource: CfnService;
private scalableTaskCount?: ScalableTaskCount;
/**
* Constructs a new instance of the BaseService class.
*/
constructor(scope: Construct,
id: string,
props: BaseServiceProps,
additionalProps: any,
taskDefinition: TaskDefinition) {
super(scope, id, {
physicalName: props.serviceName,
});
this.taskDefinition = taskDefinition;
this.resource = new CfnService(this, "Service", {
desiredCount: props.desiredCount,
serviceName: this.physicalName,
loadBalancers: Lazy.anyValue({ produce: () => this.loadBalancers }, { omitEmptyArray: true }),
deploymentConfiguration: {
maximumPercent: props.maxHealthyPercent || 200,
minimumHealthyPercent: props.minHealthyPercent === undefined ? 50 : props.minHealthyPercent
},
propagateTags: props.propagateTags === PropagatedTagSource.NONE ? undefined : props.propagateTags,
enableEcsManagedTags: props.enableECSManagedTags === undefined ? false : props.enableECSManagedTags,
launchType: props.launchType,
healthCheckGracePeriodSeconds: this.evaluateHealthGracePeriod(props.healthCheckGracePeriod),
/* role: never specified, supplanted by Service Linked Role */
networkConfiguration: Lazy.anyValue({ produce: () => this.networkConfiguration }, { omitEmptyArray: true }),
serviceRegistries: Lazy.anyValue({ produce: () => this.serviceRegistries }, { omitEmptyArray: true }),
...additionalProps
});
this.serviceArn = this.getResourceArnAttribute(this.resource.ref, {
service: 'ecs',
resource: 'service',
resourceName: `${props.cluster.clusterName}/${this.physicalName}`,
});
this.serviceName = this.getResourceNameAttribute(this.resource.attrName);
this.cluster = props.cluster;
if (props.cloudMapOptions) {
this.enableCloudMap(props.cloudMapOptions);
}
}
/**
* This method is called to attach this service to an Application Load Balancer.
*
* Don't call this function directly. Instead, call listener.addTarget()
* to add this service to a load balancer.
*/
public attachToApplicationTargetGroup(targetGroup: elbv2.ApplicationTargetGroup): elbv2.LoadBalancerTargetProps {
const ret = this.attachToELBv2(targetGroup);
// Open up security groups. For dynamic port mapping, we won't know the port range
// in advance so we need to open up all ports.
const port = this.taskDefinition.defaultContainer!.ingressPort;
const portRange = port === 0 ? EPHEMERAL_PORT_RANGE : ec2.Port.tcp(port);
targetGroup.registerConnectable(this, portRange);
return ret;
}
/**
* This method is called to attach this service to a Network Load Balancer.
*
* Don't call this function directly. Instead, call listener.addTarget()
* to add this service to a load balancer.
*/
public attachToNetworkTargetGroup(targetGroup: elbv2.NetworkTargetGroup): elbv2.LoadBalancerTargetProps {
return this.attachToELBv2(targetGroup);
}
/**
* An attribute representing the minimum and maximum task count for an AutoScalingGroup.
*/
public autoScaleTaskCount(props: appscaling.EnableScalingProps) {
if (this.scalableTaskCount) {
throw new Error('AutoScaling of task count already enabled for this service');
}
return this.scalableTaskCount = new ScalableTaskCount(this, 'TaskCount', {
serviceNamespace: appscaling.ServiceNamespace.ECS,
resourceId: `service/${this.cluster.clusterName}/${this.serviceName}`,
dimension: 'ecs:service:DesiredCount',
role: this.makeAutoScalingRole(),
...props
});
}
/**
* This method returns the specified CloudWatch metric name for this service.
*/
public metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
namespace: 'AWS/ECS',
metricName,
dimensions: { ClusterName: this.cluster.clusterName, ServiceName: this.serviceName },
...props
});
}
/**
* This method returns the CloudWatch metric for this clusters memory utilization.
*
* @default average over 5 minutes
*/
public metricMemoryUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metric('MemoryUtilization', props);
}
/**
* This method returns the CloudWatch metric for this clusters CPU utilization.
*
* @default average over 5 minutes
*/
public metricCpuUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metric('CPUUtilization', props);
}
/**
* This method is called to create a networkConfiguration.
*/
// tslint:disable-next-line:max-line-length
protected configureAwsVpcNetworking(vpc: ec2.IVpc, assignPublicIp?: boolean, vpcSubnets?: ec2.SubnetSelection, securityGroup?: ec2.ISecurityGroup) {
if (vpcSubnets === undefined) {
vpcSubnets = { subnetType: assignPublicIp ? ec2.SubnetType.PUBLIC : ec2.SubnetType.PRIVATE };
}
if (securityGroup === undefined) {
securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });
}
this.connections.addSecurityGroup(securityGroup);
this.networkConfiguration = {
awsvpcConfiguration: {
assignPublicIp: assignPublicIp ? 'ENABLED' : 'DISABLED',
subnets: vpc.selectSubnets(vpcSubnets).subnetIds,
securityGroups: Lazy.listValue({ produce: () => [securityGroup!.securityGroupId] }),
}
};
}
private renderServiceRegistry(registry: ServiceRegistry): CfnService.ServiceRegistryProperty {
return {
registryArn: registry.arn,
containerName: registry.containerName,
containerPort: registry.containerPort,
};
}
/**
* Shared logic for attaching to an ELBv2
*/
private attachToELBv2(targetGroup: elbv2.ITargetGroup): elbv2.LoadBalancerTargetProps {
if (this.taskDefinition.networkMode === NetworkMode.NONE) {
throw new Error("Cannot use a load balancer if NetworkMode is None. Use Bridge, Host or AwsVpc instead.");
}
this.loadBalancers.push({
targetGroupArn: targetGroup.targetGroupArn,
containerName: this.taskDefinition.defaultContainer!.containerName,
containerPort: this.taskDefinition.defaultContainer!.containerPort,
});
// Service creation can only happen after the load balancer has
// been associated with our target group(s), so add ordering dependency.
this.resource.node.addDependency(targetGroup.loadBalancerAttached);
const targetType = this.taskDefinition.networkMode === NetworkMode.AWS_VPC ? elbv2.TargetType.IP : elbv2.TargetType.INSTANCE;
return { targetType };
}
/**
* Generate the role that will be used for autoscaling this service
*/
private makeAutoScalingRole(): iam.IRole {
// Use a Service Linked Role.
return iam.Role.fromRoleArn(this, 'ScalingRole', Stack.of(this).formatArn({
region: '',
service: 'iam',
resource: 'role/aws-service-role/ecs.application-autoscaling.amazonaws.com',
resourceName: 'AWSServiceRoleForApplicationAutoScaling_ECSService',
}));
}
/**
* Associate Service Discovery (Cloud Map) service
*/
private addServiceRegistry(registry: ServiceRegistry) {
const sr = this.renderServiceRegistry(registry);
this.serviceRegistries.push(sr);
}
/**
* Enable CloudMap service discovery for the service
*/
private enableCloudMap(options: CloudMapOptions): cloudmap.Service {
const sdNamespace = this.cluster.defaultCloudMapNamespace;
if (sdNamespace === undefined) {
throw new Error("Cannot enable service discovery if a Cloudmap Namespace has not been created in the cluster.");
}
// Determine DNS type based on network mode
const networkMode = this.taskDefinition.networkMode;
if (networkMode === NetworkMode.NONE) {
throw new Error("Cannot use a service discovery if NetworkMode is None. Use Bridge, Host or AwsVpc instead.");
}
// Bridge or host network mode requires SRV records
let dnsRecordType = options.dnsRecordType;
if (networkMode === NetworkMode.BRIDGE || networkMode === NetworkMode.HOST) {
if (dnsRecordType === undefined) {
dnsRecordType = cloudmap.DnsRecordType.SRV;
}
if (dnsRecordType !== cloudmap.DnsRecordType.SRV) {
throw new Error("SRV records must be used when network mode is Bridge or Host.");
}
}
// Default DNS record type for AwsVpc network mode is A Records
if (networkMode === NetworkMode.AWS_VPC) {
if (dnsRecordType === undefined) {
dnsRecordType = cloudmap.DnsRecordType.A;
}
}
// If the task definition that your service task specifies uses the AWSVPC network mode and a type SRV DNS record is
// used, you must specify a containerName and containerPort combination
const containerName = dnsRecordType === cloudmap.DnsRecordType.SRV ? this.taskDefinition.defaultContainer!.containerName : undefined;
const containerPort = dnsRecordType === cloudmap.DnsRecordType.SRV ? this.taskDefinition.defaultContainer!.containerPort : undefined;
const cloudmapService = new cloudmap.Service(this, 'CloudmapService', {
namespace: sdNamespace,
name: options.name,
dnsRecordType: dnsRecordType!,
customHealthCheck: { failureThreshold: options.failureThreshold || 1 }
});
const serviceArn = cloudmapService.serviceArn;
// add Cloudmap service to the ECS Service's serviceRegistry
this.addServiceRegistry({
arn: serviceArn,
containerName,
containerPort
});
this.cloudmapService = cloudmapService;
return cloudmapService;
}
/**
* Return the default grace period when load balancers are configured and
* healthCheckGracePeriod is not already set
*/
private evaluateHealthGracePeriod(providedHealthCheckGracePeriod?: Duration): IResolvable {
return Lazy.anyValue({
produce: () => providedHealthCheckGracePeriod !== undefined ? providedHealthCheckGracePeriod.toSeconds() :
this.loadBalancers.length > 0 ? 60 :
undefined
});
}
}
/**
* The port range to open up for dynamic port mapping
*/
const EPHEMERAL_PORT_RANGE = ec2.Port.tcpRange(32768, 65535);
/**
* The options to enabling AWS Cloud Map for an Amazon ECS service.
*/
export interface CloudMapOptions {
/**
* The name of the Cloud Map service to attach to the ECS service.
*
* @default CloudFormation-generated name
*/
readonly name?: string,
/**
* The DNS record type that you want AWS Cloud Map to create. The supported record types are A or SRV.
*
* @default: A
*/
readonly dnsRecordType?: cloudmap.DnsRecordType.A | cloudmap.DnsRecordType.SRV,
/**
* The amount of time that you want DNS resolvers to cache the settings for this record.
*
* @default 60
*/
readonly dnsTtl?: Duration;
/**
* The number of 30-second intervals that you want Cloud Map to wait after receiving an UpdateInstanceCustomHealthStatus
* request before it changes the health status of a service instance.
*
* NOTE: This is used for HealthCheckCustomConfig
*/
readonly failureThreshold?: number,
}
/**
* Service Registry for ECS service
*/
interface ServiceRegistry {
/**
* Arn of the Cloud Map Service that will register a Cloud Map Instance for your ECS Service
*/
readonly arn: string;
/**
* The container name value, already specified in the task definition, to be used for your service discovery service.
* If the task definition that your service task specifies uses the bridge or host network mode,
* you must specify a containerName and containerPort combination from the task definition.
* If the task definition that your service task specifies uses the awsvpc network mode and a type SRV DNS record is
* used, you must specify either a containerName and containerPort combination or a port value, but not both.
*/
readonly containerName?: string;
/**
* The container port value, already specified in the task definition, to be used for your service discovery service.
* If the task definition that your service task specifies uses the bridge or host network mode,
* you must specify a containerName and containerPort combination from the task definition.
* If the task definition that your service task specifies uses the awsvpc network mode and a type SRV DNS record is
* used, you must specify either a containerName and containerPort combination or a port value, but not both.
*/
readonly containerPort?: number;
}
/**
* The launch type of an ECS service
*/
export enum LaunchType {
/**
* The service will be launched using the EC2 launch type
*/
EC2 = 'EC2',
/**
* The service will be launched using the FARGATE launch type
*/
FARGATE = 'FARGATE'
}
/**
* Propagate tags from either service or task definition
*/
export enum PropagatedTagSource {
/**
* Propagate tags from service
*/
SERVICE = 'SERVICE',
/**
* Propagate tags from task definition
*/
TASK_DEFINITION = 'TASK_DEFINITION',
/**
* Do not propagate
*/
NONE = 'NONE'
}