├── .github └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── package.json ├── resources ├── cwl-dashboard-source.json └── metadata.json ├── src ├── cloudwatch-util.ts ├── index.ts ├── transform-util.ts └── utils.ts ├── tsconfig.json └── tslint.json /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | yarn.lock 9 | package-lock.json 10 | 11 | # Runtime data 12 | pids 13 | *.pid 14 | *.seed 15 | *.pid.lock 16 | 17 | # Directory for instrumented libs generated by jscoverage/JSCover 18 | lib-cov 19 | 20 | # Coverage directory used by tools like istanbul 21 | coverage 22 | 23 | # nyc test coverage 24 | .nyc_output 25 | 26 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 27 | .grunt 28 | 29 | # Bower dependency directory (https://bower.io/) 30 | bower_components 31 | 32 | # node-waf configuration 33 | .lock-wscript 34 | 35 | # Compiled binary addons (https://nodejs.org/api/addons.html) 36 | build/Release 37 | 38 | # Dependency directories 39 | node_modules/ 40 | jspm_packages/ 41 | 42 | # TypeScript v1 declaration files 43 | typings/ 44 | 45 | # Optional npm cache directory 46 | .npm 47 | 48 | # Optional eslint cache 49 | .eslintcache 50 | 51 | # Optional REPL history 52 | .node_repl_history 53 | 54 | # Output of 'npm pack' 55 | *.tgz 56 | 57 | # Yarn Integrity file 58 | .yarn-integrity 59 | 60 | # dotenv environment variables file 61 | .env 62 | 63 | # next.js build output 64 | .next 65 | 66 | # custom 67 | lib 68 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/aws-samples/aws-appsync-cwl-migrator/issues), or [recently closed](https://github.com/aws-samples/aws-appsync-cwl-migrator/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws-samples/aws-appsync-cwl-migrator/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/aws-samples/aws-appsync-cwl-migrator/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | AWS AppSync CWL Migrator 2 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AWS AppSync CWL Migrator 2 | 3 | This is a sample package that migrates a given set of requestIds from the AWS AppSync logs in Amazon CloudWatch, from the current (unstructured) to the new (structured JSON) format. If you have any AWS AppSync logs from your existing APIs in an unstructured format, and are looking to run some analytics on the GraphQL tracing logs, this script will help you convert the older logs into a structured format, so you can leverage log analytics services to analyze on your existing requests. 4 | 5 | You can use this as a starter project, and modify to work according to your needs and convenience. 6 | 7 | ## Usage 8 | 9 | ### Installation 10 | 11 | You can clone this repository and fetch the dependencies by running the following commands: 12 | 13 | ```sh 14 | git clone git@github.com:aws-samples/aws-appsync-cwl-migrator.git 15 | cd aws-appsync-cwl-migrator 16 | npm install 17 | ``` 18 | 19 | ### Update Metadata 20 | 21 | Update the `awsProfile`, `graphQLAPIId`, `logGroupName` and `requestIds` from [resources/metadata.json](./resources/metadata.json): 22 | 23 | * **awsProfile** with an AWS Profile that you have created using the [AWS Command Line Interface](https://aws.amazon.com/cli/) 24 | * **graphQLAPIId** with the AWS AppSync GraphQL API ID, available from the Settings page on your AppSync Console 25 | * **logGroupName** with the log group name that contains the AppSync logs from your existing API 26 | * **requestIds** with the list of requestIds that you would like to migrate to the newer structure 27 | 28 | ### Run the Script 29 | 30 | Run `npm run start` to convert the given requestIds into a structured format. These transformed logs will appear in a new log group in Amazon CloudWatch - `aws-appsync-cwl-migrator`. 31 | 32 | ### Overview 33 | 34 | As of May 8, 2019, [AWS AppSync](https://aws.amazon.com/appsync/) generates log events as fully structured JSON. This enables you to use log analytics services such as Amazon CloudWatch Logs Insights and Amazon Elasticsearch Service to understand the performance of your GraphQL requests and usage characteristics of your schema fields. For example, you can easily identify resolvers with large latencies that may be the root cause of a performance issue. You can also identify the most and least frequently used fields in your schema and assess the impact of deprecating GraphQL fields. 35 | 36 | Using these structured logs, you can get more visibility into GraphQL performance with AWS AppSync logs, as described [here](https://aws.amazon.com/blogs/mobile/getting-more-visibility-into-graphql-performance-with-aws-appsync-logs/). 37 | 38 | ### Building Amazon CloudWatch Logs Insights dashboard 39 | 40 | For your convenience, we have added a dashboard template, that you can modify and use to build a dashboard from source, using the CloudWatch console. Use the following steps to create a dashboard in your account: 41 | 42 | * Open [resources/cwl-dashboard-source.json](./resources/cwl-dashboard-source.json) 43 | * Update all occurences of "GRAPHQL_API_ID" with your AWS AppSync API ID, available from the Settings page of your AppSync console 44 | * Update all occurences of "APPSYNC_REGION" with the region that API is created 45 | * Navigate to the “Dashboards” section on the CloudWatch Console 46 | * Click on “Create dashboard” button and provide a name 47 | * Since we are creating a Dashboard from source, you can hit “Cancel” on the Widget configuration section (in the next step) 48 | * You can now select “View/edit source” option under the “Actions” dropdown, and paste the above content from the above template with your GraphQL API ID 49 | * Hit "Save" to Save your changes. This will then create a dashboard on CloudWatch Insights 50 | 51 | You can then choose a time window that you are interested in, and run aggregated Insights queries to answer the following: 52 | 53 | * Number of unique HTTP response status codes 54 | * Top 'N' requests with maximum latency 55 | * Top 'N' resolvers with maximum latency 56 | * Most frequently invoked resolvers 57 | * Resolvers with most errors in mapping templates 58 | * Resolver latency statistics 59 | * Field latency statistics 60 | 61 | You can also go over the links to the AWS Mobile Blog and documentation pages listed above to get additional information. 62 | 63 | ## License 64 | 65 | This library is licensed under the Apache 2.0 License. 66 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cwl-ingestor", 3 | "version": "1.0.0", 4 | "description": "A test CloudWatch logs ingestor package", 5 | "main": "index.js", 6 | "scripts": { 7 | "build": "tsc", 8 | "clean": "rm -rf ./lib", 9 | "start": "npm run build && node lib/index.js" 10 | }, 11 | "keywords": [], 12 | "author": "", 13 | "license": "ISC", 14 | "dependencies": { 15 | "aws-sdk": "^2.419.0", 16 | "moment": "^2.24.0", 17 | "papaparse": "^5.3.0" 18 | }, 19 | "devDependencies": { 20 | "@types/node": "^11.11.1", 21 | "@types/papaparse": "^4.5.9", 22 | "tslint": "^5.13.1", 23 | "typescript": "^3.3.3333" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /resources/cwl-dashboard-source.json: -------------------------------------------------------------------------------- 1 | { 2 | "widgets": [ 3 | { 4 | "type": "log", 5 | "x": 0, 6 | "y": 0, 7 | "width": 24, 8 | "height": 3, 9 | "properties": { 10 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | fields requestId, latency | filter logType = \"RequestSummary\" | sort latency desc | limit 10", 11 | "region": "APPSYNC_REGION", 12 | "title": "Top 10 requests with maximum latency" 13 | } 14 | }, 15 | { 16 | "type": "log", 17 | "x": 0, 18 | "y": 6, 19 | "width": 24, 20 | "height": 3, 21 | "properties": { 22 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | fields ispresent(graphQLAPIId) as isApi | stats count() as statusCount by statusCode | filter isApi and logType = \"RequestSummary\" | sort statusCount desc", 23 | "region": "APPSYNC_REGION", 24 | "title": "Number of unique HTTP status codes" 25 | } 26 | }, 27 | { 28 | "type": "log", 29 | "x": 0, 30 | "y": 12, 31 | "width": 24, 32 | "height": 6, 33 | "properties": { 34 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | fields ispresent(resolverArn) as isRes\n| filter isRes and logType = \"Tracing\"\n| stats min(duration), max(duration), avg(duration) as avg_dur by resolverArn\n| limit 10\n| sort avg_dur desc", 35 | "region": "APPSYNC_REGION", 36 | "title": "Min, Max, Avg latencies of resolvers" 37 | } 38 | }, 39 | { 40 | "type": "log", 41 | "x": 0, 42 | "y": 18, 43 | "width": 24, 44 | "height": 6, 45 | "properties": { 46 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | fields resolverArn, duration\n| filter logType = \"Tracing\"\n| sort duration desc\n| limit 10", 47 | "region": "APPSYNC_REGION", 48 | "title": "Top 10 resolvers with maximum latency" 49 | } 50 | }, 51 | { 52 | "type": "log", 53 | "x": 0, 54 | "y": 24, 55 | "width": 24, 56 | "height": 6, 57 | "properties": { 58 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | fields ispresent(resolverArn) as isRes\n| stats count() as invocationCount by resolverArn\n| filter isRes and logType = \"Tracing\"\n| limit 10\n| sort invocationCount desc", 59 | "region": "APPSYNC_REGION", 60 | "title": "Most frequently invoked resolvers" 61 | } 62 | }, 63 | { 64 | "type": "log", 65 | "x": 0, 66 | "y": 30, 67 | "width": 24, 68 | "height": 6, 69 | "properties": { 70 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | fields ispresent(resolverArn) as isRes\n| stats count() as invocationCount by resolverArn\n| filter isRes\n| filter logType = \"Tracing\"\n| limit 10\n| sort invocationCount asc", 71 | "region": "APPSYNC_REGION", 72 | "title": "Least frequently invoked resolvers" 73 | } 74 | }, 75 | { 76 | "type": "log", 77 | "x": 0, 78 | "y": 36, 79 | "width": 24, 80 | "height": 6, 81 | "properties": { 82 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | fields ispresent(resolverArn) as isRes | stats count() as errorCount by resolverArn, logType | filter isRes and (logType = \"RequestMapping\" or logType = \"ResponseMapping\") and fieldInError | limit 10 | sort errorCount desc", 83 | "region": "APPSYNC_REGION", 84 | "title": "Resolvers with most errors in mapping templates" 85 | } 86 | }, 87 | { 88 | "type": "log", 89 | "x": 0, 90 | "y": 48, 91 | "width": 24, 92 | "height": 6, 93 | "properties": { 94 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | stats min(duration), max(duration), avg(duration) as avg_dur by concat(parentType, '/', fieldName) as fieldKey | filter logType = \"Tracing\" | limit 10 | sort avg_dur desc", 95 | "region": "APPSYNC_REGION", 96 | "title": "Field latency statistics" 97 | } 98 | }, 99 | { 100 | "type": "log", 101 | "x": 0, 102 | "y": 54, 103 | "width": 24, 104 | "height": 6, 105 | "properties": { 106 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | fields concat(parentType, '/', fieldName) as fieldKey, duration\n| filter logType = \"Tracing\"\n| sort duration desc\n| limit 10", 107 | "region": "APPSYNC_REGION", 108 | "title": "Top 10 Fields with maximum latency" 109 | } 110 | }, 111 | { 112 | "type": "log", 113 | "x": 0, 114 | "y": 60, 115 | "width": 24, 116 | "height": 6, 117 | "properties": { 118 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | stats count() as invocationCount by concat(parentType, '/', fieldName) as fieldKey\n| filter logType = \"Tracing\"\n| limit 10\n| sort invocationCount desc", 119 | "region": "APPSYNC_REGION", 120 | "title": "Most frequently invoked fields" 121 | } 122 | }, 123 | { 124 | "type": "log", 125 | "x": 0, 126 | "y": 72, 127 | "width": 24, 128 | "height": 6, 129 | "properties": { 130 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | stats count() as invocationCount by concat(parentType, '/', fieldName) as fieldKey\n| filter logType = \"Tracing\"\n| limit 10\n| sort invocationCount asc\n", 131 | "region": "APPSYNC_REGION", 132 | "title": "Least frequently invoked fields" 133 | } 134 | }, 135 | { 136 | "type": "log", 137 | "x": 0, 138 | "y": 78, 139 | "width": 24, 140 | "height": 3, 141 | "properties": { 142 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | stats min(parsing.duration), max(parsing.duration), avg(parsing.duration) as avg_dur by graphQLAPIId\n| filter logType = \"ExecutionSummary\"\n| limit 10\n| sort avg_dur desc", 143 | "region": "APPSYNC_REGION", 144 | "title": "Min, Max, Avg GraphQL Parsing Time for API" 145 | } 146 | }, 147 | { 148 | "type": "log", 149 | "x": 0, 150 | "y": 84, 151 | "width": 24, 152 | "height": 3, 153 | "properties": { 154 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | stats min(validation.duration), max(validation.duration), avg(validation.duration) as avg_dur by graphQLAPIId\n| filter logType = \"ExecutionSummary\"\n| limit 10\n| sort avg_dur desc", 155 | "region": "APPSYNC_REGION", 156 | "title": "Min, Max, Avg GraphQL Validation Time for API" 157 | } 158 | }, 159 | { 160 | "type": "log", 161 | "x": 0, 162 | "y": 90, 163 | "width": 24, 164 | "height": 6, 165 | "properties": { 166 | "query": "SOURCE '/aws/appsync/apis/GRAPHQL_API_ID' | fields @timestamp, @message\n| filter requestId = \"c93daded-04c3-40d2-a982-e2a68ff2a6d0\"\n| filter logType = \"Tracing\"\n| sort @timestamp desc", 167 | "region": "APPSYNC_REGION", 168 | "title": "Tracing information for a given requestId" 169 | } 170 | } 171 | ] 172 | } -------------------------------------------------------------------------------- /resources/metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "awsProfile": "AWS_PROFILE", 3 | "graphQLAPIId": "GRAPHQL_API_ID", 4 | "logGroupName": "/aws/appsync/apis/GRAPHQL_API_ID", 5 | "requestIds": [ 6 | "a75b5287-9ee2-486d-8d81-b6e55540a252", 7 | "4d96a00e-5fd1-4a98-9d33-0268ea7c5b6b", 8 | "8a9c248c-b89f-4c74-a8fe-cde813c46cc2", 9 | "c93daded-04c3-40d2-a982-e2a68ff2a6d0", 10 | "e7df9d64-fdc0-4332-8b38-6091c32a9897" 11 | ] 12 | } -------------------------------------------------------------------------------- /src/cloudwatch-util.ts: -------------------------------------------------------------------------------- 1 | import * as AWS from 'aws-sdk'; 2 | import moment from 'moment'; 3 | 4 | export interface LogInfo { 5 | logGroupName: string; 6 | logStreamName: string; 7 | } 8 | 9 | export const createLogGroupOrStream = async ( 10 | cwlClient: AWS.CloudWatchLogs 11 | ): Promise => { 12 | const logGroupName = 'aws-appsync-cwl-migrator'; 13 | const logStreamName = `test-${moment().format('YYYYMMDD-HH')}`; // mmss 14 | try { 15 | await cwlClient.createLogGroup({ logGroupName }).promise(); 16 | } catch (err) { 17 | const code = (err as AWS.AWSError).code; 18 | if ('ResourceAlreadyExistsException' !== code) { 19 | throw err; 20 | } 21 | console.warn(`${err.message} - ${logGroupName}`); 22 | } 23 | try { 24 | await cwlClient.createLogStream({ logGroupName, logStreamName }).promise(); 25 | } catch (err) { 26 | const code = (err as AWS.AWSError).code; 27 | if ('ResourceAlreadyExistsException' !== code) { 28 | throw err; 29 | } 30 | console.warn(`${err.message} - ${logStreamName}`); 31 | } 32 | return { 33 | logGroupName, 34 | logStreamName 35 | }; 36 | }; 37 | 38 | export const putLogEvents = ( 39 | cwlClient: AWS.CloudWatchLogs, 40 | logInfo: LogInfo, 41 | payload: string[], 42 | nextSequenceToken: string 43 | ) => { 44 | return cwlClient 45 | .putLogEvents({ 46 | logGroupName: logInfo.logGroupName, 47 | logStreamName: logInfo.logStreamName, 48 | logEvents: payload.map((message) => { 49 | const inputLogEvent: AWS.CloudWatchLogs.InputLogEvent = { 50 | timestamp: new Date().getTime(), 51 | message: message 52 | }; 53 | return inputLogEvent; 54 | }), 55 | sequenceToken: nextSequenceToken 56 | }) 57 | .promise(); 58 | }; 59 | 60 | const filterLogEventsAndRecurse = async ( 61 | cwlClient: AWS.CloudWatchLogs, 62 | logGroupName: string, 63 | filterPattern: string, 64 | nextToken: string 65 | ): Promise => { 66 | const filterLogsRequest: AWS.CloudWatchLogs.Types.FilterLogEventsRequest = { 67 | logGroupName, 68 | filterPattern: `"${filterPattern}"`, 69 | interleaved: true 70 | }; 71 | if (nextToken) { 72 | filterLogsRequest.nextToken = nextToken; 73 | } 74 | const result = await cwlClient.filterLogEvents(filterLogsRequest).promise(); 75 | const theseResults: AWS.CloudWatchLogs.FilteredLogEvents = result.events 76 | ? result.events 77 | : []; 78 | if (result.nextToken) { 79 | const downStream = await filterLogEventsAndRecurse( 80 | cwlClient, 81 | logGroupName, 82 | filterPattern, 83 | result.nextToken 84 | ); 85 | return [...theseResults, ...downStream]; 86 | } 87 | return theseResults; 88 | }; 89 | 90 | export const filterLogEvents = ( 91 | cwlClient: AWS.CloudWatchLogs, 92 | logGroupName: string, 93 | filterPattern: string 94 | ): Promise => { 95 | try { 96 | return filterLogEventsAndRecurse( 97 | cwlClient, 98 | logGroupName, 99 | filterPattern, 100 | null 101 | ); 102 | } catch (err) { 103 | console.log( 104 | `Error when filtering log events recursively - ${logGroupName}, ${filterPattern}. Ignoring. ${err}` 105 | ); 106 | return Promise.resolve([]); 107 | } 108 | }; 109 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import * as AWS from 'aws-sdk'; 2 | import { 3 | LogInfo, 4 | createLogGroupOrStream, 5 | putLogEvents, 6 | filterLogEvents 7 | } from './cloudwatch-util'; 8 | import { transform } from './transform-util'; 9 | import { sleep } from './utils'; 10 | 11 | const fs = require('fs'); 12 | 13 | const metadata = JSON.parse(fs.readFileSync('./resources/metadata.json')); 14 | 15 | const credentials = new AWS.SharedIniFileCredentials({ 16 | profile: metadata.awsProfile 17 | }); 18 | AWS.config.update({ 19 | credentials: credentials, 20 | region: 'us-west-2' 21 | }); 22 | 23 | const getNextSequenceToken = (errorMessage: string) => { 24 | return errorMessage.split(': ')[1]; 25 | }; 26 | 27 | const writeTransformedLogs = async ( 28 | cwlClient: AWS.CloudWatchLogs, 29 | logInfo: LogInfo, 30 | logEvents: any[], 31 | nextSequenceToken: string 32 | ) => { 33 | try { 34 | const result = await putLogEvents( 35 | cwlClient, 36 | logInfo, 37 | logEvents, 38 | nextSequenceToken 39 | ); 40 | const sleepTimeInMillis = 100; 41 | const errorWhileInSleep = (err) => 42 | console.error('Error occured while sleeping:', err); 43 | await sleep(sleepTimeInMillis).catch(errorWhileInSleep); // Waiting to avoid throttling 44 | return result.nextSequenceToken; 45 | } catch (err) { 46 | const awsError = err as AWS.AWSError; 47 | if ( 48 | !awsError || 49 | ('InvalidSequenceTokenException' !== awsError.code && 50 | 'DataAlreadyAcceptedException' !== awsError.code) 51 | ) { 52 | throw err; 53 | } 54 | nextSequenceToken = getNextSequenceToken(awsError.message); 55 | console.log(`NextSequenceToken: ${nextSequenceToken}`); 56 | const result = await putLogEvents( 57 | cwlClient, 58 | logInfo, 59 | logEvents, 60 | nextSequenceToken 61 | ); 62 | return result.nextSequenceToken; 63 | } 64 | }; 65 | 66 | (async () => { 67 | try { 68 | const cwlClient = new AWS.CloudWatchLogs(); 69 | const logInfo = await createLogGroupOrStream(cwlClient); 70 | 71 | const filterLogsPromises: Promise< 72 | AWS.CloudWatchLogs.FilteredLogEvent[] 73 | >[] = metadata.requestIds.map((requestId) => 74 | filterLogEvents(cwlClient, metadata.logGroupName, requestId) 75 | ); 76 | const filterLogsResponses = await Promise.all(filterLogsPromises); 77 | let nextSequenceToken = null; 78 | for (let index = 0; index < filterLogsResponses.length; index++) { 79 | const response = filterLogsResponses[index]; 80 | if (response) { 81 | nextSequenceToken = await writeTransformedLogs( 82 | cwlClient, 83 | logInfo, 84 | response.map((event) => 85 | transform(event.message, metadata.graphQLAPIId) 86 | ), 87 | nextSequenceToken 88 | ); 89 | console.log( 90 | `Ingested the transformed logs for requestId=${ 91 | metadata.requestIds[index] 92 | }. Next sequenceToken: ${nextSequenceToken}` 93 | ); 94 | } 95 | } 96 | } catch (err) { 97 | console.error(err); 98 | } 99 | })(); 100 | -------------------------------------------------------------------------------- /src/transform-util.ts: -------------------------------------------------------------------------------- 1 | import papa from 'papaparse'; 2 | import { breakStringOnFirstOccurence } from './utils'; 3 | 4 | const pathResolverMap: { [key: string]: string } = {}; 5 | 6 | const getFieldKey = (parentType: string, fieldName: string) => { 7 | return `${parentType}/${fieldName}`; 8 | }; 9 | 10 | const getFieldInfo = (resolverArn: string) => { 11 | if (!resolverArn) { 12 | return { 13 | parentType: '', 14 | fieldName: '' 15 | }; 16 | } 17 | 18 | // An Example of a resolverArn: 19 | // "arn:aws:appsync:us-west-2:1234567890:apis/abcdefghijklmno/types/ParentType/fields/fieldName" 20 | const parentFieldSubPath = resolverArn.split('/types/')[1]; 21 | const parts = parentFieldSubPath.split('/fields/'); 22 | return { 23 | parentType: parts[0], 24 | fieldName: parts[1] 25 | }; 26 | }; 27 | 28 | const getPathArray = (pathString: string) => { 29 | const csvPath = pathString.replace(/^\[(.+)\]$/, '$1'); 30 | return papa.parse(csvPath, { delimiter: ', ' }).data; 31 | }; 32 | 33 | const getMappingTemplate = (json: any) => { 34 | const oldKey = 'mappingTemplateType'; 35 | const newKey = 'logType'; 36 | const value = json[oldKey].replace(/\s/g, ''); 37 | delete Object.assign(json, { [newKey]: value })[oldKey]; 38 | const pathArray = getPathArray(json.path); 39 | if (pathArray.length > 0) { 40 | json.path = pathArray[0]; 41 | } 42 | const fieldInfo = getFieldInfo(json.resolverArn); 43 | json.parentType = fieldInfo.parentType; 44 | json.fieldName = fieldInfo.fieldName; 45 | const key = getFieldKey(fieldInfo.parentType, fieldInfo.fieldName); 46 | pathResolverMap[key] = json.resolverArn; 47 | return JSON.stringify(json); 48 | }; 49 | 50 | const getTracingInfo = (json: any) => { 51 | const key = getFieldKey(json.parentType, json.fieldName); 52 | json.resolverArn = pathResolverMap[key]; 53 | json.logType = 'Tracing'; 54 | return JSON.stringify(json); 55 | }; 56 | 57 | const getExecutionSummary = ( 58 | message: string, 59 | graphQLAPIId: string, 60 | requestId: string 61 | ) => { 62 | const parts = breakStringOnFirstOccurence(message, ':'); 63 | const jsonMessage = parts.right; 64 | if (jsonMessage === undefined) { 65 | return message; 66 | } 67 | const json = JSON.parse(jsonMessage); 68 | json.logType = 'ExecutionSummary'; 69 | json.requestId = requestId; 70 | json.graphQLAPIId = graphQLAPIId; 71 | 72 | return JSON.stringify(json); 73 | }; 74 | 75 | export const transform = (message: string, graphQLAPIId: string) => { 76 | const parts = breakStringOnFirstOccurence(message, ' '); 77 | const requestId = parts.left; 78 | const logContent = parts.right; 79 | if (logContent === undefined) { 80 | return message; 81 | } 82 | if (logContent.startsWith('{')) { 83 | const json = JSON.parse(logContent); 84 | json.requestId = requestId; 85 | json.graphQLAPIId = graphQLAPIId; 86 | 87 | if (json.context !== undefined) { 88 | return getMappingTemplate(json); 89 | } 90 | if (json.parentType) { 91 | return getTracingInfo(json); 92 | } 93 | return message; 94 | } 95 | if (logContent.startsWith('Execution Summary:')) { 96 | return getExecutionSummary(message, graphQLAPIId, requestId); 97 | } 98 | return message; 99 | }; 100 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import { setTimeout } from 'timers'; 2 | 3 | export const breakStringOnFirstOccurence = ( 4 | message: string, 5 | delimiter: string 6 | ) => { 7 | return { 8 | left: message.substr(0, message.indexOf(delimiter)), 9 | right: message.substr(message.indexOf(delimiter) + 1) 10 | }; 11 | }; 12 | 13 | export const delayedInvoke = ( 14 | waitTimeInMillis: number, 15 | callback: () => void 16 | ) => { 17 | setTimeout(() => { 18 | console.log('Waiting for %s millis', waitTimeInMillis); 19 | callback(); 20 | }, waitTimeInMillis); 21 | }; 22 | 23 | export const sleep = (timeInMillis: number) => { 24 | return new Promise((resolve) => 25 | setTimeout(() => { 26 | console.log(`Sleeping for ${timeInMillis} millis`); 27 | resolve(); 28 | }, timeInMillis) 29 | ); 30 | }; 31 | 32 | export const backoff = (fn, retries: number, delay: number) => { 33 | fn.catch((err) => 34 | retries > 1 35 | ? sleep(delay).then(() => backoff(fn, retries - 1, delay * 2)) 36 | : Promise.reject(err) 37 | ); 38 | }; 39 | 40 | export const retryWithFixedDelay = (fn, retries: number, delay: number) => { 41 | return fn() 42 | .then((result) => { 43 | return Promise.resolve(result); 44 | }) 45 | .catch((err) => { 46 | return retries > 0 47 | ? sleep(delay).then(() => retryWithFixedDelay(fn, retries - 1, delay)) 48 | : Promise.reject(err); 49 | }); 50 | }; 51 | 52 | export const promptAndExecute = (fn, msg: string) => { 53 | return new Promise((resolve, reject) => { 54 | console.log(msg); 55 | process.stdin.once('data', () => { 56 | try { 57 | resolve(fn()); 58 | } catch (err) { 59 | reject(err); 60 | } finally { 61 | (process.stdin as any).unref(); 62 | } 63 | }); 64 | }); 65 | }; 66 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "allowJs": false, 6 | "sourceMap": true, 7 | "esModuleInterop": true, 8 | "outDir": "lib", 9 | "lib": [ 10 | "es2015", 11 | "es2016.array.include", 12 | "esnext.asynciterable", 13 | "dom" 14 | ] 15 | }, 16 | "include": [ 17 | "src/**/*.ts" 18 | ], 19 | "exclude": [ 20 | "node_modules", 21 | "lib" 22 | ] 23 | } -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "class-name": true, 4 | "curly": true, 5 | "eofline": false, 6 | "forin": true, 7 | "indent": false, 8 | "label-position": true, 9 | "max-line-length": [ 10 | true, 11 | 150 12 | ], 13 | "no-arg": true, 14 | "no-bitwise": true, 15 | "no-console": false, 16 | "no-construct": true, 17 | "no-constructor-vars": false, 18 | "no-debugger": true, 19 | "no-duplicate-variable": true, 20 | "no-empty": true, 21 | "no-eval": true, 22 | "no-string-literal": true, 23 | "no-switch-case-fall-through": true, 24 | "no-trailing-whitespace": true, 25 | "no-unused-expression": true, 26 | "no-unused-variable": false, 27 | "no-use-before-declare": true, 28 | "no-var-requires": false, 29 | "one-line": [ 30 | true, 31 | "check-open-brace", 32 | "check-catch", 33 | "check-else", 34 | "check-whitespace" 35 | ], 36 | "semicolon": false, 37 | "triple-equals": [ 38 | true, 39 | "allow-null-check" 40 | ], 41 | "typedef": [ 42 | true, 43 | "callSignature", 44 | "indexSignature", 45 | "parameter", 46 | "propertySignature", 47 | "variableDeclarator", 48 | "memberVariableDeclarator" 49 | ], 50 | "use-strict": false, 51 | "variable-name": [ 52 | true, 53 | "allow-leading-underscore" 54 | ], 55 | "whitespace": [ 56 | true, 57 | "check-branch", 58 | "check-decl", 59 | "check-operator", 60 | "check-separator", 61 | "check-type" 62 | ], 63 | "quotemark": [ 64 | true, 65 | "single" 66 | ] 67 | } 68 | } --------------------------------------------------------------------------------