-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
base-service.ts
1715 lines (1515 loc) · 58.8 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
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 { Construct } from 'constructs';
import { ScalableTaskCount } from './scalable-task-count';
import { ServiceManagedVolume } from './service-managed-volume';
import * as appscaling from '../../../aws-applicationautoscaling';
import * as cloudwatch from '../../../aws-cloudwatch';
import * as ec2 from '../../../aws-ec2';
import * as elb from '../../../aws-elasticloadbalancing';
import * as elbv2 from '../../../aws-elasticloadbalancingv2';
import * as iam from '../../../aws-iam';
import * as cloudmap from '../../../aws-servicediscovery';
import {
Annotations,
Duration,
IResolvable,
IResource,
Lazy,
Resource,
Stack,
ArnFormat,
FeatureFlags,
Token,
} from '../../../core';
import * as cxapi from '../../../cx-api';
import { RegionInfo } from '../../../region-info';
import {
LoadBalancerTargetOptions,
NetworkMode,
TaskDefinition,
TaskDefinitionRevision,
} from '../base/task-definition';
import { ICluster, CapacityProviderStrategy, ExecuteCommandLogging, Cluster } from '../cluster';
import { ContainerDefinition, Protocol } from '../container-definition';
import { CfnService } from '../ecs.generated';
import { LogDriver, LogDriverConfig } from '../log-drivers/log-driver';
/**
* The interface for a service.
*/
export interface IService extends IResource {
/**
* The Amazon Resource Name (ARN) of the service.
*
* @attribute
*/
readonly serviceArn: string;
/**
* The name of the service.
*
* @attribute
*/
readonly serviceName: string;
}
/**
* The deployment controller to use for the service.
*/
export interface DeploymentController {
/**
* The deployment controller type to use.
*
* @default DeploymentControllerType.ECS
*/
readonly type?: DeploymentControllerType;
}
/**
* The deployment circuit breaker to use for the service
*/
export interface DeploymentCircuitBreaker {
/**
* Whether to enable the deployment circuit breaker logic
* @default true
*/
readonly enable?: boolean;
/**
* Whether to enable rollback on deployment failure
*
* @default false
*/
readonly rollback?: boolean;
}
/**
* Deployment behavior when an ECS Service Deployment Alarm is triggered
*/
export enum AlarmBehavior {
/**
* ROLLBACK_ON_ALARM causes the service to roll back to the previous deployment
* when any deployment alarm enters the 'Alarm' state. The Cloudformation stack
* will be rolled back and enter state "UPDATE_ROLLBACK_COMPLETE".
*/
ROLLBACK_ON_ALARM = 'ROLLBACK_ON_ALARM',
/**
* FAIL_ON_ALARM causes the deployment to fail immediately when any deployment
* alarm enters the 'Alarm' state. In order to restore functionality, you must
* roll the stack forward by pushing a new version of the ECS service.
*/
FAIL_ON_ALARM = 'FAIL_ON_ALARM',
}
/**
* Options for deployment alarms
*/
export interface DeploymentAlarmOptions {
/**
* Default rollback on alarm
* @default AlarmBehavior.ROLLBACK_ON_ALARM
*/
readonly behavior?: AlarmBehavior;
}
/**
* Configuration for deployment alarms
*/
export interface DeploymentAlarmConfig extends DeploymentAlarmOptions {
/**
* List of alarm names to monitor during deployments
*/
readonly alarmNames: string[];
}
export interface EcsTarget {
/**
* The name of the container.
*/
readonly containerName: string;
/**
* The port number of the container. Only applicable when using application/network load balancers.
*
* @default - Container port of the first added port mapping.
*/
readonly containerPort?: number;
/**
* The protocol used for the port mapping. Only applicable when using application load balancers.
*
* @default Protocol.TCP
*/
readonly protocol?: Protocol;
/**
* ID for a target group to be created.
*/
readonly newTargetGroupId: string;
/**
* Listener and properties for adding target group to the listener.
*/
readonly listener: ListenerConfig;
}
/**
* Interface for ECS load balancer target.
*/
export interface IEcsLoadBalancerTarget extends elbv2.IApplicationLoadBalancerTarget, elbv2.INetworkLoadBalancerTarget, elb.ILoadBalancerTarget {
}
/**
* Interface for Service Connect configuration.
*/
export interface ServiceConnectProps {
/**
* The cloudmap namespace to register this service into.
*
* @default the cloudmap namespace specified on the cluster.
*/
readonly namespace?: string;
/**
* The list of Services, including a port mapping, terse client alias, and optional intermediate DNS name.
*
* This property may be left blank if the current ECS service does not need to advertise any ports via Service Connect.
*
* @default none
*/
readonly services?: ServiceConnectService[];
/**
* The log driver configuration to use for the Service Connect agent logs.
*
* @default - none
*/
readonly logDriver?: LogDriver;
}
/**
* Interface for service connect Service props.
*/
export interface ServiceConnectService {
/**
* portMappingName specifies which port and protocol combination should be used for this
* service connect service.
*/
readonly portMappingName: string;
/**
* Optionally specifies an intermediate dns name to register in the CloudMap namespace.
* This is required if you wish to use the same port mapping name in more than one service.
*
* @default - port mapping name
*/
readonly discoveryName?: string;
/**
* The terse DNS alias to use for this port mapping in the service connect mesh.
* Service Connect-enabled clients will be able to reach this service at
* http://dnsName:port.
*
* @default - No alias is created. The service is reachable at `portMappingName.namespace:port`.
*/
readonly dnsName?: string;
/**
* The port for clients to use to communicate with this service via Service Connect.
*
* @default the container port specified by the port mapping in portMappingName.
*/
readonly port?: number;
/**
* Optional. The port on the Service Connect agent container to use for traffic ingress to this service.
*
* @default - none
*/
readonly ingressPortOverride?: number;
/**
* The amount of time in seconds a connection for Service Connect will stay active while idle.
*
* A value of 0 can be set to disable `idleTimeout`.
*
* If `idleTimeout` is set to a time that is less than `perRequestTimeout`, the connection will close
* when the `idleTimeout` is reached and not the `perRequestTimeout`.
*
* @default - Duration.minutes(5) for HTTP/HTTP2/GRPC, Duration.hours(1) for TCP.
*/
readonly idleTimeout?: Duration;
/**
* The amount of time waiting for the upstream to respond with a complete response per request for
* Service Connect.
*
* A value of 0 can be set to disable `perRequestTimeout`.
* Can only be set when the `appProtocol` for the application container is HTTP/HTTP2/GRPC.
*
* If `idleTimeout` is set to a time that is less than `perRequestTimeout`, the connection will close
* when the `idleTimeout` is reached and not the `perRequestTimeout`.
*
* @default - Duration.seconds(15)
*/
readonly perRequestTimeout?: Duration;
}
/**
* 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 - When creating the service, default is 1; when updating the service, default uses
* the current task number.
*/
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 propagate the tags from the task definition or the service to the tasks in the service.
* Tags can only be propagated to the tasks within the service during service creation.
*
* @deprecated Use `propagateTags` instead.
* @default PropagatedTagSource.NONE
*/
readonly propagateTaskTagsFrom?: 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;
/**
* Specifies which deployment controller to use for the service. For more information, see
* [Amazon ECS Deployment Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html)
*
* @default - Rolling update (ECS)
*/
readonly deploymentController?: DeploymentController;
/**
* Whether to enable the deployment circuit breaker. If this property is defined, circuit breaker will be implicitly
* enabled.
* @default - disabled
*/
readonly circuitBreaker?: DeploymentCircuitBreaker;
/**
* The alarm(s) to monitor during deployment, and behavior to apply if at least one enters a state of alarm
* during the deployment or bake time.
*
*
* @default - No alarms will be monitored during deployment.
*/
readonly deploymentAlarms?: DeploymentAlarmConfig;
/**
* A list of Capacity Provider strategies used to place a service.
*
* @default - undefined
*
*/
readonly capacityProviderStrategies?: CapacityProviderStrategy[];
/**
* Whether to enable the ability to execute into a container
*
* @default - undefined
*/
readonly enableExecuteCommand?: boolean;
/**
* Configuration for Service Connect.
*
* @default No ports are advertised via Service Connect on this service, and the service
* cannot make requests to other services via Service Connect.
*/
readonly serviceConnectConfiguration?: ServiceConnectProps;
/**
* Revision number for the task definition or `latest` to use the latest active task revision.
*
* @default - Uses the revision of the passed task definition deployed by CloudFormation
*/
readonly taskDefinitionRevision?: TaskDefinitionRevision;
/**
* Configuration details for a volume used by the service. This allows you to specify
* details about the EBS volume that can be attched to ECS tasks.
*
* @default - undefined
*/
readonly volumeConfigurations?: ServiceManagedVolume[];
}
/**
* 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.
*
* LaunchType will be omitted if capacity provider strategies are specified on the service.
*
* @see - https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-capacityproviderstrategy
*
* Valid values are: LaunchType.ECS or LaunchType.FARGATE or LaunchType.EXTERNAL
*/
readonly launchType: LaunchType;
}
/**
* Base class for configuring listener when registering targets.
*/
export abstract class ListenerConfig {
/**
* Create a config for adding target group to ALB listener.
*/
public static applicationListener(listener: elbv2.ApplicationListener, props?: elbv2.AddApplicationTargetsProps): ListenerConfig {
return new ApplicationListenerConfig(listener, props);
}
/**
* Create a config for adding target group to NLB listener.
*/
public static networkListener(listener: elbv2.NetworkListener, props?: elbv2.AddNetworkTargetsProps): ListenerConfig {
return new NetworkListenerConfig(listener, props);
}
/**
* Create and attach a target group to listener.
*/
public abstract addTargets(id: string, target: LoadBalancerTargetOptions, service: BaseService): void;
}
/**
* Class for configuring application load balancer listener when registering targets.
*/
class ApplicationListenerConfig extends ListenerConfig {
constructor(private readonly listener: elbv2.ApplicationListener, private readonly props?: elbv2.AddApplicationTargetsProps) {
super();
}
/**
* Create and attach a target group to listener.
*/
public addTargets(id: string, target: LoadBalancerTargetOptions, service: BaseService) {
const props = this.props || {};
const protocol = props.protocol;
const port = props.port ?? (protocol === elbv2.ApplicationProtocol.HTTPS ? 443 : 80);
this.listener.addTargets(id, {
... props,
targets: [
service.loadBalancerTarget({
...target,
}),
],
port,
});
}
}
/**
* Class for configuring network load balancer listener when registering targets.
*/
class NetworkListenerConfig extends ListenerConfig {
constructor(private readonly listener: elbv2.NetworkListener, private readonly props?: elbv2.AddNetworkTargetsProps) {
super();
}
/**
* Create and attach a target group to listener.
*/
public addTargets(id: string, target: LoadBalancerTargetOptions, service: BaseService) {
const port = this.props?.port ?? 80;
this.listener.addTargets(id, {
... this.props,
targets: [
service.loadBalancerTarget({
...target,
}),
],
port,
});
}
}
/**
* The interface for BaseService.
*/
export interface IBaseService extends IService {
/**
* The cluster that hosts the service.
*/
readonly cluster: ICluster;
}
/**
* The base class for Ec2Service and FargateService services.
*/
export abstract class BaseService extends Resource
implements IBaseService, elbv2.IApplicationLoadBalancerTarget, elbv2.INetworkLoadBalancerTarget, elb.ILoadBalancerTarget {
/**
* Import an existing ECS/Fargate Service using the service cluster format.
* The format is the "new" format "arn:aws:ecs:region:aws_account_id:service/cluster-name/service-name".
* @see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-ids
*/
public static fromServiceArnWithCluster(scope: Construct, id: string, serviceArn: string): IBaseService {
const stack = Stack.of(scope);
const arn = stack.splitArn(serviceArn, ArnFormat.SLASH_RESOURCE_NAME);
const resourceName = arn.resourceName;
if (!resourceName) {
throw new Error('Missing resource Name from service ARN: ${serviceArn}');
}
const resourceNameParts = resourceName.split('/');
if (resourceNameParts.length !== 2) {
throw new Error(`resource name ${resourceName} from service ARN: ${serviceArn} is not using the ARN cluster format`);
}
const clusterName = resourceNameParts[0];
const serviceName = resourceNameParts[1];
const clusterArn = Stack.of(scope).formatArn({
partition: arn.partition,
region: arn.region,
account: arn.account,
service: 'ecs',
resource: 'cluster',
resourceName: clusterName,
});
const cluster = Cluster.fromClusterArn(scope, `${id}Cluster`, clusterArn);
class Import extends Resource implements IBaseService {
public readonly serviceArn = serviceArn;
public readonly serviceName = serviceName;
public readonly cluster = cluster;
}
return new Import(scope, id, {
environmentFromArn: serviceArn,
});
}
private static MIN_PORT = 1;
private static MAX_PORT = 65535;
/**
* 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 deployment alarms property - this will be rendered directly and lazily as the CfnService.alarms
* property.
*/
protected deploymentAlarms?: CfnService.DeploymentAlarmsProperty;
/**
* The details of the service discovery registries to assign to this service.
* For more information, see Service Discovery.
*/
protected serviceRegistries = new Array<CfnService.ServiceRegistryProperty>();
/**
* The service connect configuration for this service.
* @internal
*/
protected _serviceConnectConfig?: CfnService.ServiceConnectConfigurationProperty;
private readonly resource: CfnService;
private scalableTaskCount?: ScalableTaskCount;
/**
* All volumes
*/
private readonly volumes: ServiceManagedVolume[] = [];
/**
* 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,
});
if (props.propagateTags && props.propagateTaskTagsFrom) {
throw new Error('You can only specify either propagateTags or propagateTaskTagsFrom. Alternatively, you can leave both blank');
}
this.taskDefinition = taskDefinition;
// launchType will set to undefined if using external DeploymentController or capacityProviderStrategies
const launchType = props.deploymentController?.type === DeploymentControllerType.EXTERNAL ||
props.capacityProviderStrategies !== undefined ?
undefined : props.launchType;
const propagateTagsFromSource = props.propagateTaskTagsFrom ?? props.propagateTags ?? PropagatedTagSource.NONE;
const deploymentController = this.getDeploymentController(props);
this.resource = new CfnService(this, 'Service', {
desiredCount: props.desiredCount,
serviceName: this.physicalName,
loadBalancers: Lazy.any({ produce: () => this.loadBalancers }, { omitEmptyArray: true }),
deploymentConfiguration: {
maximumPercent: props.maxHealthyPercent || 200,
minimumHealthyPercent: props.minHealthyPercent === undefined ? 50 : props.minHealthyPercent,
deploymentCircuitBreaker: props.circuitBreaker ? {
enable: props.circuitBreaker.enable ?? true,
rollback: props.circuitBreaker.rollback ?? false,
} : undefined,
alarms: Lazy.any({ produce: () => this.deploymentAlarms }, { omitEmptyArray: true }),
},
propagateTags: propagateTagsFromSource === PropagatedTagSource.NONE ? undefined : props.propagateTags,
enableEcsManagedTags: props.enableECSManagedTags ?? false,
deploymentController: deploymentController,
launchType: launchType,
enableExecuteCommand: props.enableExecuteCommand,
capacityProviderStrategy: props.capacityProviderStrategies,
healthCheckGracePeriodSeconds: this.evaluateHealthGracePeriod(props.healthCheckGracePeriod),
/* role: never specified, supplanted by Service Linked Role */
networkConfiguration: Lazy.any({ produce: () => this.networkConfiguration }, { omitEmptyArray: true }),
serviceRegistries: Lazy.any({ produce: () => this.serviceRegistries }, { omitEmptyArray: true }),
serviceConnectConfiguration: Lazy.any({ produce: () => this._serviceConnectConfig }, { omitEmptyArray: true }),
volumeConfigurations: Lazy.any({ produce: () => this.renderVolumes() }, { omitEmptyArray: true }),
...additionalProps,
});
this.node.addDependency(this.taskDefinition.taskRole);
if (props.deploymentController?.type === DeploymentControllerType.EXTERNAL) {
Annotations.of(this).addWarningV2('@aws-cdk/aws-ecs:externalDeploymentController', 'taskDefinition and launchType are blanked out when using external deployment controller.');
}
if (props.circuitBreaker
&& deploymentController
&& deploymentController.type !== DeploymentControllerType.ECS) {
Annotations.of(this).addError('Deployment circuit breaker requires the ECS deployment controller.');
}
if (props.deploymentAlarms
&& deploymentController
&& deploymentController.type !== DeploymentControllerType.ECS) {
throw new Error('Deployment alarms requires the ECS deployment controller.');
}
if (
props.deploymentController?.type === DeploymentControllerType.CODE_DEPLOY
&& props.taskDefinitionRevision
&& props.taskDefinitionRevision !== TaskDefinitionRevision.LATEST
) {
throw new Error('CODE_DEPLOY deploymentController can only be used with the `latest` task definition revision');
}
if (props.deploymentController?.type === DeploymentControllerType.CODE_DEPLOY) {
// Strip the revision ID from the service's task definition property to
// prevent new task def revisions in the stack from triggering updates
// to the stack's ECS service resource
this.resource.taskDefinition = taskDefinition.family;
this.node.addDependency(taskDefinition);
} else if (props.taskDefinitionRevision) {
this.resource.taskDefinition = taskDefinition.family;
if (props.taskDefinitionRevision !== TaskDefinitionRevision.LATEST) {
this.resource.taskDefinition += `:${props.taskDefinitionRevision.revision}`;
}
this.node.addDependency(taskDefinition);
}
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);
}
if (props.serviceConnectConfiguration) {
this.enableServiceConnect(props.serviceConnectConfiguration);
}
if (props.volumeConfigurations) {
props.volumeConfigurations.forEach(v => this.addVolume(v));
}
if (props.enableExecuteCommand) {
this.enableExecuteCommand();
const logging = this.cluster.executeCommandConfiguration?.logging ?? ExecuteCommandLogging.DEFAULT;
if (this.cluster.executeCommandConfiguration?.kmsKey) {
this.enableExecuteCommandEncryption(logging);
}
if (logging !== ExecuteCommandLogging.NONE) {
this.executeCommandLogConfiguration();
}
}
if (props.deploymentAlarms) {
if (props.deploymentAlarms.alarmNames.length === 0) {
throw new Error('at least one alarm name is required when specifying deploymentAlarms, received empty array');
}
this.deploymentAlarms = {
alarmNames: props.deploymentAlarms.alarmNames,
enable: true,
rollback: props.deploymentAlarms.behavior !== AlarmBehavior.FAIL_ON_ALARM,
};
// CloudWatch alarms is only supported for Amazon ECS services that use the rolling update (ECS) deployment controller.
} else if ((!props.deploymentController ||
props.deploymentController?.type === DeploymentControllerType.ECS) && this.deploymentAlarmsAvailableInRegion()) {
this.deploymentAlarms = {
alarmNames: [],
enable: false,
rollback: false,
};
}
this.node.defaultChild = this.resource;
}
/**
* Adds a volume to the Service.
*/
public addVolume(volume: ServiceManagedVolume) {
this.volumes.push(volume);
}
private renderVolumes(): CfnService.ServiceVolumeConfigurationProperty[] {
if (this.volumes.length > 1) {
throw new Error(`Only one EBS volume can be specified for 'volumeConfigurations', got: ${this.volumes.length}`);
}
return this.volumes.map(renderVolume);
function renderVolume(spec: ServiceManagedVolume): CfnService.ServiceVolumeConfigurationProperty {
const tagSpecifications = spec.config?.tagSpecifications?.map(ebsTagSpec => {
return {
resourceType: 'volume',
propagateTags: ebsTagSpec.propagateTags,
tags: ebsTagSpec.tags ? Object.entries(ebsTagSpec.tags).map(([key, value]) => ({
key: key,
value: value,
})) : undefined,
} as CfnService.EBSTagSpecificationProperty;
});
return {
name: spec.name,
managedEbsVolume: spec.config && {
roleArn: spec.role.roleArn,
encrypted: spec.config.encrypted,
filesystemType: spec.config.fileSystemType,
iops: spec.config.iops,
kmsKeyId: spec.config.kmsKeyId?.keyId,
throughput: spec.config.throughput,
volumeType: spec.config.volumeType,
snapshotId: spec.config.snapShotId,
sizeInGiB: spec.config.size?.toGibibytes(),
tagSpecifications: tagSpecifications,
},
};
}
}
/**
* Enable Deployment Alarms which take advantage of arbitrary alarms and configure them after service initialization.
* If you have already enabled deployment alarms, this function can be used to tell ECS about additional alarms that
* should interrupt a deployment.
*
* New alarms specified in subsequent calls of this function will be appended to the existing list of alarms.
*
* The same Alarm Behavior must be used on all deployment alarms. If you specify different AlarmBehavior values in
* multiple calls to this function, or the Alarm Behavior used here doesn't match the one used in the service
* constructor, an error will be thrown.
*
* If the alarm's metric references the service, you cannot pass `Alarm.alarmName` here. That will cause a circular
* dependency between the service and its deployment alarm. See this package's README for options to alarm on service
* metrics, and avoid this circular dependency.
*
*/
public enableDeploymentAlarms(alarmNames: string[], options?: DeploymentAlarmOptions) {
if (alarmNames.length === 0 ) {
throw new Error('at least one alarm name is required when calling enableDeploymentAlarms(), received empty array');
}
alarmNames.forEach(alarmName => {
if (Token.isUnresolved(alarmName)) {
Annotations.of(this).addInfo(
`Deployment alarm (${JSON.stringify(this.stack.resolve(alarmName))}) enabled on ${this.node.id} may cause a circular dependency error when this stack deploys. The alarm name references the alarm's logical id, or another resource. See the 'Deployment alarms' section in the module README for more details.`,
);
}
});
if (this.deploymentAlarms?.enable && options?.behavior) {
if (
(AlarmBehavior.ROLLBACK_ON_ALARM === options.behavior && !this.deploymentAlarms.rollback) ||
(AlarmBehavior.FAIL_ON_ALARM === options.behavior && this.deploymentAlarms.rollback)
) {
throw new Error(`all deployment alarms on an ECS service must have the same AlarmBehavior. Attempted to enable deployment alarms with ${options.behavior}, but alarms were previously enabled with ${this.deploymentAlarms.rollback ? AlarmBehavior.ROLLBACK_ON_ALARM : AlarmBehavior.FAIL_ON_ALARM}`);
}
}
if (!this.deploymentAlarms?.enable) {
this.deploymentAlarms = {
enable: true,
alarmNames: alarmNames,
rollback: options?.behavior !== AlarmBehavior.FAIL_ON_ALARM,
};
} else {
// If deployment alarms have previously been enabled, we only need to add
// the new alarm names, since rollback behaviors can't be updated/mixed.
this.deploymentAlarms.alarmNames.concat(alarmNames);
}
}
/**
* Enable Service Connect on this service.
*/
public enableServiceConnect(config?: ServiceConnectProps) {
if (this._serviceConnectConfig) {
throw new Error('Service connect configuration cannot be specified more than once.');
}
this.validateServiceConnectConfiguration(config);
let cfg = config || {};
/**
* Namespace already exists as validated in validateServiceConnectConfiguration.
* Resolve which namespace to use by picking:
* 1. The namespace defined in service connect config.
* 2. The namespace defined in the cluster's defaultCloudMapNamespace property.
*/
let namespace;
if (this.cluster.defaultCloudMapNamespace) {
namespace = this.cluster.defaultCloudMapNamespace.namespaceName;
}
if (cfg.namespace) {
namespace = cfg.namespace;
}
/**
* Map services to CFN property types. This block manages:
* 1. Finding the correct port.
* 2. Client alias enumeration
*/
const services = cfg.services?.map(svc => {
const containerPort = this.taskDefinition.findPortMappingByName(svc.portMappingName)?.containerPort;
if (!containerPort) {
throw new Error(`Port mapping with name ${svc.portMappingName} does not exist.`);
}
const alias = {
port: svc.port || containerPort,
dnsName: svc.dnsName,
};
return {
portName: svc.portMappingName,
discoveryName: svc.discoveryName,
ingressPortOverride: svc.ingressPortOverride,
clientAliases: [alias],
timeout: this.renderTimeout(svc.idleTimeout, svc.perRequestTimeout),
} as CfnService.ServiceConnectServiceProperty;
});
let logConfig: LogDriverConfig | undefined;
if (cfg.logDriver && this.taskDefinition.defaultContainer) {
// Default container existence is validated in validateServiceConnectConfiguration.
// We only need the default container so that bind() can get the task definition from the container definition.
logConfig = cfg.logDriver.bind(this, this.taskDefinition.defaultContainer);
}
this._serviceConnectConfig = {
enabled: true,
logConfiguration: logConfig,
namespace: namespace,
services: services,
};
};
/**
* Validate Service Connect Configuration
*/
private validateServiceConnectConfiguration(config?: ServiceConnectProps) {
if (!this.taskDefinition.defaultContainer) {
throw new Error('Task definition must have at least one container to enable service connect.');
}
// Check the implicit enable case; when config isn't specified or namespace isn't specified, we need to check that there is a namespace on the cluster.
if ((!config || !config.namespace) && !this.cluster.defaultCloudMapNamespace) {
throw new Error('Namespace must be defined either in serviceConnectConfig or cluster.defaultCloudMapNamespace');
}
// When config isn't specified, return.
if (!config) {
return;
}
if (!config.services) {
return;
}
let portNames = new Map<string, string[]>();
config.services.forEach(serviceConnectService => {
// port must exist on the task definition
if (!this.taskDefinition.findPortMappingByName(serviceConnectService.portMappingName)) {
throw new Error(`Port Mapping '${serviceConnectService.portMappingName}' does not exist on the task definition.`);
};
// Check that no two service connect services use the same discovery name.
const discoveryName = serviceConnectService.discoveryName || serviceConnectService.portMappingName;
if (portNames.get(serviceConnectService.portMappingName)?.includes(discoveryName)) {
throw new Error(`Cannot create multiple services with the discoveryName '${discoveryName}'.`);
}
let currentDiscoveries = portNames.get(serviceConnectService.portMappingName);
if (!currentDiscoveries) {
portNames.set(serviceConnectService.portMappingName, [discoveryName]);
} else {
currentDiscoveries.push(discoveryName);
portNames.set(serviceConnectService.portMappingName, currentDiscoveries);
}
// IngressPortOverride should be within the valid port range if it exists.
if (serviceConnectService.ingressPortOverride && !this.isValidPort(serviceConnectService.ingressPortOverride)) {
throw new Error(`ingressPortOverride ${serviceConnectService.ingressPortOverride} is not valid.`);
}
// clientAlias.port should be within the valid port range
if (serviceConnectService.port &&
!this.isValidPort(serviceConnectService.port)) {
throw new Error(`Client Alias port ${serviceConnectService.port} is not valid.`);
}
});
}
/**
* Determines if a port is valid
*
* @param port: The port number
* @returns boolean whether the port is valid
*/
private isValidPort(port?: number): boolean {
return !!(port && Number.isInteger(port) && port >= BaseService.MIN_PORT && port <= BaseService.MAX_PORT);
}
/**