-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
application-target-group.ts
712 lines (629 loc) · 24.8 KB
/
application-target-group.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
import { IConstruct, Construct } from 'constructs';
import { IApplicationListener } from './application-listener';
import { HttpCodeTarget } from './application-load-balancer';
import * as cloudwatch from '../../../aws-cloudwatch';
import * as ec2 from '../../../aws-ec2';
import { Aws, Annotations, Duration, Token } from '../../../core';
import { ApplicationELBMetrics } from '../elasticloadbalancingv2-canned-metrics.generated';
import {
BaseTargetGroupProps, ITargetGroup, loadBalancerNameFromListenerArn, LoadBalancerTargetProps,
TargetGroupAttributes, TargetGroupBase, TargetGroupImportProps,
} from '../shared/base-target-group';
import { ApplicationProtocol, ApplicationProtocolVersion, Protocol, TargetType, TargetGroupLoadBalancingAlgorithmType } from '../shared/enums';
import { ImportedTargetGroupBase } from '../shared/imported';
import { determineProtocolAndPort, parseLoadBalancerFullName, parseTargetGroupFullName } from '../shared/util';
/**
* Properties for defining an Application Target Group
*/
export interface ApplicationTargetGroupProps extends BaseTargetGroupProps {
/**
* The protocol used for communication with the target.
*
* This is not applicable for Lambda targets.
*
* @default - Determined from port if known
*/
readonly protocol?: ApplicationProtocol;
/**
* The protocol version to use
*
* @default ApplicationProtocolVersion.HTTP1
*/
readonly protocolVersion?: ApplicationProtocolVersion;
/**
* The port on which the target receives traffic.
*
* This is not applicable for Lambda targets.
*
* @default - Determined from protocol if known
*/
readonly port?: number;
/**
* The time period during which the load balancer sends a newly registered
* target a linearly increasing share of the traffic to the target group.
*
* The range is 30-900 seconds (15 minutes).
*
* @default 0
*/
readonly slowStart?: Duration;
/**
* The stickiness cookie expiration period.
*
* Setting this value enables load balancer stickiness.
*
* After this period, the cookie is considered stale. The minimum value is
* 1 second and the maximum value is 7 days (604800 seconds).
*
* @default - Stickiness is disabled
*/
readonly stickinessCookieDuration?: Duration;
/**
* The name of an application-based stickiness cookie.
*
* Names that start with the following prefixes are not allowed: AWSALB, AWSALBAPP,
* and AWSALBTG; they're reserved for use by the load balancer.
*
* Note: `stickinessCookieName` parameter depends on the presence of `stickinessCookieDuration` parameter.
* If `stickinessCookieDuration` is not set, `stickinessCookieName` will be omitted.
*
* @default - If `stickinessCookieDuration` is set, a load-balancer generated cookie is used. Otherwise, no stickiness is defined.
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html
*/
readonly stickinessCookieName?: string;
/**
* The load balancing algorithm to select targets for routing requests.
*
* @default TargetGroupLoadBalancingAlgorithmType.ROUND_ROBIN
*/
readonly loadBalancingAlgorithmType?: TargetGroupLoadBalancingAlgorithmType;
/**
* The targets to add to this target group.
*
* Can be `Instance`, `IPAddress`, or any self-registering load balancing
* target. If you use either `Instance` or `IPAddress` as targets, all
* target must be of the same type.
*
* @default - No targets.
*/
readonly targets?: IApplicationLoadBalancerTarget[];
/**
* Indicates whether anomaly mitigation is enabled.
*
* Only available when `loadBalancingAlgorithmType` is `TargetGroupLoadBalancingAlgorithmType.WEIGHTED_RANDOM`
*
* @default false
*
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html#automatic-target-weights
*/
readonly enableAnomalyMitigation?: boolean;
}
/**
* Contains all metrics for a Target Group of a Application Load Balancer.
*/
export interface IApplicationTargetGroupMetrics {
/**
* Return the given named metric for this Network Target Group
*
* @default Average over 5 minutes
*/
custom(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of IPv6 requests received by the target group
*
* @default Sum over 5 minutes
*/
ipv6RequestCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of requests processed over IPv4 and IPv6.
*
* This count includes only the requests with a response generated by a target of the load balancer.
*
* @default Sum over 5 minutes
*/
requestCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of healthy hosts in the target group
*
* @default Average over 5 minutes
*/
healthyHostCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of unhealthy hosts in the target group
*
* @default Average over 5 minutes
*/
unhealthyHostCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of HTTP 2xx/3xx/4xx/5xx response codes generated by all targets in this target group.
*
* This does not include any response codes generated by the load balancer.
*
* @default Sum over 5 minutes
*/
httpCodeTarget(code: HttpCodeTarget, props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The average number of requests received by each target in a target group.
*
* The only valid statistic is Sum. Note that this represents the average not the sum.
*
* @default Sum over 5 minutes
*/
requestCountPerTarget(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of connections that were not successfully established between the load balancer and target.
*
* @default Sum over 5 minutes
*/
targetConnectionErrorCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The time elapsed, in seconds, after the request leaves the load balancer until a response from the target is received.
*
* @default Average over 5 minutes
*/
targetResponseTime(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of TLS connections initiated by the load balancer that did not establish a session with the target.
*
* Possible causes include a mismatch of ciphers or protocols.
*
* @default Sum over 5 minutes
*/
targetTLSNegotiationErrorCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
}
/**
* The metrics for a Application Load Balancer.
*/
class ApplicationTargetGroupMetrics implements IApplicationTargetGroupMetrics {
private readonly scope: Construct;
private readonly loadBalancerFullName: string;
private readonly targetGroupFullName: string;
public constructor(scope: Construct, targetGroupFullName: string, loadBalancerFullName: string) {
this.scope = scope;
this.targetGroupFullName = targetGroupFullName;
this.loadBalancerFullName = loadBalancerFullName;
}
public custom(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
namespace: 'AWS/ApplicationELB',
metricName,
dimensionsMap: {
TargetGroup: this.targetGroupFullName,
LoadBalancer: this.loadBalancerFullName,
},
...props,
}).attachTo(this.scope);
}
public ipv6RequestCount(props?: cloudwatch.MetricOptions) {
return this.cannedMetric(ApplicationELBMetrics.iPv6RequestCountSum, props);
}
public requestCount(props?: cloudwatch.MetricOptions) {
return this.cannedMetric(ApplicationELBMetrics.requestCountSum, props);
}
public healthyHostCount(props?: cloudwatch.MetricOptions) {
return this.custom('HealthyHostCount', {
statistic: 'Average',
...props,
});
}
public unhealthyHostCount(props?: cloudwatch.MetricOptions) {
return this.custom('UnHealthyHostCount', {
statistic: 'Average',
...props,
});
}
public httpCodeTarget(code: HttpCodeTarget, props?: cloudwatch.MetricOptions) {
return this.custom(code, {
statistic: 'Sum',
...props,
});
}
public requestCountPerTarget(props?: cloudwatch.MetricOptions) {
return this.custom('RequestCountPerTarget', {
statistic: 'Sum',
...props,
});
}
public targetConnectionErrorCount(props?: cloudwatch.MetricOptions) {
return this.custom('TargetConnectionErrorCount', {
statistic: 'Sum',
...props,
});
}
public targetResponseTime(props?: cloudwatch.MetricOptions) {
return this.custom('TargetResponseTime', {
statistic: 'Average',
...props,
});
}
public targetTLSNegotiationErrorCount(props?: cloudwatch.MetricOptions) {
return this.custom('TargetTLSNegotiationErrorCount', {
statistic: 'Sum',
...props,
});
}
private cannedMetric(
fn: (dims: { LoadBalancer: string; TargetGroup: string }) => cloudwatch.MetricProps,
props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
...fn({
LoadBalancer: this.loadBalancerFullName,
TargetGroup: this.targetGroupFullName,
}),
...props,
}).attachTo(this.scope);
}
}
/**
* Define an Application Target Group
*/
export class ApplicationTargetGroup extends TargetGroupBase implements IApplicationTargetGroup {
/**
* Import an existing target group
*/
public static fromTargetGroupAttributes(scope: Construct, id: string, attrs: TargetGroupAttributes): IApplicationTargetGroup {
return new ImportedApplicationTargetGroup(scope, id, attrs);
}
/**
* Import an existing target group
*
* @deprecated Use `fromTargetGroupAttributes` instead
*/
public static import(scope: Construct, id: string, props: TargetGroupImportProps): IApplicationTargetGroup {
return ApplicationTargetGroup.fromTargetGroupAttributes(scope, id, props);
}
private readonly connectableMembers: ConnectableMember[];
private readonly listeners: IApplicationListener[];
private readonly protocol?: ApplicationProtocol;
private readonly port?: number;
private _metrics?: IApplicationTargetGroupMetrics;
constructor(scope: Construct, id: string, props: ApplicationTargetGroupProps = {}) {
const [protocol, port] = determineProtocolAndPort(props.protocol, props.port);
const { protocolVersion } = props;
super(scope, id, { ...props }, {
protocol,
protocolVersion,
port,
});
this.protocol = protocol;
this.port = port;
// this.targetType is lazy
this.node.addValidation({
validate: () => {
if (this.targetType === TargetType.LAMBDA && (this.port || this.protocol)) {
return ['port/protocol should not be specified for Lambda targets'];
} else {
return [];
}
},
});
this.connectableMembers = [];
this.listeners = [];
if (props) {
const isWeightedRandomAlgorithm = !Token.isUnresolved(props.loadBalancingAlgorithmType) &&
(props.loadBalancingAlgorithmType === TargetGroupLoadBalancingAlgorithmType.WEIGHTED_RANDOM);
if (props.slowStart !== undefined) {
// 0 is allowed and disables slow start
if ((props.slowStart.toSeconds() < 30 && props.slowStart.toSeconds() !== 0) || props.slowStart.toSeconds() > 900) {
throw new Error('Slow start duration value must be between 30 and 900 seconds, or 0 to disable slow start.');
}
this.setAttribute('slow_start.duration_seconds', props.slowStart.toSeconds().toString());
if (isWeightedRandomAlgorithm) {
throw new Error('The weighted random routing algorithm can not be used with slow start mode.');
}
}
if (props.stickinessCookieDuration) {
this.enableCookieStickiness(props.stickinessCookieDuration, props.stickinessCookieName);
} else {
this.setAttribute('stickiness.enabled', 'false');
}
if (props.loadBalancingAlgorithmType) {
this.setAttribute('load_balancing.algorithm.type', props.loadBalancingAlgorithmType);
}
this.addTarget(...(props.targets || []));
if (props.enableAnomalyMitigation !== undefined) {
if (props.enableAnomalyMitigation && !isWeightedRandomAlgorithm) {
throw new Error('Anomaly mitigation is only available when `loadBalancingAlgorithmType` is `TargetGroupLoadBalancingAlgorithmType.WEIGHTED_RANDOM`.');
}
this.setAttribute('load_balancing.algorithm.anomaly_mitigation', props.enableAnomalyMitigation ? 'on' : 'off');
}
}
}
public get metrics(): IApplicationTargetGroupMetrics {
if (!this._metrics) {
this._metrics = new ApplicationTargetGroupMetrics(this, this.targetGroupFullName, this.firstLoadBalancerFullName);
}
return this._metrics;
}
/**
* Add a load balancing target to this target group
*/
public addTarget(...targets: IApplicationLoadBalancerTarget[]) {
for (const target of targets) {
const result = target.attachToApplicationTargetGroup(this);
this.addLoadBalancerTarget(result);
}
if (this.targetType === TargetType.LAMBDA) {
this.setAttribute('stickiness.enabled', undefined);
}
}
/**
* Enable sticky routing via a cookie to members of this target group.
*
* Note: If the `cookieName` parameter is set, application-based stickiness will be applied,
* otherwise it defaults to duration-based stickiness attributes (`lb_cookie`).
*
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html
*/
public enableCookieStickiness(duration: Duration, cookieName?: string) {
if (duration.toSeconds() < 1 || duration.toSeconds() > 604800) {
throw new Error('Stickiness cookie duration value must be between 1 second and 7 days (604800 seconds).');
}
if (cookieName !== undefined) {
if (!Token.isUnresolved(cookieName) && (cookieName.startsWith('AWSALB') || cookieName.startsWith('AWSALBAPP') || cookieName.startsWith('AWSALBTG'))) {
throw new Error('App cookie names that start with the following prefixes are not allowed: AWSALB, AWSALBAPP, and AWSALBTG; they\'re reserved for use by the load balancer.');
}
if (cookieName === '') {
throw new Error('App cookie name cannot be an empty string.');
}
}
this.setAttribute('stickiness.enabled', 'true');
if (cookieName) {
this.setAttribute('stickiness.type', 'app_cookie');
this.setAttribute('stickiness.app_cookie.cookie_name', cookieName);
this.setAttribute('stickiness.app_cookie.duration_seconds', duration.toSeconds().toString());
} else {
this.setAttribute('stickiness.type', 'lb_cookie');
this.setAttribute('stickiness.lb_cookie.duration_seconds', duration.toSeconds().toString());
}
}
/**
* Register a connectable as a member of this target group.
*
* Don't call this directly. It will be called by load balancing targets.
*/
public registerConnectable(connectable: ec2.IConnectable, portRange?: ec2.Port) {
portRange = portRange || ec2.Port.tcp(this.defaultPort);
// Notify all listeners that we already know about of this new connectable.
// Then remember for new listeners that might get added later.
this.connectableMembers.push({ connectable, portRange });
for (const listener of this.listeners) {
listener.registerConnectable(connectable, portRange);
}
}
/**
* Register a listener that is load balancing to this target group.
*
* Don't call this directly. It will be called by listeners.
*/
public registerListener(listener: IApplicationListener, associatingConstruct?: IConstruct) {
// Notify this listener of all connectables that we know about.
// Then remember for new connectables that might get added later.
for (const member of this.connectableMembers) {
listener.registerConnectable(member.connectable, member.portRange);
}
this.listeners.push(listener);
this.loadBalancerAttachedDependencies.add(associatingConstruct ?? listener);
}
/**
* Full name of first load balancer
*/
public get firstLoadBalancerFullName(): string {
if (this.listeners.length === 0) {
throw new Error('The TargetGroup needs to be attached to a LoadBalancer before you can call this method');
}
return loadBalancerNameFromListenerArn(this.listeners[0].listenerArn);
}
/**
* Return the given named metric for this Application Load Balancer Target Group
*
* Returns the metric for this target group from the point of view of the first
* load balancer load balancing to it. If you have multiple load balancers load
* sending traffic to the same target group, you will have to override the dimensions
* on this metric.
*
* @default Average over 5 minutes
*/
public metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metrics.custom(metricName, props);
}
/**
* The number of IPv6 requests received by the target group
*
* @default Sum over 5 minutes
* @deprecated Use ``ApplicationTargetGroup.metrics.ipv6RequestCount`` instead
*/
public metricIpv6RequestCount(props?: cloudwatch.MetricOptions) {
return this.metrics.ipv6RequestCount(props);
}
/**
* The number of requests processed over IPv4 and IPv6.
*
* This count includes only the requests with a response generated by a target of the load balancer.
*
* @default Sum over 5 minutes
* @deprecated Use ``ApplicationTargetGroup.metrics.requestCount`` instead
*/
public metricRequestCount(props?: cloudwatch.MetricOptions) {
return this.metrics.requestCount(props);
}
/**
* The number of healthy hosts in the target group
*
* @default Average over 5 minutes
* @deprecated Use ``ApplicationTargetGroup.metrics.healthyHostCount`` instead
*/
public metricHealthyHostCount(props?: cloudwatch.MetricOptions) {
return this.metrics.healthyHostCount(props);
}
/**
* The number of unhealthy hosts in the target group
*
* @default Average over 5 minutes
* @deprecated Use ``ApplicationTargetGroup.metrics.unhealthyHostCount`` instead
*/
public metricUnhealthyHostCount(props?: cloudwatch.MetricOptions) {
return this.metrics.unhealthyHostCount(props);
}
/**
* The number of HTTP 2xx/3xx/4xx/5xx response codes generated by all targets in this target group.
*
* This does not include any response codes generated by the load balancer.
*
* @default Sum over 5 minutes
* @deprecated Use ``ApplicationTargetGroup.metrics.httpCodeTarget`` instead
*/
public metricHttpCodeTarget(code: HttpCodeTarget, props?: cloudwatch.MetricOptions) {
return this.metrics.httpCodeTarget(code, props);
}
/**
* The average number of requests received by each target in a target group.
*
* The only valid statistic is Sum. Note that this represents the average not the sum.
*
* @default Sum over 5 minutes
* @deprecated Use `ApplicationTargetGroup.metrics.requestCountPerTarget` instead
*/
public metricRequestCountPerTarget(props?: cloudwatch.MetricOptions) {
return this.metrics.requestCountPerTarget(props);
}
/**
* The number of connections that were not successfully established between the load balancer and target.
*
* @default Sum over 5 minutes
* @deprecated Use ``ApplicationTargetGroup.metrics.targetConnectionErrorCount`` instead
*/
public metricTargetConnectionErrorCount(props?: cloudwatch.MetricOptions) {
return this.metrics.targetConnectionErrorCount(props);
}
/**
* The time elapsed, in seconds, after the request leaves the load balancer until a response from the target is received.
*
* @default Average over 5 minutes
* @deprecated Use ``ApplicationTargetGroup.metrics.targetResponseTime`` instead
*/
public metricTargetResponseTime(props?: cloudwatch.MetricOptions) {
return this.metrics.targetResponseTime(props);
}
/**
* The number of TLS connections initiated by the load balancer that did not establish a session with the target.
*
* Possible causes include a mismatch of ciphers or protocols.
*
* @default Sum over 5 minutes
* @deprecated Use ``ApplicationTargetGroup.metrics.tlsNegotiationErrorCount`` instead
*/
public metricTargetTLSNegotiationErrorCount(props?: cloudwatch.MetricOptions) {
return this.metrics.targetTLSNegotiationErrorCount(props);
}
protected validateTargetGroup(): string[] {
const ret = super.validateTargetGroup();
if (this.targetType !== undefined && this.targetType !== TargetType.LAMBDA
&& (this.protocol === undefined || this.port === undefined)) {
ret.push('At least one of \'port\' or \'protocol\' is required for a non-Lambda TargetGroup');
}
if (this.healthCheck) {
if (this.healthCheck.interval && this.healthCheck.timeout &&
this.healthCheck.interval.toMilliseconds() <= this.healthCheck.timeout.toMilliseconds()) {
ret.push(`Healthcheck interval ${this.healthCheck.interval.toHumanString()} must be greater than the timeout ${this.healthCheck.timeout.toHumanString()}`);
}
if (this.healthCheck.protocol) {
if (!ALB_HEALTH_CHECK_PROTOCOLS.includes(this.healthCheck.protocol)) {
ret.push([
`Health check protocol '${this.healthCheck.protocol}' is not supported. `,
`Must be one of [${ALB_HEALTH_CHECK_PROTOCOLS.join(', ')}]`,
].join(''));
}
}
}
return ret;
}
}
/**
* A connectable member of a target group
*/
interface ConnectableMember {
/**
* The connectable member
*/
connectable: ec2.IConnectable;
/**
* The port (range) the member is listening on
*/
portRange: ec2.Port;
}
/**
* A Target Group for Application Load Balancers
*/
export interface IApplicationTargetGroup extends ITargetGroup {
/**
* All metrics available for this target group.
*/
readonly metrics: IApplicationTargetGroupMetrics;
/**
* Register a listener that is load balancing to this target group.
*
* Don't call this directly. It will be called by listeners.
*/
registerListener(listener: IApplicationListener, associatingConstruct?: IConstruct): void;
/**
* Register a connectable as a member of this target group.
*
* Don't call this directly. It will be called by load balancing targets.
*/
registerConnectable(connectable: ec2.IConnectable, portRange?: ec2.Port): void;
/**
* Add a load balancing target to this target group
*/
addTarget(...targets: IApplicationLoadBalancerTarget[]): void;
}
/**
* An imported application target group
*/
class ImportedApplicationTargetGroup extends ImportedTargetGroupBase implements IApplicationTargetGroup {
private readonly _metrics?: IApplicationTargetGroupMetrics;
public constructor(scope: Construct, id: string, props: TargetGroupAttributes) {
super(scope, id, props);
if (this.loadBalancerArns != Aws.NO_VALUE) {
const targetGroupFullName = parseTargetGroupFullName(this.targetGroupArn);
const firstLoadBalancerFullName = parseLoadBalancerFullName(this.loadBalancerArns);
this._metrics = new ApplicationTargetGroupMetrics(this, targetGroupFullName, firstLoadBalancerFullName);
}
}
public registerListener(_listener: IApplicationListener, _associatingConstruct?: IConstruct) {
// Nothing to do, we know nothing of our members
Annotations.of(this).addWarningV2('@aws-cdk/aws-elbv2:albTargetGroupCannotRegisterListener', 'Cannot register listener on imported target group -- security groups might need to be updated manually');
}
public registerConnectable(_connectable: ec2.IConnectable, _portRange?: ec2.Port | undefined): void {
Annotations.of(this).addWarningV2('@aws-cdk/aws-elbv2:albTargetGroupCannotRegisterConnectable', 'Cannot register connectable on imported target group -- security groups might need to be updated manually');
}
public addTarget(...targets: IApplicationLoadBalancerTarget[]) {
for (const target of targets) {
const result = target.attachToApplicationTargetGroup(this);
if (result.targetJson !== undefined) {
throw new Error('Cannot add a non-self registering target to an imported TargetGroup. Create a new TargetGroup instead.');
}
}
}
public get metrics(): IApplicationTargetGroupMetrics {
if (!this._metrics) {
throw new Error(
'The imported ApplicationTargetGroup needs the associated ApplicationBalancer to be able to provide metrics. ' +
'Please specify the ARN value when importing it.');
}
return this._metrics;
}
}
/**
* Interface for constructs that can be targets of an application load balancer
*/
export interface IApplicationLoadBalancerTarget {
/**
* Attach load-balanced target to a TargetGroup
*
* May return JSON to directly add to the [Targets] list, or return undefined
* if the target will register itself with the load balancer.
*/
attachToApplicationTargetGroup(targetGroup: IApplicationTargetGroup): LoadBalancerTargetProps;
}
const ALB_HEALTH_CHECK_PROTOCOLS = [Protocol.HTTP, Protocol.HTTPS];