/
rds.py
429 lines (350 loc) · 15.8 KB
/
rds.py
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
# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
import re
from . import AWSHelperFn, AWSObject, AWSProperty, Tags
from .validators import (boolean, network_port, integer, positive_integer,
integer_range)
# Taken from:
# http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBInstance.html
VALID_STORAGE_TYPES = ('standard', 'gp2', 'io1')
VALID_DB_ENGINES = ('MySQL', 'mysql', 'oracle-se1', 'oracle-se2', 'oracle-se',
'oracle-ee', 'sqlserver-ee', 'sqlserver-se',
'sqlserver-ex', 'sqlserver-web', 'postgres', 'aurora',
'aurora-mysql', 'aurora-postgresql', 'mariadb')
VALID_DB_ENGINE_MODES = ('provisioned', 'serverless')
VALID_LICENSE_MODELS = ('license-included', 'bring-your-own-license',
'general-public-license', 'postgresql-license')
VALID_SCALING_CONFIGURATION_CAPACITIES = (2, 4, 8, 16, 32, 64, 128, 256)
def validate_iops(iops):
"""DBInstance Iops validation rules."""
iops = integer(iops)
if int(iops) == 0:
return iops
if int(iops) < 1000:
raise ValueError("DBInstance Iops, if set, must be greater than 1000.")
return iops
def validate_storage_type(storage_type):
"""Validate StorageType for DBInstance"""
if storage_type not in VALID_STORAGE_TYPES:
raise ValueError("DBInstance StorageType must be one of: %s" %
", ".join(VALID_STORAGE_TYPES))
return storage_type
def validate_engine(engine):
"""Validate database Engine for DBInstance """
if engine not in VALID_DB_ENGINES:
raise ValueError("DBInstance Engine must be one of: %s" %
", ".join(VALID_DB_ENGINES))
return engine
def validate_engine_mode(engine_mode):
"""Validate database EngineMode for DBCluster"""
if engine_mode not in VALID_DB_ENGINE_MODES:
raise ValueError("DBCluster EngineMode must be one of: %s" %
", ".join(VALID_DB_ENGINE_MODES))
return engine_mode
def validate_license_model(license_model):
"""Validate LicenseModel for DBInstance"""
if license_model not in VALID_LICENSE_MODELS:
raise ValueError("DBInstance LicenseModel must be one of: %s" %
", ".join(VALID_LICENSE_MODELS))
return license_model
def validate_backup_window(window):
"""Validate PreferredBackupWindow for DBInstance"""
hour = r'[01]?[0-9]|2[0-3]'
minute = r'[0-5][0-9]'
r = ("(?P<start_hour>%s):(?P<start_minute>%s)-"
"(?P<end_hour>%s):(?P<end_minute>%s)") % (hour, minute, hour, minute)
range_regex = re.compile(r)
m = range_regex.match(window)
if not m:
raise ValueError("DBInstance PreferredBackupWindow must be in the "
"format: hh24:mi-hh24:mi")
start_ts = (int(m.group('start_hour')) * 60) + int(m.group('start_minute'))
end_ts = (int(m.group('end_hour')) * 60) + int(m.group('end_minute'))
if abs(end_ts - start_ts) < 30:
raise ValueError("DBInstance PreferredBackupWindow must be at least "
"30 minutes long.")
return window
def validate_maintenance_window(window):
"""Validate PreferredMaintenanceWindow for DBInstance"""
days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
day_re = r'[A-Z]{1}[a-z]{2}'
hour = r'[01]?[0-9]|2[0-3]'
minute = r'[0-5][0-9]'
r = ("(?P<start_day>%s):(?P<start_hour>%s):(?P<start_minute>%s)-"
"(?P<end_day>%s):(?P<end_hour>%s):(?P<end_minute>%s)") % (day_re,
hour,
minute,
day_re,
hour,
minute)
range_regex = re.compile(r)
m = range_regex.match(window)
if not m:
raise ValueError("DBInstance PreferredMaintenanceWindow must be in "
"the format: ddd:hh24:mi-ddd:hh24:mi")
if m.group('start_day') not in days or m.group('end_day') not in days:
raise ValueError("DBInstance PreferredMaintenanceWindow day part of "
"ranges must be one of: %s" % ", ".join(days))
start_ts = (days.index(m.group('start_day')) * 24 * 60) + \
(int(m.group('start_hour')) * 60) + int(m.group('start_minute'))
end_ts = (days.index(m.group('end_day')) * 24 * 60) + \
(int(m.group('end_hour')) * 60) + int(m.group('end_minute'))
if abs(end_ts - start_ts) < 30:
raise ValueError("DBInstance PreferredMaintenanceWindow must be at "
"least 30 minutes long.")
return window
def validate_backup_retention_period(days):
"""Validate BackupRetentionPeriod for DBInstance"""
days = positive_integer(days)
if int(days) > 35:
raise ValueError("DBInstance BackupRetentionPeriod cannot be larger "
"than 35 days.")
return days
def validate_capacity(capacity):
"""Validate ScalingConfiguration capacity for serverless DBCluster"""
if capacity not in VALID_SCALING_CONFIGURATION_CAPACITIES:
raise ValueError(
"ScalingConfiguration capacity must be one of: {}".format(
", ".join(map(
str,
VALID_SCALING_CONFIGURATION_CAPACITIES
))
)
)
return capacity
class ProcessorFeature(AWSProperty):
props = {
'Name': (basestring, False),
'Value': (basestring, False),
}
class DBInstance(AWSObject):
resource_type = "AWS::RDS::DBInstance"
props = {
'AllocatedStorage': (positive_integer, False),
'AllowMajorVersionUpgrade': (boolean, False),
'AutoMinorVersionUpgrade': (boolean, False),
'AvailabilityZone': (basestring, False),
'BackupRetentionPeriod': (validate_backup_retention_period, False),
'CharacterSetName': (basestring, False),
'CopyTagsToSnapshot': (boolean, False),
'DBClusterIdentifier': (basestring, False),
'DBInstanceClass': (basestring, True),
'DBInstanceIdentifier': (basestring, False),
'DBName': (basestring, False),
'DBParameterGroupName': (basestring, False),
'DBSecurityGroups': (list, False),
'DBSnapshotIdentifier': (basestring, False),
'DBSubnetGroupName': (basestring, False),
'DeleteAutomatedBackups': (boolean, False),
'DeletionProtection': (boolean, False),
'Domain': (basestring, False),
'DomainIAMRoleName': (basestring, False),
'EnableCloudwatchLogsExports': ([basestring], False),
'EnableIAMDatabaseAuthentication': (boolean, False),
'EnablePerformanceInsights': (boolean, False),
'Engine': (validate_engine, False),
'EngineVersion': (basestring, False),
'Iops': (validate_iops, False),
'KmsKeyId': (basestring, False),
'LicenseModel': (validate_license_model, False),
'MasterUsername': (basestring, False),
'MasterUserPassword': (basestring, False),
'MonitoringInterval': (positive_integer, False),
'MonitoringRoleArn': (basestring, False),
'MultiAZ': (boolean, False),
'OptionGroupName': (basestring, False),
'PerformanceInsightsKMSKeyId': (basestring, False),
'PerformanceInsightsRetentionPeriod': (positive_integer, False),
'Port': (network_port, False),
'PreferredBackupWindow': (validate_backup_window, False),
'PreferredMaintenanceWindow': (basestring, False),
'ProcessorFeatures': ([ProcessorFeature], False),
'PromotionTier': (positive_integer, False),
'PubliclyAccessible': (boolean, False),
'SourceDBInstanceIdentifier': (basestring, False),
'SourceRegion': (basestring, False),
'StorageEncrypted': (boolean, False),
'StorageType': (basestring, False),
'Tags': ((Tags, list), False),
'Timezone': (basestring, False),
'VPCSecurityGroups': ([basestring], False),
}
def validate(self):
if 'DBSnapshotIdentifier' not in self.properties:
if 'Engine' not in self.properties:
raise ValueError(
'Resource Engine is required in type %s'
% self.resource_type)
if 'SourceDBInstanceIdentifier' in self.properties:
invalid_replica_properties = (
'BackupRetentionPeriod', 'DBName', 'MasterUsername',
'MasterUserPassword', 'PreferredBackupWindow', 'MultiAZ',
'DBSnapshotIdentifier',
)
invalid_properties = [s for s in self.properties.keys() if
s in invalid_replica_properties]
if invalid_properties:
raise ValueError(
('{0} properties can\'t be provided when '
'SourceDBInstanceIdentifier is present '
'AWS::RDS::DBInstance.'
).format(', '.join(sorted(invalid_properties))))
if ('DBSnapshotIdentifier' not in self.properties and
'SourceDBInstanceIdentifier' not in self.properties) and \
('MasterUsername' not in self.properties or
'MasterUserPassword' not in self.properties) and \
('DBClusterIdentifier' not in self.properties):
raise ValueError(
r"Either (MasterUsername and MasterUserPassword) or"
r" DBSnapshotIdentifier are required in type "
r"AWS::RDS::DBInstance."
)
if 'KmsKeyId' in self.properties and \
'StorageEncrypted' not in self.properties:
raise ValueError(
'If KmsKeyId is provided, StorageEncrypted is required '
'AWS::RDS::DBInstance.'
)
nonetype = type(None)
avail_zone = self.properties.get('AvailabilityZone', None)
multi_az = self.properties.get('MultiAZ', None)
if not (isinstance(avail_zone, (AWSHelperFn, nonetype)) and
isinstance(multi_az, (AWSHelperFn, nonetype))):
if avail_zone and multi_az in [True, 1, '1', 'true', 'True']:
raise ValueError("AvailabiltyZone cannot be set on "
"DBInstance if MultiAZ is set to true.")
storage_type = self.properties.get('StorageType', None)
if storage_type and storage_type == 'io1' and \
'Iops' not in self.properties:
raise ValueError("Must specify Iops if using StorageType io1")
allocated_storage = self.properties.get('AllocatedStorage')
iops = self.properties.get('Iops', None)
if iops and not isinstance(iops, AWSHelperFn):
if not isinstance(allocated_storage, AWSHelperFn) and \
int(allocated_storage) < 100:
raise ValueError("AllocatedStorage must be at least 100 when "
"Iops is set.")
if not isinstance(allocated_storage, AWSHelperFn) and not \
isinstance(iops, AWSHelperFn) and \
float(iops) / float(allocated_storage) > 50.0:
raise ValueError("AllocatedStorage must be no less than "
"1/50th the provisioned Iops")
return True
class DBParameterGroup(AWSObject):
resource_type = "AWS::RDS::DBParameterGroup"
props = {
'Description': (basestring, False),
'Family': (basestring, False),
'Parameters': (dict, False),
'Tags': ((Tags, list), False),
}
class DBSubnetGroup(AWSObject):
resource_type = "AWS::RDS::DBSubnetGroup"
props = {
'DBSubnetGroupDescription': (basestring, True),
'DBSubnetGroupName': (basestring, False),
'SubnetIds': (list, True),
'Tags': ((Tags, list), False),
}
class RDSSecurityGroup(AWSProperty):
props = {
'CIDRIP': (basestring, False),
'EC2SecurityGroupId': (basestring, False),
'EC2SecurityGroupName': (basestring, False),
'EC2SecurityGroupOwnerId': (basestring, False),
}
class DBSecurityGroup(AWSObject):
resource_type = "AWS::RDS::DBSecurityGroup"
props = {
'EC2VpcId': (basestring, False),
'DBSecurityGroupIngress': (list, True),
'GroupDescription': (basestring, True),
'Tags': ((Tags, list), False),
}
class DBSecurityGroupIngress(AWSObject):
resource_type = "AWS::RDS::DBSecurityGroupIngress"
props = {
'CIDRIP': (basestring, False),
'DBSecurityGroupName': (basestring, True),
'EC2SecurityGroupId': (basestring, False),
'EC2SecurityGroupName': (basestring, False),
'EC2SecurityGroupOwnerId': (basestring, False),
}
class EventSubscription(AWSObject):
resource_type = "AWS::RDS::EventSubscription"
props = {
'Enabled': (boolean, False),
'EventCategories': ([basestring], False),
'SnsTopicArn': (basestring, True),
'SourceIds': ([basestring], False),
'SourceType': (basestring, False),
}
class OptionSetting(AWSProperty):
props = {
'Name': (basestring, False),
'Value': (basestring, False),
}
class OptionConfiguration(AWSProperty):
props = {
'DBSecurityGroupMemberships': ([basestring], False),
'OptionName': (basestring, True),
'OptionSettings': ([OptionSetting], False),
'OptionVersion': (basestring, False),
'Port': (network_port, False),
'VpcSecurityGroupMemberships': ([basestring], False),
}
class OptionGroup(AWSObject):
resource_type = "AWS::RDS::OptionGroup"
props = {
'EngineName': (basestring, True),
'MajorEngineVersion': (basestring, True),
'OptionGroupDescription': (basestring, True),
'OptionConfigurations': ([OptionConfiguration], True),
'Tags': ((Tags, list), False),
}
class DBClusterParameterGroup(AWSObject):
resource_type = "AWS::RDS::DBClusterParameterGroup"
props = {
'Description': (basestring, True),
'Family': (basestring, True),
'Parameters': (dict, False),
'Tags': ((Tags, list), False),
}
class ScalingConfiguration(AWSProperty):
props = {
'AutoPause': (boolean, False),
'MaxCapacity': (validate_capacity, False),
'MinCapacity': (validate_capacity, False),
'SecondsUntilAutoPause': (positive_integer, False),
}
class DBCluster(AWSObject):
resource_type = "AWS::RDS::DBCluster"
props = {
'AvailabilityZones': ([basestring], False),
'BacktrackWindow': (integer_range(0, 259200), False),
'BackupRetentionPeriod': (validate_backup_retention_period, False),
'DatabaseName': (basestring, False),
'DBClusterIdentifier': (basestring, False),
'DBClusterParameterGroupName': (basestring, False),
'DBSubnetGroupName': (basestring, False),
'DeletionProtection': (boolean, False),
'EnableCloudwatchLogsExports': ([basestring], False),
'EnableIAMDatabaseAuthentication': (boolean, False),
'Engine': (validate_engine, True),
'EngineMode': (validate_engine_mode, False),
'EngineVersion': (basestring, False),
'KmsKeyId': (basestring, False),
'MasterUsername': (basestring, False),
'MasterUserPassword': (basestring, False),
'Port': (network_port, False),
'PreferredBackupWindow': (validate_backup_window, False),
'PreferredMaintenanceWindow': (basestring, False),
'ReplicationSourceIdentifier': (basestring, False),
'ScalingConfiguration': (ScalingConfiguration, False),
'SnapshotIdentifier': (basestring, False),
'StorageEncrypted': (boolean, False),
'Tags': ((Tags, list), False),
'VpcSecurityGroupIds': ([basestring], False),
}