├── .DS_Store ├── .circleci └── config.yml ├── .eslintrc.json ├── .github └── CODEOWNERS ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── __testUtils__ ├── awsMocker.ts ├── firehoseMocker.ts ├── fixtures.ts └── jest.setup.ts ├── __tests__ ├── index.test.ts └── utils │ ├── awsUtils.test.ts │ ├── firehoseClient.test.ts │ └── generalUtils.test.ts ├── jest.config.js ├── package-lock.json ├── package.json ├── scripts ├── checks.sh ├── ci_deploy.sh └── deploy.sh ├── src ├── index.ts ├── types │ └── awsTypes.ts └── utils │ ├── awsUtils.ts │ ├── consts.ts │ ├── firehoseClient.ts │ ├── generalUtils.ts │ ├── logger.ts │ └── stsUtils.ts └── tsconfig.json /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumigo-io/lumigo-node-log-shipper/375d38ee07219112b79dbf0ddc44a6b5ba7bdc81/.DS_Store -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | orbs: 4 | lumigo-orb: &lumigo_orb_version lumigo/lumigo-orb@volatile 5 | 6 | workflows: 7 | test-deploy: 8 | jobs: 9 | - lumigo-orb/print_orb_versions: 10 | lumigo_orb_version: *lumigo_orb_version 11 | 12 | - lumigo-orb/test: 13 | context: common 14 | filters: 15 | branches: 16 | ignore: master 17 | 18 | - lumigo-orb/is_environment_available: 19 | context: common 20 | filters: 21 | branches: 22 | ignore: master 23 | 24 | - lumigo-orb/be-deploy: 25 | context: common 26 | requires: 27 | - lumigo-orb/is_environment_available 28 | 29 | - lumigo-orb/integration-test-prep: 30 | context: common 31 | run_test_cleanup: false 32 | requires: 33 | - lumigo-orb/be-deploy 34 | 35 | - lumigo-orb/integration-test-cleanup: 36 | name: pre-test-cleanup 37 | context: common 38 | requires: 39 | - lumigo-orb/integration-test-prep 40 | 41 | - lumigo-orb/integration-test-limited-flows: 42 | context: common 43 | run_test_cleanup: false 44 | requires: 45 | - pre-test-cleanup 46 | 47 | - lumigo-orb/integration-test-parallel: 48 | context: common 49 | run_test_cleanup: false 50 | requires: 51 | - lumigo-orb/integration-test-limited-flows 52 | 53 | - lumigo-orb/integration-test-cleanup: 54 | name: post-test-cleanup 55 | context: common 56 | requires: 57 | - lumigo-orb/integration-test-parallel 58 | 59 | - lumigo-orb/e2e-test: 60 | context: common 61 | requires: 62 | - lumigo-orb/integration-test-limited-flows 63 | 64 | - lumigo-orb/workflow-completed-successfully: 65 | context: common 66 | requires: 67 | - lumigo-orb/test 68 | - lumigo-orb/integration-test-parallel 69 | - lumigo-orb/e2e-test 70 | 71 | - lumigo-orb/deploy: 72 | context: 73 | - common 74 | - node.js 75 | filters: 76 | branches: 77 | only: master 78 | 79 | jobs: 80 | deploy: 81 | docker: 82 | - image: 'circleci/node:latest' 83 | steps: 84 | - checkout 85 | - run: 86 | name: release 87 | command: ./scripts/deploy.sh 88 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": false, 4 | "es6": true, 5 | "mocha": true, 6 | "node": true, 7 | "jest/globals": true 8 | }, 9 | "parser": "@typescript-eslint/parser", 10 | "parserOptions": { 11 | "ecmaVersion": 2019, 12 | "sourceType": "module" 13 | }, 14 | "rules": { 15 | "indent": [ 16 | "error", 17 | "tab" 18 | ], 19 | "linebreak-style": [ 20 | "error", 21 | "unix" 22 | ], 23 | "quotes": [ 24 | "error", 25 | "double", 26 | { 27 | "avoidEscape": true 28 | } 29 | ], 30 | "semi": [ 31 | "error", 32 | "always" 33 | ], 34 | "no-console": 0 35 | }, 36 | "extends": [ 37 | "eslint:recommended", 38 | "prettier" 39 | ], 40 | "globals": { 41 | "console": true, 42 | "require": true, 43 | "module": true, 44 | "process": true, 45 | "setTimeout": true 46 | }, 47 | 48 | "plugins": [ 49 | "jest", 50 | "@typescript-eslint" 51 | ] 52 | } -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @lumigo-io/delta -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Coverage directory used by tools like istanbul 9 | coverage 10 | 11 | # nyc test coverage 12 | .nyc_output 13 | 14 | # Bower dependency directory (https://bower.io/) 15 | bower_components 16 | 17 | # Compiled binary addons (https://nodejs.org/api/addons.html) 18 | build/Release 19 | 20 | # Dependency directories 21 | node_modules/ 22 | jspm_packages/ 23 | 24 | # Optional npm cache directory 25 | .npm 26 | 27 | # Optional eslint cache 28 | .eslintcache 29 | 30 | # Optional REPL history 31 | .node_repl_history 32 | 33 | # Output of 'npm pack' 34 | *.tgz 35 | 36 | # VIM 37 | *.swp 38 | 39 | # Yarn Integrity file 40 | .yarn-integrity 41 | 42 | # dotenv environment variables file 43 | .env 44 | .env_* 45 | 46 | # next.js build output 47 | .next 48 | 49 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 50 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 51 | 52 | # User-specific stuff 53 | .idea/**/workspace.xml 54 | .idea/**/tasks.xml 55 | .idea/**/usage.statistics.xml 56 | .idea/**/dictionaries 57 | .idea/**/shelf 58 | 59 | # Generated files 60 | .idea/**/contentModel.xml 61 | 62 | # Sensitive or high-churn files 63 | .idea/**/dataSources/ 64 | .idea/**/dataSources.ids 65 | .idea/**/dataSources.local.xml 66 | .idea/**/sqlDataSources.xml 67 | .idea/**/dynamic.xml 68 | .idea/**/uiDesigner.xml 69 | .idea/**/dbnavigator.xml 70 | 71 | # Gradle 72 | .idea/**/gradle.xml 73 | .idea/**/libraries 74 | 75 | # Gradle and Maven with auto-import 76 | # When using Gradle or Maven with auto-import, you should exclude module files, 77 | # since they will be recreated, and may cause churn. Uncomment if using 78 | # auto-import. 79 | # .idea/modules.xml 80 | # .idea/*.iml 81 | # .idea/modules 82 | 83 | # CMake 84 | cmake-build-*/ 85 | 86 | # Mongo Explorer plugin 87 | .idea/**/mongoSettings.xml 88 | 89 | # File-based project format 90 | *.iws 91 | 92 | # IntelliJ 93 | out/ 94 | 95 | # mpeltonen/sbt-idea plugin 96 | .idea_modules/ 97 | 98 | # JIRA plugin 99 | atlassian-ide-plugin.xml 100 | 101 | # Cursive Clojure plugin 102 | .idea/replstate.xml 103 | 104 | # Crashlytics plugin (for Android Studio and IntelliJ) 105 | com_crashlytics_export_strings.xml 106 | crashlytics.properties 107 | crashlytics-build.properties 108 | fabric.properties 109 | 110 | # Editor-based Rest Client 111 | .idea/httpRequests 112 | 113 | # Android studio 3.1+ serialized cache file 114 | .idea/caches/build_file_checksums.ser 115 | 116 | # src package for test 117 | src/package.json 118 | src/node_modules 119 | node_modules* 120 | 121 | # package-lock 122 | dist/ 123 | .idea/ -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "tabWidth": 2, 4 | "semi": true, 5 | "singleQuote": true, 6 | "trailingComma": "es5", 7 | "useTabs": false, 8 | "parser": "babel", 9 | "overrides": [ 10 | { 11 | "files": "*.json", 12 | "options": { "parser": "json", "printWidth": 200 } 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /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 | # lumigo-node-log-shipper 2 | 3 | [`@lumigo/lumigo-log-shipper`](https://) is Lumigo's log shipper for Node.js. 4 | 5 | ## Usage 6 | 7 | Install `@lumigo/lumigo-log-shipper`: 8 | 9 | npm: 10 | ~~~bash 11 | $ npm i @lumigo/lumigo-log-shipper 12 | ~~~ 13 | 14 | In your lambda's code: 15 | ~~~js 16 | const LumigoLogger = require("@lumigo/lumigo-log-shipper"); 17 | 18 | module.exports. = (event, context, callback) => { 19 | LumigoLogger.shipLogs(event); 20 | }; 21 | ~~~ 22 | 23 | With programtic error: 24 | ~~~js 25 | const LumigoLogger = require("@lumigo/lumigo-log-shipper"); 26 | 27 | module.exports. = (event, context, callback) => { 28 | LumigoLogger.shipLogs(event, "[Error]"); 29 | }; 30 | ~~~ 31 | Add to your lambda's `serverless.yml` 32 | ```bash 33 | - Effect: Allow 34 | Action: 35 | - "sts:AssumeRole" 36 | Resource: 37 | - "*" 38 | ``` -------------------------------------------------------------------------------- /__testUtils__/awsMocker.ts: -------------------------------------------------------------------------------- 1 | import { AwsFirehoseClient, FirehoseDataForTesting } from "./firehoseMocker"; 2 | 3 | const noop = () => {}; 4 | 5 | export class AwsMocker { 6 | static applyMock = () => { 7 | jest.mock("aws-sdk", () => { 8 | return { 9 | Firehose: AwsFirehoseClient, 10 | config: { 11 | update: noop, 12 | }, 13 | }; 14 | }); 15 | }; 16 | static resetAll = () => { 17 | FirehoseDataForTesting.reset(); 18 | }; 19 | } 20 | -------------------------------------------------------------------------------- /__testUtils__/firehoseMocker.ts: -------------------------------------------------------------------------------- 1 | import { Firehose } from "aws-sdk"; 2 | import { int } from "aws-sdk/clients/datapipeline"; 3 | 4 | type FirehoseRequest = Firehose.Record[]; 5 | 6 | export class FirehoseDataForTesting { 7 | private static requests: FirehoseRequest[] = []; 8 | private static pendingFailedRequests: number = 0; 9 | 10 | static addRequest = (request: FirehoseRequest): void => { 11 | FirehoseDataForTesting.requests.push(request); 12 | }; 13 | static getRequests = () => FirehoseDataForTesting.requests; 14 | 15 | static reset = () => { 16 | FirehoseDataForTesting.requests = []; 17 | }; 18 | 19 | static failedForTheNext = (times: int): void => { 20 | FirehoseDataForTesting.pendingFailedRequests = times; 21 | }; 22 | 23 | static isFailInNextRequest = (): boolean => { 24 | if (FirehoseDataForTesting.pendingFailedRequests > 0) { 25 | FirehoseDataForTesting.pendingFailedRequests--; 26 | return true; 27 | } 28 | return false; 29 | }; 30 | } 31 | 32 | export class AwsFirehoseClient { 33 | private static createFhResponse = (recordsCount: number, failed: boolean) => { 34 | let records = []; 35 | for (let i = 0; i < recordsCount; i++) { 36 | let record = { RecordId: i }; 37 | if (failed) { 38 | record = { 39 | ...record, 40 | // @ts-ignore 41 | ErrorCode: "ServiceUnavailableException", 42 | ErrorMessage: "ServiceUnavailableException bla bla bla", 43 | }; 44 | } 45 | records.push(record); 46 | } 47 | return { FailedPutCount: failed ? records.length : 0, RequestResponses: records }; 48 | }; 49 | putRecordBatch(params: Firehose.PutRecordBatchInput): any { 50 | FirehoseDataForTesting.addRequest(params.Records); 51 | const failed = FirehoseDataForTesting.isFailInNextRequest(); 52 | return { 53 | promise: async () => { 54 | return AwsFirehoseClient.createFhResponse(params.Records.length, failed); 55 | }, 56 | }; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /__testUtils__/fixtures.ts: -------------------------------------------------------------------------------- 1 | import { AwsLogSubscriptionEvent } from "../src/types/awsTypes"; 2 | 3 | export function firehoseEvents() { 4 | return [ 5 | { 6 | Data: '{"event_details":{"function_details":{"resource_id":"arn:aws:lambda:us-west-2:142423218622:function:guymoses_customers-service_add-new-user","memory":0},"timestamp":1569495175073,"aws_account_id":"142423218622"},"message":"[ERROR] ParameterNotFound: Missing Authorization\\rTraceback (most recent call last):\\r  File \\"/var/task/lumigo_tracer/sync_http/sync_hook.py\\", line 134, in lambda_wrapper\\r    return func(*args, **kwargs)\\r  File \\"/var/task/_lumigo/add-new-user.py\\", line 7, in handler\\r    return userHandler(event, context)\\r  File \\"/var/task/lumigo_common_utils/aws/aws_utils.py\\", line 375, in wrapper\\r    args[0][\\"customer_id\\"] = get_authenticated_customer_id(args[0])\\r  File \\"/var/task/lumigo_common_utils/aws/aws_utils.py\\", line 348, in get_authenticated_customer_id\\r    customer_id = get_jwt_payload_attribute_or_default(event, \\"custom:customer\\")\\r  File \\"/var/task/lumigo_common_utils/aws/aws_utils.py\\", line 331, in get_jwt_payload_attribute_or_default\\r    token = get_header_or_fail(event, \\"Authorization\\")\\r  File \\"/var/task/lumigo_common_utils/aws/aws_utils.py\\", line 267, in get_header_or_fail\\r    raise ParameterNotFound(f\\"Missing {name}\\")\\n","timestamp":1569495175073}\n', 7 | }, 8 | ]; 9 | } 10 | 11 | export function simpleAwsEvent(): AwsLogSubscriptionEvent { 12 | return { 13 | messageType: "DATA_MESSAGE", 14 | owner: "142423218622", 15 | logGroup: "/aws/lambda/guymoses_customers-service_add-new-user", 16 | logStream: "2019/09/26/[$LATEST]04de06936c794b6aba43996905b492ba", 17 | subscriptionFilters: ["cloudwatch"], 18 | logEvents: [ 19 | { 20 | id: "35000911989626184511773790667568665149429700037560893440", 21 | timestamp: 1569495175073, 22 | message: 23 | '[ERROR] ParameterNotFound: Missing Authorization\rTraceback (most recent call last):\r  File "/var/task/lumigo_tracer/sync_http/sync_hook.py", line 134, in lambda_wrapper\r    return func(*args, **kwargs)\r  File "/var/task/_lumigo/add-new-user.py", line 7, in handler\r    return userHandler(event, context)\r  File "/var/task/lumigo_common_utils/aws/aws_utils.py", line 375, in wrapper\r    args[0]["customer_id"] = get_authenticated_customer_id(args[0])\r  File "/var/task/lumigo_common_utils/aws/aws_utils.py", line 348, in get_authenticated_customer_id\r    customer_id = get_jwt_payload_attribute_or_default(event, "custom:customer")\r  File "/var/task/lumigo_common_utils/aws/aws_utils.py", line 331, in get_jwt_payload_attribute_or_default\r    token = get_header_or_fail(event, "Authorization")\r  File "/var/task/lumigo_common_utils/aws/aws_utils.py", line 267, in get_header_or_fail\r    raise ParameterNotFound(f"Missing {name}")\n', 24 | }, 25 | ], 26 | }; 27 | } 28 | 29 | export function rawAwsEvent(): any { 30 | return { 31 | awslogs: { 32 | data: "H4sIAAAAAAAAAK2TS27bMBCGr0IQXTiBU70p00AXBuqki6YtYu8sQxhRtM1aIgWSiusGuUvOkpOV8iNxkKbdBIIAaYac//tnyDtcc2NgyafbhuMh/jyajvLr8WQyuhrjPlYbybULB3EYh1EYDEgYunCllldatY3LeLAxXgV1UYK3bLe1MtzkrDVW1VybC8P1rWA8h7K8kHxz0brAvsDEag61qxD6AfV86oXEm334OpqOJ9O5H5fcJzQiLKVxQaCAOKKUUD8pYhoW4EqYtjBMi8YKJS9FZZ0aHs4wq1RbbsCyFZ7vdMa3XNoudYdF6eSixPd9GgR0QElIgkGcBEGaRin1CUkTMiAkCWIahzR16yIX8Qc0imPfSVrhmmWhdr6DhNCYJkGa+GnUPzbRlZ+Nb26+38zRD9BQc0f1TdlL1cpyiK6FMUIu0ai1K6XFb+jQMz3VwHgBbI16rnsWac4cMWJQVagCY8+GmX58eHxwJjnKsHcL2rNg1l7V1mKpctvt157ZSpavrG0OX0qtPzbbDPdRJSRHQRT3kZBoP6p8o6FpuN5X7h7NbaslWrSS9c5BL00fnZ+vN93X2Rv6+R7AO53tqWS6E1yBLKu/KHWrv+xzPd7NqI+Ykpb/sm/pHfwyVddK5q0VldmdPvfu/07F3eR28q+Mdo5m/nyW4eMpzUWZ4Tn6hJbc5uCG42AEA8vL/GRJ77DxfejiwY7un4rPzCfBA+bPjc0b2FYKyhys1aJoLc+Vzku+gLayx5YeXQ6PJTL8Pgai4MnA/1iefVi15vLgYMWhdI7csgWI6pn35e14H9qQpE+0L3VPjiUIw19f294iw8eLeydd7r5jkvh+fv8H3pJOiDwFAAA=", 33 | }, 34 | }; 35 | } 36 | 37 | export function lumigoKinesisEvent(): any { 38 | return [ 39 | { 40 | event_details: { 41 | function_details: { 42 | resource_id: 43 | "arn:aws:lambda:us-west-2:142423218622:function:guymoses_customers-service_add-new-user", 44 | memory: 0, 45 | }, 46 | timestamp: 1569495175073, 47 | aws_account_id: "142423218622", 48 | }, 49 | message: 50 | '[ERROR] ParameterNotFound: Missing Authorization\rTraceback (most recent call last):\r  File "/var/task/lumigo_tracer/sync_http/sync_hook.py", line 134, in lambda_wrapper\r    return func(*args, **kwargs)\r  File "/var/task/_lumigo/add-new-user.py", line 7, in handler\r    return userHandler(event, context)\r  File "/var/task/lumigo_common_utils/aws/aws_utils.py", line 375, in wrapper\r    args[0]["customer_id"] = get_authenticated_customer_id(args[0])\r  File "/var/task/lumigo_common_utils/aws/aws_utils.py", line 348, in get_authenticated_customer_id\r    customer_id = get_jwt_payload_attribute_or_default(event, "custom:customer")\r  File "/var/task/lumigo_common_utils/aws/aws_utils.py", line 331, in get_jwt_payload_attribute_or_default\r    token = get_header_or_fail(event, "Authorization")\r  File "/var/task/lumigo_common_utils/aws/aws_utils.py", line 267, in get_header_or_fail\r    raise ParameterNotFound(f"Missing {name}")\n', 51 | timestamp: 1569495175073, 52 | }, 53 | ]; 54 | } 55 | -------------------------------------------------------------------------------- /__testUtils__/jest.setup.ts: -------------------------------------------------------------------------------- 1 | import { AwsMocker } from "./awsMocker"; 2 | 3 | const oldEnv = Object.assign({}, process.env); 4 | const oldConsole = Object.assign({}, console); 5 | 6 | AwsMocker.applyMock(); 7 | 8 | beforeEach(() => { 9 | process.env = { ...oldEnv }; 10 | console = { ...oldConsole }; 11 | AwsMocker.resetAll(); 12 | }); 13 | 14 | afterEach(() => { 15 | process.env = { ...oldEnv }; 16 | console = { ...oldConsole }; 17 | }); 18 | -------------------------------------------------------------------------------- /__tests__/index.test.ts: -------------------------------------------------------------------------------- 1 | import { shipLogs } from "../src"; 2 | import * as stsUtils from "../src/utils/stsUtils"; 3 | import * as fixutres from "../__testUtils__/fixtures"; 4 | 5 | //TODO: Remove this mocks into a infra mocker 6 | export const STS_MOCKED_RESPONSE: any = { 7 | Credentials: { 8 | AccessKeyId: "AccessKeyId", 9 | SecretAccessKey: "SecretAccessKey", 10 | SessionToken: "SessionToken", 11 | }, 12 | }; 13 | 14 | //TODO: Remove this mocks into a infra mocker 15 | describe("log shipping functionality ", () => { 16 | it("sends logs - happy flow", async () => { 17 | jest.spyOn(stsUtils, "assumeRole").mockReturnValueOnce(STS_MOCKED_RESPONSE); 18 | 19 | const result = await shipLogs(fixutres.rawAwsEvent(), "[ERROR]"); 20 | expect(result).toEqual(1); 21 | }); 22 | 23 | it("doesn't ship big event", async () => { 24 | process.env.LUMIGO_ITEM_MAX_SIZE = String(1); 25 | 26 | const result = await shipLogs(fixutres.rawAwsEvent()); 27 | expect(result).toEqual(0); 28 | }); 29 | 30 | it("doesn't ship anything", async () => { 31 | const result = await shipLogs({}); 32 | 33 | expect(result).toEqual(0); 34 | }); 35 | 36 | it("ships 0 logs when kinesis couldn't be initiated", async () => { 37 | jest.spyOn(stsUtils, "assumeRole").mockRejectedValue(() => Error("RandomError")); 38 | 39 | const result = await shipLogs(fixutres.rawAwsEvent()); 40 | expect(result).toEqual(0); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /__tests__/utils/awsUtils.test.ts: -------------------------------------------------------------------------------- 1 | import { extractAwsLogEvent } from "../../src/utils/awsUtils"; 2 | import * as fixtures from "../../__testUtils__/fixtures"; 3 | 4 | describe("aws utils functionality ", () => { 5 | it("extracts aws log event", () => { 6 | let parsedEvent = extractAwsLogEvent(fixtures.rawAwsEvent()); 7 | expect(parsedEvent).toEqual(fixtures.simpleAwsEvent()); 8 | }); 9 | }); 10 | -------------------------------------------------------------------------------- /__tests__/utils/firehoseClient.test.ts: -------------------------------------------------------------------------------- 1 | import { FirehoseClient } from "../../src/utils/firehoseClient"; 2 | import * as stsUtils from "../../src/utils/stsUtils"; 3 | import * as fixutres from "../../__testUtils__/fixtures"; 4 | import { STS_MOCKED_RESPONSE } from "../index.test"; 5 | import { FirehoseDataForTesting } from "../../__testUtils__/firehoseMocker"; 6 | 7 | describe("FirehoseClient", () => { 8 | let firehose: any; 9 | beforeEach(() => { 10 | firehose = new FirehoseClient("test-firehose-log-stream", "142423218622"); 11 | jest.spyOn(stsUtils, "assumeRole").mockReturnValueOnce(STS_MOCKED_RESPONSE); 12 | }); 13 | 14 | it("converts to firehose events", () => { 15 | let events = firehose.convertToFirehoseEvents(fixutres.lumigoKinesisEvent()); 16 | expect(events).toEqual(fixutres.firehoseEvents()); 17 | }); 18 | 19 | it("pareses problematic firehose response records", () => { 20 | let responseRecords = [ 21 | { ErrorCode: "ServiceUnavailableException", ErrorMessage: "Error #1" }, 22 | { ErrorCode: "otherException", ErrorMessage: "Error #2" }, 23 | { ErrorCode: "InternalFailure", ErrorMessage: "Error #3" }, 24 | ]; 25 | 26 | let problematicRecords = 27 | firehose.parseFirehoseProblematicRecords(responseRecords); 28 | expect(problematicRecords).toBeInstanceOf(Array); 29 | expect(problematicRecords).toEqual([0, 2]); 30 | }); 31 | 32 | it("checks validity of a firehose event", () => { 33 | expect(firehose.validFirehoseEvent({ Data: "" }, 1)).toBeFalsy(); 34 | expect(firehose.validFirehoseEvent({ Data: "" }, 100)).toBeTruthy(); 35 | }); 36 | 37 | it("handles retry items", () => { 38 | let allRecrds = [ 39 | { id: 1 }, 40 | { id: 2 }, 41 | { id: 3 }, 42 | { id: 4 }, 43 | { id: 4 }, 44 | { id: 5 }, 45 | ]; 46 | let retryItems = [0, 2]; 47 | expect(firehose.handleRetryItems(allRecrds, retryItems)).toEqual([ 48 | { id: 1 }, 49 | { id: 3 }, 50 | ]); 51 | }); 52 | 53 | it("pushes items to firehose", async () => { 54 | const result = await firehose.pushToFirehose( 55 | fixutres.firehoseEvents(), 56 | "stream-name" 57 | ); 58 | 59 | const requests = FirehoseDataForTesting.getRequests(); 60 | expect(result).toEqual({ 61 | FailedPutCount: 0, 62 | RequestResponses: [{ RecordId: 0 }], 63 | }); 64 | //TODO: Compare object 65 | expect(requests).toEqual([ 66 | [ 67 | { 68 | Data: '{"event_details":{"function_details":{"resource_id":"arn:aws:lambda:us-west-2:142423218622:function:guymoses_customers-service_add-new-user","memory":0},"timestamp":1569495175073,"aws_account_id":"142423218622"},"message":"[ERROR] ParameterNotFound: Missing Authorization\\rTraceback (most recent call last):\\r  File \\"/var/task/lumigo_tracer/sync_http/sync_hook.py\\", line 134, in lambda_wrapper\\r    return func(*args, **kwargs)\\r  File \\"/var/task/_lumigo/add-new-user.py\\", line 7, in handler\\r    return userHandler(event, context)\\r  File \\"/var/task/lumigo_common_utils/aws/aws_utils.py\\", line 375, in wrapper\\r    args[0][\\"customer_id\\"] = get_authenticated_customer_id(args[0])\\r  File \\"/var/task/lumigo_common_utils/aws/aws_utils.py\\", line 348, in get_authenticated_customer_id\\r    customer_id = get_jwt_payload_attribute_or_default(event, \\"custom:customer\\")\\r  File \\"/var/task/lumigo_common_utils/aws/aws_utils.py\\", line 331, in get_jwt_payload_attribute_or_default\\r    token = get_header_or_fail(event, \\"Authorization\\")\\r  File \\"/var/task/lumigo_common_utils/aws/aws_utils.py\\", line 267, in get_header_or_fail\\r    raise ParameterNotFound(f\\"Missing {name}\\")\\n","timestamp":1569495175073}\n', 69 | }, 70 | ], 71 | ]); 72 | }); 73 | 74 | it("puts records batch", async () => { 75 | const result = await firehose.putRecordsBatch(fixutres.lumigoKinesisEvent()); 76 | 77 | expect(result).toEqual(1); 78 | }); 79 | 80 | it("puts records batch with greater than max retries", async () => { 81 | FirehoseDataForTesting.failedForTheNext(100); 82 | 83 | const result = await firehose.putRecordsBatch(fixutres.lumigoKinesisEvent()); 84 | 85 | expect(result).toEqual(0); 86 | }); 87 | 88 | it("puts records batch with less than max retries", async () => { 89 | FirehoseDataForTesting.failedForTheNext(1); 90 | 91 | const result = await firehose.putRecordsBatch(fixutres.lumigoKinesisEvent()); 92 | 93 | expect(result).toEqual(1); 94 | }); 95 | }); 96 | -------------------------------------------------------------------------------- /__tests__/utils/generalUtils.test.ts: -------------------------------------------------------------------------------- 1 | import * as generalUtils from "../../src/utils/generalUtils"; 2 | import * as fixutres from "../../__testUtils__/fixtures"; 3 | import { AwsLogEvent } from "../../src/types/awsTypes"; 4 | 5 | const eventFromMessage = (message: string): AwsLogEvent => ({ 6 | message: message, 7 | id: "Dummy", 8 | timestamp: 123456, 9 | }); 10 | 11 | describe("general utils functionality ", () => { 12 | it("validates record", () => { 13 | let event1 = eventFromMessage("AAAAAA-Task timed out-BBBBB"); 14 | let event2 = eventFromMessage("Process exited before completing request-BBBBB"); 15 | let event3 = eventFromMessage("REPORT RequestId"); 16 | let event4 = eventFromMessage("NON-VALID-EVENT"); 17 | 18 | expect(generalUtils.isValidEvent(event1)).toEqual(true); 19 | expect(generalUtils.isValidEvent(event2)).toEqual(true); 20 | expect(generalUtils.isValidEvent(event3)).toEqual(true); 21 | expect(generalUtils.isValidEvent(event4)).toEqual(false); 22 | }); 23 | 24 | it("adds programatic error and validates it", () => { 25 | let programaticError = "[ERROR]"; 26 | let event1 = fixutres.simpleAwsEvent(); 27 | event1.logEvents[0].message = "SHOULD_NOT_WORK"; 28 | let event2 = fixutres.simpleAwsEvent(); 29 | event2.logEvents[0].message = "[ERROR] 12345"; 30 | 31 | expect(generalUtils.filterMessagesFromRecord(event1).logEvents).toHaveLength(0); 32 | expect(generalUtils.filterMessagesFromRecord(event2, programaticError)).toEqual( 33 | event2 34 | ); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | collectCoverage: true, 3 | 4 | collectCoverageFrom: ["src/**/*.ts", "src/**/*.js"], 5 | coverageThreshold: { 6 | global: { 7 | branches: 60, 8 | functions: 70, 9 | lines: 80, 10 | statements: 80 11 | } 12 | }, 13 | testEnvironment: "node", 14 | preset: "ts-jest", 15 | setupFilesAfterEnv: ["./__testUtils__/jest.setup.ts"] 16 | }; 17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@lumigo/lumigo-log-shipper", 3 | "version": "0.0.0-development", 4 | "description": "Lumigo Node.js Log Shipper", 5 | "main": "dist/index.js", 6 | "scripts": { 7 | "test": "jest", 8 | "checks": "./scripts/checks.sh", 9 | "ts": "tsc", 10 | "lint:fix": "eslint ./src --ext .ts --ignore-pattern node_modules/ --fix", 11 | "build": "tsc", 12 | "lint-staged": "lint-staged", 13 | "prettier:fix": "prettier --write \"./**/*.ts\"", 14 | "prettier:check": "prettier --check \"./src/**/*.ts\"", 15 | "semantic-release": "semantic-release" 16 | }, 17 | "author": "", 18 | "license": "ISC", 19 | "devDependencies": { 20 | "@types/jest": "^26.0.13", 21 | "@types/node": "^14.10.2", 22 | "@typescript-eslint/eslint-plugin": "^4.1.1", 23 | "@typescript-eslint/parser": "^4.1.1", 24 | "aws-sdk": "^2.533.0", 25 | "eslint": "^5.16.0", 26 | "eslint-config-prettier": "^3.1.0", 27 | "eslint-plugin-jest": "^24.0.1", 28 | "jest": "^26.4.2", 29 | "lint-staged": "^7.3.0", 30 | "nock": "^10.0.2", 31 | "prettier": "^2.8.1", 32 | "semantic-release": "^17.1.2", 33 | "ts-jest": "^26.3.0", 34 | "typescript": "^4.0.2", 35 | "zlib": "^1.0.5" 36 | }, 37 | "prettier": { 38 | "useTabs": true, 39 | "tabWidth": 4, 40 | "printWidth": 90 41 | }, 42 | "lint-staged": { 43 | "*.js": [ 44 | "prettier" 45 | ] 46 | }, 47 | "dependencies": { 48 | "buffer": "^5.4.3" 49 | }, 50 | "files": [ 51 | "dist/**/*" 52 | ], 53 | "repository": { 54 | "type": "git", 55 | "url": "https://github.com/lumigo-io/lumigo-node-log-shipper.git" 56 | }, 57 | "publishConfig": { 58 | "access": "restricted" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /scripts/checks.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | npm run ts 5 | npm run prettier:check 6 | npm run lint:fix 7 | npm run test -------------------------------------------------------------------------------- /scripts/ci_deploy.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -eo pipefail 3 | 4 | pushd "$(dirname "$0")" &> /dev/null 5 | # Go back one spot because we are on scripts dir. The other scripts assume you are in the root folder 6 | cd .. 7 | ../utils/common_bash/defaults/ci_deploy.sh lumigo-node-log-shipper 8 | popd &> /dev/null -------------------------------------------------------------------------------- /scripts/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | npm i 5 | npm run build 6 | npm run semantic-release -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { FirehoseClient } from "./utils/firehoseClient"; 2 | import { extractAwsLogEvent } from "./utils/awsUtils"; 3 | import { filterMessagesFromRecord } from "./utils/generalUtils"; 4 | import { getStreamName } from "./utils/consts"; 5 | import { logDebug } from "./utils/logger"; 6 | 7 | export const shipLogs = async function ( 8 | record: any, 9 | programaticError?: string 10 | ): Promise { 11 | try { 12 | const streamName = getStreamName(); 13 | const extractedRecord = extractAwsLogEvent(record); 14 | logDebug( 15 | `Got ${extractedRecord.logEvents.length} log events from ${extractedRecord.logGroup}` 16 | ); 17 | let filteredRecord = filterMessagesFromRecord(extractedRecord, programaticError); 18 | if (filteredRecord.logEvents.length > 0) { 19 | logDebug(`About to send ${extractedRecord.logEvents.length} events`, { 20 | streamName, 21 | }); 22 | let firehose = new FirehoseClient(streamName, filteredRecord.owner); 23 | return await firehose.putRecordsBatch([filteredRecord]); 24 | } 25 | } catch (e) { 26 | // couldn't ship logs 27 | logDebug("Got an error from shipper", e); 28 | } 29 | return 0; 30 | }; 31 | -------------------------------------------------------------------------------- /src/types/awsTypes.ts: -------------------------------------------------------------------------------- 1 | export interface AwsLogEvent { 2 | id: string; 3 | timestamp: number; 4 | message: string; 5 | } 6 | 7 | export interface AwsLogSubscriptionEvent { 8 | messageType: string; 9 | owner: string; 10 | logGroup: string; 11 | logStream: string; 12 | subscriptionFilters: string[]; 13 | logEvents: AwsLogEvent[]; 14 | } 15 | -------------------------------------------------------------------------------- /src/utils/awsUtils.ts: -------------------------------------------------------------------------------- 1 | import { Buffer } from "buffer"; 2 | import { gunzipSync } from "zlib"; 3 | import { AwsLogSubscriptionEvent } from "../types/awsTypes"; 4 | 5 | export const extractAwsLogEvent = function (event: any): AwsLogSubscriptionEvent { 6 | let decodedData = Buffer.from(event["awslogs"]["data"], "base64"); 7 | let decompressedData = gunzipSync(decodedData).toString("utf-8"); 8 | return JSON.parse(decompressedData); 9 | }; 10 | 11 | export const getCurrentRegion = function (): string { 12 | return process.env.AWS_REGION || "us-west-2"; 13 | }; 14 | -------------------------------------------------------------------------------- /src/utils/consts.ts: -------------------------------------------------------------------------------- 1 | const runOnAws = !!process.env.AWS_EXECUTION_ENV; 2 | const CURRENT_ENV = runOnAws ? process.env.ENV : process.env.USER; 3 | 4 | export let TARGET_ENV: string = process.env.TARGET_ENV ? process.env.TARGET_ENV : "prod"; 5 | if (TARGET_ENV === "SELF" && CURRENT_ENV) TARGET_ENV = CURRENT_ENV; 6 | export const TARGET_ACCOUNT_ID = process.env.TARGET_ACCOUNT_ID || "114300393969"; 7 | export const SELF_ACCOUNT_ID = "SELF"; 8 | 9 | export const isSendingLogsToMyself = (): boolean => TARGET_ACCOUNT_ID === SELF_ACCOUNT_ID; 10 | 11 | export const getStreamName = (): string => { 12 | const targetEnv = isSendingLogsToMyself() ? CURRENT_ENV : TARGET_ENV; 13 | return `${targetEnv}_logs-edge-stfl_customer-logs-firehose`; 14 | }; 15 | -------------------------------------------------------------------------------- /src/utils/firehoseClient.ts: -------------------------------------------------------------------------------- 1 | import { AWSError } from "aws-sdk/lib/error"; 2 | import { PromiseResult } from "aws-sdk/lib/request"; 3 | 4 | import AWS from "aws-sdk"; 5 | import { AwsLogSubscriptionEvent } from "../types/awsTypes"; 6 | import { getCurrentRegion } from "./awsUtils"; 7 | import { isSendingLogsToMyself, TARGET_ACCOUNT_ID, TARGET_ENV } from "./consts"; 8 | import { logDebug } from "./logger"; 9 | import { assumeRole } from "./stsUtils"; 10 | 11 | const ALLOW_RETRY_ERROR_CODES = ["ServiceUnavailableException", "InternalFailure"]; 12 | 13 | const MAX_RETRY_COUNT = 3; 14 | const MAX_ITEM_SIZE = 1048576; 15 | const MAX_FIREHOSE_BATCH_SIZE = 250; 16 | const EOL = "\n"; 17 | 18 | const getItemMaxSize = (): number => { 19 | if (process.env.LUMIGO_ITEM_MAX_SIZE) { 20 | return parseInt(process.env.LUMIGO_ITEM_MAX_SIZE); 21 | } 22 | return MAX_ITEM_SIZE; 23 | }; 24 | 25 | export class FirehoseClient { 26 | private readonly streamName: string; 27 | private readonly accountId: string; 28 | private firehose?: AWS.Firehose; 29 | 30 | constructor(streamName: string, accountId: string) { 31 | this.streamName = streamName; 32 | this.accountId = accountId; 33 | } 34 | 35 | private async getFirehoseClient(): Promise { 36 | const region = getCurrentRegion(); 37 | if (this.accountId != TARGET_ACCOUNT_ID && !isSendingLogsToMyself()) { 38 | const stsResponse = await assumeRole(TARGET_ACCOUNT_ID, TARGET_ENV); 39 | if (!stsResponse.Credentials) throw Error("AssumeRoleFailed"); 40 | logDebug("Create firehose client", { 41 | accountId: this.accountId, 42 | streamName: this.streamName, 43 | targetAccountId: TARGET_ACCOUNT_ID, 44 | }); 45 | return new AWS.Firehose({ 46 | region: region, 47 | accessKeyId: stsResponse.Credentials.AccessKeyId, 48 | secretAccessKey: stsResponse.Credentials.SecretAccessKey, 49 | sessionToken: stsResponse.Credentials.SessionToken, 50 | }); 51 | } 52 | logDebug("Using local firshose client", { 53 | accountId: this.accountId, 54 | targetAccountId: TARGET_ACCOUNT_ID, 55 | }); 56 | return new AWS.Firehose({ region }); 57 | } 58 | 59 | async putRecordsBatch(records: AwsLogSubscriptionEvent[]) { 60 | const itemMaxSize = getItemMaxSize(); 61 | let recordsToWrite = []; 62 | let numberOfRecords = 0; 63 | let rawEvents = records; 64 | 65 | while (rawEvents.length > 0) { 66 | let event = rawEvents.pop(); 67 | if (!this.validFirehoseEvent(event, itemMaxSize)) { 68 | // event is too big 69 | continue; 70 | } 71 | recordsToWrite.push(event); 72 | if ( 73 | rawEvents.length === 0 || 74 | recordsToWrite.length === MAX_FIREHOSE_BATCH_SIZE 75 | ) { 76 | let retryCounter = 0; 77 | while (retryCounter < MAX_RETRY_COUNT) { 78 | try { 79 | let response = await this.pushToFirehose( 80 | this.convertToFirehoseEvents(recordsToWrite), 81 | this.streamName 82 | ); 83 | numberOfRecords += 84 | recordsToWrite.length - response["FailedPutCount"]; 85 | if (response["FailedPutCount"] === 0) { 86 | break; 87 | } 88 | let retryItems = this.parseFirehoseProblematicRecords( 89 | response["RequestResponses"] 90 | ); 91 | recordsToWrite = this.handleRetryItems( 92 | recordsToWrite, 93 | retryItems 94 | ); 95 | retryCounter++; 96 | } catch (ex) { 97 | retryCounter++; 98 | } 99 | } 100 | recordsToWrite = []; 101 | } 102 | } 103 | return numberOfRecords; 104 | } 105 | 106 | validFirehoseEvent(event: any, maxSize: number): boolean { 107 | let eventSize = JSON.stringify(event).length; 108 | return eventSize < maxSize; 109 | } 110 | 111 | async pushToFirehose( 112 | records: any, 113 | streamName: any 114 | ): Promise> { 115 | let params = { 116 | DeliveryStreamName: streamName, 117 | Records: records, 118 | }; 119 | if (!this.firehose) { 120 | this.firehose = await this.getFirehoseClient(); 121 | } 122 | return await this.firehose.putRecordBatch(params).promise(); 123 | } 124 | 125 | convertToFirehoseEvents(events: AwsLogSubscriptionEvent[]): any[] { 126 | let firehoseRecords: any[] = []; 127 | events.forEach(function (event) { 128 | try { 129 | const eventAsString = `${JSON.stringify(event)}${EOL}`; 130 | firehoseRecords.push({ Data: eventAsString }); 131 | } catch (ex) { 132 | logDebug("Failed to convert record", { 133 | error: ex, 134 | record: event, 135 | }); 136 | } 137 | }); 138 | return firehoseRecords; 139 | } 140 | 141 | handleRetryItems(allRecords: any[], retryItems: any[]): any[] { 142 | let retryBatch: any[] = []; 143 | retryItems.forEach(function (item) { 144 | retryBatch.push(allRecords[item]); 145 | }); 146 | return retryBatch; 147 | } 148 | 149 | parseFirehoseProblematicRecords(records: any[]) { 150 | let retryItems: any[] = []; 151 | records.forEach(function (record, index) { 152 | if (Object.prototype.hasOwnProperty.call(record, "ErrorCode")) { 153 | if (ALLOW_RETRY_ERROR_CODES.includes(record["ErrorCode"])) { 154 | retryItems.push(index); 155 | } 156 | } 157 | }); 158 | return retryItems; 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/utils/generalUtils.ts: -------------------------------------------------------------------------------- 1 | import { AwsLogEvent, AwsLogSubscriptionEvent } from "../types/awsTypes"; 2 | 3 | let FILTER_KEYWORDS = [ 4 | "Task timed out", 5 | "Process exited before completing request", 6 | "REPORT RequestId", 7 | "[ERROR]", 8 | "[LUMIGO_LOG]", 9 | "@lumigo", 10 | "LambdaRuntimeClientError", 11 | "Invoke Error", 12 | "Uncaught Exception", 13 | "Unhandled Promise Rejection", 14 | "Traceback", 15 | ]; 16 | 17 | export const isValidEvent = function (record: AwsLogEvent): boolean { 18 | return FILTER_KEYWORDS.some((filterWord) => record.message.includes(filterWord)); 19 | }; 20 | 21 | export const filterMessagesFromRecord = function ( 22 | record: AwsLogSubscriptionEvent, 23 | programaticError?: string 24 | ): AwsLogSubscriptionEvent { 25 | programaticError && FILTER_KEYWORDS.push(programaticError); 26 | record.logEvents = record.logEvents.filter(isValidEvent); 27 | return record; 28 | }; 29 | -------------------------------------------------------------------------------- /src/utils/logger.ts: -------------------------------------------------------------------------------- 1 | const LOG_PREFIX = "[LUMIGO]"; 2 | const isDebug = (): boolean => !!process.env.LUMIGO_DEBUG; 3 | 4 | export const logDebug = (message: string, obj?: any): void => { 5 | if (isDebug()) { 6 | console.log(`${LOG_PREFIX} - ${message}`, obj); 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /src/utils/stsUtils.ts: -------------------------------------------------------------------------------- 1 | import { STS } from "aws-sdk"; 2 | import { PromiseResult } from "aws-sdk/lib/request"; 3 | import { AWSError } from "aws-sdk/lib/error"; 4 | 5 | export async function assumeRole( 6 | targetAccountId: string, 7 | targetEnv: string 8 | ): Promise> { 9 | let sts = new STS(); 10 | return await sts 11 | .assumeRole({ 12 | RoleArn: `arn:aws:iam::${targetAccountId}:role/${targetEnv}-CustomerLogsWriteRole`, 13 | RoleSessionName: "AssumeCrossAccountRole", 14 | DurationSeconds: 900, 15 | }) 16 | .promise(); 17 | } 18 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "lib": ["es5", "es6", "es2015", "es2016", "es2017", "es2018", "esnext", "dom"], 6 | "declaration": true, 7 | "sourceMap": true, 8 | "outDir": "./dist", 9 | "removeComments": true, 10 | "strict": true, 11 | "noImplicitAny": true, 12 | "strictNullChecks": true, 13 | "strictFunctionTypes": true, 14 | "strictPropertyInitialization": true, 15 | "noImplicitThis": true, 16 | "alwaysStrict": true, 17 | "noUnusedLocals": true, 18 | "noUnusedParameters": true, 19 | "noImplicitReturns": true, 20 | "noFallthroughCasesInSwitch": true, 21 | "moduleResolution": "node", 22 | "rootDirs": ["./", "./src"], 23 | "typeRoots": ["./types", "./@types", "node_modules/@types"], 24 | "types": ["node", "jest"], 25 | "esModuleInterop": true, 26 | "preserveConstEnums": true, 27 | "suppressImplicitAnyIndexErrors": true, 28 | "forceConsistentCasingInFileNames": true, 29 | "incremental": true 30 | }, 31 | "include": ["src"], 32 | "exclude": ["node_modules", "**/__tests__/*","**/__testUtils__/*", "coverage"] 33 | } --------------------------------------------------------------------------------