-
Notifications
You must be signed in to change notification settings - Fork 4k
/
cluster.ts
544 lines (466 loc) · 15.5 KB
/
cluster.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
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as kms from '@aws-cdk/aws-kms';
import { Aws, Duration, IResource, Lazy, RemovalPolicy, Resource, Token } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { Endpoint } from './endpoint';
import { InstanceType } from './instance';
import { CfnDBCluster, CfnDBInstance } from './neptune.generated';
import { IClusterParameterGroup, IParameterGroup } from './parameter-group';
import { ISubnetGroup, SubnetGroup } from './subnet-group';
/**
* Possible Instances Types to use in Neptune cluster
* used for defining {@link DatabaseClusterProps.engineVersion}.
*/
export class EngineVersion {
/**
* Neptune engine version 1.0.1.0
*/
public static readonly V1_0_1_0 = new EngineVersion('1.0.1.0');
/**
* Neptune engine version 1.0.1.1
*/
public static readonly V1_0_1_1 = new EngineVersion('1.0.1.1');
/**
* Neptune engine version 1.0.1.2
*/
public static readonly V1_0_1_2 = new EngineVersion('1.0.1.2');
/**
* Neptune engine version 1.0.2.1
*/
public static readonly V1_0_2_1 = new EngineVersion('1.0.2.1');
/**
* Neptune engine version 1.0.2.2
*/
public static readonly V1_0_2_2 = new EngineVersion('1.0.2.2');
/**
* Neptune engine version 1.0.3.0
*/
public static readonly V1_0_3_0 = new EngineVersion('1.0.3.0');
/**
* Neptune engine version 1.0.4.0
*/
public static readonly V1_0_4_0 = new EngineVersion('1.0.4.0');
/**
* Neptune engine version 1.0.4.1
*/
public static readonly V1_0_4_1 = new EngineVersion('1.0.4.1');
/**
* Neptune engine version 1.0.5.0
*/
public static readonly V1_0_5_0 = new EngineVersion('1.0.5.0');
/**
* Neptune engine version 1.1.0.0
*/
public static readonly V1_1_0_0 = new EngineVersion('1.1.0.0');
/**
* Constructor for specifying a custom engine version
* @param version the engine version of Neptune
*/
public constructor(public readonly version: string) {}
}
/**
* Properties for a new database cluster
*/
export interface DatabaseClusterProps {
/**
* What version of the database to start
*
* @default - The default engine version.
*/
readonly engineVersion?: EngineVersion;
/**
* The port the Neptune cluster will listen on
*
* @default - The default engine port
*/
readonly port?: number;
/**
* How many days to retain the backup
*
* @default - cdk.Duration.days(1)
*/
readonly backupRetention?: Duration;
/**
* A daily time range in 24-hours UTC format in which backups preferably execute.
*
* Must be at least 30 minutes long.
*
* Example: '01:00-02:00'
*
* @default - a 30-minute window selected at random from an 8-hour block of
* time for each AWS Region. To see the time blocks available, see
*/
readonly preferredBackupWindow?: string;
/**
* The KMS key for storage encryption.
*
* @default - default master key.
*/
readonly kmsKey?: kms.IKey;
/**
* Whether to enable storage encryption
*
* @default true
*/
readonly storageEncrypted?: boolean;
/**
* Number of Neptune compute instances
*
* @default 1
*/
readonly instances?: number;
/**
* An optional identifier for the cluster
*
* @default - A name is automatically generated.
*/
readonly dbClusterName?: string;
/**
* Map AWS Identity and Access Management (IAM) accounts to database accounts
*
* @default - `false`
*/
readonly iamAuthentication?: boolean;
/**
* Base identifier for instances
*
* Every replica is named by appending the replica number to this string, 1-based.
*
* @default - `dbClusterName` is used with the word "Instance" appended. If `dbClusterName` is not provided, the
* identifier is automatically generated.
*/
readonly instanceIdentifierBase?: string;
/**
* What type of instance to start for the replicas
*/
readonly instanceType: InstanceType;
/**
* A list of AWS Identity and Access Management (IAM) role that can be used by the cluster to access other AWS services.
*
* @default - No role is attached to the cluster.
*/
readonly associatedRoles?: iam.IRole[];
/**
* Indicates whether the DB cluster should have deletion protection enabled.
*
* @default - true if ``removalPolicy`` is RETAIN, false otherwise
*/
readonly deletionProtection?: boolean;
/**
* A weekly time range in which maintenance should preferably execute.
*
* Must be at least 30 minutes long.
*
* Example: 'tue:04:17-tue:04:47'
*
* @default - 30-minute window selected at random from an 8-hour block of time for
* each AWS Region, occurring on a random day of the week.
*/
readonly preferredMaintenanceWindow?: string;
/**
* Additional parameters to pass to the database engine
*
* @default - No parameter group.
*/
readonly clusterParameterGroup?: IClusterParameterGroup;
/**
* The DB parameter group to associate with the instance.
*
* @default no parameter group
*/
readonly parameterGroup?: IParameterGroup;
/**
* Existing subnet group for the cluster.
*
* @default - a new subnet group will be created.
*/
readonly subnetGroup?: ISubnetGroup;
/**
* What subnets to run the Neptune instances in.
*
* Must be at least 2 subnets in two different AZs.
*/
readonly vpc: ec2.IVpc;
/**
* Where to place the instances within the VPC
*
* @default private subnets
*/
readonly vpcSubnets?: ec2.SubnetSelection;
/**
* Security group.
*
* @default a new security group is created.
*/
readonly securityGroups?: ec2.ISecurityGroup[];
/**
* The removal policy to apply when the cluster and its instances are removed
* or replaced during a stack update, or when the stack is deleted. This
* removal policy also applies to the implicit security group created for the
* cluster if one is not supplied as a parameter.
*
* @default - Retain cluster.
*/
readonly removalPolicy?: RemovalPolicy
/**
* If set to true, Neptune will automatically update the engine of the entire
* cluster to the latest minor version after a stabilization window of 2 to 3 weeks.
*
* @default - false
*/
readonly autoMinorVersionUpgrade?: boolean;
}
/**
* Create a clustered database with a given number of instances.
*/
export interface IDatabaseCluster extends IResource, ec2.IConnectable {
/**
* Identifier of the cluster
*/
readonly clusterIdentifier: string;
/**
* Resource identifier of the cluster
* @attribute ClusterResourceId
*/
readonly clusterResourceIdentifier: string;
/**
* The endpoint to use for read/write operations
* @attribute Endpoint,Port
*/
readonly clusterEndpoint: Endpoint;
/**
* Endpoint to use for load-balanced read-only operations.
* @attribute ReadEndpoint
*/
readonly clusterReadEndpoint: Endpoint;
/**
* Grant the given identity connection access to the database.
*/
grantConnect(grantee: iam.IGrantable): iam.Grant;
}
/**
* Properties that describe an existing cluster instance
*/
export interface DatabaseClusterAttributes {
/**
* The database port
*/
readonly port: number;
/**
* The security group of the database cluster
*/
readonly securityGroup: ec2.ISecurityGroup;
/**
* Identifier for the cluster
*/
readonly clusterIdentifier: string;
/**
* Resource Identifier for the cluster
*/
readonly clusterResourceIdentifier: string;
/**
* Cluster endpoint address
*/
readonly clusterEndpointAddress: string;
/**
* Reader endpoint address
*/
readonly readerEndpointAddress: string;
}
/**
* A new or imported database cluster.
*/
export abstract class DatabaseClusterBase extends Resource implements IDatabaseCluster {
/**
* Import an existing DatabaseCluster from properties
*/
public static fromDatabaseClusterAttributes(scope: Construct, id: string, attrs: DatabaseClusterAttributes): IDatabaseCluster {
class Import extends DatabaseClusterBase implements IDatabaseCluster {
public readonly defaultPort = ec2.Port.tcp(attrs.port);
public readonly connections = new ec2.Connections({
securityGroups: [attrs.securityGroup],
defaultPort: this.defaultPort,
});
public readonly clusterIdentifier = attrs.clusterIdentifier;
public readonly clusterResourceIdentifier = attrs.clusterResourceIdentifier;
public readonly clusterEndpoint = new Endpoint(attrs.clusterEndpointAddress, attrs.port);
public readonly clusterReadEndpoint = new Endpoint(attrs.readerEndpointAddress, attrs.port);
protected enableIamAuthentication = true;
}
return new Import(scope, id);
}
/**
* Identifier of the cluster
*/
public abstract readonly clusterIdentifier: string;
/**
* Resource identifier of the cluster
*/
public abstract readonly clusterResourceIdentifier: string;
/**
* The endpoint to use for read/write operations
*/
public abstract readonly clusterEndpoint: Endpoint;
/**
* Endpoint to use for load-balanced read-only operations.
*/
public abstract readonly clusterReadEndpoint: Endpoint;
/**
* The connections object to implement IConnectable
*/
public abstract readonly connections: ec2.Connections;
protected abstract enableIamAuthentication?: boolean;
public grantConnect(grantee: iam.IGrantable): iam.Grant {
if (this.enableIamAuthentication === false) {
throw new Error('Cannot grant connect when IAM authentication is disabled');
}
this.enableIamAuthentication = true;
return iam.Grant.addToPrincipal({
grantee,
actions: ['neptune-db:*'],
resourceArns: [
[
'arn',
Aws.PARTITION,
'neptune-db',
Aws.REGION,
Aws.ACCOUNT_ID,
`${this.clusterResourceIdentifier}/*`,
].join(':'),
],
});
}
}
/**
* Create a clustered database with a given number of instances.
*
* @resource AWS::Neptune::DBCluster
*/
export class DatabaseCluster extends DatabaseClusterBase implements IDatabaseCluster {
/**
* The default number of instances in the Neptune cluster if none are
* specified
*/
public static readonly DEFAULT_NUM_INSTANCES = 1;
public readonly clusterIdentifier: string;
public readonly clusterEndpoint: Endpoint;
public readonly clusterReadEndpoint: Endpoint;
public readonly connections: ec2.Connections;
/**
* The resource id for the cluster; for example: cluster-ABCD1234EFGH5678IJKL90MNOP. The cluster ID uniquely
* identifies the cluster and is used in things like IAM authentication policies.
* @attribute ClusterResourceId
*/
public readonly clusterResourceIdentifier: string;
/**
* The VPC where the DB subnet group is created.
*/
public readonly vpc: ec2.IVpc;
/**
* The subnets used by the DB subnet group.
*/
public readonly vpcSubnets: ec2.SubnetSelection;
/**
* Subnet group used by the DB
*/
public readonly subnetGroup: ISubnetGroup;
/**
* Identifiers of the instance
*/
public readonly instanceIdentifiers: string[] = [];
/**
* Endpoints which address each individual instance.
*/
public readonly instanceEndpoints: Endpoint[] = [];
protected enableIamAuthentication?: boolean;
constructor(scope: Construct, id: string, props: DatabaseClusterProps) {
super(scope, id);
this.vpc = props.vpc;
this.vpcSubnets = props.vpcSubnets ?? { subnetType: ec2.SubnetType.PRIVATE_WITH_NAT };
// Determine the subnet(s) to deploy the Neptune cluster to
const { subnetIds, internetConnectivityEstablished } = this.vpc.selectSubnets(this.vpcSubnets);
// Cannot test whether the subnets are in different AZs, but at least we can test the amount.
if (subnetIds.length < 2) {
throw new Error(`Cluster requires at least 2 subnets, got ${subnetIds.length}`);
}
this.subnetGroup = props.subnetGroup ?? new SubnetGroup(this, 'Subnets', {
description: `Subnets for ${id} database`,
vpc: this.vpc,
vpcSubnets: this.vpcSubnets,
removalPolicy: props.removalPolicy === RemovalPolicy.RETAIN ? props.removalPolicy : undefined,
});
const securityGroups = props.securityGroups ?? [
new ec2.SecurityGroup(this, 'SecurityGroup', {
description: 'Neptune security group',
vpc: this.vpc,
}),
];
// Default to encrypted storage
const storageEncrypted = props.storageEncrypted ?? true;
if (props.kmsKey && !storageEncrypted) {
throw new Error('KMS key supplied but storageEncrypted is false');
}
const deletionProtection = props.deletionProtection ?? (props.removalPolicy === RemovalPolicy.RETAIN ? true : undefined);
this.enableIamAuthentication = props.iamAuthentication;
// Create the Neptune cluster
const cluster = new CfnDBCluster(this, 'Resource', {
// Basic
engineVersion: props.engineVersion?.version,
dbClusterIdentifier: props.dbClusterName,
dbSubnetGroupName: this.subnetGroup.subnetGroupName,
port: props.port,
vpcSecurityGroupIds: securityGroups.map(sg => sg.securityGroupId),
dbClusterParameterGroupName: props.clusterParameterGroup?.clusterParameterGroupName,
deletionProtection: deletionProtection,
associatedRoles: props.associatedRoles ? props.associatedRoles.map(role => ({ roleArn: role.roleArn })) : undefined,
iamAuthEnabled: Lazy.any({ produce: () => this.enableIamAuthentication }),
// Backup
backupRetentionPeriod: props.backupRetention?.toDays(),
preferredBackupWindow: props.preferredBackupWindow,
preferredMaintenanceWindow: props.preferredMaintenanceWindow,
// Encryption
kmsKeyId: props.kmsKey?.keyArn,
storageEncrypted,
});
cluster.applyRemovalPolicy(props.removalPolicy, {
applyToUpdateReplacePolicy: true,
});
this.clusterIdentifier = cluster.ref;
this.clusterResourceIdentifier = cluster.attrClusterResourceId;
const port = Token.asNumber(cluster.attrPort);
this.clusterEndpoint = new Endpoint(cluster.attrEndpoint, port);
this.clusterReadEndpoint = new Endpoint(cluster.attrReadEndpoint, port);
// Create the instances
const instanceCount = props.instances ?? DatabaseCluster.DEFAULT_NUM_INSTANCES;
if (instanceCount < 1) {
throw new Error('At least one instance is required');
}
for (let i = 0; i < instanceCount; i++) {
const instanceIndex = i + 1;
const instanceIdentifier = props.instanceIdentifierBase != null ? `${props.instanceIdentifierBase}${instanceIndex}`
: props.dbClusterName != null ? `${props.dbClusterName}instance${instanceIndex}` : undefined;
const instance = new CfnDBInstance(this, `Instance${instanceIndex}`, {
// Link to cluster
dbClusterIdentifier: cluster.ref,
dbInstanceIdentifier: instanceIdentifier,
// Instance properties
dbInstanceClass: props.instanceType._instanceType,
dbParameterGroupName: props.parameterGroup?.parameterGroupName,
autoMinorVersionUpgrade: props.autoMinorVersionUpgrade === true,
});
// We must have a dependency on the NAT gateway provider here to create
// things in the right order.
instance.node.addDependency(internetConnectivityEstablished);
instance.applyRemovalPolicy(props.removalPolicy, {
applyToUpdateReplacePolicy: true,
});
this.instanceIdentifiers.push(instance.ref);
this.instanceEndpoints.push(new Endpoint(instance.attrEndpoint, port));
}
this.connections = new ec2.Connections({
defaultPort: ec2.Port.tcp(port),
securityGroups: securityGroups,
});
}
}