├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.rst ├── assets ├── graph-overview.png └── graph-overview.xml ├── requirements.txt ├── setup.py └── sqs_s3_logger ├── __init__.py ├── environment.py ├── lambda_function.py ├── lambda_function_builder.py ├── main.py ├── tests.py └── version.py /.gitignore: -------------------------------------------------------------------------------- 1 | venv 2 | .idea 3 | *.pyc 4 | *.egg-info 5 | *.egg 6 | *.DS_Store 7 | dist 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | include LICENSE 3 | include requirements.txt -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | sqs-s3-logger 2 | ============= 3 | 4 | A library to persist messages on S3 using serverless architecture. It is 5 | mainly targeted at cheaply archiving low-volume, sporadic events from 6 | applications without a need to spin additional infrastructure. 7 | 8 | |Overall idea| 9 | 10 | What it’s not 11 | ------------- 12 | 13 | Not a replacement for general logging systems or libraries. Provides no 14 | filtering or aggregation. 15 | 16 | AWS Alternatives 17 | ---------------- 18 | 19 | - `Cloudwach Logs`_ 20 | - `Kinesis Firehose`_ 21 | 22 | Usage 23 | ===== 24 | 25 | Configure ``boto3``\ ’s credentials as per: 26 | http://boto3.readthedocs.io/en/latest/guide/quickstart.html#configuration 27 | 28 | Make sure you setup: 29 | 30 | - ``AWS_ACCESS_KEY_ID`` 31 | - ``AWS_SECRET_ACCESS_KEY`` 32 | - ``AWS_DEFAULT_REGION`` (optionally) 33 | 34 | Take a look at ``main.py``. 35 | 36 | For help: ``python3 main.py -h`` 37 | 38 | For example (backup at midnight each Saturday from ``app-logs`` queue to 39 | ``app-logs-archive`` bucket): 40 | 41 | :: 42 | 43 | sqs-s3-logger create -b app-logs-archive -q app-logs -f app-logs-backup -s 'cron(0 0 ? * SAT *)' 44 | 45 | Sending messages to a queue 46 | --------------------------- 47 | 48 | Ideally you should use another AWS IAM user with permissions restricted 49 | to getting SQS queues and writing messages. 50 | 51 | :: 52 | 53 | import boto3 54 | sqs = boto3.resource('sqs') 55 | queue = sqs.get_queue_by_name(QueueName='') 56 | queue.send_message(MessageBody='') 57 | 58 | Limitations 59 | =========== 60 | 61 | - Maximum SQS message size is limited to 256 KB 62 | - There could be no more than 120,000 messages in a queue at a time. 63 | - SQS messages cannot persist for longer than 14 days. 64 | - Lambda environment has up to 512MB of ephemeral disk capacity. 65 | - By default it does not guarantee correct time-based ordering 66 | 67 | You may need to adjust your CRON settings depending on your volume. 68 | 69 | Testing 70 | ======= 71 | 72 | ``python3 setup.py test`` 73 | 74 | These will use your AWS account to instantiate a temporary integration 75 | environment. 76 | 77 | .. |Overall idea| image:: assets/graph-overview.png?raw=true : 78 | .. _Kinesis Firehose: https://aws.amazon.com/kinesis/firehose/ 79 | .. _Cloudwach logs: https://aws.amazon.com/cloudwatch/details/#log-monitoring 80 | -------------------------------------------------------------------------------- /assets/graph-overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ellimilial/sqs-s3-logger/34d1b3f9e518f3772d36c78dff1a4506fbc50382/assets/graph-overview.png -------------------------------------------------------------------------------- /assets/graph-overview.xml: -------------------------------------------------------------------------------- 1 | 1ZZNj9owEIZ/DVJ7WJQPAuFI2W17aKWtqNTuCRnbJNY6ceQ4BPrrO46dkMSsygFalQPYr2f88Yxn8CRcZ8dPEhXpV0EonwQeOU7Cx0kQRPM5fGvhZIRZsDRCIhkxkn8WNuwXtaJn1YoRWg4MlRBcsWIoYpHnFKuBhqQU9dBsL/hw1QIl1BE2GHFX/cGISo0aR95Z/0xZkrYr+54d2SH8mkhR5Xa9SRDum48ZzlA7l7UvU0RE3ZPCp0m4lkIo08qOa8o12hab8fv4xmi3b0lzdY1DYBwOiFf26JtvG7s1dWpxlEqK144EbPJDqjIOTR+acIRC22XHRN+F6Z6LGqdIqilhEoKzJUghsKtTpuimQFgb12AKml2dSkWPb57A77jAdaMio0qewKR1WFiU9qr5S9uvz4HrwpP2gja3GrJ3JemmPvOChkV2GV/o4gtvRS+r4L4/EIGrrEFxL4Az788A4/g+/CKH3xeU7QhyGA6JmZTxoENQmVJiO4izJIc2hpNTCYLmwiCrV3YgY4ToGR3qpmYE5ldPq1l407luakwzPX0uFE7tUjfgHixH3OPouou7uAH42AG/Kopb3VyMJLnffQ3H2P5ivi8uYSv/D27+P6yTS4fbmouK1EhnVDDnurwRdoBmopvfJUsSyGA7ArP3Bi/Yv4N/zPz91eattJNjZex6o0pOZUK3Qm5LJWTz8rhXjINlOAyy7wZ5Gd0nxr7vBNkBSHOyMiX2EXNUlgwPGcIx5emnrbFN56UpxFHbfaaSwc50de/VYUqc59yIGOxCVBLTQRorBHFRvYeQy7XHLbqQG60mKUeKHYabuATTrvAsGGyvC9tDNMzNMBzFw2zeevWfc+1E1jGIR47miI5jE8vumJfCC93zK9SYn1/64dNv -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.4.7 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup 3 | from pip.req import parse_requirements 4 | from sqs_s3_logger import __version__ 5 | 6 | 7 | install_reqs = parse_requirements('requirements.txt', session='setup') 8 | reqs = [str(ir.req) for ir in install_reqs] 9 | curr_dir = os.path.abspath(os.path.dirname(__file__)) 10 | with open(os.path.join(curr_dir, 'README.rst'), encoding='utf-8') as f: 11 | long_description = f.read() 12 | 13 | setup( 14 | name='sqs-s3-logger', 15 | version=__version__, 16 | install_requires=reqs, 17 | tests_require=reqs, 18 | packages=['sqs_s3_logger'], 19 | entry_points={ 20 | 'console_scripts': ['sqs-s3-logger=sqs_s3_logger.main:main'], 21 | }, 22 | url='https://github.com/ellimilial/sqs-s3-logger', 23 | author='Mateusz Kaczyński', 24 | author_email='contact@ellimilial.com', 25 | description='Automated serverless logging to S3 via SQS.', 26 | long_description=long_description, 27 | keywords='logging sqs s3 archive storage' 28 | ) 29 | -------------------------------------------------------------------------------- /sqs_s3_logger/__init__.py: -------------------------------------------------------------------------------- 1 | from .version import __version__ 2 | -------------------------------------------------------------------------------- /sqs_s3_logger/environment.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import datetime 3 | from time import sleep 4 | import boto3 as boto 5 | from botocore.exceptions import ClientError 6 | 7 | 8 | LOGGER = logging.getLogger(__name__) 9 | 10 | 11 | class Environment(object): 12 | TWO_WEEKS = 1209600 13 | 14 | def __init__(self, queue_name, bucket_name, function_name, cron_schedule='rate(1 day)'): 15 | self._queue_name = queue_name 16 | self._bucket_name = bucket_name 17 | self._function_name = function_name 18 | self._cron_schedule = cron_schedule, 19 | self._s3 = boto.resource('s3') 20 | self._sqs = boto.resource('sqs') 21 | self._lambda_client = boto.client('lambda') 22 | self._iam_client = boto.client('iam') 23 | self._queue = None 24 | self._bucket = None 25 | 26 | def _create_queue_with_pushback(self, name, att_dict): 27 | """ 28 | If a SQS queue is deleted recently (for example during testing), we have to wait 60 secs before recreating. 29 | """ 30 | try: 31 | q = self._sqs.create_queue(QueueName=name, Attributes=att_dict) 32 | except ClientError as e: 33 | if e.response['Error']['Code'] == 'AWS.SimpleQueueService.QueueDeletedRecently': 34 | sleep(60) 35 | q = self._sqs.create_queue(QueueName=name, Attributes=att_dict) 36 | else: 37 | raise e 38 | return q 39 | 40 | def get_create_queue(self): 41 | if not self._queue: 42 | try: 43 | q = self._sqs.get_queue_by_name(QueueName=self._queue_name) 44 | except ClientError as e: 45 | if e.response['Error']['Code'] == 'AWS.SimpleQueueService.NonExistentQueue': 46 | q = None 47 | else: 48 | raise e 49 | if not q: 50 | LOGGER.info('Creating queue {}'.format(self._queue_name)) 51 | q = self._create_queue_with_pushback( 52 | self._queue_name, 53 | {'MessageRetentionPeriod': str(self.TWO_WEEKS)} 54 | ) 55 | 56 | self._queue = q 57 | return self._queue 58 | 59 | def _bucket_exists(self, name): 60 | try: 61 | self._s3.meta.client.head_bucket(Bucket=name) 62 | return True 63 | except ClientError as e: 64 | if e.response['Error']['Code'] == '404': 65 | return False 66 | else: 67 | raise e 68 | 69 | def get_create_bucket(self): 70 | if not self._bucket: 71 | b = self._s3.Bucket(self._bucket_name) 72 | if not self._bucket_exists(self._bucket_name): 73 | LOGGER.info('Creating bucket {}'.format(self._bucket_name)) 74 | region_name = boto.session.Session().region_name 75 | b = self._s3.create_bucket( 76 | Bucket=self._bucket_name, 77 | CreateBucketConfiguration={ 78 | 'LocationConstraint': region_name 79 | } 80 | ) 81 | self._bucket = b 82 | return self._bucket 83 | 84 | def _delete_function_if_exists(self, function_name): 85 | try: 86 | self._lambda_client.get_function(FunctionName=self._function_name) 87 | logging.info('Deleting old version of the function {}'.format(self._function_name)) 88 | self._lambda_client.delete_function(FunctionName=self._function_name) 89 | except ClientError as e: 90 | if e.response['Error']['Code'] == 'ResourceNotFoundException': 91 | pass 92 | else: 93 | raise e 94 | 95 | def update_function(self, role_arn, filepath, memory_size=128, timeout=300, schedule=None): 96 | env_variables = { 97 | 'QUEUE_NAME': self._queue_name, 98 | 'BUCKET_NAME': self._bucket_name 99 | } 100 | self._delete_function_if_exists(function_name=self._function_name) 101 | 102 | uploaded_package_name = '_function/{}{}.zip'.format(self._function_name, datetime.datetime.now()) 103 | self.get_create_bucket().upload_file(filepath, uploaded_package_name) 104 | res = self._lambda_client.create_function( 105 | FunctionName=self._function_name, 106 | Runtime='python3.6', 107 | Role=role_arn, 108 | Handler='lambda_function.handler', 109 | Code={ 110 | 'S3Bucket': self._bucket_name, 111 | 'S3Key': uploaded_package_name, 112 | }, 113 | MemorySize=memory_size, 114 | Timeout=timeout, 115 | Environment={ 116 | 'Variables': env_variables 117 | } 118 | ) 119 | 120 | self.get_create_queue() 121 | # TODO This doesn't seem to be deleting the temp function. 122 | self.get_create_bucket().delete_objects(Delete={'Objects': [{'Key': uploaded_package_name}]}) 123 | if schedule: 124 | self._schedule_function(res['FunctionArn'], schedule) 125 | 126 | return res 127 | 128 | def _schedule_function(self, function_arn, schedule): 129 | LOGGER.info('Scheduling function {} to {}'.format(self._function_name, schedule)) 130 | events_client = boto.client('events') 131 | trigger_name = '{}-trigger'.format(self._function_name) 132 | 133 | rule_response = events_client.put_rule( 134 | Name=trigger_name, 135 | ScheduleExpression=schedule, 136 | State='ENABLED', 137 | ) 138 | self._lambda_client.add_permission( 139 | FunctionName=self._function_name, 140 | StatementId="{0}-Event".format(trigger_name), 141 | Action='lambda:InvokeFunction', 142 | Principal='events.amazonaws.com', 143 | SourceArn=rule_response['RuleArn'], 144 | ) 145 | events_client.put_targets( 146 | Rule=trigger_name, 147 | Targets=[{'Id': "1", 'Arn': function_arn}] 148 | ) 149 | 150 | def update_role_policy(self, role_name, policy_config): 151 | assume_role_policy = '''{ 152 | "Version": "2012-10-17", 153 | "Statement": [ 154 | { 155 | "Effect": "Allow", 156 | "Principal": { 157 | "Service": "lambda.amazonaws.com" 158 | }, 159 | "Action": "sts:AssumeRole" 160 | } 161 | ] 162 | } 163 | ''' 164 | LOGGER.info('Updating role policy {}'.format(role_name)) 165 | try: 166 | self._iam_client.create_role(RoleName=role_name, AssumeRolePolicyDocument=assume_role_policy) 167 | except ClientError as e: 168 | if e.response['Error']['Code'] == 'EntityAlreadyExists': 169 | pass 170 | else: 171 | raise e 172 | self._iam_client.put_role_policy( 173 | PolicyDocument=policy_config, 174 | PolicyName=role_name+'Policy', 175 | RoleName=role_name 176 | ) 177 | return self._iam_client.get_role(RoleName=role_name)['Role']['Arn'] 178 | 179 | def destroy(self, delete_function=False, delete_s3_bucket=False): 180 | LOGGER.info('Deleting queue {}'.format(self._queue_name)) 181 | self.get_create_queue().delete() 182 | if delete_function: 183 | LOGGER.info('Deleting function {}'.format(self._function_name)) 184 | self._lambda_client.delete_function(FunctionName=self._function_name) 185 | if delete_s3_bucket: 186 | LOGGER.info('Deleting bucket {}'.format(self._bucket_name)) 187 | b = self.get_create_bucket() 188 | for k in b.objects.all(): 189 | k.delete() 190 | b.delete() 191 | -------------------------------------------------------------------------------- /sqs_s3_logger/lambda_function.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | import boto3 as boto 4 | import datetime 5 | 6 | LOGGER = logging.getLogger() 7 | LOGGER.setLevel(logging.INFO) 8 | 9 | sqs = boto.resource('sqs') 10 | s3 = boto.resource('s3') 11 | 12 | 13 | def handler(event, context): 14 | """ 15 | Reads contents of a SQS queue messages' body and uploads them as a timestamped file to a S3 bucket. 16 | Requires QUEUE_NAME, BUCKET_NAME env variables in addition to boto3 credentials. 17 | """ 18 | LOGGER.info('event: {}\ncontext: {}'.format(event, context)) 19 | 20 | q_name = os.environ['QUEUE_NAME'] 21 | b_name = os.environ['BUCKET_NAME'] 22 | temp_filepath = os.environ.get('TEMP_FILE_PATH', '/tmp/logs.txt') 23 | 24 | LOGGER.info('Storing messages from queue {} to bucket {}'.format(q_name, b_name)) 25 | q = sqs.get_queue_by_name(QueueName=q_name) 26 | s3.meta.client.head_bucket(Bucket=b_name) # Check that the bucket exists. 27 | b = s3.Bucket(b_name) 28 | msgs = read_queue(q) 29 | dump_messages_to_file(msgs, temp_filepath) 30 | b.upload_file(temp_filepath, '{}.txt'.format(datetime.datetime.now())) 31 | 32 | 33 | def read_queue(queue): 34 | messages = queue.receive_messages( 35 | MaxNumberOfMessages=10, WaitTimeSeconds=1) 36 | while len(messages) > 0: 37 | for message in messages: 38 | yield message 39 | # TODO instead of deleting those, keep the handles, remove in batch once they're on S3 40 | message.delete() 41 | messages = queue.receive_messages( 42 | MaxNumberOfMessages=10, WaitTimeSeconds=1) 43 | 44 | 45 | def dump_messages_to_file(msgs, file): 46 | with open(file, 'w') as f: 47 | for message in msgs: 48 | f.write(message.body + '\n') 49 | -------------------------------------------------------------------------------- /sqs_s3_logger/lambda_function_builder.py: -------------------------------------------------------------------------------- 1 | import os 2 | import zipfile 3 | import pip 4 | import shutil 5 | import tempfile 6 | import datetime 7 | import logging 8 | 9 | LOGGER = logging.getLogger(__name__) 10 | 11 | module_path = os.path.dirname(os.path.realpath(__file__)) 12 | 13 | REQUIRED_PACKAGES = [] 14 | REQUIRED_FILES = ['lambda_function.py'] 15 | ROLE_NAME = 'LambdaS3WriteSQSRead' 16 | ROLE_POLICY = '''{ 17 | "Version": "2012-10-17", 18 | "Statement": [ 19 | { 20 | "Effect": "Allow", 21 | "Action": [ 22 | "logs:CreateLogGroup", 23 | "logs:CreateLogStream", 24 | "logs:PutLogEvents" 25 | ], 26 | "Resource": "*" 27 | }, 28 | { 29 | "Effect": "Allow", 30 | "Action": [ 31 | "sqs:DeleteMessage", 32 | "sqs:GetQueueUrl", 33 | "sqs:ReceiveMessage" 34 | ], 35 | "Resource": "*" 36 | }, 37 | { 38 | "Effect": "Allow", 39 | "Action": [ 40 | "s3:ListBucket", 41 | "s3:PutObject" 42 | ], 43 | "Resource": "*" 44 | } 45 | ] 46 | } 47 | ''' 48 | 49 | 50 | def build_package(): 51 | build_dir = tempfile.mkdtemp(prefix='lambda_package_') 52 | install_packages(build_dir, REQUIRED_PACKAGES) 53 | for f in REQUIRED_FILES: 54 | shutil.copyfile( 55 | src=os.path.join(module_path, f), 56 | dst=os.path.join(build_dir, f) 57 | ) 58 | 59 | out_file = os.path.join( 60 | tempfile.mkdtemp(prefix='lambda_package_built'), 61 | 'sqs_s3_logger_lambda_{}.zip'.format(datetime.datetime.now().isoformat()) 62 | ) 63 | LOGGER.info('Creating a function package file at {}'.format(out_file)) 64 | 65 | archive(build_dir, out_file) 66 | return out_file 67 | 68 | 69 | def install_packages(dest, packages): 70 | for p in packages: 71 | pip.main(['install', '-t', dest, p]) 72 | 73 | 74 | def archive(src_dir, output_file): 75 | with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as f: 76 | src_dir_len = len(src_dir) 77 | for root, _, files in os.walk(src_dir): 78 | for file in files: 79 | fn = os.path.join(root, file) 80 | f.write(fn, fn[src_dir_len+1:]) 81 | 82 | if __name__ == '__main__': 83 | build_package() 84 | -------------------------------------------------------------------------------- /sqs_s3_logger/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import argparse 4 | from sqs_s3_logger.environment import Environment 5 | from sqs_s3_logger.lambda_function_builder import build_package, ROLE_NAME, ROLE_POLICY 6 | 7 | 8 | def get_environment(args): 9 | f_name = args.function if args.function is not None else\ 10 | '{}-to-{}'.format(args.queue, args.bucket) 11 | return Environment( 12 | queue_name=args.queue, 13 | bucket_name=args.bucket, 14 | function_name=f_name 15 | ) 16 | 17 | 18 | def create(args): 19 | env = get_environment(args) 20 | package_file = build_package() 21 | role_arn = env.update_role_policy(ROLE_NAME, ROLE_POLICY) 22 | env.update_function(role_arn, package_file, schedule=args.schedule) 23 | 24 | 25 | def purge(args): 26 | env = get_environment(args) 27 | env.destroy(delete_function=True) 28 | 29 | 30 | def main(): 31 | parser = argparse.ArgumentParser() 32 | parser.add_argument('command', nargs='?', default='create', 33 | help='create(default) / purge'), 34 | parser.add_argument('-b', '--bucket', required=True, 35 | help='Name of the bucket to drop logs to') 36 | parser.add_argument('-q', '--queue', required=True, 37 | help='Name of the queue to be used') 38 | parser.add_argument('-f', '--function', 39 | help='Name of the read/push function - will be replaced if exists') 40 | parser.add_argument('-s', '--schedule', default='rate(1 day)', 41 | help='A cron/rate at which the function will execute.') 42 | args = parser.parse_args() 43 | if args.command == 'create': 44 | create(args) 45 | elif args.command == 'purge': 46 | purge(args) 47 | 48 | 49 | if __name__ == '__main__': 50 | main() 51 | -------------------------------------------------------------------------------- /sqs_s3_logger/tests.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import os 3 | import tempfile 4 | from unittest import TestCase, skip 5 | from sqs_s3_logger.environment import Environment 6 | from sqs_s3_logger.lambda_function import read_queue, handler 7 | from sqs_s3_logger.lambda_function_builder import build_package, ROLE_NAME, ROLE_POLICY 8 | 9 | 10 | class EnvironmentMixin(object): 11 | @classmethod 12 | def _init_environment(cls): 13 | now = datetime.datetime.now() 14 | cls.environment = Environment( 15 | queue_name='sqs_s3_logger_test-{}'.format(cls.__name__), 16 | bucket_name='sqs-s3-logger-test-{}'.format( 17 | now.isoformat().lower().replace(':', '-')), 18 | function_name='sqs_s3_logger_test' 19 | ) 20 | 21 | @classmethod 22 | def _tear_environment(cls): 23 | cls.environment.destroy(delete_s3_bucket=True) 24 | 25 | 26 | class EnvironmentTest(TestCase, EnvironmentMixin): 27 | 28 | @classmethod 29 | def setUpClass(cls): 30 | cls._init_environment() 31 | 32 | @classmethod 33 | def tearDownClass(cls): 34 | cls.environment.destroy(delete_s3_bucket=True) 35 | 36 | def test_can_get_queue(self): 37 | q = self.environment.get_create_queue() 38 | self.assertIn('sqs_s3_logger_test', q.url) 39 | 40 | def test_can_get_bucket(self): 41 | b = self.environment.get_create_bucket() 42 | self.assertIn('sqs-s3-logger-test', b.name) 43 | self.assertIsNotNone(b.creation_date) 44 | 45 | def test_can_create_function(self): 46 | package_file = build_package() 47 | role_arn = self.environment.update_role_policy(ROLE_NAME, ROLE_POLICY) 48 | res = self.environment.update_function(role_arn, package_file) 49 | self.assertIsNotNone(res) 50 | 51 | def test_can_create_role_policy(self): 52 | r = self.environment.update_role_policy(ROLE_NAME, ROLE_POLICY) 53 | self.assertIsNotNone(r) 54 | self.assertIn('LambdaS3WriteSQSRead', r) 55 | 56 | 57 | class LambdaFunctionTest(TestCase, EnvironmentMixin): 58 | @classmethod 59 | def setUpClass(cls): 60 | cls._init_environment() 61 | 62 | @classmethod 63 | def tearDownClass(cls): 64 | cls._tear_environment() 65 | 66 | def _send_messages_to_the_queue(self, count): 67 | q = self.environment.get_create_queue() 68 | for i in range(count): 69 | q.send_message(MessageBody='message {}'.format(i)) 70 | 71 | def test_can_read_single_message(self): 72 | self._send_messages_to_the_queue(1) 73 | res = [m for m in read_queue(self.environment.get_create_queue())] 74 | self.assertIsNotNone(res) 75 | self.assertEqual(1, len(res)) 76 | self.assertEqual('message 0', res[0].body) 77 | 78 | def test_handler_uploads_queue_contents_to_bucket(self): 79 | self._send_messages_to_the_queue(1) 80 | b = self.environment.get_create_bucket() 81 | self.assertEqual(0, sum(1 for _ in b.objects.all())) 82 | _, temp_filepath = tempfile.mkstemp() 83 | os.environ.update({ 84 | 'QUEUE_NAME': self.environment._queue_name, 85 | 'BUCKET_NAME': self.environment._bucket_name, 86 | 'TEMP_FILE_PATH': temp_filepath 87 | }) 88 | handler(None, None) 89 | self.assertEqual(1, sum(1 for _ in b.objects.all())) 90 | 91 | @skip('Heavier load test, takes too long to be worth it.') 92 | def test_can_handle_many_messages(self): 93 | msg_count = 10000 94 | self._send_messages_to_the_queue(msg_count) 95 | res = [m for m in read_queue(self.environment.get_create_queue())] 96 | self.assertEqual(msg_count, len(res)) 97 | 98 | 99 | class LambdaFunctionBuilderTest(TestCase): 100 | def test_zip_file_is_created(self): 101 | archive_path = build_package() 102 | self.assertTrue(archive_path.endswith('.zip')) 103 | self.assertTrue(os.path.exists(archive_path)) 104 | -------------------------------------------------------------------------------- /sqs_s3_logger/version.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.0.7' 2 | --------------------------------------------------------------------------------