-
Notifications
You must be signed in to change notification settings - Fork 4k
/
base-service.ts
1434 lines (1260 loc) · 47.7 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 * as appscaling from '@aws-cdk/aws-applicationautoscaling';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as elb from '@aws-cdk/aws-elasticloadbalancing';
import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2';
import * as iam from '@aws-cdk/aws-iam';
import * as cloudmap from '@aws-cdk/aws-servicediscovery';
import {
Annotations,
Duration,
IResolvable,
IResource,
Lazy,
Resource,
Stack,
ArnFormat,
FeatureFlags,
} from '@aws-cdk/core';
import * as cxapi from '@aws-cdk/cx-api';
import { Construct } from 'constructs';
import { ScalableTaskCount } from './scalable-task-count';
import { LoadBalancerTargetOptions, NetworkMode, TaskDefinition } 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 rollback on deployment failure
* @default false
*/
readonly rollback?: boolean;
}
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 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;
/**
* 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;
}
/**
* 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 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;
/**
* 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: true,
rollback: props.circuitBreaker.rollback ?? false,
} : undefined,
},
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 }),
...additionalProps,
});
if (props.deploymentController?.type === DeploymentControllerType.EXTERNAL) {
Annotations.of(this).addWarning('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.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);
}
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.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();
}
}
this.node.defaultChild = this.resource;
}
/** * Enable Service Connect
*/
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],
} 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);
}
/**
* The CloudMap service created for this service, if any.
*/
public get cloudMapService(): cloudmap.IService | undefined {
return this.cloudmapService;
}
private getDeploymentController(props: BaseServiceProps): DeploymentController | undefined {
if (props.deploymentController) {
// The customer is always right
return props.deploymentController;
}
const disableCircuitBreakerEcsDeploymentControllerFeatureFlag =
FeatureFlags.of(this).isEnabled(cxapi.ECS_DISABLE_EXPLICIT_DEPLOYMENT_CONTROLLER_FOR_CIRCUIT_BREAKER);
if (!disableCircuitBreakerEcsDeploymentControllerFeatureFlag && props.circuitBreaker) {
// This is undesirable behavior (the controller is implicitly ECS anyway when left
// undefined, so specifying it is not necessary but DOES trigger a CFN replacement)
// but we leave it in for backwards compat.
return {
type: DeploymentControllerType.ECS,
};
}
return undefined;
}
private executeCommandLogConfiguration() {
const logConfiguration = this.cluster.executeCommandConfiguration?.logConfiguration;
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
'logs:DescribeLogGroups',
],
resources: ['*'],
}));
const logGroupArn = logConfiguration?.cloudWatchLogGroup ? `arn:${this.stack.partition}:logs:${this.env.region}:${this.env.account}:log-group:${logConfiguration.cloudWatchLogGroup.logGroupName}:*` : '*';
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
'logs:CreateLogStream',
'logs:DescribeLogStreams',
'logs:PutLogEvents',
],
resources: [logGroupArn],
}));
if (logConfiguration?.s3Bucket?.bucketName) {
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
's3:GetBucketLocation',
],
resources: ['*'],
}));
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
's3:PutObject',
],
resources: [`arn:${this.stack.partition}:s3:::${logConfiguration.s3Bucket.bucketName}/*`],
}));
if (logConfiguration.s3EncryptionEnabled) {
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
's3:GetEncryptionConfiguration',
],
resources: [`arn:${this.stack.partition}:s3:::${logConfiguration.s3Bucket.bucketName}`],
}));
}
}
}
private enableExecuteCommandEncryption(logging: ExecuteCommandLogging) {
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
'kms:Decrypt',
'kms:GenerateDataKey',
],
resources: [`${this.cluster.executeCommandConfiguration?.kmsKey?.keyArn}`],
}));
this.cluster.executeCommandConfiguration?.kmsKey?.addToResourcePolicy(new iam.PolicyStatement({
actions: [
'kms:*',
],
resources: ['*'],
principals: [new iam.ArnPrincipal(`arn:${this.stack.partition}:iam::${this.env.account}:root`)],
}));
if (logging === ExecuteCommandLogging.DEFAULT || this.cluster.executeCommandConfiguration?.logConfiguration?.cloudWatchEncryptionEnabled) {
this.cluster.executeCommandConfiguration?.kmsKey?.addToResourcePolicy(new iam.PolicyStatement({
actions: [
'kms:Encrypt*',
'kms:Decrypt*',
'kms:ReEncrypt*',
'kms:GenerateDataKey*',
'kms:Describe*',
],
resources: ['*'],
principals: [new iam.ServicePrincipal(`logs.${this.env.region}.amazonaws.com`)],
conditions: {
ArnLike: { 'kms:EncryptionContext:aws:logs:arn': `arn:${this.stack.partition}:logs:${this.env.region}:${this.env.account}:*` },
},
}));
}
}
/**
* This method is called to attach this service to an Application Load Balancer.
*
* Don't call this function directly. Instead, call `listener.addTargets()`
* to add this service to a load balancer.
*/
public attachToApplicationTargetGroup(targetGroup: elbv2.IApplicationTargetGroup): elbv2.LoadBalancerTargetProps {
return this.defaultLoadBalancerTarget.attachToApplicationTargetGroup(targetGroup);
}
/**
* Registers the service as a target of a Classic Load Balancer (CLB).
*
* Don't call this. Call `loadBalancer.addTarget()` instead.
*/
public attachToClassicLB(loadBalancer: elb.LoadBalancer): void {
return this.defaultLoadBalancerTarget.attachToClassicLB(loadBalancer);
}
/**
* Return a load balancing target for a specific container and port.
*
* Use this function to create a load balancer target if you want to load balance to
* another container than the first essential container or the first mapped port on
* the container.
*
* Use the return value of this function where you would normally use a load balancer
* target, instead of the `Service` object itself.
*
* @example
*
* declare const listener: elbv2.ApplicationListener;
* declare const service: ecs.BaseService;
* listener.addTargets('ECS', {
* port: 80,
* targets: [service.loadBalancerTarget({
* containerName: 'MyContainer',
* containerPort: 1234,
* })],
* });
*/
public loadBalancerTarget(options: LoadBalancerTargetOptions): IEcsLoadBalancerTarget {
const self = this;
const target = this.taskDefinition._validateTarget(options);
const connections = self.connections;
return {
attachToApplicationTargetGroup(targetGroup: elbv2.ApplicationTargetGroup): elbv2.LoadBalancerTargetProps {
targetGroup.registerConnectable(self, self.taskDefinition._portRangeFromPortMapping(target.portMapping));
return self.attachToELBv2(targetGroup, target.containerName, target.portMapping.containerPort);
},
attachToNetworkTargetGroup(targetGroup: elbv2.NetworkTargetGroup): elbv2.LoadBalancerTargetProps {
return self.attachToELBv2(targetGroup, target.containerName, target.portMapping.containerPort);
},
connections,
attachToClassicLB(loadBalancer: elb.LoadBalancer): void {
return self.attachToELB(loadBalancer, target.containerName, target.portMapping.containerPort);
},
};
}
/**
* Use this function to create all load balancer targets to be registered in this service, add them to
* target groups, and attach target groups to listeners accordingly.
*
* Alternatively, you can use `listener.addTargets()` to create targets and add them to target groups.
*
* @example
*
* declare const listener: elbv2.ApplicationListener;
* declare const service: ecs.BaseService;
* service.registerLoadBalancerTargets(
* {
* containerName: 'web',
* containerPort: 80,
* newTargetGroupId: 'ECS',
* listener: ecs.ListenerConfig.applicationListener(listener, {
* protocol: elbv2.ApplicationProtocol.HTTPS
* }),
* },
* )
*/
public registerLoadBalancerTargets(...targets: EcsTarget[]) {
for (const target of targets) {
target.listener.addTargets(target.newTargetGroupId, {
containerName: target.containerName,
containerPort: target.containerPort,
protocol: target.protocol,
}, this);
}
}
/**
* This method is called to attach this service to a Network Load Balancer.
*
* Don't call this function directly. Instead, call `listener.addTargets()`
* to add this service to a load balancer.
*/
public attachToNetworkTargetGroup(targetGroup: elbv2.INetworkTargetGroup): elbv2.LoadBalancerTargetProps {
return this.defaultLoadBalancerTarget.attachToNetworkTargetGroup(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,
});
}
/**
* Enable CloudMap service discovery for the service
*
* @returns The created CloudMap service
*/
public enableCloudMap(options: CloudMapOptions): cloudmap.Service {
const sdNamespace = options.cloudMapNamespace ?? this.cluster.defaultCloudMapNamespace;
if (sdNamespace === undefined) {
throw new Error('Cannot enable service discovery if a Cloudmap Namespace has not been created in the cluster.');
}
if (sdNamespace.type === cloudmap.NamespaceType.HTTP) {
throw new Error('Cannot enable DNS service discovery for HTTP Cloudmap Namespace.');
}
// 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) {