├── LICENSE ├── README.md ├── assets ├── cloudwatchrule.png ├── crule2.png ├── ctarget.png ├── dynamodb1.png ├── gcode.png ├── glue_job1.png ├── glueconfig.png ├── glueschedule.png └── rdslog.drawio.png └── connectors └── mysql.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # serverless-log-connector 2 | 3 | ## 架构图 4 | ![架构图](/assets/rdslog.drawio.png) 5 | 6 | ## 部署方法 7 | ### 手动部署 8 | 9 | #### 配置任务 10 | 1. 进入glue服务,创建一个 glue python script job 11 | ![glue job](/assets/glue_job1.png) 12 | 2. 将connectors文件夹下的mysql.py 的python code 复制脚本编辑器。注意修改注释部分 13 | ![glue job](/assets/gcode.png) 14 | 3. 配置 glue job相关的参数,如执行role, 重试次数改为 0,超时时间根据要同步的数据量估计,1GB的数据大概要3分钟 15 | ![glue job](/assets/glueconfig.png) 16 | 17 | 4. 配置执行角色,角色策略参考下图及代码 18 | ![glue role](/assets/rolerule.png) 19 | ```json 20 | { 21 | "Version": "2012-10-17", 22 | "Statement": [ 23 | { 24 | "Sid": "VisualEditor0", 25 | "Effect": "Allow", 26 | "Action": [ 27 | "s3:PutObject", 28 | "dynamodb:PutItem", 29 | "rds:DownloadDBLogFilePortion", 30 | "dynamodb:GetItem", 31 | "rds:DownloadCompleteDBLogFile", 32 | "rds:DescribeDBLogFiles", 33 | "s3:PutObjectTagging" 34 | ], 35 | "Resource": [ 36 | "arn:aws-cn:rds:cn-northwest-1:xxxxxxx:db:*", 37 | "arn:aws-cn:dynamodb:cn-northwest-1:xxxxxx:table/db_log_to_s3", 38 | "arn:aws-cn:s3:::tx-audit-log2/*" 39 | ] 40 | } 41 | ] 42 | } 43 | ``` 44 | 注意修改上面的账号信息,dynamodb 表信息,s3 桶信息 45 | 4. 在 glue schedules页面配置执行计划 (第一次同步,由于数据量较大,建议手动触发, 等第一次同步成功以后,后续的增量同步,可以使用scheduler触发执行) 46 | ![glue job](/assets/glueschedule.png) 47 | 5. 配置dynamodb, 如图新建一个dynamodb table, 并按截图配置 48 | ![dynamodb](/assets/dynamodb1.png) 49 | 50 | #### 配置监控 51 | 1. 进入sns控制台 创建 sns topic 52 | 2. 在sns 控制台,右边导航栏创建订阅,配置相关的收件人信息 53 | 3. 在cloudwatch 创建rule, event patten 如下,将 rds_to_s3 替换成你的glue job name 54 | ![cloudwatchrule](/assets/cloudwatchrule.png) 55 | 56 | 要把 rds_to_s3 改成你的glue job的名称 57 | ``` 58 | { 59 | "source": ["aws.glue"], 60 | "detail-type": ["Glue Job State Change"], 61 | "detail": { 62 | "jobName": ["rds_to_s3"], 63 | "state": ["FAILED"] 64 | } 65 | } 66 | 67 | ``` 68 | 4. 配置cloudwatch rule 目标。选择前面创建的主题作为规则目标 69 | ![cloudwatchrule](/assets/ctarget.png) 70 | 71 | ## 注意 72 | 第一次跑,要评估一下目前审计日志的大小,如果使用glue 跑,超时时间大一些,或者不同的job跑不同的db 73 | 74 | 75 | -------------------------------------------------------------------------------- /assets/cloudwatchrule.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nwcd-samples/serverless-log-connector/e9f9785a32b14ad6a566fdbb42797c3e00eefc66/assets/cloudwatchrule.png -------------------------------------------------------------------------------- /assets/crule2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nwcd-samples/serverless-log-connector/e9f9785a32b14ad6a566fdbb42797c3e00eefc66/assets/crule2.png -------------------------------------------------------------------------------- /assets/ctarget.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nwcd-samples/serverless-log-connector/e9f9785a32b14ad6a566fdbb42797c3e00eefc66/assets/ctarget.png -------------------------------------------------------------------------------- /assets/dynamodb1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nwcd-samples/serverless-log-connector/e9f9785a32b14ad6a566fdbb42797c3e00eefc66/assets/dynamodb1.png -------------------------------------------------------------------------------- /assets/gcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nwcd-samples/serverless-log-connector/e9f9785a32b14ad6a566fdbb42797c3e00eefc66/assets/gcode.png -------------------------------------------------------------------------------- /assets/glue_job1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nwcd-samples/serverless-log-connector/e9f9785a32b14ad6a566fdbb42797c3e00eefc66/assets/glue_job1.png -------------------------------------------------------------------------------- /assets/glueconfig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nwcd-samples/serverless-log-connector/e9f9785a32b14ad6a566fdbb42797c3e00eefc66/assets/glueconfig.png -------------------------------------------------------------------------------- /assets/glueschedule.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nwcd-samples/serverless-log-connector/e9f9785a32b14ad6a566fdbb42797c3e00eefc66/assets/glueschedule.png -------------------------------------------------------------------------------- /assets/rdslog.drawio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nwcd-samples/serverless-log-connector/e9f9785a32b14ad6a566fdbb42797c3e00eefc66/assets/rdslog.drawio.png -------------------------------------------------------------------------------- /connectors/mysql.py: -------------------------------------------------------------------------------- 1 | ###################################### 2 | # refer to 3 | # https://github.com/ccampo133/rds-logs-to-s3 4 | # https://github.com/awslabs/rds-support-tools/tree/master/database-logs/move-rds-logs-to-s3 5 | # why do i make some change? 6 | # 1.incremental appending 7 | # 2.support big size file 8 | # 3.add s3 prefix to easy to query by athena 9 | # 4.gzip 10 | ###################################### 11 | from __future__ import print_function 12 | import boto3 13 | import botocore 14 | from botocore.exceptions import ClientError 15 | from datetime import datetime 16 | import io 17 | import gzip 18 | 19 | 20 | # change it to your region code 21 | region = "cn-northwest-1" 22 | 23 | 24 | # initialize 25 | rds_client = boto3.client('rds', region_name=region) 26 | s3client = boto3.client('s3', region_name=region) 27 | # used to save status info 28 | dynamodb = boto3.client('dynamodb', region_name=region) 29 | 30 | 31 | def copy_logs_from_rds_to_s3(rds_instance_name: str, 32 | tag:str, 33 | s3_bucket_name: str, 34 | log_name_prefix: str): 35 | last_writen_key = rds_instance_name + "_" + "last_writen" 36 | 37 | last_written_time = 0 38 | last_written_this_run = 0 39 | backup_start_time = datetime.now() 40 | 41 | # check if the S3 bucket exists and is accessible 42 | try: 43 | s3client.head_bucket(Bucket=s3_bucket_name) 44 | except botocore.exceptions.ClientError as e: 45 | error_code = int(e.response['ResponseMetadata']['HTTPStatusCode']) 46 | if error_code == 404: 47 | print("Error: Bucket name provided not found") 48 | raise e 49 | else: 50 | print("Error: Unable to access bucket name, error: " + e.response['Error']['Message']) 51 | raise e 52 | 53 | # get the config file, if the config isn't present this is the first run 54 | try: 55 | # query last_written_time 56 | wr = dynamodb.get_item(TableName='db_log_to_s3', Key={'db_log_name': {'S': last_writen_key}}) 57 | if 'Item' in wr: 58 | last_written_time = int(wr['Item']['mark']['S']) 59 | 60 | print("Found marker from last log download, retrieving log files with lastWritten time after %s" % str( 61 | last_written_time)) 62 | except botocore.exceptions.ClientError as e: 63 | print("Failed to access dynamodb table db_log_to_s3: ", e) 64 | raise e 65 | 66 | # copy the logs in batches to s3 67 | copied_file_count = 0 68 | log_marker = "" 69 | more_logs_remaining = True 70 | while more_logs_remaining: 71 | db_logs = rds_client.describe_db_log_files(DBInstanceIdentifier=rds_instance_name, 72 | FilenameContains=log_name_prefix, 73 | FileLastWritten=last_written_time, Marker=log_marker) 74 | if 'Marker' in db_logs and db_logs['Marker'] != "": 75 | log_marker = db_logs['Marker'] 76 | else: 77 | more_logs_remaining = False 78 | 79 | # copy the logs in this batch 80 | for dbLog in db_logs['DescribeDBLogFiles']: 81 | print("FileNumber: ", copied_file_count + 1) 82 | print("Downloading log file: %s found and with LastWritten value of: %s " % ( 83 | dbLog['LogFileName'], dbLog['LastWritten'])) 84 | if int(dbLog['LastWritten']) > last_written_this_run: 85 | last_written_this_run = int(dbLog['LastWritten']) 86 | 87 | log_file_key = f"{rds_instance_name}-{dbLog['LogFileName']}" 88 | 89 | # get last mark 90 | lr = dynamodb.get_item(TableName='db_log_to_s3', Key={'db_log_name': {'S': log_file_key}}) 91 | if 'Item' in lr: 92 | marker = lr['Item']['mark']['S'] 93 | else: 94 | marker = '0' 95 | 96 | # download the log file 97 | 98 | try: 99 | part = 0 100 | while True: 101 | log_file = rds_client.download_db_log_file_portion(DBInstanceIdentifier=rds_instance_name, 102 | LogFileName=dbLog['LogFileName'], Marker=marker) 103 | print(f"download log file {dbLog['LogFileName']}") 104 | 105 | log_file_data = log_file['LogFileData'] 106 | 107 | log_file_data_cleaned = log_file_data.encode('utf-8') 108 | my_gzipped_bytes = gzip.compress(log_file_data_cleaned) 109 | content = io.BytesIO(my_gzipped_bytes) 110 | # upload the log file to S3 111 | 112 | time_prefix = backup_start_time.strftime('%Y-%m-%dT%H:%M') 113 | log_name = dbLog['LogFileName'].replace("/", "_") 114 | o_name = f"tag={tag}/db={rds_instance_name}/ingestion_time={time_prefix}/log={log_name}/{part}.log.gz" 115 | 116 | s3client.put_object(Bucket=s3_bucket_name, Key=o_name, Body=content) 117 | print(f"Uploaded {dbLog['LogFileName']}:{part} to S3 {s3_bucket_name}") 118 | part += 1 119 | marker = log_file['Marker'] 120 | if not log_file['AdditionalDataPending']: 121 | break 122 | except Exception as e: 123 | print("File download failed: ", e) 124 | continue 125 | finally: 126 | dynamodb.put_item(TableName='db_log_to_s3', Item={ 127 | 'db_log_name': {'S': log_file_key}, 128 | 'mark': {'S': marker} 129 | }) 130 | 131 | copied_file_count += 1 132 | print("Uploaded log file %s to S3 bucket %s" % (dbLog['LogFileName'], s3_bucket_name)) 133 | 134 | print("Copied ", copied_file_count, "file(s) to s3") 135 | 136 | # Update the last written time in the config 137 | if last_written_this_run > 0: 138 | try: 139 | dynamodb.put_item(TableName='db_log_to_s3', Item={ 140 | 'db_log_name': {'S': last_writen_key}, 141 | 'mark': {'S': str(last_written_this_run)} 142 | }) 143 | except botocore.exceptions.ClientError as e: 144 | print( 145 | f"Failed to set last_written_this_run: {last_written_this_run}, error {e.response['Error']['Message']}") 146 | raise e 147 | 148 | print("Log file export complete") 149 | 150 | if __name__ == '__main__': 151 | # change it to your bucket 152 | target_s3_bucket = "tx-audit-log2" 153 | # log file prefix 154 | log_prefix = "audit" 155 | # change it to your db identifier and db tag 156 | dbinfo = [ 157 | {"name":"demo", "tag":"prod"}, 158 | {"name":"stage", "tag":"test"} 159 | ] 160 | for info in dbinfo: 161 | db = info['name'] 162 | tag = info['tag'] 163 | print(f"process {db} ....") 164 | copy_logs_from_rds_to_s3(db, tag, target_s3_bucket, log_prefix) 165 | print(f"success to sync log file for {db} ....") 166 | --------------------------------------------------------------------------------