-
Notifications
You must be signed in to change notification settings - Fork 3
/
rds_logs_archiver.py
219 lines (157 loc) · 7.34 KB
/
rds_logs_archiver.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
from __future__ import print_function, unicode_literals
import argparse
import logging
import os
import sys
import boto3
import botocore.awsrequest
from botocore.exceptions import ClientError
MAX_LOG_FILES_PER_EXECUTION = 10
LAST_WRITTEN_KEY = 'last_written.txt'
logger = logging.getLogger()
def archive_rds_logs_lambda_handler(event, context):
# Lambda sets up logging, but the default level does not include INFO
logger.setLevel(logging.INFO)
db_identifier = os.environ['db_identifier']
if not db_identifier:
raise ValueError('the environment variable db_identifier was not set')
bucket_name = os.environ['bucket_name']
if not bucket_name:
raise ValueError('the environment variable bucket_name was not set')
bucket_prefix = os.environ.get('bucket_prefix', '')
more_logs = archive_rds_logs(db_identifier, bucket_name, bucket_prefix)
if more_logs:
reinvoke_self(context)
def archive_rds_logs(db_identifier, bucket_name, bucket_prefix):
logger.info('Archiving RDS logs for "%s" to s3://%s/%s', db_identifier, bucket_name, bucket_prefix)
s3 = boto3.client('s3', region_name='eu-west-1')
rds = boto3.client('rds', region_name='eu-west-1')
last_written_in_bucket = get_last_written_in_bucket(s3, bucket_name, bucket_prefix)
logger.info('Last written log in bucket - %s', last_written_in_bucket)
log_metadata_dicts, more_logs = get_rds_log_metadata_dicts(rds, db_identifier, last_written_in_bucket)
for log_metadata_dict in log_metadata_dicts:
log_filename = log_metadata_dict["filename"]
log_size_bytes = log_metadata_dict["size_bytes"]
log_last_written = log_metadata_dict["last_written"]
logger.info('Archiving %s (%d bytes) to S3', log_filename, log_size_bytes)
log_size_bytes_archived = archive_rds_log_file(
rds, db_identifier, log_filename, log_size_bytes, s3, bucket_name, bucket_prefix,
)
set_last_written_in_bucket(s3, bucket_name, bucket_prefix, log_last_written)
logger.info('Archived %s (%d bytes)', log_filename, log_size_bytes_archived)
if more_logs:
logger.info('there are more logs available to archive - call this again')
return more_logs
def get_last_written_in_bucket(s3, bucket_name, bucket_prefix):
key = get_last_written_bucket_key(bucket_prefix)
try:
response = s3.get_object(Bucket=bucket_name, Key=key)
except ClientError as e:
error = e.response.get('Error', {})
logger.info(error)
if error.get('Code') == 'NoSuchKey':
return None
raise
timestamp = response['Body'].read().strip()
timestamp = int(timestamp)
return timestamp
def set_last_written_in_bucket(s3, bucket_name, bucket_prefix, last_written):
key = get_last_written_bucket_key(bucket_prefix)
s3.put_object(Bucket=bucket_name, Key=key, Body=str(last_written))
def get_last_written_bucket_key(bucket_prefix):
key_parts = []
if bucket_prefix:
key_parts.append(bucket_prefix)
key_parts.append(LAST_WRITTEN_KEY)
key = '/'.join(key_parts)
return key
def get_rds_log_metadata_dicts(rds, db_identifier, last_written):
"""
This will return logs inclusive of those that match the last_written timestamp. Therefore on each execution, we will
re-retrieve the log that was last uploaded in the last execution, even if nothing has changed.
"""
logger.info(
'Retrieving log filenames, from last written %s, up to %d logs', last_written, MAX_LOG_FILES_PER_EXECUTION,
)
# we can't use max records to return only the records we want because the API returns the latest logs first, where
# we want the oldest logs first, so later executions can process the newer logs. RDS only stores up to 7 days'
# worth of logs, so this shouldn't be a big problem
all_log_metadata_dicts = []
marker = None
while True:
args = dict(DBInstanceIdentifier=db_identifier, FileLastWritten=0)
if last_written is not None:
args['FileLastWritten'] = last_written
if marker is not None:
args['Marker'] = marker
response_data = rds.describe_db_log_files(**args)
log_metadata_dicts, marker = parse_log_metadata_dicts_from_response(response_data)
all_log_metadata_dicts.extend(log_metadata_dicts)
if marker is None:
break
all_log_metadata_dicts.sort(key=lambda x: x["last_written"])
more_logs = len(all_log_metadata_dicts) > MAX_LOG_FILES_PER_EXECUTION
log_metadata_dicts_within_max = all_log_metadata_dicts[:MAX_LOG_FILES_PER_EXECUTION]
logger.info('Found %d log files, more_logs = %s', len(log_metadata_dicts_within_max), more_logs)
return log_metadata_dicts_within_max, more_logs
def parse_log_metadata_dicts_from_response(response_data):
file_dicts = response_data['DescribeDBLogFiles']
log_metadata_dicts = [
dict(filename=file_dict['LogFileName'], size_bytes=file_dict['Size'], last_written=file_dict['LastWritten'])
for file_dict in file_dicts
]
marker = response_data.get('Marker')
return log_metadata_dicts, marker
def archive_rds_log_file(rds, db_identifier, log_filename, log_size_bytes, s3, bucket_name, bucket_prefix):
path = '/v13/downloadCompleteLogFile/{}/{}'.format(db_identifier, log_filename)
url = '{}{}'.format(rds.meta.endpoint_url, path)
request = botocore.awsrequest.AWSRequest(
method='GET',
url=url,
data=None,
headers={'User-Agent': rds.meta.config.user_agent},
)
request.context.update({'client_config': rds.meta.config})
rds.meta.events.emit('request-created.rds', request=request)
response = rds._endpoint.http_session.send(request.prepare(), stream=True)
key = log_filename
if bucket_prefix is not None:
key = '{}/{}'.format(bucket_prefix, key)
bytes_read_count_accumulator = Accumulator()
try:
s3.upload_fileobj(
response.raw,
Bucket=bucket_name,
Key=key,
Callback=bytes_read_count_accumulator.add,
)
finally:
response.raw.close()
bytes_read_count = bytes_read_count_accumulator.total
# the logs may have further entries between the calls, so we just want to make sure we're getting at least the
# number of bytes promised in the Describe call
if bytes_read_count < log_size_bytes:
raise Exception('Expected at least {} bytes, got {} bytes instead'.format(log_size_bytes, bytes_read_count))
return bytes_read_count
class Accumulator(object):
def __init__(self, start=0):
self.total = start
def add(self, value):
self.total += value
def reinvoke_self(context):
lambda_client = boto3.client('lambda')
lambda_client.invoke(
FunctionName=context.function_name,
InvocationType='Event',
)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('db_identifier', help='identifier of database in RDS')
parser.add_argument('bucket_name', help='name of bucket to archive logs into')
parser.add_argument('bucket_prefix', help='prefix to use for log files in bucket')
args = parser.parse_args()
archive_rds_logs(args.db_identifier, args.bucket_name, args.bucket_prefix)
return 0
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format="%(asctime)s (%(levelname)s) %(message)s")
sys.exit(main())