-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
application-target-group.ts
507 lines (453 loc) · 17.3 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
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as ec2 from '@aws-cdk/aws-ec2';
import { Annotations, Duration, Token } from '@aws-cdk/core';
import { IConstruct, Construct } from 'constructs';
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 } from '../shared/util';
import { IApplicationListener } from './application-listener';
import { HttpCodeTarget } from './application-load-balancer';
// keep this import separate from other imports to reduce chance for merge conflicts with v2-main
// eslint-disable-next-line no-duplicate-imports, import/order
import { Construct as CoreConstruct } from '@aws-cdk/core';
/**
* Properties for defining an Application Target Group
*/
export interface ApplicationTargetGroupProps extends BaseTargetGroupProps {
/**
* The protocol to use
*
* @default - Determined from port if known, optional for Lambda targets.
*/
readonly protocol?: ApplicationProtocol;
/**
* The protocol version to use
*
* @default ApplicationProtocolVersion.HTTP1
*/
readonly protocolVersion?: ApplicationProtocolVersion;
/**
* The port on which the listener listens for requests.
*
* @default - Determined from protocol if known, optional for Lambda targets.
*/
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 Duration.days(1)
*/
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[];
}
/**
* 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;
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) {
if (props.slowStart !== undefined) {
if (props.slowStart.toSeconds() < 30 || props.slowStart.toSeconds() > 900) {
throw new Error('Slow start duration value must be between 30 and 900 seconds.');
}
this.setAttribute('slow_start.duration_seconds', props.slowStart.toSeconds().toString());
}
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 || []));
}
}
/**
* 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) as CoreConstruct);
}
/**
* 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 new cloudwatch.Metric({
namespace: 'AWS/ApplicationELB',
metricName,
dimensionsMap: {
TargetGroup: this.targetGroupFullName,
LoadBalancer: this.firstLoadBalancerFullName,
},
...props,
}).attachTo(this);
}
/**
* The number of IPv6 requests received by the target group
*
* @default Sum over 5 minutes
*/
public metricIpv6RequestCount(props?: cloudwatch.MetricOptions) {
return this.cannedMetric(ApplicationELBMetrics.iPv6RequestCountSum, 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
*/
public metricRequestCount(props?: cloudwatch.MetricOptions) {
return this.cannedMetric(ApplicationELBMetrics.requestCountSum, props);
}
/**
* The number of healthy hosts in the target group
*
* @default Average over 5 minutes
*/
public metricHealthyHostCount(props?: cloudwatch.MetricOptions) {
return this.metric('HealthyHostCount', {
statistic: 'Average',
...props,
});
}
/**
* The number of unhealthy hosts in the target group
*
* @default Average over 5 minutes
*/
public metricUnhealthyHostCount(props?: cloudwatch.MetricOptions) {
return this.metric('UnHealthyHostCount', {
statistic: 'Average',
...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
*/
public metricHttpCodeTarget(code: HttpCodeTarget, props?: cloudwatch.MetricOptions) {
return this.metric(code, {
statistic: 'Sum',
...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
*/
public metricRequestCountPerTarget(props?: cloudwatch.MetricOptions) {
return this.metric('RequestCountPerTarget', {
statistic: 'Sum',
...props,
});
}
/**
* The number of connections that were not successfully established between the load balancer and target.
*
* @default Sum over 5 minutes
*/
public metricTargetConnectionErrorCount(props?: cloudwatch.MetricOptions) {
return this.metric('TargetConnectionErrorCount', {
statistic: 'Sum',
...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
*/
public metricTargetResponseTime(props?: cloudwatch.MetricOptions) {
return this.metric('TargetResponseTime', {
statistic: 'Average',
...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
*/
public metricTargetTLSNegotiationErrorCount(props?: cloudwatch.MetricOptions) {
return this.metric('TargetTLSNegotiationErrorCount', {
statistic: 'Sum',
...props,
});
}
protected validate(): string[] {
const ret = super.validate();
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 && this.healthCheck.protocol) {
if (ALB_HEALTH_CHECK_PROTOCOLS.includes(this.healthCheck.protocol)) {
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 (!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;
}
private cannedMetric(
fn: (dims: { LoadBalancer: string, TargetGroup: string }) => cloudwatch.MetricProps,
props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
...fn({
LoadBalancer: this.firstLoadBalancerFullName,
TargetGroup: this.targetGroupFullName,
}),
...props,
}).attachTo(this);
}
}
/**
* 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 {
/**
* 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 {
public registerListener(_listener: IApplicationListener, _associatingConstruct?: IConstruct) {
// Nothing to do, we know nothing of our members
Annotations.of(this).addWarning('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).addWarning('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.');
}
}
}
}
/**
* 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];