-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsnapshots_tool_utils.py
368 lines (258 loc) · 14 KB
/
snapshots_tool_utils.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
'''
Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
'''
# snapshots_tool_utils
# Support module for the Snapshot Tool for RDS
import boto3
from datetime import datetime, timedelta
import os
import logging
import re
# Initialize everything
_LOGLEVEL = os.getenv('LOG_LEVEL', 'ERROR').strip()
_DESTINATION_REGION = os.getenv(
'DEST_REGION', os.getenv('AWS_DEFAULT_REGION')).strip()
_KMS_KEY_DEST_REGION = os.getenv('KMS_KEY_DEST_REGION', 'None').strip()
_KMS_KEY_SOURCE_REGION = os.getenv('KMS_KEY_SOURCE_REGION', 'None').strip()
_TIMESTAMP_FORMAT = '%Y-%m-%d-%H-%M'
if os.getenv('REGION_OVERRIDE', 'NO') != 'NO':
_REGION = os.getenv('REGION_OVERRIDE').strip()
else:
_REGION = os.getenv('AWS_DEFAULT_REGION')
_SUPPORTED_ENGINES = ['mariadb', 'sqlserver-se', 'sqlserver-ee', 'sqlserver-ex',
'sqlserver-web', 'mysql', 'oracle-se', 'oracle-se1', 'oracle-se2', 'oracle-ee', 'postgres']
logger = logging.getLogger()
logger.setLevel(_LOGLEVEL.upper())
class SnapshotToolException(Exception):
pass
def search_tag_copydbsnapshot(response):
# Takes a list_tags_for_resource response and searches for our CopyDBSnapshot tag
try:
for tag in response['TagList']:
if tag['Key'] == 'CopyDBSnapshot' and tag['Value'] == 'True':
return True
except Exception:
return False
else:
return False
def search_tag_created(response):
# Takes a describe_db_snapshots response and searches for our CreatedBy tag
try:
for tag in response['TagList']:
if tag['Key'] == 'CreatedBy' and tag['Value'] == 'Snapshot Tool for RDS':
return True
except Exception:
return False
else:
return False
def search_tag_shared(response):
# Takes a describe_db_snapshots response and searches for our shareAndCopy tag
try:
for tag in response['TagList']:
if tag['Key'] == 'shareAndCopy' and tag['Value'] == 'YES':
for tag2 in response['TagList']:
if tag2['Key'] == 'CreatedBy' and tag2['Value'] == 'Snapshot Tool for RDS':
return True
except Exception:
return False
return False
def search_tag_copied(response):
# Search for a tag indicating we copied this snapshot
try:
for tag in response['TagList']:
if tag['Key'] == 'CopiedBy' and tag['Value'] == 'Snapshot Tool for RDS':
return True
except Exception:
return False
return False
def get_own_snapshots_no_x_account(pattern, response, REGION):
# Filters our own snapshots
filtered = {}
for snapshot in response['DBSnapshots']:
if snapshot['SnapshotType'] == 'manual' and re.search(pattern, snapshot['DBInstanceIdentifier']) and snapshot['Engine'] in _SUPPORTED_ENGINES:
client = boto3.client('rds', region_name=REGION)
response_tags = client.list_tags_for_resource(
ResourceName=snapshot['DBSnapshotArn'])
if search_tag_created(response_tags):
filtered[snapshot['DBSnapshotIdentifier']] = {
'Arn': snapshot['DBSnapshotArn'], 'Status': snapshot['Status'], 'DBInstanceIdentifier': snapshot['DBInstanceIdentifier']}
# Changed the next line to search for ALL_CLUSTERS or ALL_SNAPSHOTS so it will work with no-x-account
elif snapshot['SnapshotType'] == 'manual' and pattern == 'ALL_SNAPSHOTS' and snapshot['Engine'] in _SUPPORTED_ENGINES:
client = boto3.client('rds', region_name=REGION)
response_tags = client.list_tags_for_resource(
ResourceName=snapshot['DBSnapshotArn'])
if search_tag_created(response_tags):
filtered[snapshot['DBSnapshotIdentifier']] = {
'Arn': snapshot['DBSnapshotArn'], 'Status': snapshot['Status'], 'DBInstanceIdentifier': snapshot['DBInstanceIdentifier']}
return filtered
def get_shared_snapshots(pattern, response):
# Returns a dict with only shared snapshots filtered by pattern, with DBSnapshotIdentifier as key and the response as attribute
filtered = {}
for snapshot in response['DBSnapshots']:
if snapshot['SnapshotType'] == 'shared' and re.search(pattern, snapshot['DBInstanceIdentifier']) and snapshot['Engine'] in _SUPPORTED_ENGINES:
filtered[get_snapshot_identifier(snapshot)] = {
'Arn': snapshot['DBSnapshotIdentifier'], 'Encrypted': snapshot['Encrypted'], 'DBInstanceIdentifier': snapshot['DBInstanceIdentifier']}
if snapshot['Encrypted'] is True:
filtered[get_snapshot_identifier(snapshot)]['KmsKeyId'] = snapshot['KmsKeyId']
elif snapshot['SnapshotType'] == 'shared' and pattern == 'ALL_SNAPSHOTS' and snapshot['Engine'] in _SUPPORTED_ENGINES:
filtered[get_snapshot_identifier(snapshot)] = {
'Arn': snapshot['DBSnapshotIdentifier'], 'Encrypted': snapshot['Encrypted'], 'DBInstanceIdentifier': snapshot['DBInstanceIdentifier']}
if snapshot['Encrypted'] is True:
filtered[get_snapshot_identifier(snapshot)]['KmsKeyId'] = snapshot['KmsKeyId']
return filtered
def get_snapshot_identifier(snapshot):
# Function that will return the RDS Snapshot identifier given an ARN
match = re.match('arn:aws:rds:.*:.*:snapshot:(.+)',
snapshot['DBSnapshotArn'])
return match.group(1)
def get_own_snapshots_dest(pattern, response):
# Returns a dict with local snapshots, filtered by pattern, with DBSnapshotIdentifier as key and Arn, Status as attributes
filtered = {}
for snapshot in response['DBSnapshots']:
if snapshot['SnapshotType'] == 'manual' and re.search(pattern, snapshot['DBInstanceIdentifier']) and snapshot['Engine'] in _SUPPORTED_ENGINES:
filtered[snapshot['DBSnapshotIdentifier']] = {
'Arn': snapshot['DBSnapshotArn'], 'Status': snapshot['Status'], 'Encrypted': snapshot['Encrypted'], 'DBInstanceIdentifier': snapshot['DBInstanceIdentifier']}
if snapshot['Encrypted'] is True:
filtered[snapshot['DBSnapshotIdentifier']]['KmsKeyId'] = snapshot['KmsKeyId']
elif snapshot['SnapshotType'] == 'manual' and pattern == 'ALL_SNAPSHOTS' and snapshot['Engine'] in _SUPPORTED_ENGINES:
filtered[snapshot['DBSnapshotIdentifier']] = {
'Arn': snapshot['DBSnapshotArn'], 'Status': snapshot['Status'], 'Encrypted': snapshot['Encrypted'], 'DBInstanceIdentifier': snapshot['DBInstanceIdentifier']}
if snapshot['Encrypted'] is True:
filtered[snapshot['DBSnapshotIdentifier']]['KmsKeyId'] = snapshot['KmsKeyId']
return filtered
def filter_instances(taggedinstance, pattern, instance_list):
# Takes the response from describe-db-instances and filters according to pattern in DBInstanceIdentifier
filtered_list = []
for instance in instance_list['DBInstances']:
if taggedinstance == 'TRUE':
client = boto3.client('rds', region_name=_REGION)
response = client.list_tags_for_resource(ResourceName=instance['DBInstanceArn'])
print(response)
if pattern == 'ALL_INSTANCES' and instance['Engine'] in _SUPPORTED_ENGINES:
if (taggedinstance == 'TRUE' and search_tag_copydbsnapshot(response)) or taggedinstance == 'FALSE':
filtered_list.append(instance)
else:
match = re.search(pattern, instance['DBInstanceIdentifier'])
if match and instance['Engine'] in _SUPPORTED_ENGINES:
if (taggedinstance == 'TRUE' and search_tag_copydbsnapshot(response)) or taggedinstance == 'FALSE':
filtered_list.append(instance)
return filtered_list
def get_own_snapshots_source(pattern, response, backup_interval=None):
# Filters our own snapshots
filtered = {}
for snapshot in response['DBSnapshots']:
# No need to consider snapshots that are still in progress
if 'SnapshotCreateTime' not in snapshot:
continue
# No need to get tags for snapshots outside of the backup interval
if backup_interval and snapshot['SnapshotCreateTime'].replace(tzinfo=None) < datetime.utcnow().replace(tzinfo=None) - timedelta(hours=backup_interval):
continue
if snapshot['SnapshotType'] == 'manual' and re.search(pattern, snapshot['DBInstanceIdentifier']) and snapshot['Engine'] in _SUPPORTED_ENGINES:
client = boto3.client('rds', region_name=_REGION)
response_tags = client.list_tags_for_resource(
ResourceName=snapshot['DBSnapshotArn'])
if search_tag_created(response_tags):
filtered[snapshot['DBSnapshotIdentifier']] = {
'Arn': snapshot['DBSnapshotArn'], 'Status': snapshot['Status'], 'DBInstanceIdentifier': snapshot['DBInstanceIdentifier']}
elif snapshot['SnapshotType'] == 'manual' and (pattern == 'ALL_CLUSTERS' or pattern == 'ALL_SNAPSHOTS' or pattern == 'ALL_INSTANCES') and snapshot['Engine'] in _SUPPORTED_ENGINES:
client = boto3.client('rds', region_name=_REGION)
response_tags = client.list_tags_for_resource(
ResourceName=snapshot['DBSnapshotArn'])
if search_tag_created(response_tags):
filtered[snapshot['DBSnapshotIdentifier']] = {
'Arn': snapshot['DBSnapshotArn'], 'Status': snapshot['Status'], 'DBInstanceIdentifier': snapshot['DBInstanceIdentifier']}
return filtered
def get_timestamp_no_minute(snapshot_identifier, snapshot_list):
# Get a timestamp from the name of a snapshot and strip out the minutes
pattern = '%s-(.+)-\d{2}' % snapshot_list[snapshot_identifier]['DBInstanceIdentifier']
timestamp_format = '%Y-%m-%d-%H'
date_time = re.search(pattern, snapshot_identifier)
if date_time is not None:
return datetime.strptime(date_time.group(1), timestamp_format)
def get_timestamp(snapshot_identifier, snapshot_list):
# Searches for a timestamp on a snapshot name
pattern = '%s-(.+)' % snapshot_list[snapshot_identifier]['DBInstanceIdentifier']
date_time = re.search(pattern, snapshot_identifier)
if date_time is not None:
try:
return datetime.strptime(date_time.group(1), _TIMESTAMP_FORMAT)
except Exception:
return None
return None
def get_latest_snapshot_ts(instance_identifier, filtered_snapshots):
# Get latest snapshot for a specific DBInstanceIdentifier
timestamps = []
for snapshot, snapshot_object in filtered_snapshots.items():
if snapshot_object['DBInstanceIdentifier'] == instance_identifier:
timestamp = get_timestamp_no_minute(snapshot, filtered_snapshots)
if timestamp is not None:
timestamps.append(timestamp)
if len(timestamps) > 0:
return max(timestamps)
else:
return None
def requires_backup(backup_interval, instance, filtered_snapshots):
# Returns True if latest snapshot is older than INTERVAL
latest = get_latest_snapshot_ts(instance['DBInstanceIdentifier'], filtered_snapshots)
if latest is not None:
backup_age = datetime.now() - latest
if backup_age.total_seconds() >= (backup_interval * 60 * 60):
return True
else:
return False
elif latest is None:
return True
def paginate_api_call(client, api_call, objecttype, *args, **kwargs):
# Takes an RDS boto client and paginates through api_call calls and returns a list of objects of objecttype
response = {}
response[objecttype] = []
# Create a paginator
paginator = client.get_paginator(api_call)
# Create a PageIterator from the Paginator
page_iterator = paginator.paginate(**kwargs)
for page in page_iterator:
for item in page[objecttype]:
response[objecttype].append(item)
return response
def copy_local(snapshot_identifier, snapshot_object):
client = boto3.client('rds', region_name=_REGION)
print(_KMS_KEY_SOURCE_REGION)
tags = [{
'Key': 'CopiedBy',
'Value': 'Snapshot Tool for RDS'
}]
if snapshot_object['Encrypted']:
logger.info('Copying encrypted snapshot %s locally' % snapshot_identifier)
response = client.copy_db_snapshot(
SourceDBSnapshotIdentifier=snapshot_object['Arn'],
TargetDBSnapshotIdentifier=snapshot_identifier,
KmsKeyId=_KMS_KEY_SOURCE_REGION,
Tags=tags)
else:
logger.info('Copying snapshot %s locally' % snapshot_identifier)
response = client.copy_db_snapshot(
SourceDBSnapshotIdentifier=snapshot_object['Arn'],
TargetDBSnapshotIdentifier=snapshot_identifier,
Tags=tags)
return response
def copy_remote(snapshot_identifier, snapshot_object):
client = boto3.client('rds', region_name=_DESTINATION_REGION)
if snapshot_object['Encrypted']:
logger.info('Copying encrypted snapshot %s to remote region %s' % (snapshot_object['Arn'], _DESTINATION_REGION))
response = client.copy_db_snapshot(
SourceDBSnapshotIdentifier=snapshot_object['Arn'],
TargetDBSnapshotIdentifier=snapshot_identifier,
KmsKeyId=_KMS_KEY_DEST_REGION,
SourceRegion=_REGION,
CopyTags=True)
else:
logger.info('Copying snapshot %s to remote region %s' % (snapshot_object['Arn'], _DESTINATION_REGION))
response = client.copy_db_snapshot(
SourceDBSnapshotIdentifier=snapshot_object['Arn'],
TargetDBSnapshotIdentifier=snapshot_identifier,
SourceRegion=_REGION,
CopyTags=True)
return response