├── .github └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.txt ├── NOTICE.txt ├── README.md ├── deployment ├── build-s3-dist.sh ├── manifest-generator │ ├── app.js │ └── package.json ├── real-time-iot-device-monitoring-with-kinesis.yaml └── run-unit-tests.sh └── source ├── custom-resource ├── index.js ├── lib │ ├── kinesis-helper.js │ ├── metrics-helper.js │ ├── s3-bucket-encryption-helper.js │ └── website-helper.js └── package.json ├── demo └── send-messages.sh ├── update_ddb_from_stream └── update_ddb_from_stream.py └── web_site ├── css ├── custom.css └── jquery-jvectormap-2.0.3.css ├── favicon.ico ├── index.html └── js ├── app-variables.js.example ├── aws-cognito-sdk.min.js └── dash.js /.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 | **/dist 2 | **/.zip 3 | **/.DS_Store 4 | /dev/**/* 5 | node_modules/ 6 | package-lock.json -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [1.1.1] - 2019-11-19 8 | ### Added 9 | - CHANGELOG templated file 10 | - Added licenses info in NOTICE.txt for aws-sdk, boto3, amazon-cognito-identity, aws-cognito-sdk, node-uuid, underscore and font-awesome 11 | 12 | ### Updated 13 | - The Solution to Node.js 12.x and Python 3.8 14 | - The license information to Apache 2.0 License 15 | 16 | ### Deleted 17 | - Third party sources (e.g., bootstrap, chart.js, jquery, font-awesome). They will be added through build scripts. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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/awslabs/real-time-iot-device-monitoring-with-kinesis/issues), or [recently closed](https://github.com/awslabs/real-time-iot-device-monitoring-with-kinesis/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/awslabs/real-time-iot-device-monitoring-with-kinesis/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/awslabs/real-time-iot-device-monitoring-with-kinesis/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. -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | Real Time IoT Device Monitoring with Kinesis Analytics 2 | 3 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except 5 | in compliance with the License. A copy of the License is located at http://www.apache.org/licenses/ 6 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, 7 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. See the License for the 8 | specific language governing permissions and limitations under the License. 9 | 10 | ==THIRD PARTY LICENSES== 11 | 12 | ** bootstrap (v3.3.7); version 3.3.6 -- https://github.com/twbs/bootstrap 13 | Copyright 2011-2015 Twitter, Inc. 14 | 15 | The MIT License (MIT) 16 | 17 | Copyright (c) 2011-2016 Twitter, Inc. 18 | 19 | Permission is hereby granted, free of charge, to any person obtaining a copy 20 | of this software and associated documentation files (the "Software"), to deal 21 | in the Software without restriction, including without limitation the rights 22 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 23 | copies of the Software, and to permit persons to whom the Software is 24 | furnished to do so, subject to the following conditions: 25 | 26 | The above copyright notice and this permission notice shall be included in 27 | all copies or substantial portions of the Software. 28 | 29 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 30 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 31 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 32 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 33 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 34 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 35 | THE SOFTWARE. 36 | 37 | ----- 38 | 39 | ** Moment; version 2.20.1 -- https://github.com/moment/moment 40 | Copyright (c) JS Foundation and other contributors 41 | 42 | Copyright (c) JS Foundation and other contributors 43 | 44 | Permission is hereby granted, free of charge, to any person 45 | obtaining a copy of this software and associated documentation 46 | files (the "Software"), to deal in the Software without 47 | restriction, including without limitation the rights to use, 48 | copy, modify, merge, publish, distribute, sublicense, and/or sell 49 | copies of the Software, and to permit persons to whom the 50 | Software is furnished to do so, subject to the following 51 | conditions: 52 | 53 | The above copyright notice and this permission notice shall be 54 | included in all copies or substantial portions of the Software. 55 | 56 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 57 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 58 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 59 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 60 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 61 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 62 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 63 | OTHER DEALINGS IN THE SOFTWARE. 64 | 65 | ----- 66 | 67 | ** jquery.min; version 2.2.4 -- https://www.jquery.com 68 | Copyright jQuery Foundation and other contributors, https://jquery.org/ This software consists of voluntary contributions made by many 69 | individuals. 70 | 71 | Copyright jQuery Foundation and other contributors, https://jquery.org/ 72 | 73 | This software consists of voluntary contributions made by many individuals. For 74 | exact contribution history, see the revision history available at 75 | https://github.com/jquery/jquery-ui 76 | 77 | The following license applies to all parts of this software except as 78 | documented below: 79 | 80 | ==== 81 | Permission is hereby granted, free of charge, to any person obtaining a copy of 82 | this software and associated documentation files (the "Software"), to deal in 83 | the Software without restriction, including without limitation the rights to 84 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 85 | of the Software, and to permit persons to whom the Software is furnished to do 86 | so, subject to the following conditions: 87 | 88 | The above copyright notice and this permission notice shall be included in all 89 | copies or substantial portions of the Software. 90 | 91 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 92 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 93 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 94 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 95 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 96 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 97 | SOFTWARE. 98 | ==== 99 | Copyright and related rights for sample code are waived via CC0. Sample code is 100 | defined as all source code contained within the demos directory. 101 | 102 | CC0: http://creativecommons.org/publicdomain/zero/1.0/ 103 | 104 | ==== 105 | 106 | All files located in the node_modules and external directories are externally 107 | maintained libraries used by this software which have their own licenses; we 108 | recommend you read them, as their terms may differ from the terms above. 109 | 110 | ----- 111 | 112 | ** Chart.js; version 2.3.0 -- https://github.com/chartjs/Chart.js 113 | /*! 114 | * Chart.js 115 | * http://chartjs.org/ 116 | * Version: 2.3.0 117 | * 118 | * Copyright 2016 Nick Downie 119 | * Released under the MIT license 120 | * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md 121 | */ 122 | 123 | The MIT License (MIT) 124 | 125 | Copyright (c) 2018 Chart.js Contributors 126 | 127 | Permission is hereby granted, free of charge, to any person obtaining a copy of 128 | this software and associated documentation files (the "Software"), to deal in 129 | the Software without restriction, including without limitation the rights to 130 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 131 | of the Software, and to permit persons to whom the Software is furnished to do 132 | so, subject to the following conditions: 133 | 134 | The above copyright notice and this permission notice shall be included in all 135 | copies or substantial portions of the Software. 136 | 137 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 138 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 139 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 140 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 141 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 142 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 143 | SOFTWARE. 144 | 145 | ----- 146 | 147 | ** AWS SDK under the Apache License Version 2.0 148 | 149 | ----- 150 | 151 | ** Boto3 AWS SDK under the Apache License Version 2.0 152 | 153 | ----- 154 | 155 | ** amazon-cognito-identity under the Apache License Version 2.0 156 | 157 | ----- 158 | 159 | ** aws-cognito-sdk under the Apache License Version 2.0 160 | 161 | ----- 162 | 163 | ** node-uuid under the Massachusetts Institute of Technology (MIT) license 164 | 165 | ----- 166 | 167 | ** underscore under the Massachusetts Institute of Technology (MIT) license 168 | 169 | ----- 170 | 171 | ** font-awesome under the Massachusetts Institute of Technology (MIT) license -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deprecation Notice 2 | 3 | This AWS Solution has been archived and is no longer maintained by AWS. To discover other solutions, please visit the [AWS Solutions Library](https://aws.amazon.com/solutions/). 4 | 5 | # Real Time IoT Device Monitoring with Kinesis Analytics 6 | AWS Solution for analyzing IoT Device Connectivity using Kinesis Analytics 7 | 8 | ## OS/Python Environment Setup 9 | ```bash 10 | sudo apt-get update 11 | sudo apt-get install install zip wget gawk sed -y 12 | ``` 13 | 14 | ## Building Lambda Package 15 | ```bash 16 | cd deployment/ 17 | ./build-s3-dist.sh source-bucket-base-name solution-name solution-version 18 | ``` 19 | source-bucket-base-name should be the base name for the S3 bucket location where the template will source the Lambda code from. 20 | The template will append '-[region_name]' to this value. 21 | For example: ./build-s3-dist.sh solutions 22 | The template will then expect the source code to be located in the solutions-[region_name] bucket 23 | 24 | ## CF template and Lambda function 25 | The CF Template is located in `deployment/global-s3-assets` directory. The Lambda function is located in `deployment/regional-s3-assets` directory. 26 | 27 | ## Collection of operational metrics 28 | 29 | This solution collects anonymous operational metrics to help AWS improve the quality of features of the solution. For more information, including how to disable this capability, please see the [implementation guide](https://docs.aws.amazon.com/solutions/latest/real-time-iot-device-monitoring-with-kinesis/appendix-c.html). 30 | 31 | *** 32 | 33 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 34 | 35 | Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 36 | 37 | http://www.apache.org/licenses/ 38 | 39 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and limitations under the License. 40 | -------------------------------------------------------------------------------- /deployment/build-s3-dist.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # This assumes all of the OS-level configuration has been completed and git repo has already been cloned 4 | # 5 | # This script should be run from the repo's deployment directory 6 | # cd deployment 7 | # ./build-s3-dist.sh source-bucket-base-name trademarked-solution-name version-code 8 | # 9 | # Parameters: 10 | # - source-bucket-base-name: Name for the S3 bucket location where the template will source the Lambda 11 | # code from. The template will append '-[region_name]' to this bucket name. 12 | # For example: ./build-s3-dist.sh solutions my-solution v1.0.0 13 | # The template will then expect the source code to be located in the solutions-[region_name] bucket 14 | # 15 | # - trademarked-solution-name: name of the solution for consistency 16 | # 17 | # - version-code: version of the solution 18 | 19 | set -e 20 | 21 | # Check to see if input has been provided: 22 | if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then 23 | echo "Please provide the base source bucket name, trademark approved solution name and version where the lambda code will eventually reside." 24 | echo "For example: ./build-s3-dist.sh solutions trademarked-solution-name v1.0.0" 25 | exit 1 26 | fi 27 | 28 | # Get reference for all important folders 29 | template_dir="$PWD" 30 | template_dist_dir="$template_dir/global-s3-assets" 31 | build_dist_dir="$template_dir/regional-s3-assets" 32 | source_dir="$template_dir/../source" 33 | 34 | echo "------------------------------------------------------------------------------" 35 | echo "[Init] Clean old dist folders" 36 | echo "------------------------------------------------------------------------------" 37 | echo "rm -rf $template_dist_dir" 38 | rm -rf $template_dist_dir 39 | echo "mkdir -p $template_dist_dir" 40 | mkdir -p $template_dist_dir 41 | echo "rm -rf $build_dist_dir" 42 | rm -rf $build_dist_dir 43 | echo "mkdir -p $build_dist_dir" 44 | mkdir -p $build_dist_dir 45 | 46 | echo "------------------------------------------------------------------------------" 47 | echo "[Packaging] Global Assets: Cloudformation Templates" 48 | echo "------------------------------------------------------------------------------" 49 | echo "copy yaml templates and rename" 50 | cp $template_dir/real-time-iot-device-monitoring-with-kinesis.yaml $template_dist_dir/ 51 | cd $template_dist_dir 52 | # Rename all *.yaml to *.template 53 | for f in *.yaml; do 54 | mv -- "$f" "${f%.yaml}.template" 55 | done 56 | 57 | echo "Updating code source bucket name in template with $1" 58 | bucket_name="s/%%BUCKET_NAME%%/$1/g" 59 | echo "sed -i -e $bucket_name $template_dist_dir/*.template" 60 | sed -i -e $bucket_name $template_dist_dir/*.template 61 | 62 | echo "Updating code source solution name in template with $2" 63 | solution_name="s/%%SOLUTION_NAME%%/$2/g" 64 | echo "sed -i -e $solution_name $template_dist_dir/*.template" 65 | sed -i -e $solution_name $template_dist_dir/*.template 66 | 67 | echo "Updating code source version in template with $3" 68 | s_version="s/%%VERSION%%/$3/g" 69 | echo "sed -i -e $s_version $template_dist_dir/*.template" 70 | sed -i -e $s_version $template_dist_dir/*.template 71 | 72 | echo "------------------------------------------------------------------------------" 73 | echo "[Packaging] Region Assets: Source" 74 | echo "------------------------------------------------------------------------------" 75 | 76 | # Build Custom Resource 77 | echo "Building CFN custom resource helper Lambda function" 78 | cd $source_dir/custom-resource 79 | npm install 80 | npm run build 81 | npm run zip 82 | cp ./dist/custom-resource-helper.zip $build_dist_dir/custom-resource-helper.zip 83 | rm -rf dist 84 | rm -rf node_modules 85 | 86 | # Build UpdateDDBLambda 87 | echo "Building UpdateDDBLambda" 88 | cd $source_dir/update_ddb_from_stream 89 | zip -r $build_dist_dir/update_ddb_from_stream.zip * 90 | 91 | # Build Demo script 92 | echo "Building Demo Script" 93 | cd $source_dir/demo 94 | zip -r $build_dist_dir/demo.zip * 95 | 96 | echo "Getting third party libraries for web site" 97 | cd $source_dir/web_site 98 | npm install bootstrap@3.3.7 99 | cp node_modules/bootstrap/dist/css/bootstrap.min.css css/ 100 | cp node_modules/bootstrap/dist/js/bootstrap.min.js js/ 101 | 102 | npm install font-awesome 103 | cp -r node_modules/font-awesome/fonts ./ 104 | cp node_modules/font-awesome/css/font-awesome.min.css css/ 105 | 106 | npm install chart.js 107 | cp node_modules/chart.js/dist/Chart.min.js js/ 108 | 109 | npm install amazon-cognito-identity-js 110 | cp node_modules/amazon-cognito-identity-js/dist/amazon-cognito-identity.min.js js/ 111 | 112 | npm install jquery 113 | cp node_modules/jquery/dist/jquery.min.js js/ 114 | 115 | rm -rf node_modules 116 | rm package-lock.json 117 | 118 | echo "Copying web site content to $build_dist_dir" 119 | cd $source_dir 120 | cp -r web_site $build_dist_dir/ 121 | 122 | echo "Generating web site manifest" 123 | cd $template_dir/manifest-generator 124 | npm install 125 | node app.js --target $build_dist_dir/web_site --output $build_dist_dir/web-site-manifest.json 126 | 127 | cd $template_dir 128 | 129 | echo "Completed building distribution" 130 | -------------------------------------------------------------------------------- /deployment/manifest-generator/app.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/ * 8 | * * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | const fs = require('fs'); 21 | const path = require('path'); 22 | const args = require('minimist')(process.argv.slice(2)); 23 | 24 | let getFileList = function(path) { 25 | let fileInfo; 26 | let filesFound; 27 | let fileList = []; 28 | 29 | filesFound = fs.readdirSync(path); 30 | for (let i = 0; i < filesFound.length; i++) { 31 | fileInfo = fs.lstatSync([path, filesFound[i]].join('/')); 32 | if (fileInfo.isFile()) { 33 | fileList.push(filesFound[i]); 34 | } 35 | 36 | if (fileInfo.isDirectory()) { 37 | console.log([path, filesFound[i]].join('/')); 38 | } 39 | } 40 | 41 | return fileList; 42 | }; 43 | 44 | // List all files in a directory in Node.js recursively in a synchronous fashion 45 | let walkSync = function(dir, filelist) { 46 | // let filelist = []; //getFileList('./temp/site'); 47 | let files = fs.readdirSync(dir); 48 | filelist = filelist || []; 49 | files.forEach(function(file) { 50 | if (fs.statSync(path.join(dir, file)).isDirectory()) { 51 | filelist = walkSync(path.join(dir, file), filelist); 52 | } else { 53 | filelist.push(path.join(dir, file)); 54 | } 55 | }); 56 | 57 | return filelist; 58 | }; 59 | 60 | let _filelist = []; 61 | let _manifest = { 62 | files: [] 63 | }; 64 | 65 | if (!args.hasOwnProperty('target')) { 66 | console.log('--target parameter missing. This should be the target directory containing content for the manifest.'); 67 | process.exit(1); 68 | } 69 | 70 | if (!args.hasOwnProperty('output')) { 71 | console.log('--ouput parameter missing. This should be the out directory where the manifest file will be generated.'); 72 | process.exit(1); 73 | } 74 | 75 | console.log(`Generating a manifest file ${args.output} for directory ${args.target}`); 76 | 77 | walkSync(args.target, _filelist); 78 | 79 | for (let i = 0; i < _filelist.length; i++) { 80 | _manifest.files.push(_filelist[i].replace(`${args.target}/`, '')); 81 | }; 82 | 83 | fs.writeFileSync(args.output, JSON.stringify(_manifest, null, 4)); 84 | console.log(`Manifest file ${args.output} generated.`); -------------------------------------------------------------------------------- /deployment/manifest-generator/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "manifest-generator", 3 | "version": "0.0.0", 4 | "private": true, 5 | "description": "Helper utility to create web site manifest for deployment", 6 | "main": "app.js", 7 | "author": { 8 | "name": "aws-solutions-builder" 9 | }, 10 | "dependencies": { 11 | "minimist": "*" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /deployment/real-time-iot-device-monitoring-with-kinesis.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: "2010-09-09" 2 | Description: "(SO0039) - Real-Time IoT Device Monitoring with Kinesis Analytics: Analyze IoT Device Connectivity using Kinesis Analytics, Version %%VERSION%%" 3 | Parameters: 4 | UserName: 5 | Description: The username of the user you want to create in Amazon Cognito. 6 | Type: String 7 | AllowedPattern: "^(?=\\s*\\S).*$" 8 | ConstraintDescription: " cannot be empty" 9 | MinLength: 1 10 | UserEmail: 11 | Type: String 12 | Description: Email address for dashboard user. After successfully launching this 13 | solution, you will receive an email with instructions to log in. 14 | AllowedPattern: ^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$ 15 | MinLength: 1 16 | IoTTopicName: 17 | Type: String 18 | MinLength: 1 19 | Default: "iot_device_analytics" 20 | Description: "IoT Topic Name that your devices will send messages to." 21 | 22 | Metadata: 23 | AWS::CloudFormation::Interface: 24 | ParameterGroups: 25 | - Label: 26 | default: Cognito User for Access to the Dashboard 27 | Parameters: 28 | - UserName 29 | - UserEmail 30 | - Label: 31 | default: IoT Settings 32 | Parameters: 33 | - IoTTopicName 34 | ParameterLabels: 35 | UserName: 36 | default: "User Name" 37 | UserEmail: 38 | default: "User Email Address" 39 | IoTTopicName: 40 | default: "IoT Topic to monitor" 41 | 42 | Mappings: 43 | SourceCode: 44 | General: 45 | S3Bucket: '%%BUCKET_NAME%%' 46 | KeyPrefix: '%%SOLUTION_NAME%%/%%VERSION%%' 47 | LogPrefix: '%%SOLUTION_NAME%%/' 48 | KinesisAnalyticsApp: 49 | Outputs: 50 | FireHoseStreamName: PROCESSED_METRICS_S3_STREAM 51 | LambdaStreamName: UPDATE_DDB_LAMBDA_STREAM 52 | DDB: 53 | Scaling: 54 | ReadTargetUtilization: 70 55 | ReadCapacityMin: 1 56 | ReadCapacityMax: 100 57 | WriteTargetUtilization: 50 58 | WriteCapacityMin: 5 59 | WriteCapacityMax: 1000 60 | Solution: 61 | Data: 62 | ID: SO0039 63 | Version: '%%VERSION%%' 64 | SendAnonymousUsageData: 'True' 65 | 66 | Resources: 67 | IoTMetricsLogGroup: 68 | Type: AWS::Logs::LogGroup 69 | Properties: 70 | RetentionInDays: 7 71 | 72 | IotMetricsLogStream: 73 | Type: AWS::Logs::LogStream 74 | Properties: 75 | LogGroupName: !Ref IoTMetricsLogGroup 76 | 77 | IoTTopicRule: 78 | Type: AWS::IoT::TopicRule 79 | Properties: 80 | TopicRulePayload: 81 | Description: 'Send IoT Device data in raw format to Kinesis Analytics' 82 | AwsIotSqlVersion: '2016-03-23' 83 | RuleDisabled: 'false' 84 | Sql: !Sub 'SELECT *, parse_time("yyyy-MM-dd HH:mm:ss", timestamp()) as ts FROM "${IoTTopicName}"' 85 | Actions: 86 | - Firehose: 87 | DeliveryStreamName: !Ref RawMetricsDeliveryStream 88 | RoleArn: !Sub '${IoTTopicRuleRole.Arn}' 89 | Separator: "\n" 90 | 91 | IoTTopicRuleRole: 92 | Type: AWS::IAM::Role 93 | Properties: 94 | AssumeRolePolicyDocument: 95 | Version: '2012-10-17' 96 | Statement: 97 | - Effect: Allow 98 | Principal: 99 | Service: 100 | - 'iot.amazonaws.com' 101 | Action: 102 | - 'sts:AssumeRole' 103 | Path: / 104 | Policies: 105 | 106 | # Posts to RawMetricsDeliveryStream 107 | - PolicyName: 'IoTTopicRulePolicy' 108 | PolicyDocument: 109 | Version: '2012-10-17' 110 | Statement: 111 | Effect: Allow 112 | Action: 113 | - firehose:DescribeDeliveryStream 114 | - firehose:ListDeliveryStreams 115 | - firehose:PutRecord 116 | - firehose:PutRecordBatch 117 | Resource: !Sub '${RawMetricsDeliveryStream.Arn}' 118 | 119 | RawMetricsDeliveryStream: 120 | Type: AWS::KinesisFirehose::DeliveryStream 121 | Properties: 122 | S3DestinationConfiguration: 123 | BucketARN: !GetAtt RawMetricsBucket.Arn 124 | BufferingHints: 125 | IntervalInSeconds: 60 126 | SizeInMBs: 10 127 | CloudWatchLoggingOptions: 128 | Enabled: true 129 | LogGroupName: !Ref IoTMetricsLogGroup 130 | LogStreamName: 'RawMetricsS3Delivery' 131 | CompressionFormat: 'UNCOMPRESSED' 132 | EncryptionConfiguration: 133 | NoEncryptionConfig: 'NoEncryption' 134 | Prefix: !FindInMap 135 | - SourceCode 136 | - General 137 | - LogPrefix 138 | RoleARN: !GetAtt RawMetricsDeliveryStreamRole.Arn 139 | 140 | RawMetricsBucket: 141 | DeletionPolicy: Retain 142 | Type: AWS::S3::Bucket 143 | Properties: 144 | BucketEncryption: 145 | ServerSideEncryptionConfiguration: 146 | - ServerSideEncryptionByDefault: 147 | SSEAlgorithm: AES256 148 | PublicAccessBlockConfiguration: 149 | BlockPublicAcls: true 150 | BlockPublicPolicy: true 151 | IgnorePublicAcls: true 152 | RestrictPublicBuckets: true 153 | LoggingConfiguration: 154 | DestinationBucketName: !Ref LogsBucket 155 | LogFilePrefix: raw-metrics-bucket/ 156 | LifecycleConfiguration: 157 | Rules: 158 | - Id: ExpirationRule 159 | Status: Enabled 160 | ExpirationInDays: '7' 161 | Metadata: 162 | cfn_nag: 163 | rules_to_suppress: 164 | - id: W51 165 | reason: "This is a private bucket. Does not require bucket policy" 166 | 167 | RawMetricsDeliveryStreamRole: 168 | Type: AWS::IAM::Role 169 | Properties: 170 | AssumeRolePolicyDocument: 171 | Version: '2012-10-17' 172 | Statement: 173 | - Effect: Allow 174 | Principal: 175 | Service: 176 | - 'firehose.amazonaws.com' 177 | Action: 178 | - 'sts:AssumeRole' 179 | Path: / 180 | Policies: 181 | 182 | # Puts objects in RawMetricsBucket 183 | - PolicyName: 'RawMetricsS3UploadPolicy' 184 | PolicyDocument: 185 | Version: '2012-10-17' 186 | Statement: 187 | - Effect: Allow 188 | Action: 189 | - s3:AbortMultipartUpload 190 | - s3:GetBucketLocation 191 | - s3:GetObject 192 | - s3:PutObject 193 | - s3:ListBucket 194 | - s3:ListBucketMultipartUploads 195 | Resource: 196 | - !Sub '${RawMetricsBucket.Arn}' 197 | - !Sub '${RawMetricsBucket.Arn}/' 198 | - !Sub '${RawMetricsBucket.Arn}/*' 199 | 200 | # Write to CloudWatch 201 | - PolicyName: RawMetricsDeliveryStreamLogging 202 | PolicyDocument: 203 | Version: '2012-10-17' 204 | Statement: 205 | - Effect: Allow 206 | Action: 207 | - logs:CreateLogGroup 208 | - logs:CreateLogStream 209 | - logs:PutDestination 210 | - logs:PutLogEvents 211 | Resource: 212 | !Join 213 | - '' 214 | - - 'arn:aws:logs:' 215 | - !Ref AWS::Region 216 | - ':' 217 | - !Ref AWS::AccountId 218 | - ':log-group:*' 219 | Metadata: 220 | cfn_nag: 221 | rules_to_suppress: 222 | - id: W11 223 | reason: "The wildcard action in the logs policy is required" 224 | 225 | KinesisAnalyticsApp: 226 | Type: AWS::KinesisAnalytics::Application 227 | Properties: 228 | ApplicationDescription: 'IOT Device Monitoring Analysis' 229 | ApplicationCode: !Sub 230 | - | 231 | -- Create a common format to be used for all the different metrics for IoT device monitoring 232 | CREATE OR REPLACE STREAM FAN_OUT_STREAM 233 | ( eventTimeStamp TIMESTAMP, computationType VARCHAR(128), category VARCHAR(128), subcategory INTEGER, unit VARCHAR(128), unitValue DOUBLE); 234 | 235 | -- 1. Create an output stream, which is used to send unique number of connected IoT devices to the destination 236 | CREATE OR REPLACE PUMP connected_device_pump AS INSERT INTO FAN_OUT_STREAM 237 | SELECT current_timestamp as eventTimeStamp, 'ConnectedDevicesCount', 'None', 0, 'Count', * FROM ( 238 | SELECT STREAM * FROM TABLE(COUNT_DISTINCT_ITEMS_TUMBLING( 239 | CURSOR(SELECT STREAM * FROM source_sql_stream_001), 240 | 'device', 241 | 60 242 | ) 243 | ) 244 | ); 245 | 246 | -- 2. Max of the data point (temp) per connected device 247 | CREATE OR REPLACE PUMP per_device_max_pump AS INSERT INTO FAN_OUT_STREAM 248 | SELECT STREAM 249 | STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE) AS eventTimeStamp, 250 | 'PerDeviceMaxTemp', 251 | "device", 252 | 0, 253 | 'Maximum', 254 | MAX("temp") AS max_value 255 | FROM source_sql_stream_001 256 | GROUP BY "device", STEP(source_sql_stream_001.rowtime BY INTERVAL '1' MINUTE), STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE); 257 | 258 | -- 3. Min of the data point (temp) per connected device 259 | CREATE OR REPLACE PUMP per_device_min_pump AS INSERT INTO FAN_OUT_STREAM 260 | SELECT STREAM 261 | STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE) AS eventTimeStamp, 262 | 'PerDeviceMinTemp', 263 | "device", 264 | 0, 265 | 'Minimum', 266 | MIN("temp") AS min_value 267 | FROM source_sql_stream_001 268 | GROUP BY "device", STEP(source_sql_stream_001.rowtime BY INTERVAL '1' MINUTE), STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE); 269 | 270 | -- 4. Avg of the data point (temp) per connected device 271 | CREATE OR REPLACE PUMP per_device_avg_pump AS INSERT INTO FAN_OUT_STREAM 272 | SELECT STREAM 273 | STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE) AS eventTimeStamp, 274 | 'PerDeviceAvgTemp', 275 | "device", 276 | 0, 277 | 'Average', 278 | AVG("temp") AS avg_value 279 | FROM source_sql_stream_001 280 | GROUP BY "device", STEP(source_sql_stream_001.rowtime BY INTERVAL '1' MINUTE), STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE); 281 | 282 | -- Setup for Anomaly detection 283 | CREATE OR REPLACE STREAM temp_stream (temp INTEGER, device varchar(4), anomaly_score DOUBLE); 284 | 285 | CREATE OR REPLACE PUMP temp_pump AS INSERT INTO temp_stream 286 | SELECT STREAM "temp", "device", anomaly_score 287 | FROM TABLE(RANDOM_CUT_FOREST( 288 | CURSOR(SELECT STREAM * FROM source_sql_stream_001) 289 | )); 290 | 291 | -- 5. Anomaly detection on the value sent (temp) 292 | CREATE OR REPLACE PUMP anomaly_pump AS INSERT INTO FAN_OUT_STREAM 293 | SELECT STREAM 294 | STEP(temp_stream.rowtime BY INTERVAL '1' MINUTE) as eventTimeStamp, 295 | 'DeviceTempAnomalyScore', 296 | device, 297 | temp, 298 | 'AnomalyScore', 299 | anomaly_score 300 | FROM temp_stream 301 | ORDER BY STEP(temp_stream.rowtime BY INTERVAL '1' MINUTE), anomaly_score DESC; 302 | 303 | -- 6. Average of the data point (temp) across all devices 304 | CREATE OR REPLACE PUMP avg_aggregate_pump AS INSERT INTO FAN_OUT_STREAM 305 | SELECT STREAM 306 | STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE) AS event_timestamp, 307 | 'AvgTempValue', 308 | 'All', 309 | 0, 310 | 'Average', 311 | AVG("temp") AS avg_value 312 | FROM source_sql_stream_001 313 | GROUP BY STEP(source_sql_stream_001.rowtime BY INTERVAL '1' MINUTE), STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE); 314 | 315 | -- 7. Min of the data point (temp) across all devices 316 | CREATE OR REPLACE PUMP min_aggregate_pump AS INSERT INTO FAN_OUT_STREAM 317 | SELECT STREAM 318 | STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE) AS event_timestamp, 319 | 'MinTempValue', 320 | 'All', 321 | 0, 322 | 'Minimum', 323 | MIN("temp") AS min_value 324 | FROM source_sql_stream_001 325 | GROUP BY STEP(source_sql_stream_001.rowtime BY INTERVAL '1' MINUTE), STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE); 326 | 327 | -- 8. Max of the data point (temp) across all devices 328 | CREATE OR REPLACE PUMP max_aggregate_pump AS INSERT INTO FAN_OUT_STREAM 329 | SELECT STREAM 330 | STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE) AS event_timestamp, 331 | 'MaxTempValue', 332 | 'All', 333 | 0, 334 | 'Maximum', 335 | MAX("temp") AS max_value 336 | FROM source_sql_stream_001 337 | GROUP BY STEP(source_sql_stream_001.rowtime BY INTERVAL '1' MINUTE), STEP(source_sql_stream_001."COL_time" BY INTERVAL '1' MINUTE); 338 | 339 | --Setup for 9-14 340 | -- Sort stream and apply sessions 341 | CREATE OR REPLACE STREAM sorted_stream (event_timestamp TIMESTAMP, device VARCHAR(4), flow INTEGER, temp INTEGER, humidity INTEGER); 342 | 343 | CREATE OR REPLACE PUMP sort_pump AS INSERT INTO sorted_stream 344 | SELECT STREAM "COL_time" AS event_timestamp, "device", "flow", "temp", "humidity" 345 | FROM source_sql_stream_001 346 | ORDER BY STEP(source_sql_stream_001.rowtime BY INTERVAL '10' SECOND), "COL_time"; 347 | 348 | 349 | CREATE OR REPLACE STREAM time_between_events_stream (event_timestamp TIMESTAMP, seconds_between_events INTEGER, device VARCHAR(4)); 350 | 351 | CREATE OR REPLACE PUMP time_between_events_pump AS INSERT INTO time_between_events_stream 352 | SELECT STREAM event_timestamp, 353 | -- Calculates the time between session events. 354 | -- tsdiff takes the difference between to timestamps in ms 355 | -- compares the current timestamp in the row to the last timestamp 356 | TSDIFF(event_timestamp, 357 | -- Lag pulls a column from a previous event relative to the current event 358 | -- In this case, we use 1 because we want the time between the two events 359 | LAG(event_timestamp, 1) OVER W1) / 1000 360 | AS seconds_between_events, 361 | device 362 | FROM sorted_stream 363 | WINDOW W1 as ( 364 | -- If no unique session_id exists or no client event for ending a session, you must define the start and end of a session. 365 | -- If users are expected to have multiple sessions online at a given time, another unique identifier must be added to the partition. 366 | PARTITION BY device 367 | RANGE INTERVAL '1' HOUR PRECEDING 368 | ); 369 | 370 | 371 | CREATE OR REPLACE STREAM connected_flag_stream (new_session_indicator BIGINT, event_timestamp TIMESTAMP, seconds_between_events INTEGER, device VARCHAR(4)); 372 | 373 | CREATE OR REPLACE PUMP connected_flag_pump AS INSERT INTO connected_flag_stream 374 | SELECT STREAM 375 | -- Flag new connected sessions which makes other analytics easier 376 | -- Assumes no device has more than one active session 377 | (CASE 378 | -- time interval >= 0, part of the same session 379 | WHEN seconds_between_events >= 0 AND seconds_between_events <= 60 THEN 0 380 | -- time interval null, new session 381 | WHEN seconds_between_events IS NULL OR seconds_between_events > 60 THEN UNIX_TIMESTAMP(event_timestamp) 382 | ELSE NULL 383 | END) AS new_session_indicator, 384 | event_timestamp, seconds_between_events, device 385 | FROM time_between_events_stream; 386 | 387 | --Group sessions together 388 | CREATE OR REPLACE STREAM device_session_stream (sesson_id VARCHAR(128), seconds_between_events INTEGER, device VARCHAR(4)); 389 | 390 | CREATE OR REPLACE PUMP device_session_pump AS INSERT INTO device_session_stream 391 | SELECT STREAM (device || '_' || 392 | -- If users are expected to have multiple sessions online at a given time, another unique identifer must be added here. 393 | CAST(MAX(new_session_indicator) OVER W1 AS VARCHAR(128)) 394 | ) as session_id, seconds_between_events, device 395 | FROM connected_flag_stream 396 | WINDOW W1 AS ( 397 | PARTITION BY device 398 | RANGE INTERVAL '1' HOUR PRECEDING 399 | ); 400 | 401 | -- Calculate connected time events for devices 402 | CREATE OR REPLACE STREAM session_connected_time_stream (sesson_id VARCHAR(128), connected_time_seconds INTEGER); 403 | 404 | CREATE OR REPLACE PUMP session_connected_time_pump AS INSERT INTO session_connected_time_stream 405 | SELECT STREAM sesson_id, SUM(seconds_between_events) OVER W1 AS connected_time_seconds 406 | FROM device_session_stream 407 | WINDOW W1 AS ( 408 | PARTITION BY sesson_id 409 | RANGE INTERVAL '1' HOUR PRECEDING 410 | ); 411 | 412 | --Per session time stream for disconnected devices that came back online within an hour 413 | CREATE OR REPLACE STREAM per_session_disconnected_time_stream (sesson_id VARCHAR(128), max_disconnected_time_seconds INTEGER, avg_disconnected_time_seconds INTEGER, min_disconnected_time_seconds INTEGER); 414 | 415 | CREATE OR REPLACE PUMP per_session_disconnected_time_pump AS INSERT INTO per_session_disconnected_time_stream 416 | SELECT STREAM sesson_id, 417 | MAX(connected_time_seconds) AS max_disconnected_time_seconds, 418 | AVG(connected_time_seconds) AS avg_disconnected_time_seconds, 419 | MIN(connected_time_seconds) AS min_disconnected_time_seconds 420 | FROM session_connected_time_stream 421 | WHERE connected_time_seconds > 60 422 | GROUP BY STEP(session_connected_time_stream.rowtime BY INTERVAL '10' SECOND), sesson_id; 423 | 424 | --9. Max for disconnected devices that came back online within an hour 425 | CREATE OR REPLACE PUMP maximum_disconnected_time_pump AS INSERT INTO FAN_OUT_STREAM 426 | SELECT STREAM 427 | STEP(per_session_disconnected_time_stream.rowtime BY INTERVAL '10' SECOND) AS event_timestamp, 428 | 'MaxDisconnTime', 429 | 'None', 430 | 0, 431 | 'Maximum', 432 | MAX(max_disconnected_time_seconds) AS max_value 433 | FROM per_session_disconnected_time_stream 434 | GROUP BY STEP(per_session_disconnected_time_stream.rowtime BY INTERVAL '10' SECOND); 435 | 436 | --10. Min for disconnected devices that came back online within an hour 437 | CREATE OR REPLACE PUMP minimum_disconnected_time_pump AS INSERT INTO FAN_OUT_STREAM 438 | SELECT STREAM 439 | STEP(per_session_disconnected_time_stream.rowtime BY INTERVAL '10' SECOND) AS event_timestamp, 440 | 'MinDisconnTime', 441 | 'None', 442 | 0, 443 | 'Minimum', 444 | MIN(min_disconnected_time_seconds) AS min_value 445 | FROM per_session_disconnected_time_stream 446 | GROUP BY STEP(per_session_disconnected_time_stream.rowtime BY INTERVAL '10' SECOND); 447 | 448 | --11. Avg for disconnected devices that came back online within an hour 449 | CREATE OR REPLACE PUMP average_disconnected_time_pump AS INSERT INTO FAN_OUT_STREAM 450 | SELECT STREAM 451 | STEP(per_session_disconnected_time_stream.rowtime BY INTERVAL '10' SECOND) AS event_timestamp, 452 | 'AvgDisconnTime', 453 | 'None', 454 | 0, 455 | 'Average', 456 | AVG(avg_disconnected_time_seconds) AS avg_value 457 | FROM per_session_disconnected_time_stream 458 | GROUP BY STEP(per_session_disconnected_time_stream.rowtime BY INTERVAL '10' SECOND); 459 | 460 | --Per session time stream for connected devices 461 | CREATE OR REPLACE STREAM per_session_connected_time_stream (sesson_id VARCHAR(128), max_connected_time_seconds INTEGER, avg_connected_time_seconds INTEGER, min_connected_time_seconds INTEGER); 462 | 463 | CREATE OR REPLACE PUMP per_session_connected_time_pump AS INSERT INTO per_session_connected_time_stream 464 | SELECT STREAM sesson_id, 465 | MAX(connected_time_seconds) AS max_connected_time_seconds, 466 | AVG(connected_time_seconds) AS avg_connected_time_seconds, 467 | MIN(connected_time_seconds) AS min_connected_time_seconds 468 | FROM session_connected_time_stream 469 | WHERE connected_time_seconds <= 60 470 | GROUP BY STEP(session_connected_time_stream.rowtime BY INTERVAL '10' SECOND), sesson_id; 471 | 472 | --12. Max for connected devices 473 | CREATE OR REPLACE PUMP maximum_connected_time_pump AS INSERT INTO FAN_OUT_STREAM 474 | SELECT STREAM 475 | STEP(per_session_connected_time_stream.rowtime BY INTERVAL '10' SECOND) AS event_timestamp, 476 | 'MaxConnTime', 477 | 'None', 478 | 0, 479 | 'Maximum', 480 | MAX(max_connected_time_seconds) AS max_value 481 | FROM per_session_connected_time_stream 482 | GROUP BY STEP(per_session_connected_time_stream.rowtime BY INTERVAL '10' SECOND); 483 | 484 | --13. Min for connected devices 485 | CREATE OR REPLACE PUMP minimum_connected_time_pump AS INSERT INTO FAN_OUT_STREAM 486 | SELECT STREAM 487 | STEP(per_session_connected_time_stream.rowtime BY INTERVAL '10' SECOND) AS event_timestamp, 488 | 'MinConnTime', 489 | 'None', 490 | 0, 491 | 'Minimum', 492 | MIN(min_connected_time_seconds) AS min_value 493 | FROM per_session_connected_time_stream 494 | GROUP BY STEP(per_session_connected_time_stream.rowtime BY INTERVAL '10' SECOND); 495 | 496 | --14. Avg for connected devices 497 | CREATE OR REPLACE PUMP average_connected_time_pump AS INSERT INTO FAN_OUT_STREAM 498 | SELECT STREAM 499 | STEP(per_session_connected_time_stream.rowtime BY INTERVAL '10' SECOND) AS event_timestamp, 500 | 'AvgConnTime', 501 | 'None', 502 | 0, 503 | 'Average', 504 | AVG(avg_connected_time_seconds) AS avg_value 505 | FROM per_session_connected_time_stream 506 | GROUP BY STEP(per_session_connected_time_stream.rowtime BY INTERVAL '10' SECOND); 507 | 508 | --15. Fan out to multiple Kinesis Analytics Outputs 509 | CREATE STREAM ${LambdaStreamName} 510 | ( eventTimeStamp TIMESTAMP, computationType VARCHAR(128), category VARCHAR(128), subcategory INTEGER, unit VARCHAR(128), unitValue DOUBLE); 511 | 512 | CREATE OR REPLACE PUMP fan_out_lambda_pump AS 513 | INSERT INTO ${LambdaStreamName} 514 | SELECT * 515 | FROM FAN_OUT_STREAM; 516 | 517 | CREATE STREAM ${FireHoseStreamName} 518 | ( eventTimeStamp TIMESTAMP, computationType VARCHAR(128), category VARCHAR(128), subcategory INTEGER, unit VARCHAR(128), unitValue DOUBLE); 519 | 520 | CREATE OR REPLACE PUMP fan_out_firehose_pump AS 521 | INSERT INTO ${FireHoseStreamName} 522 | SELECT * 523 | FROM FAN_OUT_STREAM; 524 | - LambdaStreamName: !FindInMap 525 | - KinesisAnalyticsApp 526 | - Outputs 527 | - LambdaStreamName 528 | FireHoseStreamName: !FindInMap 529 | - KinesisAnalyticsApp 530 | - Outputs 531 | - FireHoseStreamName 532 | 533 | Inputs: 534 | - NamePrefix: 'SOURCE_SQL_STREAM' 535 | InputSchema: 536 | RecordColumns: 537 | - Name: 'COL_time' 538 | SqlType: 'TIMESTAMP' 539 | Mapping: '$.ts' 540 | - Name: 'device' 541 | SqlType: 'VARCHAR(4)' 542 | Mapping: '$.device' 543 | - Name: 'flow' 544 | SqlType: 'INTEGER' 545 | Mapping: '$.flow' 546 | - Name: 'temp' 547 | SqlType: 'INTEGER' 548 | Mapping: '$.temp' 549 | - Name: 'humidity' 550 | SqlType: 'INTEGER' 551 | Mapping: '$.humidity' 552 | RecordFormat: 553 | RecordFormatType: 'JSON' 554 | MappingParameters: 555 | JSONMappingParameters: 556 | RecordRowPath: '$' 557 | RecordEncoding: 'UTF-8' 558 | KinesisFirehoseInput: 559 | ResourceARN: !GetAtt RawMetricsDeliveryStream.Arn 560 | RoleARN: !GetAtt KinesisAnalyticsAppRole.Arn 561 | 562 | KinesisAnalyticsAppRole: 563 | Type: AWS::IAM::Role 564 | Properties: 565 | AssumeRolePolicyDocument: 566 | Version: '2012-10-17' 567 | Statement: 568 | - Effect: Allow 569 | Principal: 570 | Service: kinesisanalytics.amazonaws.com 571 | Action: 'sts:AssumeRole' 572 | Path: '/' 573 | Policies: 574 | # Read from RawMetricsDeliveryStream 575 | - PolicyName: 'KinesisAnalyticsReadRawMetrics' 576 | PolicyDocument: 577 | Version: '2012-10-17' 578 | Statement: 579 | - Effect: Allow 580 | Action: 581 | - firehose:DescribeDeliveryStream 582 | - firehose:Get* 583 | Resource: !Sub '${RawMetricsDeliveryStream.Arn}' 584 | # Post to ProcessedMetricsDeliveryStream 585 | - PolicyName: 'KinesisAnalyticsPutProcessedMetrics' 586 | PolicyDocument: 587 | Version: '2012-10-17' 588 | Statement: 589 | - Effect: Allow 590 | Action: 591 | - firehose:DescribeDeliveryStream 592 | - firehose:ListDeliveryStreams 593 | - firehose:PutRecord 594 | - firehose:PutRecordBatch 595 | Resource: !Sub '${ProcessedMetricsDeliveryStream.Arn}' 596 | # Invoke UpdateDDBLambda 597 | - PolicyName: UpdateDDBLambdaInvocation 598 | PolicyDocument: 599 | Version: '2012-10-17' 600 | Statement: 601 | - Effect: Allow 602 | Action: 603 | - lambda:InvokeFunction 604 | Resource: !Sub '${UpdateDDBLambda.Arn}' 605 | # Write to CloudWatch 606 | - PolicyName: KinesisAnalyticsAppLogging 607 | PolicyDocument: 608 | Version: '2012-10-17' 609 | Statement: 610 | - Effect: Allow 611 | Action: 612 | - logs:CreateLogGroup 613 | - logs:CreateLogStream 614 | - logs:PutDestination 615 | - logs:PutLogEvents 616 | Resource: 617 | !Join 618 | - '' 619 | - - 'arn:aws:logs:' 620 | - !Ref AWS::Region 621 | - ':' 622 | - !Ref AWS::AccountId 623 | - ':log-group:*' 624 | Metadata: 625 | cfn_nag: 626 | rules_to_suppress: 627 | - id: W11 628 | reason: "The wildcard action in the logs policy is required" 629 | - id: F3 630 | reason: "The wildcard action in the KinesisAnalyticsReadRawMetrics policy permits the KinesisAnalyticsApp to read from the RawMetricsDeliveryStream. The wildcard resource in the KinesisAnalyticsAppLogging policy permits the KinesisAnalyticsApp to log events to CloudWatch." 631 | 632 | KinesisAnalyticsAppFirehoseOutput: 633 | Type: AWS::KinesisAnalytics::ApplicationOutput 634 | Properties: 635 | ApplicationName: !Ref KinesisAnalyticsApp 636 | Output: 637 | DestinationSchema: 638 | RecordFormatType: 'CSV' 639 | KinesisFirehoseOutput: 640 | ResourceARN: !Sub '${ProcessedMetricsDeliveryStream.Arn}' 641 | RoleARN: !Sub '${KinesisAnalyticsAppRole.Arn}' 642 | Name: !FindInMap 643 | - KinesisAnalyticsApp 644 | - Outputs 645 | - FireHoseStreamName 646 | 647 | KinesisAnalyticsAppLambdaOutput: 648 | Type: AWS::KinesisAnalytics::ApplicationOutput 649 | 650 | # Use DependsOn to serialize adding Application Outputs to reduce likelihood of errors. 651 | DependsOn: KinesisAnalyticsAppFirehoseOutput 652 | Properties: 653 | ApplicationName: !Ref KinesisAnalyticsApp 654 | Output: 655 | DestinationSchema: 656 | RecordFormatType: 'CSV' 657 | LambdaOutput: 658 | ResourceARN: !Sub '${UpdateDDBLambda.Arn}' 659 | RoleARN: !Sub '${KinesisAnalyticsAppRole.Arn}' 660 | Name: !FindInMap 661 | - KinesisAnalyticsApp 662 | - Outputs 663 | - LambdaStreamName 664 | 665 | ProcessedMetricsDeliveryStream: 666 | Type: AWS::KinesisFirehose::DeliveryStream 667 | Properties: 668 | DeliveryStreamType: 'DirectPut' 669 | S3DestinationConfiguration: 670 | BucketARN: !Sub '${ProcessedMetricsBucket.Arn}' 671 | BufferingHints: 672 | IntervalInSeconds: 60 673 | SizeInMBs: 10 674 | CloudWatchLoggingOptions: 675 | Enabled: true 676 | LogGroupName: !Ref IoTMetricsLogGroup 677 | LogStreamName: 'ProcessedMetricsS3Delivery' 678 | CompressionFormat: 'UNCOMPRESSED' 679 | EncryptionConfiguration: 680 | NoEncryptionConfig: 'NoEncryption' 681 | Prefix: !FindInMap 682 | - SourceCode 683 | - General 684 | - LogPrefix 685 | RoleARN: !Sub '${ProcessedMetricsDeliveryStreamRole.Arn}' 686 | 687 | ProcessedMetricsBucket: 688 | DeletionPolicy: Retain 689 | Type: AWS::S3::Bucket 690 | Properties: 691 | BucketEncryption: 692 | ServerSideEncryptionConfiguration: 693 | - ServerSideEncryptionByDefault: 694 | SSEAlgorithm: AES256 695 | PublicAccessBlockConfiguration: 696 | BlockPublicAcls: true 697 | BlockPublicPolicy: true 698 | IgnorePublicAcls: true 699 | RestrictPublicBuckets: true 700 | LoggingConfiguration: 701 | DestinationBucketName: !Ref LogsBucket 702 | LogFilePrefix: processed-metrics-bucket/ 703 | LifecycleConfiguration: 704 | Rules: 705 | - Id: ExpirationRule 706 | Status: Enabled 707 | ExpirationInDays: '7' 708 | Metadata: 709 | cfn_nag: 710 | rules_to_suppress: 711 | - id: W51 712 | reason: "This is a private bucket. Does not require bucket policy" 713 | 714 | ProcessedMetricsDeliveryStreamRole: 715 | Type: AWS::IAM::Role 716 | Properties: 717 | AssumeRolePolicyDocument: 718 | Version: '2012-10-17' 719 | Statement: 720 | - Effect: Allow 721 | Principal: 722 | Service: 723 | - firehose.amazonaws.com 724 | Action: 725 | - sts:AssumeRole 726 | Path: / 727 | Policies: 728 | 729 | # Put objects in ProcessedMetricsBucket 730 | - PolicyName: 'ProcessedMetricsS3Delivery' 731 | PolicyDocument: 732 | Version: '2012-10-17' 733 | Statement: 734 | Action: 735 | - s3:AbortMultipartUpload 736 | - s3:GetBucketLocation 737 | - s3:PutObject 738 | - s3:GetObject 739 | - s3:ListBucket 740 | - s3:ListBucketMultipartUploads 741 | Effect: Allow 742 | Resource: 743 | - !Sub '${ProcessedMetricsBucket.Arn}' 744 | - !Sub '${ProcessedMetricsBucket.Arn}/' 745 | - !Sub '${ProcessedMetricsBucket.Arn}/*' 746 | 747 | # Write to CloudWatch 748 | - PolicyName: ProcessedMetricsLogging 749 | PolicyDocument: 750 | Version: '2012-10-17' 751 | Statement: 752 | - Effect: Allow 753 | Action: 754 | - logs:CreateLogGroup 755 | - logs:CreateLogStream 756 | - logs:PutDestination 757 | - logs:PutLogEvents 758 | Resource: 759 | !Join 760 | - '' 761 | - - 'arn:aws:logs:' 762 | - !Ref AWS::Region 763 | - ':' 764 | - !Ref AWS::AccountId 765 | - ':log-group:*' 766 | Metadata: 767 | cfn_nag: 768 | rules_to_suppress: 769 | - id: W11 770 | reason: "The wildcard action in the logs policy is required" 771 | # UpdateDDBLambda 772 | UpdateDDBLambda: 773 | Type: AWS::Lambda::Function 774 | Properties: 775 | Code: 776 | S3Bucket: !Sub 777 | - ${Param1}-${AWS::Region} 778 | - Param1: !FindInMap 779 | - SourceCode 780 | - General 781 | - S3Bucket 782 | S3Key: !Sub 783 | - ${Param1}/update_ddb_from_stream.zip 784 | - Param1: !FindInMap 785 | - SourceCode 786 | - General 787 | - KeyPrefix 788 | Environment: 789 | Variables: 790 | ANALYTICS_TABLE: !Ref AnalyticsTable 791 | SOLUTION_UUID: !GetAtt GenerateUUID.UUID 792 | SOLUTION_ID: !FindInMap 793 | - Solution 794 | - Data 795 | - ID 796 | SOLUTION_VERSION: !FindInMap 797 | - Solution 798 | - Data 799 | - Version 800 | SEND_ANONYMOUS_DATA: !FindInMap 801 | - Solution 802 | - Data 803 | - SendAnonymousUsageData 804 | Description: Puts ProcessedMetrics data into AnalyticsTable. 805 | Handler: update_ddb_from_stream.lambda_handler 806 | MemorySize: 256 807 | Role: !GetAtt UpdateDDBLambdaRole.Arn 808 | Runtime: python3.8 809 | Timeout: 300 810 | 811 | UpdateDDBLambdaRole: 812 | Type: AWS::IAM::Role 813 | Properties: 814 | AssumeRolePolicyDocument: 815 | Version: '2012-10-17' 816 | Statement: 817 | - Effect: Allow 818 | Principal: 819 | Service: 820 | - lambda.amazonaws.com 821 | Action: 822 | - sts:AssumeRole 823 | Path: "/" 824 | Policies: 825 | - PolicyName: root 826 | PolicyDocument: 827 | Version: '2012-10-17' 828 | Statement: 829 | 830 | # Read from ProcessedMetricsDeliveryStream 831 | - Effect: Allow 832 | Action: 833 | - firehose:DescribeDeliveryStream 834 | - firehose:Get* 835 | Resource: 836 | - !Sub '${ProcessedMetricsDeliveryStream.Arn}' 837 | 838 | # Update AnalyticsTable 839 | - Effect: Allow 840 | Action: 841 | - dynamodb:GetItem 842 | - dynamodb:PutItem 843 | Resource: 844 | - !Sub '${AnalyticsTable.Arn}' 845 | 846 | # Write to CloudWatch 847 | - PolicyName: UpdateDDBLambdaLogging 848 | PolicyDocument: 849 | Version: '2012-10-17' 850 | Statement: 851 | - Effect: Allow 852 | Action: 853 | - logs:CreateLogGroup 854 | - logs:CreateLogStream 855 | - logs:PutDestination 856 | - logs:PutLogEvents 857 | Resource: 858 | !Join 859 | - '' 860 | - - 'arn:aws:logs:' 861 | - !Ref AWS::Region 862 | - ':' 863 | - !Ref AWS::AccountId 864 | - ':log-group:*' 865 | Metadata: 866 | cfn_nag: 867 | rules_to_suppress: 868 | - id: F3 869 | reason: "The wildcard action in the root policy permits the UpdateDDBLambda function to read from the ProcessedMetricsDeliveryStream. The wilcard resource in the UpdateDDBLambdaLogging policy permits the UpdateDDBLambda function to log events to CloudWatch." 870 | - id: W11 871 | reason: "The wildcard action required to log events to CloudWatch." 872 | 873 | # Database 874 | AnalyticsTable: 875 | Type: AWS::DynamoDB::Table 876 | Properties: 877 | AttributeDefinitions: 878 | - AttributeName: MetricType 879 | AttributeType: S 880 | - AttributeName: EventTime 881 | AttributeType: S 882 | KeySchema: 883 | - KeyType: HASH 884 | AttributeName: MetricType 885 | - KeyType: RANGE 886 | AttributeName: EventTime 887 | ProvisionedThroughput: 888 | ReadCapacityUnits: 20 889 | WriteCapacityUnits: 20 890 | 891 | AnalyticsTableScalingRole: 892 | Type: AWS::IAM::Role 893 | Properties: 894 | AssumeRolePolicyDocument: 895 | Version: '2012-10-17' 896 | Statement: 897 | - Effect: Allow 898 | Principal: 899 | Service: 900 | - application-autoscaling.amazonaws.com 901 | Action: 902 | - sts:AssumeRole 903 | Path: '/' 904 | Policies: 905 | - PolicyName: AnalyticsTableScalingPolicy 906 | PolicyDocument: 907 | Version: '2012-10-17' 908 | Statement: 909 | 910 | # Allows updating AnalyticsTable capacity. 911 | - Effect: Allow 912 | Action: 913 | - dynamodb:DescribeTable 914 | - dynamodb:UpdateTable 915 | Resource: 916 | - !Sub '${AnalyticsTable.Arn}' 917 | 918 | # Allows access to AnalyticsTable cloudwatch logs. 919 | - Effect: Allow 920 | Action: 921 | - cloudwatch:PutMetricAlarm 922 | - cloudwatch:DescribeAlarms 923 | - cloudwatch:GetMetricStatistics 924 | - cloudwatch:SetAlarmState 925 | - cloudwatch:DeleteAlarms 926 | Resource: 927 | - '*' 928 | Metadata: 929 | cfn_nag: 930 | rules_to_suppress: 931 | - id: W11 932 | reason: "The wildcard action in the root policy permits the UpdateDDBLambda function to read from the ProcessedMetricsDeliveryStream. The wilcard resource in the UpdateDDBLambdaLogging policy permits the UpdateDDBLambda function to log events to CloudWatch." 933 | 934 | AnalyticsTableWriteCapacityTarget: 935 | Type: AWS::ApplicationAutoScaling::ScalableTarget 936 | Properties: 937 | MaxCapacity: !FindInMap [DDB, Scaling, WriteCapacityMax] 938 | MinCapacity: !FindInMap [DDB, Scaling, WriteCapacityMin] 939 | ResourceId: !Sub 'table/${AnalyticsTable}' 940 | RoleARN: !Sub '${AnalyticsTableScalingRole.Arn}' 941 | ScalableDimension: dynamodb:table:WriteCapacityUnits 942 | ServiceNamespace: dynamodb 943 | 944 | AnalyticsTableWriteScalingPolicy: 945 | Type: AWS::ApplicationAutoScaling::ScalingPolicy 946 | Properties: 947 | PolicyName: WriteAutoScalingPolicy 948 | PolicyType: TargetTrackingScaling 949 | ScalingTargetId: !Ref AnalyticsTableWriteCapacityTarget 950 | TargetTrackingScalingPolicyConfiguration: 951 | TargetValue: !FindInMap [DDB, Scaling, WriteTargetUtilization] 952 | ScaleInCooldown: 300 953 | ScaleOutCooldown: 60 954 | PredefinedMetricSpecification: 955 | PredefinedMetricType: DynamoDBWriteCapacityUtilization 956 | 957 | AnalyticsTableReadCapacityTarget: 958 | Type: AWS::ApplicationAutoScaling::ScalableTarget 959 | Properties: 960 | MaxCapacity: !FindInMap [DDB, Scaling, ReadCapacityMax] 961 | MinCapacity: !FindInMap [DDB, Scaling, ReadCapacityMin] 962 | ResourceId: !Sub 'table/${AnalyticsTable}' 963 | RoleARN: !Sub '${AnalyticsTableScalingRole.Arn}' 964 | ScalableDimension: dynamodb:table:ReadCapacityUnits 965 | ServiceNamespace: dynamodb 966 | 967 | AnalyticsTableReadScalingPolicy: 968 | Type: AWS::ApplicationAutoScaling::ScalingPolicy 969 | Properties: 970 | PolicyName: ReadAutoScalingPolicy 971 | PolicyType: TargetTrackingScaling 972 | ScalingTargetId: !Ref AnalyticsTableReadCapacityTarget 973 | TargetTrackingScalingPolicyConfiguration: 974 | TargetValue: !FindInMap [DDB, Scaling, ReadTargetUtilization] 975 | ScaleInCooldown: 300 976 | ScaleOutCooldown: 60 977 | PredefinedMetricSpecification: 978 | PredefinedMetricType: DynamoDBReadCapacityUtilization 979 | 980 | # Dashboard Website 981 | WebsiteBucket: 982 | Type: AWS::S3::Bucket 983 | DeletionPolicy: Retain 984 | Properties: 985 | BucketEncryption: 986 | ServerSideEncryptionConfiguration: 987 | - ServerSideEncryptionByDefault: 988 | SSEAlgorithm: AES256 989 | PublicAccessBlockConfiguration: 990 | BlockPublicAcls: true 991 | BlockPublicPolicy: true 992 | IgnorePublicAcls: true 993 | RestrictPublicBuckets: true 994 | LoggingConfiguration: 995 | DestinationBucketName: !Ref LogsBucket 996 | LogFilePrefix: website-bucket/ 997 | WebsiteConfiguration: 998 | IndexDocument: "index.html" 999 | ErrorDocument: "index.html" 1000 | WebsiteBucketPolicy: 1001 | Type: "AWS::S3::BucketPolicy" 1002 | Properties: 1003 | Bucket: 1004 | Ref: "WebsiteBucket" 1005 | PolicyDocument: 1006 | Statement: 1007 | - 1008 | Action: 1009 | - "s3:GetObject" 1010 | Effect: "Allow" 1011 | Resource: 1012 | Fn::Join: 1013 | - "" 1014 | - 1015 | - "arn:aws:s3:::" 1016 | - 1017 | Ref: "WebsiteBucket" 1018 | - "/*" 1019 | Principal: 1020 | CanonicalUser: !GetAtt WebsiteOriginAccessIdentity.S3CanonicalUserId 1021 | WebsiteOriginAccessIdentity: 1022 | Type: AWS::CloudFront::CloudFrontOriginAccessIdentity 1023 | Properties: 1024 | CloudFrontOriginAccessIdentityConfig: 1025 | Comment: !Sub "access-identity-${WebsiteBucket}" 1026 | WebsiteDistribution: 1027 | Type: AWS::CloudFront::Distribution 1028 | Properties: 1029 | DistributionConfig: 1030 | Comment: "Website distribution for solution" 1031 | Origins: 1032 | - 1033 | Id: S3-solution-website 1034 | DomainName: !Sub "${WebsiteBucket}.s3.${AWS::Region}.amazonaws.com" 1035 | S3OriginConfig: 1036 | OriginAccessIdentity: !Sub "origin-access-identity/cloudfront/${WebsiteOriginAccessIdentity}" 1037 | DefaultCacheBehavior: 1038 | TargetOriginId: S3-solution-website 1039 | AllowedMethods: 1040 | - GET 1041 | - HEAD 1042 | - OPTIONS 1043 | - PUT 1044 | - POST 1045 | - PATCH 1046 | - DELETE 1047 | CachedMethods: 1048 | - GET 1049 | - HEAD 1050 | - OPTIONS 1051 | ForwardedValues: 1052 | QueryString: 'false' 1053 | ViewerProtocolPolicy: redirect-to-https 1054 | IPV6Enabled: 'true' 1055 | ViewerCertificate: 1056 | CloudFrontDefaultCertificate: 'true' 1057 | Enabled: 'true' 1058 | HttpVersion: 'http2' 1059 | Logging: 1060 | IncludeCookies: 'false' 1061 | Bucket: !GetAtt LogsBucket.DomainName 1062 | Prefix: cloudfront-logs/ 1063 | 1064 | ##Logging bucket for cloudFront and other solution buckets 1065 | LogsBucket: 1066 | DeletionPolicy: Retain 1067 | Type: AWS::S3::Bucket 1068 | Properties: 1069 | BucketEncryption: 1070 | ServerSideEncryptionConfiguration: 1071 | - ServerSideEncryptionByDefault: 1072 | SSEAlgorithm: AES256 1073 | PublicAccessBlockConfiguration: 1074 | BlockPublicAcls: true 1075 | BlockPublicPolicy: true 1076 | IgnorePublicAcls: true 1077 | RestrictPublicBuckets: true 1078 | AccessControl: LogDeliveryWrite 1079 | Metadata: 1080 | cfn_nag: 1081 | rules_to_suppress: 1082 | - id: W35 1083 | reason: "This is the logs bucket for all the other S3 Buckets and CloudFront" 1084 | - id: W51 1085 | reason: "This is a private bucket. Does not require bucket policy" 1086 | 1087 | 1088 | # Cognito for Dashboard Users 1089 | CognitoUserPool: 1090 | Type: AWS::Cognito::UserPool 1091 | Properties: 1092 | AliasAttributes: 1093 | - email 1094 | AutoVerifiedAttributes: 1095 | - email 1096 | AdminCreateUserConfig: 1097 | AllowAdminCreateUserOnly: True 1098 | InviteMessageTemplate: 1099 | EmailMessage: 1100 | !Sub | 1101 |

You are invited to join the Real-Time IoT Device Monitoring dashboard. Your dashboard credentials are as follows:

1102 |

1103 | Username: {username}
1104 | Password: {####} 1105 |

1106 |

1107 | Please sign in to the dashboard with the user name and your temporary password provided above at:
1108 | https://${WebsiteDistribution.DomainName}/index.html 1109 |

1110 | EmailSubject: 'Your Real-Time IoT Device Monitoring dashboard Login' 1111 | UnusedAccountValidityDays: 7 1112 | EmailVerificationMessage: 1113 | !Sub | 1114 |

You are invited to join the Real-Time IoT Device Monitoring dashboard. Your dashboard credentials are as follows:

1115 |

1116 | Username: {username}
1117 | Password: {####} 1118 |

1119 |

1120 | Please sign in to the dashboard with the user name and temporary password provided above at:
1121 | https://${WebsiteDistribution.DomainName}/index.html 1122 |

1123 | EmailVerificationSubject: 'Your Real-Time IoT Device Monitoring dashboard Login' 1124 | Policies: 1125 | PasswordPolicy: 1126 | MinimumLength: 8 1127 | RequireLowercase: True 1128 | RequireNumbers: True 1129 | RequireSymbols: False 1130 | RequireUppercase: True 1131 | Schema: 1132 | - AttributeDataType: String 1133 | Name: email 1134 | Required: True 1135 | 1136 | CognitoUserPoolClient: 1137 | Type: AWS::Cognito::UserPoolClient 1138 | Properties: 1139 | GenerateSecret: False 1140 | WriteAttributes: 1141 | - address 1142 | - email 1143 | - phone_number 1144 | ReadAttributes: 1145 | - name 1146 | - email 1147 | - email_verified 1148 | - address 1149 | - phone_number 1150 | - phone_number_verified 1151 | RefreshTokenValidity: 1 1152 | UserPoolId: !Ref CognitoUserPool 1153 | 1154 | CognitoIdentityPool: 1155 | Type: AWS::Cognito::IdentityPool 1156 | Properties: 1157 | CognitoIdentityProviders: 1158 | - ClientId: !Ref CognitoUserPoolClient 1159 | ProviderName: !GetAtt CognitoUserPool.ProviderName 1160 | AllowUnauthenticatedIdentities: false 1161 | 1162 | CognitoIdentityPoolRoleAttachment: 1163 | Type: AWS::Cognito::IdentityPoolRoleAttachment 1164 | Properties: 1165 | IdentityPoolId: !Sub '${CognitoIdentityPool}' 1166 | Roles: 1167 | unauthenticated: !GetAtt UnauthenticatedUserRole.Arn 1168 | authenticated: !GetAtt AuthenticatedUserRole.Arn 1169 | 1170 | AuthenticatedUserRole: 1171 | Type: AWS::IAM::Role 1172 | Properties: 1173 | AssumeRolePolicyDocument: 1174 | Version: '2012-10-17' 1175 | Statement: 1176 | - Effect: Allow 1177 | Principal: 1178 | Federated: 1179 | - cognito-identity.amazonaws.com 1180 | Action: 1181 | - sts:AssumeRoleWithWebIdentity 1182 | Condition: 1183 | StringEquals: 1184 | cognito-identity.amazonaws.com:aud: !Sub '${CognitoIdentityPool}' 1185 | ForAnyValue:StringLike: 1186 | cognito-identity.amazonaws.com:amr: authenticated 1187 | Path: / 1188 | Policies: 1189 | 1190 | # Cognito Sync 1191 | - PolicyName: 'cognito-sync' 1192 | PolicyDocument: 1193 | Version: '2012-10-17' 1194 | Statement: 1195 | - Effect: Allow 1196 | Action: 1197 | - mobileanalytics:PutEvents 1198 | - cognito-identity:* 1199 | Resource: !Sub 'arn:aws:cognito-identity:${AWS::Region}:${AWS::AccountId}:identitypool/${CognitoIdentityPool}' 1200 | 1201 | # Get metrics from AnalyticsTable 1202 | - PolicyName: 'ReadAnalyticsTable' 1203 | PolicyDocument: 1204 | Version: '2012-10-17' 1205 | Statement: 1206 | - Effect: Allow 1207 | Action: 1208 | - dynamodb:BatchGetItem 1209 | - dynamodb:GetItem 1210 | - dynamodb:GetRecords 1211 | - dynamodb:GetShardIterator 1212 | - dynamodb:Query 1213 | - dynamodb:Scan 1214 | Resource: 1215 | - !GetAtt AnalyticsTable.Arn 1216 | Metadata: 1217 | cfn_nag: 1218 | rules_to_suppress: 1219 | - id: F3 1220 | reason: "The wildcard action in the cognito-sync policy permits the AuthenticatedUser role to interface with Amazon Cognito." 1221 | 1222 | UnauthenticatedUserRole: 1223 | Type: AWS::IAM::Role 1224 | Properties: 1225 | AssumeRolePolicyDocument: 1226 | Version: '2012-10-17' 1227 | Statement: 1228 | - Effect: Allow 1229 | Principal: 1230 | Federated: 1231 | - cognito-identity.amazonaws.com 1232 | Action: 1233 | - sts:AssumeRoleWithWebIdentity 1234 | Condition: 1235 | StringEquals: 1236 | "cognito-identity.amazonaws.com:aud": !Ref CognitoIdentityPool 1237 | ForAnyValue:StringLike: 1238 | "cognito-identity.amazonaws.com:amr": unauthenticated 1239 | Path: / 1240 | Policies: 1241 | - PolicyName: root 1242 | PolicyDocument: 1243 | Version: '2012-10-17' 1244 | Statement: 1245 | - Effect: Allow 1246 | Action: 1247 | - mobileanalytics:PutEvents 1248 | Resource: !Sub 'arn:aws:cognito-identity:${AWS::Region}:${AWS::AccountId}:identitypool/${CognitoIdentityPool}' 1249 | 1250 | CognitoUser: 1251 | DependsOn: 1252 | 1253 | # Wait for the website to come up before emailing a registration link 1254 | - ConfigureWebsite 1255 | Type: AWS::Cognito::UserPoolUser 1256 | Properties: 1257 | DesiredDeliveryMediums: 1258 | - EMAIL 1259 | ForceAliasCreation: True 1260 | UserAttributes: 1261 | - Name: email 1262 | Value: !Ref UserEmail 1263 | - Name: email_verified 1264 | Value: True 1265 | Username: !Ref UserName 1266 | UserPoolId: !Ref CognitoUserPool 1267 | 1268 | # Custom Resource 1269 | CustomResourceHelper: 1270 | Type: AWS::Lambda::Function 1271 | Properties: 1272 | Code: 1273 | S3Bucket: !Sub 1274 | - ${Param1}-${AWS::Region} 1275 | - Param1: !FindInMap 1276 | - SourceCode 1277 | - General 1278 | - S3Bucket 1279 | S3Key: !Sub 1280 | - ${Param1}/custom-resource-helper.zip 1281 | - Param1: !FindInMap 1282 | - SourceCode 1283 | - General 1284 | - KeyPrefix 1285 | Environment: 1286 | Variables: 1287 | SOLUTION_ID: !FindInMap 1288 | - Solution 1289 | - Data 1290 | - ID 1291 | SOLUTION_VERSION: !FindInMap 1292 | - Solution 1293 | - Data 1294 | - Version 1295 | SEND_ANONYMOUS_DATA: !FindInMap 1296 | - Solution 1297 | - Data 1298 | - SendAnonymousUsageData 1299 | Description: Helps set up the Real Time IoT Device Monitoring with Kinesis solution. 1300 | Handler: index.handler 1301 | MemorySize: 256 1302 | Role: !GetAtt CustomResourceHelperRole.Arn 1303 | Runtime: nodejs12.x 1304 | Timeout: 300 1305 | 1306 | CustomResourceHelperRole: 1307 | Type: AWS::IAM::Role 1308 | Properties: 1309 | AssumeRolePolicyDocument: 1310 | Version: '2012-10-17' 1311 | Statement: 1312 | - Effect: Allow 1313 | Principal: 1314 | Service: 1315 | - lambda.amazonaws.com 1316 | Action: 1317 | - sts:AssumeRole 1318 | Path: / 1319 | Policies: 1320 | - PolicyName: ConfigureWebsitePolicy 1321 | PolicyDocument: 1322 | Version: '2012-10-17' 1323 | Statement: 1324 | # Get website objects from AWS Solutions bucket. 1325 | - Effect: Allow 1326 | Action: 1327 | - s3:GetObject 1328 | Resource: 1329 | - !Sub 1330 | - arn:aws:s3:::${Param1}-${AWS::Region}/${Param2}/* 1331 | - Param1: !FindInMap 1332 | - SourceCode 1333 | - General 1334 | - S3Bucket 1335 | Param2: !FindInMap 1336 | - SourceCode 1337 | - General 1338 | - KeyPrefix 1339 | # Put website objects into WebsiteBucket 1340 | - Effect: Allow 1341 | Action: 1342 | - s3:PutObject 1343 | - s3:PutObjectAcl 1344 | - s3:DeleteObject 1345 | - s3:ListObjects 1346 | - s3:ListBucket 1347 | Resource: 1348 | - !Sub '${WebsiteBucket.Arn}' 1349 | - !Sub '${WebsiteBucket.Arn}/' 1350 | - !Sub '${WebsiteBucket.Arn}/*' 1351 | # Enable Bucket Encryption 1352 | - PolicyName: EnableBucketEncryption 1353 | PolicyDocument: 1354 | Version: '2012-10-17' 1355 | Statement: 1356 | - Effect: Allow 1357 | Action: 1358 | - s3:PutEncryptionConfiguration 1359 | Resource: 1360 | - !Sub '${RawMetricsBucket.Arn}' 1361 | - !Sub '${ProcessedMetricsBucket.Arn}' 1362 | # Write to CloudWatch 1363 | - PolicyName: CloudWatchLoggingPolicy 1364 | PolicyDocument: 1365 | Version: '2012-10-17' 1366 | Statement: 1367 | - Effect: Allow 1368 | Action: 1369 | - logs:CreateLogGroup 1370 | - logs:CreateLogStream 1371 | - logs:PutDestination 1372 | - logs:PutLogEvents 1373 | Resource: 1374 | !Join 1375 | - '' 1376 | - - 'arn:aws:logs:' 1377 | - !Ref AWS::Region 1378 | - ':' 1379 | - !Ref AWS::AccountId 1380 | - ':log-group:*' 1381 | Metadata: 1382 | cfn_nag: 1383 | rules_to_suppress: 1384 | - id: W11 1385 | reason: "The wildcard action in the logs policy is required" 1386 | 1387 | CustomResourceKinesisAnalyticsPolicy: 1388 | Type: AWS::IAM::Policy 1389 | Properties: 1390 | PolicyName: StartKinesisApplicationPolicy 1391 | PolicyDocument: 1392 | Version: '2012-10-17' 1393 | Statement: 1394 | - Effect: Allow 1395 | Action: 1396 | - 'kinesisanalytics:DescribeApplication' 1397 | - 'kinesisanalytics:StartApplication' 1398 | - 'kinesisanalytics:StopApplication' 1399 | Resource: 1400 | 1401 | # KinesisAnalytics Application ARN isn't available via GetAtt 1402 | - !Sub 'arn:aws:kinesisanalytics:${AWS::Region}:${AWS::AccountId}:application/${KinesisAnalyticsApp}' 1403 | Roles: 1404 | - !Ref CustomResourceHelperRole 1405 | 1406 | # Custom Resource Invocations 1407 | GenerateUUID: 1408 | Type: Custom::LoadLambda 1409 | Properties: 1410 | ServiceToken: !GetAtt CustomResourceHelper.Arn 1411 | CustomResourceAction: GenerateUUID 1412 | 1413 | DeployWebsite: 1414 | Type: Custom::LoadLambda 1415 | Properties: 1416 | ServiceToken: !GetAtt CustomResourceHelper.Arn 1417 | Region: !Ref AWS::Region 1418 | CustomResourceAction: DeployWebsite 1419 | SourceS3Bucket: !Sub 1420 | - ${Param1}-${AWS::Region} 1421 | - Param1: !FindInMap 1422 | - SourceCode 1423 | - General 1424 | - S3Bucket 1425 | SourceS3Key: !Sub 1426 | - ${Param1}/web_site 1427 | - Param1: !FindInMap 1428 | - SourceCode 1429 | - General 1430 | - KeyPrefix 1431 | WebsiteBucket: !Ref WebsiteBucket 1432 | sourceManifest: !Join ["/", [!FindInMap ["SourceCode", "General", "KeyPrefix"], "web-site-manifest.json"]] 1433 | UUID: !GetAtt GenerateUUID.UUID 1434 | 1435 | ConfigureWebsite: 1436 | Type: Custom::LoadLambda 1437 | Properties: 1438 | ServiceToken: !GetAtt CustomResourceHelper.Arn 1439 | Region: !Ref AWS::Region 1440 | CustomResourceAction: ConfigureWebsite 1441 | WebsiteBucket: !Ref WebsiteBucket 1442 | UUID: !GetAtt GenerateUUID.UUID 1443 | Configuration: 1444 | IdentityPoolId: !Ref CognitoIdentityPool 1445 | UserPoolId: !Ref CognitoUserPool 1446 | UserPoolClientId: !Ref CognitoUserPoolClient 1447 | AnalyticsTable: !Ref AnalyticsTable 1448 | Region: !Ref AWS::Region 1449 | 1450 | EnableRawMetricsBucketEncryption: 1451 | Type: Custom::LoadLambda 1452 | Properties: 1453 | ServiceToken: !GetAtt CustomResourceHelper.Arn 1454 | Region: !Ref AWS::Region 1455 | CustomResourceAction: EnableBucketEncryption 1456 | Bucket: !Ref RawMetricsBucket 1457 | SSEAlgorithm: "AES256" 1458 | 1459 | EnableProcessedMetricsBucketEncryption: 1460 | Type: Custom::LoadLambda 1461 | Properties: 1462 | ServiceToken: !GetAtt CustomResourceHelper.Arn 1463 | Region: !Ref AWS::Region 1464 | CustomResourceAction: EnableBucketEncryption 1465 | Bucket: !Ref ProcessedMetricsBucket 1466 | SSEAlgorithm: "AES256" 1467 | 1468 | StartKinesisAnalyticsApp: 1469 | Type: Custom::LoadLambda 1470 | DependsOn: 1471 | - KinesisAnalyticsAppFirehoseOutput 1472 | - KinesisAnalyticsAppLambdaOutput 1473 | - CustomResourceKinesisAnalyticsPolicy 1474 | Properties: 1475 | ServiceToken: !GetAtt CustomResourceHelper.Arn 1476 | Region: !Ref AWS::Region 1477 | ApplicationName: !Ref KinesisAnalyticsApp 1478 | CustomResourceAction: StartKinesisApplication 1479 | UUID: !GetAtt GenerateUUID.UUID 1480 | 1481 | Outputs: 1482 | DashboardUrl: 1483 | Description: The URL to the Dashboard. 1484 | Value: !Sub 'https://${WebsiteDistribution.DomainName}/index.html' 1485 | IoTTopicName: 1486 | Description: The IoT Topic to monitor. 1487 | Value: !Ref IoTTopicName 1488 | DemoScriptLocation: 1489 | Description: The location of the zipped demo script to send messages to your IoT topic. 1490 | Value: !Sub 1491 | - https://s3.${AWS::Region}.amazonaws.com/${Bucket}-${AWS::Region}/${Key}/demo.zip 1492 | - Bucket: !FindInMap 1493 | - SourceCode 1494 | - General 1495 | - S3Bucket 1496 | Key: !FindInMap 1497 | - SourceCode 1498 | - General 1499 | - KeyPrefix 1500 | DemoCommand: 1501 | Description: Command to run the demo script. 1502 | Value: !Sub 1503 | - './send-messages.sh --topic ${Topic} --region ${Region}' 1504 | - Topic: !Ref IoTTopicName 1505 | Region: !Ref AWS::Region 1506 | -------------------------------------------------------------------------------- /deployment/run-unit-tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # This script should be run from the repo's deployment directory 4 | # cd deployment 5 | # ./run-unit-tests.sh 6 | 7 | export initial_dir=`pwd` 8 | 9 | # Run unit tests 10 | echo "Running unit tests" 11 | echo "No unit tests to run..." 12 | 13 | cd "$initial_dir" 14 | 15 | echo "Completed unit tests" 16 | -------------------------------------------------------------------------------- /source/custom-resource/index.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/ * 8 | * * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | 'use strict'; 15 | 16 | console.log('Loading function'); 17 | 18 | const https = require('https'); 19 | const url = require('url'); 20 | const moment = require('moment'); 21 | 22 | const UUID = require('node-uuid'); 23 | const MetricsHelper = require('./lib/metrics-helper'); 24 | const KinesisAppHelper = require('./lib/kinesis-helper'); 25 | const WebsiteHelper = require('./lib/website-helper'); 26 | const S3BucketEncryptionHelper = require('./lib/s3-bucket-encryption-helper'); 27 | 28 | /** 29 | * Request handler. 30 | */ 31 | exports.handler = (event, context, callback) => { 32 | console.log('Received event:', JSON.stringify(event, null, 2)); 33 | 34 | let responseStatus = 'FAILED'; 35 | let responseData = {}; 36 | 37 | let _bucketEncryptionHelper = new S3BucketEncryptionHelper(); 38 | let _kinesisAppHelper = new KinesisAppHelper(); 39 | let _websiteHelper = new WebsiteHelper(); 40 | let _metricsHelper = new MetricsHelper(); 41 | 42 | switch (event.ResourceProperties.CustomResourceAction) { 43 | case 'EnableBucketEncryption': 44 | switch (event.RequestType) { 45 | case 'Create': 46 | 47 | _bucketEncryptionHelper.enableDefaultBucketEncryption(event.ResourceProperties.Bucket, 48 | event.ResourceProperties.SSEAlgorithm, event.ResourceProperties.KMSMasterKeyID, 49 | (err, data) => { 50 | if (err) { 51 | responseData = { 52 | Error: 'Enabling S3 bucket encryption failed' 53 | }; 54 | console.log([responseData.Error, ':\n', err].join('')); 55 | } else { 56 | responseStatus = 'SUCCESS'; 57 | responseData = {}; 58 | } 59 | 60 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData); 61 | }); 62 | break; 63 | 64 | case 'Delete': 65 | 66 | // Do nothing. 67 | sendResponse(event, callback, context.logStreamName, 'SUCCESS'); 68 | break; 69 | default: 70 | 71 | // Fail if RequestType is unexpected. 72 | sendResponse(event, callback, context.logStreamName, 'FAILED'); 73 | } 74 | break; 75 | 76 | case 'StartKinesisApplication': 77 | switch (event.RequestType) { 78 | case 'Create': 79 | 80 | _kinesisAppHelper.startApplication(event.ResourceProperties.ApplicationName, event.ResourceProperties.Region, 81 | function(err, data) { 82 | if (err) { 83 | responseData = { 84 | Error: 'Starting kinesis application failed' 85 | }; 86 | console.log([responseData.Error, ':\n', err].join('')); 87 | } else { 88 | responseStatus = 'SUCCESS'; 89 | responseData = {}; 90 | } 91 | 92 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData); 93 | }); 94 | break; 95 | 96 | case 'Delete': 97 | 98 | _kinesisAppHelper.stopApplication(event.ResourceProperties.ApplicationName, event.ResourceProperties.Region, 99 | function(err, data) { 100 | if (err) { 101 | responseData = { 102 | Error: 'Stopping kinesis application failed' 103 | }; 104 | console.log([responseData.Error, ':\n', err].join('')); 105 | } else { 106 | responseStatus = 'SUCCESS'; 107 | responseData = {}; 108 | } 109 | 110 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData); 111 | }); 112 | break; 113 | 114 | default: 115 | 116 | // Fail if RequestType is unexpected. 117 | sendResponse(event, callback, context.logStreamName, 'FAILED'); 118 | } 119 | break; 120 | 121 | default: 122 | if (event.RequestType === 'Delete') { 123 | if (event.ResourceProperties.CustomResourceAction === 'SendMetric') { 124 | responseStatus = 'SUCCESS'; 125 | 126 | let _metricsHelper = new MetricsHelper(); 127 | 128 | let _metric = { 129 | Solution: process.env.SOLUTION_ID, 130 | UUID: event.ResourceProperties.UUID, 131 | TimeStamp: moment().utc().format('YYYY-MM-DD HH:mm:ss.S'), 132 | Data: { 133 | Version: process.env.SOLUTION_VERSION, 134 | Deleted: moment().utc().format() 135 | } 136 | }; 137 | 138 | _metricsHelper.sendAnonymousMetric(_metric, function(err, data) { 139 | if (err) { 140 | responseData = { 141 | Error: 'Sending metrics helper delete failed' 142 | }; 143 | console.log([responseData.Error, ':\n', err].join('')); 144 | } 145 | sendResponse(event, callback, context.logStreamName, 'SUCCESS'); 146 | }); 147 | } else { 148 | sendResponse(event, callback, context.logStreamName, 'SUCCESS'); 149 | } 150 | } 151 | 152 | if (event.RequestType === 'Create') { 153 | if (event.ResourceProperties.CustomResourceAction === 'ConfigureWebsite') { 154 | 155 | _websiteHelper.configureWebsite(event.ResourceProperties.WebsiteBucket, event.ResourceProperties.Region, 156 | event.ResourceProperties.UUID, event.ResourceProperties.Configuration, 157 | (err, data) => { 158 | if (err) { 159 | responseData = { 160 | Error: 'Error creating website configuration file' 161 | }; 162 | console.log([responseData.Error, ':\n', err].join('')); 163 | } else { 164 | responseStatus = 'SUCCESS'; 165 | responseData = {}; 166 | } 167 | 168 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData); 169 | }); 170 | } else if (event.ResourceProperties.CustomResourceAction === 'DeployWebsite') { 171 | 172 | _websiteHelper.deployWebsite(event.ResourceProperties.SourceS3Bucket, event.ResourceProperties.sourceManifest, 173 | event.ResourceProperties.SourceS3Key, event.ResourceProperties.WebsiteBucket, 174 | (err, data) => { 175 | if (err) { 176 | responseData = { 177 | Error: 'Website deployment failed' 178 | }; 179 | console.log([responseData.Error, ':\n', err].join('')); 180 | } else { 181 | responseStatus = 'SUCCESS'; 182 | responseData = {}; 183 | } 184 | 185 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData); 186 | }) 187 | 188 | } else if (event.ResourceProperties.CustomResourceAction === 'GenerateUUID') { 189 | responseStatus = 'SUCCESS'; 190 | responseData = { 191 | UUID: UUID.v4() 192 | }; 193 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData); 194 | 195 | } else if (event.ResourceProperties.CustomResourceAction === 'SendMetric') { 196 | 197 | let _metric = { 198 | Solution: process.env.SOLUTION_ID, 199 | UUID: event.ResourceProperties.UUID, 200 | TimeStamp: moment().utc().format('YYYY-MM-DD HH:mm:ss.S'), 201 | Data: { 202 | Version: process.env.SOLUTION_VERSION, 203 | SendAnonymousData: process.env.SEND_ANONYMOUS_DATA, 204 | Launch: moment().utc().format() 205 | } 206 | }; 207 | 208 | _metricsHelper.sendAnonymousMetric(_metric, function(err, data) { 209 | if (err) { 210 | responseData = { 211 | Error: 'Sending anonymous launch metric failed' 212 | }; 213 | console.log([responseData.Error, ':\n', err].join('')); 214 | } else { 215 | responseStatus = 'SUCCESS'; 216 | responseData = {}; 217 | } 218 | }); 219 | sendResponse(event, callback, context.logStreamName, 'SUCCESS'); 220 | 221 | } else { 222 | console.log('CustomResourceAction is not defined'); 223 | sendResponse(event, callback, context.logStreamName, 'FAILED'); 224 | } 225 | 226 | } 227 | } 228 | 229 | }; 230 | 231 | /** 232 | * Sends a response to the pre-signed S3 URL 233 | */ 234 | let sendResponse = function(event, callback, logStreamName, responseStatus, responseData) { 235 | const responseBody = JSON.stringify({ 236 | Status: responseStatus, 237 | Reason: `See the details in CloudWatch Log Stream: ${logStreamName}`, 238 | PhysicalResourceId: logStreamName, 239 | StackId: event.StackId, 240 | RequestId: event.RequestId, 241 | LogicalResourceId: event.LogicalResourceId, 242 | Data: responseData, 243 | }); 244 | 245 | console.log('RESPONSE BODY:\n', responseBody); 246 | const parsedUrl = url.parse(event.ResponseURL); 247 | const options = { 248 | hostname: parsedUrl.hostname, 249 | port: 443, 250 | path: parsedUrl.path, 251 | method: 'PUT', 252 | headers: { 253 | 'Content-Type': '', 254 | 'Content-Length': responseBody.length, 255 | } 256 | }; 257 | 258 | const req = https.request(options, (res) => { 259 | console.log('STATUS:', res.statusCode); 260 | console.log('HEADERS:', JSON.stringify(res.headers)); 261 | callback(null, 'Successfully sent stack response!'); 262 | }); 263 | 264 | req.on('error', (err) => { 265 | console.log('sendResponse Error:\n', err); 266 | callback(err); 267 | }); 268 | 269 | req.write(responseBody); 270 | req.end(); 271 | }; -------------------------------------------------------------------------------- /source/custom-resource/lib/kinesis-helper.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/ * 8 | * * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | let AWS = require('aws-sdk'); 21 | 22 | /** 23 | * Helper function to turn on a Kinesis Analytics app cfn custom resource. 24 | * 25 | * @class bucketEncryptionHelper 26 | */ 27 | let kinesisAnalyticsAppHelper = (function() { 28 | 29 | /** 30 | * @class bucketEncryptionHelper 31 | * @constructor 32 | */ 33 | let kinesisAnalyticsAppHelper = function() {}; 34 | 35 | /** 36 | * Starts a Kinesis Data Analytics application. 37 | * @param {string} ApplicationName - Name of the Kinesis Data Analytics application. 38 | * @param {copyWebSiteAssets~requestCallback} cb - The callback that handles the response. 39 | */ 40 | kinesisAnalyticsAppHelper.prototype.startApplication = function(ApplicationName, region, cb) { 41 | console.log(['Looking up Kinesis Data Analytics application:', ApplicationName].join(' ')); 42 | 43 | AWS.config.update({region: region}) 44 | 45 | let ka = new AWS.KinesisAnalytics(); 46 | 47 | var params = { 48 | ApplicationName: ApplicationName 49 | }; 50 | 51 | ka.describeApplication(params, function(err, response) { 52 | console.log('response: ', response); 53 | if (err) { 54 | console.log(['Failed to describe application:', err].join(' ')); 55 | return cb(err, null); 56 | } else { 57 | if (response == null) { 58 | console.log(['Could not find application:', ApplicationName].join(' ')); 59 | return cb(['Kinesis Data Analytics application,', ApplicationName, ', could not be found!'].join(' '), null); 60 | } 61 | if (response.ApplicationDetail.ApplicationStatus === 'READY') { 62 | 63 | // Start App 64 | params = { 65 | ApplicationName: ApplicationName, 66 | InputConfigurations: [ 67 | { 68 | 'Id': '1.1', 69 | 'InputStartingPositionConfiguration': { 70 | 'InputStartingPosition': 'NOW' 71 | } 72 | } 73 | ] 74 | }; 75 | console.log("Starting application"); 76 | ka.startApplication(params, function(err, response) { 77 | if (err) { 78 | console.log(['Failed to start application', item.ApplicationName, ': ', err].join(' ')); 79 | return cb(err, null); 80 | } else { 81 | return cb(null, "SUCCESS"); 82 | } 83 | }); 84 | } else { 85 | return cb(['Kinesis Data Analytics Application was not in READY state (app status === ', response.ApplicationDetail.ApplicationStatus,')'].join(''), null); 86 | } 87 | } 88 | }); 89 | }; 90 | 91 | /** 92 | * Starts a Kinesis Data Analytics application. 93 | * @param {string} ApplicationName - Name of the Kinesis Data Analytics application. 94 | * @param {copyWebSiteAssets~requestCallback} cb - The callback that handles the response. 95 | */ 96 | kinesisAnalyticsAppHelper.prototype.stopApplication = function(ApplicationName, region, cb) { 97 | console.log(['Looking up Kinesis Data Analytics application:', ApplicationName].join(' ')); 98 | 99 | AWS.config.update({region: region}) 100 | 101 | let ka = new AWS.KinesisAnalytics(); 102 | 103 | var params = { 104 | ApplicationName: ApplicationName 105 | }; 106 | 107 | ka.describeApplication(params, function(err, response) { 108 | console.log('response: ', response); 109 | if (err) { 110 | console.log(['Failed to describe application:', err].join(' ')); 111 | return cb(err, null); 112 | } else { 113 | if (response == null) { 114 | console.log(['Could not find application:', ApplicationName].join(' ')); 115 | return cb(['Kinesis Data Analytics application,', ApplicationName, ', could not be found!'].join(' '), null); 116 | } 117 | if (response.ApplicationDetail.ApplicationStatus === 'RUNNING') { 118 | 119 | // Stop App 120 | params = { 121 | ApplicationName: ApplicationName 122 | }; 123 | 124 | console.log("Starting application"); 125 | ka.stopApplication(params, function(err, response) { 126 | if (err) { 127 | console.log(['Failed to stop application', item.ApplicationName, ': ', err].join(' ')); 128 | return cb(err, null); 129 | } else { 130 | return cb(null, "SUCCESS"); 131 | } 132 | }); 133 | } else { 134 | return cb(['Kinesis Data Analytics Application was not in RUNNING state (app status === ', response.ApplicationDetail.ApplicationStatus,')'].join(''), null); 135 | } 136 | } 137 | }); 138 | }; 139 | 140 | return kinesisAnalyticsAppHelper; 141 | 142 | })(); 143 | 144 | module.exports = kinesisAnalyticsAppHelper; 145 | -------------------------------------------------------------------------------- /source/custom-resource/lib/metrics-helper.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/ * 8 | * * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | let https = require('https'); 21 | 22 | /** 23 | * Helper function to send anonymous data from cfn custom resource. 24 | * 25 | * @class metricsHelper 26 | */ 27 | let metricsHelper = (function() { 28 | 29 | /** 30 | * @class metricsHelper 31 | * @constructor 32 | */ 33 | let metricsHelper = function() {}; 34 | 35 | /** 36 | * Sends opt-in, anonymous metric. 37 | * @param {json} metric - metric to send to opt-in, anonymous collection. 38 | * @param {sendAnonymousMetric~requestCallback} cb - The callback that handles the response. 39 | */ 40 | metricsHelper.prototype.sendAnonymousMetric = function(metric, cb) { 41 | let _options = { 42 | hostname: 'metrics.awssolutionsbuilder.com', 43 | port: 443, 44 | path: '/generic', 45 | method: 'POST', 46 | headers: { 47 | 'Content-Type': 'application/json' 48 | } 49 | }; 50 | 51 | let request = https.request(_options, function(response) { 52 | // data is streamed in chunks from the server 53 | // so we have to handle the "data" event 54 | let buffer; 55 | let data; 56 | let route; 57 | 58 | response.on('data', function(chunk) { 59 | buffer += chunk; 60 | }); 61 | 62 | response.on('end', function(err) { 63 | data = buffer; 64 | cb(null, data); 65 | }); 66 | }); 67 | 68 | if (metric) { 69 | request.write(JSON.stringify(metric)); 70 | } 71 | 72 | request.end(); 73 | 74 | request.on('error', (e) => { 75 | console.error(e); 76 | cb(['Error occurred when sending metric request.', JSON.stringify(_payload)].join(' '), null); 77 | }); 78 | }; 79 | 80 | return metricsHelper; 81 | 82 | })(); 83 | 84 | module.exports = metricsHelper; 85 | -------------------------------------------------------------------------------- /source/custom-resource/lib/s3-bucket-encryption-helper.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/ * 8 | * * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | let AWS = require('aws-sdk'); 21 | let s3 = new AWS.S3(); 22 | 23 | /** 24 | * Helper function to turn on S3 default bucket encryption for cfn custom resource. 25 | * 26 | * @class bucketEncryptionHelper 27 | */ 28 | let bucketEncryptionHelper = (function() { 29 | 30 | /** 31 | * @class bucketEncryptionHelper 32 | * @constructor 33 | */ 34 | let bucketEncryptionHelper = function() {}; 35 | 36 | /** 37 | * Enables default encryption for a given bucket. 38 | * @param {string} S3Bucket - S3 Bucket to enable default encryption. 39 | * @param {copyWebSiteAssets~requestCallback} cb - The callback that handles the response. 40 | */ 41 | bucketEncryptionHelper.prototype.enableDefaultBucketEncryption = function(bucket, algorithm, key, cb) { 42 | console.log(['Enabling default encryption on bucket:', bucket].join(' ')); 43 | var params = { 44 | Bucket: bucket, 45 | ServerSideEncryptionConfiguration: { 46 | Rules: [ 47 | { 48 | ApplyServerSideEncryptionByDefault: { 49 | SSEAlgorithm: algorithm 50 | } 51 | } 52 | ] 53 | } 54 | }; 55 | if (algorithm === 'aws:kms') { 56 | params.ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault.KMSMasterKeyID = key; 57 | } 58 | 59 | s3.putBucketEncryption(params, (err, result) => { 60 | if (err) { 61 | console.log(['Failed to enable default bucket encryption:', err].join(' ')); 62 | return cb(err, null); 63 | } else { 64 | console.log("Successfully enabled default bucket encryption."); 65 | return cb(null, "SUCCESS"); 66 | } 67 | }); 68 | }; 69 | 70 | return bucketEncryptionHelper; 71 | 72 | })(); 73 | 74 | module.exports = bucketEncryptionHelper; 75 | -------------------------------------------------------------------------------- /source/custom-resource/lib/website-helper.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/ * 8 | * * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | let AWS = require('aws-sdk'); 21 | let s3 = new AWS.S3(); 22 | const fs = require('fs'); 23 | const _downloadLocation = '/tmp/web-site-manifest.json'; 24 | 25 | /** 26 | * Helper function to interact with s3 hosted website for cfn custom resource. 27 | * 28 | * @class websiteHelper 29 | */ 30 | let websiteHelper = (function() { 31 | 32 | /** 33 | * @class websiteHelper 34 | * @constructor 35 | */ 36 | let websiteHelper = function() {}; 37 | 38 | websiteHelper.prototype.deployWebsite = function(sourceS3Bucket, sourceManifest, sourceS3prefix, websiteBucket, cb) { 39 | console.log(`Copying website from ${sourceS3Bucket}/${sourceS3prefix} to ${websiteBucket}`); 40 | 41 | downloadWebsiteManifest(sourceS3Bucket, sourceManifest, _downloadLocation, function(err, data) { 42 | if (err) { 43 | console.log(err); 44 | return cb(err, null); 45 | } 46 | 47 | console.log('data:', data); 48 | 49 | fs.readFile(_downloadLocation, 'utf8', function(err, data) { 50 | if (err) { 51 | console.log(err); 52 | return cb(err, null); 53 | } 54 | 55 | console.log(data); 56 | let _manifest = validateJSON(data); 57 | 58 | if (!_manifest) { 59 | return cb('Unable to validate downloaded manifest file JSON', null); 60 | } else { 61 | uploadFile(_manifest.files, 0, websiteBucket, [sourceS3Bucket, sourceS3prefix] 62 | .join('/'), 63 | function(err, result) { 64 | if (err) { 65 | return cb(err, null); 66 | } 67 | 68 | return cb(null, result); 69 | 70 | }); 71 | } 72 | 73 | }); 74 | 75 | }); 76 | } 77 | 78 | websiteHelper.prototype.configureWebsite = function(websiteBucket, region, UUID, configuration, cb) { 79 | try { 80 | let _content = ''; 81 | 82 | // Add each key/value to localStorage. 83 | for (var key in configuration) { 84 | _content += `localStorage.setItem('${key}', '${configuration[key]}');`; 85 | } 86 | 87 | _content += `var _dashboard_usage = '${process.env.SEND_ANONYMOUS_DATA}';`; 88 | _content += ` 89 | var _hit_data = { 90 | Solution: '${process.env.SOLUTION_ID}', 91 | UUID: '${UUID}', 92 | Data: { 93 | dashboard: 1, 94 | region: '${region}' 95 | } 96 | } 97 | ` 98 | 99 | let params = { 100 | Bucket: websiteBucket, 101 | Key: 'js/app-variables.js', 102 | Body: _content 103 | }; 104 | 105 | s3.putObject(params, (err, data) => { 106 | if (err) { 107 | console.log(err); 108 | return cb('error creating js/app-variables.js file for website UI', null); 109 | } 110 | 111 | console.log(data); 112 | return cb(null, data); 113 | }); 114 | } 115 | catch (err) { 116 | return cb(err, null); 117 | } 118 | 119 | } 120 | 121 | /** 122 | * Helper function to validate the JSON structure of contents of an import manifest file. 123 | * @param {string} body - JSON object stringify-ed. 124 | * @returns {JSON} - The JSON parsed string or null if string parsing failed 125 | */ 126 | let validateJSON = function(body) { 127 | try { 128 | let data = JSON.parse(body); 129 | console.log(data); 130 | return data; 131 | } catch (e) { 132 | // failed to parse 133 | console.log('Manifest file contains invalid JSON.'); 134 | return null; 135 | } 136 | }; 137 | 138 | let uploadFile = function(filelist, index, websiteBucket, sourceS3prefix, cb) { 139 | if (filelist.length > index) { 140 | let params = { 141 | Bucket: websiteBucket, 142 | Key: filelist[index], 143 | CopySource: [sourceS3prefix, filelist[index]].join('/'), 144 | }; 145 | if (filelist[index].endsWith('.htm') || filelist[index].endsWith('.html')) { 146 | params.ContentType = "text/html"; 147 | params.MetadataDirective = "REPLACE"; 148 | } else if (filelist[index].endsWith('.css')) { 149 | params.ContentType = "text/css"; 150 | params.MetadataDirective = "REPLACE"; 151 | } else if (filelist[index].endsWith('.js')) { 152 | params.ContentType = "application/javascript"; 153 | params.MetadataDirective = "REPLACE"; 154 | } else if (filelist[index].endsWith('.png')) { 155 | params.ContentType = "image/png"; 156 | params.MetadataDirective = "REPLACE"; 157 | } else if (filelist[index].endsWith('.jpg') || filelist[index].endsWith('.jpeg')) { 158 | params.ContentType = "image/jpeg"; 159 | params.MetadataDirective = "REPLACE"; 160 | } else if (filelist[index].endsWith('.gif')) { 161 | params.ContentType = "image/gif"; 162 | params.MetadataDirective = "REPLACE"; 163 | }; 164 | 165 | s3.copyObject(params, function(err, data) { 166 | if (err) { 167 | return cb(['error copying ', [sourceS3prefix, filelist[index]].join('/'), '\n', err] 168 | .join( 169 | ''), 170 | null); 171 | } 172 | 173 | console.log([ 174 | [sourceS3prefix, filelist[index]].join('/'), 'uploaded successfully' 175 | ].join(' ')); 176 | let _next = index + 1; 177 | uploadFile(filelist, _next, websiteBucket, sourceS3prefix, function(err, resp) { 178 | if (err) { 179 | return cb(err, null); 180 | } 181 | 182 | cb(null, resp); 183 | }); 184 | }); 185 | } else { 186 | cb(null, [index, 'files copied'].join(' ')); 187 | } 188 | 189 | }; 190 | 191 | /** 192 | * Helper function to download the website manifest to local storage for processing. 193 | * @param {string} s3_bucket - Amazon S3 bucket of the website manifest to download. 194 | * @param {string} s3_key - Amazon S3 key of the website manifest to download. 195 | * @param {string} downloadLocation - Local storage location to download the Amazon S3 object. 196 | * @param {downloadManifest~requestCallback} cb - The callback that handles the response. 197 | */ 198 | let downloadWebsiteManifest = function(s3Bucket, sourceManifest, downloadLocation, cb) { 199 | let params = { 200 | Bucket: s3Bucket, 201 | Key: sourceManifest 202 | }; 203 | 204 | console.log(params); 205 | 206 | // check to see if the manifest file exists 207 | s3.headObject(params, function(err, metadata) { 208 | if (err) { 209 | console.log(err); 210 | } 211 | 212 | if (err && err.code === 'NotFound') { 213 | // Handle no object on cloud here 214 | console.log('file doesnt exist'); 215 | return cb('Manifest file was not found.', null); 216 | } else { 217 | console.log('file exists'); 218 | console.log(metadata); 219 | let file = require('fs').createWriteStream(downloadLocation); 220 | 221 | s3.getObject(params). 222 | on('httpData', function(chunk) { 223 | file.write(chunk); 224 | }). 225 | on('httpDone', function() { 226 | file.end(); 227 | console.log('website manifest downloaded for processing...'); 228 | return cb(null, 'success'); 229 | }). 230 | send(); 231 | } 232 | }); 233 | }; 234 | 235 | return websiteHelper; 236 | 237 | })(); 238 | 239 | module.exports = websiteHelper; -------------------------------------------------------------------------------- /source/custom-resource/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "custom-resource-helper", 3 | "description": "Solutions Builder custom resource helper Lambda function", 4 | "main": "index.js", 5 | "author": { 6 | "name": "aws-solutions-builder" 7 | }, 8 | "version": "0.0.1", 9 | "private": "true", 10 | "dependencies": { 11 | "amazon-cognito-identity-js": "^1.31.0", 12 | "moment": "*", 13 | "node-uuid": "*", 14 | "underscore": "*" 15 | }, 16 | "devDependencies": { 17 | "aws-sdk": "*", 18 | "chai": "*", 19 | "sinon": "*", 20 | "sinon-chai": "*", 21 | "mocha": "*", 22 | "aws-sdk-mock": "*", 23 | "npm-run-all": "*" 24 | }, 25 | "scripts": { 26 | "pretest": "npm install", 27 | "test": "mocha lib/*.spec.js", 28 | "build-init": "rm -rf dist && rm -f archive.zip && mkdir dist && mkdir dist/lib", 29 | "build:copy": "cp index.js dist/ && cp -r lib/*.js dist/lib", 30 | "build:install": "cp package.json dist/ && cd dist && npm install --production", 31 | "build": "npm-run-all -s build-init build:copy build:install", 32 | "zip": "cd dist && zip -rq custom-resource-helper.zip ." 33 | }, 34 | "bundledDependencies": [ 35 | "moment", 36 | "underscore", 37 | "node-uuid" 38 | ] 39 | } 40 | -------------------------------------------------------------------------------- /source/demo/send-messages.sh: -------------------------------------------------------------------------------- 1 | # Set Defaults 2 | REGION='us-east-1' 3 | TOPIC='iot_device_analytics' 4 | PROFILE='default' 5 | ITERATIONS=1000 6 | WAIT=2 7 | 8 | # Get command line parameters 9 | while [ "$1" != "" ]; do 10 | case $1 in 11 | -r | --region ) 12 | shift 13 | REGION=$1 14 | ;; 15 | 16 | -t | --topic ) 17 | shift 18 | TOPIC=$1 19 | ;; 20 | 21 | -p | --profile ) 22 | shift 23 | PROFILE=$1 24 | ;; 25 | 26 | -i | --iterations ) 27 | shift 28 | ITERATIONS=$1 29 | ;; 30 | 31 | -w | --wait ) 32 | shift 33 | WAIT=$1 34 | ;; 35 | esac 36 | shift 37 | done 38 | 39 | 40 | for (( i = 1; i <= $ITERATIONS; i++)) { 41 | 42 | DEVICE="P0"$((1 + $RANDOM % 5)) 43 | FLOW=$(( 60 + $RANDOM % 40 )) 44 | TEMP=$(( 15 + $RANDOM % 20 )) 45 | HUMIDITY=$(( 50 + $RANDOM % 40 )) 46 | SOUND=$(( 100 + $RANDOM % 40 )) 47 | 48 | # 3% chance of throwing an anomalous temperature reading 49 | if [ $(($RANDOM % 100)) -gt 97 ] 50 | then 51 | echo "TEMPERATURE OUT OF RANGE" 52 | TEMP=$(($TEMP*6)) 53 | fi 54 | 55 | echo "Publishing message $i/$ITERATIONS to IoT topic $TOPIC:" 56 | echo "device: $DEVICE" 57 | echo "flow: $FLOW" 58 | echo "temp: $TEMP" 59 | echo "humidity: $HUMIDITY" 60 | echo "sound: $SOUND" 61 | 62 | aws iot-data publish --topic "$TOPIC" --payload "{\"id\":\"1\",\"device\":\"$DEVICE\",\"flow\":$FLOW,\"temp\":$TEMP,\"humidity\":$HUMIDITY,\"sound\":$SOUND}" --profile "$PROFILE" --region "$REGION" 63 | 64 | sleep $WAIT 65 | 66 | } 67 | -------------------------------------------------------------------------------- /source/update_ddb_from_stream/update_ddb_from_stream.py: -------------------------------------------------------------------------------- 1 | ###################################################################################################################### 2 | # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # 3 | # # 4 | # Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance # 5 | # with the License. A copy of the License is located at # 6 | # # 7 | # http://www.apache.org/licenses/ # 8 | # # 9 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # 10 | # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions # 11 | # and limitations under the License. # 12 | ###################################################################################################################### 13 | 14 | from itertools import groupby 15 | import boto3 16 | import botocore 17 | import base64 18 | import logging 19 | import os 20 | import urllib.request, urllib.error, urllib.parse 21 | from json import loads,dumps 22 | from collections import OrderedDict 23 | from datetime import datetime 24 | from operator import itemgetter 25 | from random import randint 26 | from sys import maxsize 27 | from time import sleep 28 | 29 | log_level = str(os.environ.get('LOG_LEVEL')).upper() 30 | if log_level not in ['DEBUG', 'INFO','WARNING', 'ERROR','CRITICAL']: 31 | log_level = 'ERROR' 32 | log = logging.getLogger() 33 | log.setLevel(log_level) 34 | 35 | send_anonymous_data = str(os.environ.get('SEND_ANONYMOUS_DATA')).upper() 36 | table_name = os.environ["ANALYTICS_TABLE"] 37 | max_retry_attempts = 5 38 | client = boto3.client('dynamodb') 39 | avg = lambda lst : float(sum(lst))/len(lst) 40 | type_operator_map = { 41 | 'ConnectedDevicesCount' : max, 42 | 'PerDeviceMaxTemp' : max, 43 | 'PerDeviceMinTemp': min, 44 | 'PerDeviceAvgTemp': avg, 45 | 'DeviceTempAnomalyScore': max, 46 | 'AvgTempValue': avg, 47 | 'MinTempValue': min, 48 | 'MaxTempValue': max, 49 | 'MaxDisconnTime': max, 50 | 'MinDisconnTime': min, 51 | 'AvgDisconnTime': avg, 52 | 'MaxConnTime': max, 53 | 'MinConnTime': min, 54 | 'AvgConnTime': avg 55 | } 56 | 57 | def put_record_with_retry(metric_type, event_time, record_data, merged_data, concurrency_token, attempt=0): 58 | print("Retry: {0} {1} {2}".format(metric_type, event_time, str(attempt))) 59 | if attempt > max_retry_attempts: return 60 | try: 61 | put_record(metric_type, event_time, merged_data, concurrency_token) 62 | except botocore.exceptions.ClientError as e: 63 | if e.response['Error']['Code'] == 'ConditionalCheckFailedException': 64 | sleep(randint(0,5)) 65 | ddb_record = client.get_item( 66 | TableName = table_name, 67 | Key = { 68 | 'MetricType': {'S': metric_type}, 69 | 'EventTime': {'S': event_time} 70 | }, 71 | ConsistentRead = True 72 | ) 73 | merged_data = merge_record_with_ddb(record_data, ddb_record) 74 | put_record_with_retry(metric_type, event_time, record_data, merged_data, concurrency_token, attempt+1) 75 | else: raise 76 | 77 | def put_record(metric_type, event_time, data, concurrency_token=None): 78 | item = { 79 | 'MetricType': {'S':metric_type}, 80 | 'EventTime': {'S':event_time}, 81 | 'Data': {'S':dumps(data)}, 82 | 'ConcurrencyToken': {'N':str(randint(0,maxsize))} 83 | } 84 | 85 | if concurrency_token: 86 | client.put_item( 87 | TableName = table_name, 88 | Item = item, 89 | ConditionExpression = 'ConcurrencyToken = :concurrency_token', 90 | ExpressionAttributeValues = {':concurrency_token': {'N': str(concurrency_token)}} 91 | ) 92 | else: 93 | client.put_item(TableName = table_name, Item = item) 94 | 95 | def merge_record_with_ddb(record_data, ddb_record): 96 | ddb_data = loads(ddb_record['Item']['Data']['S']) 97 | metric_type = ddb_record['Item']['MetricType']['S'] 98 | concurrency_token = int(ddb_record['Item']['ConcurrencyToken']['N']) 99 | merged_data = { k : merge_values(record_data, ddb_data, metric_type, k) for k in set(record_data) | set(ddb_data) } 100 | merged_data = OrderedDict(sorted(iter(merged_data.items()), key=itemgetter(1), reverse=True)) 101 | return merged_data 102 | 103 | def merge_values(record_data, set_data, metric_type, k): 104 | if k not in record_data: return set_data[k] 105 | if k not in set_data: return record_data[k] 106 | return type_operator_map[metric_type]([set_data[k], record_data[k]]) 107 | 108 | def merge_record_values(metric_key, grouped_rows): 109 | if 'DeviceTempAnomalyScore' in metric_key: 110 | return max(float(key[5]) for key in grouped_rows) 111 | else: 112 | metric_key_split = metric_key.split('|') 113 | metric_key_value = metric_key_split[1] 114 | return type_operator_map[metric_key_value]([float(key[5]) for key in grouped_rows]) 115 | 116 | # This function sends anonymous usage data, if enabled 117 | def sendAnonymousData(event_time,dataDict): 118 | log.debug("Sending Anonymous Data") 119 | postDict = {} 120 | postDict['Data'] = dataDict 121 | postDict['TimeStamp'] = event_time 122 | postDict['Solution'] = os.environ.get('SOLUTION_ID') 123 | postDict['Version'] = os.environ.get('SOLUTION_VERSION') 124 | postDict['UUID'] = os.environ.get('SOLUTION_UUID') 125 | # API Gateway URL to make HTTP POST call 126 | url = 'https://metrics.awssolutionsbuilder.com/generic' 127 | data=dumps(postDict) 128 | data_utf8 = data.encode('utf-8') 129 | log.debug('sendAnonymousData data: %s', data) 130 | headers = { 131 | 'content-type': 'application/json; charset=utf-8', 132 | 'content-length': len(data_utf8) 133 | } 134 | req = urllib.request.Request(url, data_utf8, headers) 135 | rsp = urllib.request.urlopen(req) 136 | rspcode = rsp.getcode() 137 | content = rsp.read() 138 | log.debug("Response from APIGateway: %s, %s", rspcode, content) 139 | 140 | def lambda_handler(event, context): 141 | log.debug('event: %s', event) 142 | payload = event['records'] 143 | output = {} 144 | output_array = [] 145 | log.debug('processing %s records', len(payload)) 146 | 147 | # event_time = str(datetime.now()) 148 | 149 | for record in payload: 150 | 151 | decoded_data = base64.b64decode(record['data']).decode("utf-8") 152 | 153 | log.debug('decoded_data: %s', decoded_data) 154 | 155 | data = [decoded_data.strip().split(',')] 156 | data = [x for x in data if x[2]!="null"] 157 | 158 | for metric_key, metric_group in groupby(data, key=lambda x:"{0}|{1}".format(x[0],x[1])): 159 | grouped_metric = list(metric_group) 160 | for category_key, grouped_rows in groupby(grouped_metric, key=lambda x: "{0}|{1}".format(x[2],x[3])): 161 | output.setdefault(metric_key, {})[category_key] = merge_record_values(metric_key, list(grouped_rows)) 162 | 163 | for record_key in output: 164 | log.debug('record_key: %s', record_key) 165 | event_time, metric_type = record_key.split('|') 166 | log.debug('event_time: %s', event_time) 167 | log.debug('metric_type: %s', metric_type) 168 | record_data = OrderedDict(sorted(iter(output[record_key].items()), key=itemgetter(1), reverse=True)) 169 | 170 | ddb_record = client.get_item( 171 | TableName=table_name, 172 | Key={ 173 | 'MetricType': {'S':metric_type}, 174 | 'EventTime': {'S':event_time} 175 | }, 176 | ConsistentRead=True 177 | ) 178 | 179 | if 'Item' not in ddb_record: 180 | put_record(metric_type, event_time, record_data) 181 | else: 182 | merged_data = merge_record_with_ddb(record_data, ddb_record) 183 | put_record_with_retry(metric_type, event_time, record_data, merged_data, int(ddb_record['Item']['ConcurrencyToken']['N'])) 184 | 185 | output_record = { 186 | 'recordId': record['recordId'], 187 | 'result': 'Ok', 188 | 'data': base64.b64encode(decoded_data.encode("utf-8")).decode("utf-8") 189 | } 190 | output_array.append(output_record) 191 | 192 | if send_anonymous_data == "TRUE": 193 | try: 194 | metric_data = {} 195 | metric_data['RecordsProcessed'] = len(payload) 196 | sendAnonymousData(event_time, metric_data) 197 | except Exception as error: 198 | log.error('send_anonymous_data error: %s', error) 199 | else: 200 | log.info('Anonymous usage metrics collection disabled.') 201 | 202 | log.debug('returning records: %s', output_array) 203 | 204 | return {'records': output_array} 205 | -------------------------------------------------------------------------------- /source/web_site/css/jquery-jvectormap-2.0.3.css: -------------------------------------------------------------------------------- 1 | svg { 2 | touch-action: none; 3 | } 4 | 5 | .jvectormap-container { 6 | width: 100%; 7 | height: 100%; 8 | position: relative; 9 | overflow: hidden; 10 | touch-action: none; 11 | } 12 | 13 | .jvectormap-tip { 14 | position: absolute; 15 | display: none; 16 | border: solid 1px #CDCDCD; 17 | border-radius: 3px; 18 | background: #292929; 19 | color: white; 20 | font-family: sans-serif, Verdana; 21 | font-size: smaller; 22 | padding: 3px; 23 | } 24 | 25 | .jvectormap-zoomin, .jvectormap-zoomout, .jvectormap-goback { 26 | position: absolute; 27 | left: 10px; 28 | border-radius: 3px; 29 | background: #292929; 30 | padding: 3px; 31 | color: white; 32 | cursor: pointer; 33 | line-height: 10px; 34 | text-align: center; 35 | box-sizing: content-box; 36 | } 37 | 38 | .jvectormap-zoomin, .jvectormap-zoomout { 39 | width: 10px; 40 | height: 10px; 41 | } 42 | 43 | .jvectormap-zoomin { 44 | top: 10px; 45 | } 46 | 47 | .jvectormap-zoomout { 48 | top: 30px; 49 | } 50 | 51 | .jvectormap-goback { 52 | bottom: 10px; 53 | z-index: 1000; 54 | padding: 6px; 55 | } 56 | 57 | .jvectormap-spinner { 58 | position: absolute; 59 | left: 0; 60 | top: 0; 61 | right: 0; 62 | bottom: 0; 63 | background: center no-repeat url(data:image/gif;base64,R0lGODlhIAAgAPMAAP///wAAAMbGxoSEhLa2tpqamjY2NlZWVtjY2OTk5Ly8vB4eHgQEBAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAIAAgAAAE5xDISWlhperN52JLhSSdRgwVo1ICQZRUsiwHpTJT4iowNS8vyW2icCF6k8HMMBkCEDskxTBDAZwuAkkqIfxIQyhBQBFvAQSDITM5VDW6XNE4KagNh6Bgwe60smQUB3d4Rz1ZBApnFASDd0hihh12BkE9kjAJVlycXIg7CQIFA6SlnJ87paqbSKiKoqusnbMdmDC2tXQlkUhziYtyWTxIfy6BE8WJt5YJvpJivxNaGmLHT0VnOgSYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ/V/nmOM82XiHRLYKhKP1oZmADdEAAAh+QQJCgAAACwAAAAAIAAgAAAE6hDISWlZpOrNp1lGNRSdRpDUolIGw5RUYhhHukqFu8DsrEyqnWThGvAmhVlteBvojpTDDBUEIFwMFBRAmBkSgOrBFZogCASwBDEY/CZSg7GSE0gSCjQBMVG023xWBhklAnoEdhQEfyNqMIcKjhRsjEdnezB+A4k8gTwJhFuiW4dokXiloUepBAp5qaKpp6+Ho7aWW54wl7obvEe0kRuoplCGepwSx2jJvqHEmGt6whJpGpfJCHmOoNHKaHx61WiSR92E4lbFoq+B6QDtuetcaBPnW6+O7wDHpIiK9SaVK5GgV543tzjgGcghAgAh+QQJCgAAACwAAAAAIAAgAAAE7hDISSkxpOrN5zFHNWRdhSiVoVLHspRUMoyUakyEe8PTPCATW9A14E0UvuAKMNAZKYUZCiBMuBakSQKG8G2FzUWox2AUtAQFcBKlVQoLgQReZhQlCIJesQXI5B0CBnUMOxMCenoCfTCEWBsJColTMANldx15BGs8B5wlCZ9Po6OJkwmRpnqkqnuSrayqfKmqpLajoiW5HJq7FL1Gr2mMMcKUMIiJgIemy7xZtJsTmsM4xHiKv5KMCXqfyUCJEonXPN2rAOIAmsfB3uPoAK++G+w48edZPK+M6hLJpQg484enXIdQFSS1u6UhksENEQAAIfkECQoAAAAsAAAAACAAIAAABOcQyEmpGKLqzWcZRVUQnZYg1aBSh2GUVEIQ2aQOE+G+cD4ntpWkZQj1JIiZIogDFFyHI0UxQwFugMSOFIPJftfVAEoZLBbcLEFhlQiqGp1Vd140AUklUN3eCA51C1EWMzMCezCBBmkxVIVHBWd3HHl9JQOIJSdSnJ0TDKChCwUJjoWMPaGqDKannasMo6WnM562R5YluZRwur0wpgqZE7NKUm+FNRPIhjBJxKZteWuIBMN4zRMIVIhffcgojwCF117i4nlLnY5ztRLsnOk+aV+oJY7V7m76PdkS4trKcdg0Zc0tTcKkRAAAIfkECQoAAAAsAAAAACAAIAAABO4QyEkpKqjqzScpRaVkXZWQEximw1BSCUEIlDohrft6cpKCk5xid5MNJTaAIkekKGQkWyKHkvhKsR7ARmitkAYDYRIbUQRQjWBwJRzChi9CRlBcY1UN4g0/VNB0AlcvcAYHRyZPdEQFYV8ccwR5HWxEJ02YmRMLnJ1xCYp0Y5idpQuhopmmC2KgojKasUQDk5BNAwwMOh2RtRq5uQuPZKGIJQIGwAwGf6I0JXMpC8C7kXWDBINFMxS4DKMAWVWAGYsAdNqW5uaRxkSKJOZKaU3tPOBZ4DuK2LATgJhkPJMgTwKCdFjyPHEnKxFCDhEAACH5BAkKAAAALAAAAAAgACAAAATzEMhJaVKp6s2nIkolIJ2WkBShpkVRWqqQrhLSEu9MZJKK9y1ZrqYK9WiClmvoUaF8gIQSNeF1Er4MNFn4SRSDARWroAIETg1iVwuHjYB1kYc1mwruwXKC9gmsJXliGxc+XiUCby9ydh1sOSdMkpMTBpaXBzsfhoc5l58Gm5yToAaZhaOUqjkDgCWNHAULCwOLaTmzswadEqggQwgHuQsHIoZCHQMMQgQGubVEcxOPFAcMDAYUA85eWARmfSRQCdcMe0zeP1AAygwLlJtPNAAL19DARdPzBOWSm1brJBi45soRAWQAAkrQIykShQ9wVhHCwCQCACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq+E71SRQeyqUToLA7VxF0JDyIQh/MVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiRMDjI0Fd30/iI2UA5GSS5UDj2l6NoqgOgN4gksEBgYFf0FDqKgHnyZ9OX8HrgYHdHpcHQULXAS2qKpENRg7eAMLC7kTBaixUYFkKAzWAAnLC7FLVxLWDBLKCwaKTULgEwbLA4hJtOkSBNqITT3xEgfLpBtzE/jiuL04RGEBgwWhShRgQExHBAAh+QQJCgAAACwAAAAAIAAgAAAE7xDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfZiCqGk5dTESJeaOAlClzsJsqwiJwiqnFrb2nS9kmIcgEsjQydLiIlHehhpejaIjzh9eomSjZR+ipslWIRLAgMDOR2DOqKogTB9pCUJBagDBXR6XB0EBkIIsaRsGGMMAxoDBgYHTKJiUYEGDAzHC9EACcUGkIgFzgwZ0QsSBcXHiQvOwgDdEwfFs0sDzt4S6BK4xYjkDOzn0unFeBzOBijIm1Dgmg5YFQwsCMjp1oJ8LyIAACH5BAkKAAAALAAAAAAgACAAAATwEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq+E71SRQeyqUToLA7VxF0JDyIQh/MVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GGl6NoiPOH16iZKNlH6KmyWFOggHhEEvAwwMA0N9GBsEC6amhnVcEwavDAazGwIDaH1ipaYLBUTCGgQDA8NdHz0FpqgTBwsLqAbWAAnIA4FWKdMLGdYGEgraigbT0OITBcg5QwPT4xLrROZL6AuQAPUS7bxLpoWidY0JtxLHKhwwMJBTHgPKdEQAACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq+E71SRQeyqUToLA7VxF0JDyIQh/MVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GAULDJCRiXo1CpGXDJOUjY+Yip9DhToJA4RBLwMLCwVDfRgbBAaqqoZ1XBMHswsHtxtFaH1iqaoGNgAIxRpbFAgfPQSqpbgGBqUD1wBXeCYp1AYZ19JJOYgH1KwA4UBvQwXUBxPqVD9L3sbp2BNk2xvvFPJd+MFCN6HAAIKgNggY0KtEBAAh+QQJCgAAACwAAAAAIAAgAAAE6BDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfYIDMaAFdTESJeaEDAIMxYFqrOUaNW4E4ObYcCXaiBVEgULe0NJaxxtYksjh2NLkZISgDgJhHthkpU4mW6blRiYmZOlh4JWkDqILwUGBnE6TYEbCgevr0N1gH4At7gHiRpFaLNrrq8HNgAJA70AWxQIH1+vsYMDAzZQPC9VCNkDWUhGkuE5PxJNwiUK4UfLzOlD4WvzAHaoG9nxPi5d+jYUqfAhhykOFwJWiAAAIfkECQoAAAAsAAAAACAAIAAABPAQyElpUqnqzaciSoVkXVUMFaFSwlpOCcMYlErAavhOMnNLNo8KsZsMZItJEIDIFSkLGQoQTNhIsFehRww2CQLKF0tYGKYSg+ygsZIuNqJksKgbfgIGepNo2cIUB3V1B3IvNiBYNQaDSTtfhhx0CwVPI0UJe0+bm4g5VgcGoqOcnjmjqDSdnhgEoamcsZuXO1aWQy8KAwOAuTYYGwi7w5h+Kr0SJ8MFihpNbx+4Erq7BYBuzsdiH1jCAzoSfl0rVirNbRXlBBlLX+BP0XJLAPGzTkAuAOqb0WT5AH7OcdCm5B8TgRwSRKIHQtaLCwg1RAAAOwAAAAAAAAAAAA==); 64 | } 65 | 66 | .jvectormap-legend-title { 67 | font-weight: bold; 68 | font-size: 14px; 69 | text-align: center; 70 | } 71 | 72 | .jvectormap-legend-cnt { 73 | position: absolute; 74 | } 75 | 76 | .jvectormap-legend-cnt-h { 77 | bottom: 0; 78 | right: 0; 79 | } 80 | 81 | .jvectormap-legend-cnt-v { 82 | top: 0; 83 | right: 0; 84 | } 85 | 86 | .jvectormap-legend { 87 | background: black; 88 | color: white; 89 | border-radius: 3px; 90 | } 91 | 92 | .jvectormap-legend-cnt-h .jvectormap-legend { 93 | float: left; 94 | margin: 0 10px 10px 0; 95 | padding: 3px 3px 1px 3px; 96 | } 97 | 98 | .jvectormap-legend-cnt-h .jvectormap-legend .jvectormap-legend-tick { 99 | float: left; 100 | } 101 | 102 | .jvectormap-legend-cnt-v .jvectormap-legend { 103 | margin: 10px 10px 0 0; 104 | padding: 3px; 105 | } 106 | 107 | .jvectormap-legend-cnt-h .jvectormap-legend-tick { 108 | width: 40px; 109 | } 110 | 111 | .jvectormap-legend-cnt-h .jvectormap-legend-tick-sample { 112 | height: 15px; 113 | } 114 | 115 | .jvectormap-legend-cnt-v .jvectormap-legend-tick-sample { 116 | height: 20px; 117 | width: 20px; 118 | display: inline-block; 119 | vertical-align: middle; 120 | } 121 | 122 | .jvectormap-legend-tick-text { 123 | font-size: 12px; 124 | } 125 | 126 | .jvectormap-legend-cnt-h .jvectormap-legend-tick-text { 127 | text-align: center; 128 | } 129 | 130 | .jvectormap-legend-cnt-v .jvectormap-legend-tick-text { 131 | display: inline-block; 132 | vertical-align: middle; 133 | line-height: 20px; 134 | padding-left: 3px; 135 | } 136 | -------------------------------------------------------------------------------- /source/web_site/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-solutions/real-time-iot-device-monitoring-with-kinesis/c6522117bfb54d8ed8b47202f467eb23292f5a89/source/web_site/favicon.ico -------------------------------------------------------------------------------- /source/web_site/index.html: -------------------------------------------------------------------------------- 1 | 13 | 14 | 15 | 16 | 17 | 18 | AWS IoT Device Monitoring Dashboard 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
32 |
33 | 34 |
35 | 40 | AWS IoT Device Monitoring Dashboard 41 |
42 | 43 |
44 |
    45 |
  • 46 | 47 | Configure 48 |
  • 49 | 53 |
  • 54 | 55 | Signing In 56 |
  • 57 | 58 |
  • 59 | 60 | Log Out 61 |
  • 62 | 63 |
64 |
65 |
66 | 67 |
68 |
69 | 70 |
71 | 72 |
73 |
74 | 75 |
76 | 77 | 78 |
79 |
80 |

AWS IoT Device Monitoring Dashboard

81 |

Sign in to get started.

83 |
84 |
85 | 86 |
87 |
88 |
89 |
90 | 93 |

Configuration

94 |
95 |
96 |
97 | The Dashboard is not configured correctly. Please ensure these values are set and are accurate. 98 |
99 | 100 |

101 | These values are used by the Dashboard to validate users in your Cognito User Pool. Don't change these values unless you 102 | know what you're doing! 103 |

104 |
105 |
106 |
107 | 108 | 109 |
110 |
111 | 112 | 113 |
114 |
115 | 116 | 117 |
118 |
119 | 120 | 121 |
122 |
123 | 124 | 125 |
126 |
127 |
128 |
129 |
130 | 131 | 132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 | 143 |

Create New Password

144 |
145 |
146 |
147 | The passwords you entered do not match! 148 |
149 |
150 | The password you entered does not meet the following complexity requirements: 151 |
    152 |
  • 8 or more characters
  • 153 |
  • Upper case character
  • 154 |
  • Lower case character
  • 155 |
  • Number
  • 156 |
157 |
158 |
159 |
160 |

161 | Your temporary password must be changed! Please create a new password (8 or more characters, one of which must be 162 | uppercase, lowercase, and a number). 163 |

164 |
165 |
166 |
167 | 168 | 169 |
170 |
171 | 172 | 173 |
174 |
175 | 176 |
177 |
178 |
179 |
180 | 181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |

Total number of connected devices

189 |
190 |
191 |
192 |

Count: 0

193 |
194 | 195 | Last Updated: 196 |

0

197 |
198 |
199 |
200 |
201 |
202 | 203 |
204 |
205 |
206 |

Anomaly Scores 207 | Updated every 10 seconds 208 |

209 |
210 |
211 | 212 |
213 |
214 |
215 | 216 |
217 |
218 | 219 |
220 |

Average Temperature Value

221 |
222 |
223 | 224 |
225 |
226 | 227 |
228 |
229 |

Minimum Temperature Value

230 |
231 |
232 | 233 |
234 |
235 |
236 | 237 |
238 |
239 | 240 |
241 |

Maximum Temperature Value

242 |
243 |
244 | 245 |
246 |
247 | 248 |
249 |
250 |

Avg Temperature per Device

251 |
252 |
253 | 254 |
255 |
256 |
257 | 258 |
259 |
260 | 261 |
262 |

Min Temperature per Device

263 |
264 |
265 | 266 |
267 |
268 | 269 |
270 |
271 |

Max Temperature per Device

272 |
273 |
274 | 275 |
276 |
277 |
278 | 279 |
280 |
281 | 282 |
283 |

Average Connection Time

284 |
285 |
286 | 287 |
288 |
289 | 290 |
291 |
292 |

Average Disconnect Time

293 |
294 |
295 | 296 |
297 |
298 |
299 | 300 |
301 |
302 |
303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 315 | 316 | 317 | -------------------------------------------------------------------------------- /source/web_site/js/app-variables.js.example: -------------------------------------------------------------------------------- 1 | localStorage.setItem('UserPoolClientId', ''); 2 | localStorage.setItem('UserPoolId', ''); 3 | localStorage.setItem('AnalyticsTable', ''); 4 | localStorage.setItem('Region', ''); 5 | localStorage.setItem('IdentityPoolId', ''); 6 | var _dashboard_usage = 'True'; 7 | var _hit_data = { 8 | Solution: '', 9 | UUID: '', 10 | Data: { 11 | dashboard: 1, 12 | region: '' 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /source/web_site/js/dash.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/ * 8 | * * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | function init() { 15 | 16 | console.log('dash.js initialized'); 17 | 18 | const clientIdParamName = "UserPoolClientId"; 19 | const userPoolIdParamName = "UserPoolId"; 20 | const identityPoolIdParamName = "IdentityPoolId"; 21 | const cognitoRegionParamName = "Region"; 22 | 23 | var streamName, 24 | streamType, 25 | rate, 26 | sendDataHandle, 27 | totalRecordsSent = 0, 28 | cognitoAppClientId = getConfigParameterByName(clientIdParamName), 29 | cognitoUserPoolId = getConfigParameterByName(userPoolIdParamName), 30 | cognitoIdentityPoolId = getConfigParameterByName(identityPoolIdParamName), 31 | cognitoRegion = getConfigParameterByName(cognitoRegionParamName), 32 | cognitoUser; 33 | 34 | let tableName = getConfigParameterByName('AnalyticsTable'); 35 | 36 | // Populate the dashboard settings UI 37 | $("#userPoolId").val(cognitoUserPoolId); 38 | $("#identityPoolId").val(cognitoIdentityPoolId); 39 | $("#clientId").val(cognitoAppClientId); 40 | $("#userPoolRegion").val(cognitoRegion); 41 | $("#tableName").val(tableName); 42 | 43 | function getConfigParameterByName(name) { 44 | var data = getQSParameterByName(name); 45 | 46 | if (data == null || data == '') { 47 | data = localStorage.getItem(name); 48 | return data; 49 | } 50 | localStorage.setItem(name, data); 51 | return data; 52 | } 53 | 54 | function getQSParameterByName(name, url) { 55 | if (!url) { 56 | url = window.location.href; 57 | } 58 | 59 | name = name.replace(/[\[\]]/g, "\\$&"); 60 | var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"); 61 | var results = regex.exec(url); 62 | if (!results) return null; 63 | if (!results[2]) return ''; 64 | return decodeURIComponent(results[2].replace(/\+/g, " ")); 65 | } 66 | 67 | var dateTime = []; 68 | var usersCounter = []; 69 | var androidUsers = []; 70 | var iOSUsers = []; 71 | var windowsUsers = []; 72 | var otherUsers = []; 73 | var quadA = []; 74 | var quadB = []; 75 | var quadC = []; 76 | var quadD = []; 77 | 78 | var osUsageData = []; 79 | var quadrantData = []; 80 | 81 | var colors = ["red", "green", "blue", "orange", "purple", "cyan", "magenta", "lime", "pink", "teal", "lavender", "brown", "beige", "maroon", "mint", "olive", "coral"]; 82 | var dynamicColors = function(i) { 83 | if (i >= 0 && i < colors.length) return colors[i]; 84 | var r = Math.floor(Math.random() * 255); 85 | var g = Math.floor(Math.random() * 255); 86 | var b = Math.floor(Math.random() * 255); 87 | return "rgb(" + r + "," + g + "," + b + ")"; 88 | } 89 | 90 | var identity = function(arg1) { 91 | return arg1; 92 | }; 93 | 94 | function addData(chart, label, data) { 95 | chart.data.labels = label; 96 | for (var i = 0; i < chart.data.datasets.length; i++) { 97 | dataset = chart.data.datasets[i]; 98 | dataset.data = data; 99 | dataset.fill = false; 100 | var color = dynamicColors(colors.length - 1 - i); 101 | dataset.fillColor = color; 102 | dataset.hightlightFill = color; 103 | dataset.backgroundColor = color; 104 | dataset.borderColor = color; 105 | }; 106 | chart.update(); 107 | } 108 | 109 | function updateData(chart, labels, data, datasetLabel, separateAxes = false) { 110 | chart.data.labels = labels; 111 | chart.data.datasets = new Array(); 112 | 113 | for (var i = 0; i < data.length; i++) { 114 | var dataset = {}; 115 | dataset.data = data[i]; 116 | dataset.label = datasetLabel[i]; 117 | if (separateAxes) dataset.yAxisID = datasetLabel[i]; 118 | dataset.fill = false; 119 | var color = dynamicColors(i); 120 | dataset.backgroundColor = color; 121 | dataset.borderColor = color; 122 | chart.data.datasets.push(dataset); 123 | } 124 | chart.update(); 125 | } 126 | 127 | var generateLineChartConfig = function(label) { 128 | var config = { 129 | type: "line", 130 | data: { 131 | labels: [], 132 | datasets: [ 133 | { 134 | label: label, 135 | data: [] 136 | } 137 | ] 138 | }, 139 | options: { 140 | responsive: true, 141 | scales: { 142 | xAxes: [ 143 | { 144 | ticks: { 145 | autoSkip: true, 146 | maxTicksLimit: 4 147 | }, 148 | display: true 149 | } 150 | ], 151 | yAxes: [ 152 | { 153 | ticks: { 154 | stepSize: 50, 155 | suggestedMin: 0, 156 | suggestedMax: 100 157 | }, 158 | display: true 159 | } 160 | ] 161 | } 162 | } 163 | }; 164 | return config; 165 | } 166 | 167 | var generateHorizontalBarChartConfig = function(label) { 168 | var config = { 169 | type: "horizontalBar", 170 | data: { 171 | labels: [], 172 | datasets: [ 173 | { 174 | label: label, 175 | data: [] 176 | } 177 | ] 178 | }, 179 | options: { 180 | legend: { 181 | display: true 182 | }, 183 | responsive: true, 184 | scales: { 185 | yAxes: [{ 186 | stacked: true 187 | }], 188 | xAxes: [{ 189 | display: true, 190 | scaleLabel: { 191 | display: false 192 | }, 193 | ticks: { 194 | stepSize: 10, 195 | suggestedMin: 0, 196 | suggestedMax: 10 197 | 198 | } 199 | }] 200 | } 201 | } 202 | }; 203 | return config; 204 | } 205 | 206 | var generateLineChart = function(divId, label) { 207 | var ctx = document.getElementById(divId).getContext("2d"); 208 | var config = generateLineChartConfig(label); 209 | return new Chart(ctx, config); 210 | }; 211 | 212 | var generateHorizontalBarChart = function(divId, label) { 213 | var ctx = document.getElementById(divId).getContext("2d"); 214 | var config = generateHorizontalBarChartConfig(label); 215 | return new Chart(ctx, config); 216 | }; 217 | 218 | var getTimeSecsAgo = function(secsAgo = 0) { 219 | return new Date(new Date().getTime() - secsAgo*1000).toISOString().replace('T',' ').replace('Z',''); 220 | }; 221 | 222 | var currentTime = new Date(); 223 | 224 | var totalCallCurrentTime = new Date(currentTime.getTime() - 600000).toISOString().replace('T',' ').replace('Z',''); 225 | 226 | var AvgConnTimeQueryTime = new Date(currentTime.getTime() - 6000000).toISOString().replace('T',' ').replace('Z',''); 227 | var AvgConnTimeMap = {}; 228 | var AvgConnTimeCallLabels = new Array(); 229 | var AvgConnTimeCallChart = generateLineChart("connTime", "Average Connection Time"); 230 | 231 | var AvgDisConnTimeQueryTime = new Date(currentTime.getTime() - 6000000).toISOString().replace('T',' ').replace('Z',''); 232 | var AvgDisConnTimeMap = {}; 233 | var AvgDisConnTimeCallLabels = new Array(); 234 | var AvgDisConnTimeCallChart = generateLineChart("disconnTime", "Average DisConnection Time"); 235 | 236 | var AvgTempValueQueryTime = new Date(currentTime.getTime() - 6000000).toISOString().replace('T',' ').replace('Z',''); 237 | var AvgTempCallMap = {}; 238 | var AvgTempCallLabels = new Array(); 239 | var AvgTempCallChart = generateLineChart("avgTempValueCanvas", "Average Temp"); 240 | 241 | var MinTempValueQueryTime = new Date(currentTime.getTime() - 6000000).toISOString().replace('T',' ').replace('Z',''); 242 | var MinTempCallMap = {}; 243 | var MinTempCallLabels = new Array(); 244 | var MinTempCallChart = generateLineChart("minTempValueCanvas", "Minimum Temp"); 245 | 246 | var MaxTempValueQueryTime = new Date(currentTime.getTime() - 6000000).toISOString().replace('T',' ').replace('Z',''); 247 | var MaxTempCallMap = {}; 248 | var MaxTempCallLabels = new Array(); 249 | var MaxTempCallChart = generateLineChart("maxTempValueCanvas", "Maximum Temp"); 250 | 251 | var anomalyScoreCurrentTime = new Date(currentTime.getTime() - 600000).toISOString().replace('T',' ').replace('Z',''); 252 | var anomalyCallMap = {"Average Anomaly Score": []}; 253 | var anomalyCallLabels= new Array(); 254 | var anomalyChartConfig = generateLineChartConfig("Average Anomaly Score"); 255 | var anomalyCtx = document.getElementById("anomalyCanvas").getContext("2d"); 256 | 257 | anomalyChartConfig.options.scales.yAxes = [ 258 | { 259 | id: 'Average Anomaly Score', 260 | type: 'linear', 261 | position: 'left', 262 | ticks: { 263 | stepSize: 1, 264 | max: 3, 265 | min: 0 266 | } 267 | } 268 | ]; 269 | anomalyChart = new Chart(anomalyCtx, anomalyChartConfig) 270 | 271 | var avgTempPerDeviceQueryTime = new Date(currentTime.getTime() - 600000).toISOString().replace('T',' ').replace('Z',''); 272 | var avgTempPerDeviceChart = generateHorizontalBarChart("avgTempCanvas", "Avg Temp per device"); 273 | 274 | var minTempPerDeviceQueryTime = new Date(currentTime.getTime() - 600000).toISOString().replace('T',' ').replace('Z',''); 275 | var minTempPerDeviceChart = generateHorizontalBarChart("minTempCanvas", "Min Temp per device"); 276 | 277 | var maxTempPerDeviceQueryTime = new Date(currentTime.getTime() - 600000).toISOString().replace('T',' ').replace('Z',''); 278 | var maxTempPerDeviceChart = generateHorizontalBarChart("maxTempCanvas", "Max Temp per device"); 279 | 280 | var totalCallCtx = document.getElementById("A_count"); 281 | var totalCallTimeCtx = document.getElementById("A_percent"); 282 | var totalConnectedDevices = 0; 283 | 284 | var splitFunc = function(entry) {return entry.split('|')[0]; }; 285 | 286 | var retrieveParams = function(metricType, eventTime) { 287 | return { 288 | TableName: tableName, 289 | ConsistentRead: true, 290 | ScanIndexForward: true, 291 | KeyConditionExpression: "MetricType = :TrailLog AND EventTime > :currentTime", 292 | ExpressionAttributeValues: { ":currentTime": eventTime, ":TrailLog": metricType } 293 | } 294 | }; 295 | 296 | var retrieveParamsFromMaxTable = function(metricType, eventTime) { 297 | var date = eventTime.split(' '); 298 | var time = date[1].split(':'); 299 | var hour = date[0]+ " " + time[0]; 300 | var min = time[1]; 301 | return { 302 | TableName: tableName, 303 | ConsistentRead: true, 304 | ScanIndexForward: true, 305 | KeyConditionExpression: "#hour = :hour AND #min > :minute", 306 | ExpressionAttributeNames: {"#hour": "Hour", "#min": "Minute"}, 307 | ExpressionAttributeValues: { ":hour": hour, ":minute": min } 308 | } 309 | } 310 | 311 | var updateHorizontalBarChart = function(data, noOfTopItems, chartName, queryTime, labelFunc=identity) { 312 | var items = data.Items; 313 | var ipCountMap = {}; 314 | 315 | // Merge the counts of each DDB item into a single map. 316 | for (var i=0; i 0) { 323 | queryTime = items[items.length-1].EventTime; 324 | 325 | var topIps = Object.keys(ipCountMap).sort(function(a,b) { return ipCountMap[b] - ipCountMap[a]}).slice(0,noOfTopItems); 326 | 327 | var topIpCounts = topIps.map(function(ip) {return ipCountMap[ip]; }) 328 | topIps = topIps.map(labelFunc); 329 | addData(chartName,topIps,topIpCounts); 330 | } 331 | return queryTime; 332 | }; 333 | 334 | var splitLabel = function(label) { 335 | return [''].concat(label.split(' ')); 336 | } 337 | var updateLineChart = function(data, AvgTempCallLabels, AvgTempCallMap, chart, queryTime, labelFunc=identity) { 338 | var items = data.Items; 339 | var l = items.length 340 | let past_time; 341 | var now = new Date(); 342 | var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()).getTime(); 343 | for (var i=0; i 5) { 372 | AvgTempCallLabels.push(splitLabel(queryTime.split('.')[0])); 373 | for (var key in AvgTempCallMap) { 374 | AvgTempCallMap[key].push(0); 375 | } 376 | } 377 | } 378 | 379 | updateData(chart, AvgTempCallLabels, Object.values(AvgTempCallMap), Object.keys(AvgTempCallMap).map(labelFunc)); 380 | 381 | return queryTime; 382 | } 383 | 384 | var getLatestRecord = function(){ 385 | console.log('Getting latest records from DynamoDB'); 386 | var params = retrieveParams("ConnectedDevicesCount", totalCallCurrentTime); 387 | var PerDeviceMaxTempParams = retrieveParams("PerDeviceMaxTemp", maxTempPerDeviceQueryTime); 388 | var PerDeviceAvgTempParams = retrieveParams("PerDeviceAvgTemp", avgTempPerDeviceQueryTime); 389 | var PerDeviceMinTempParams = retrieveParams("PerDeviceMinTemp", minTempPerDeviceQueryTime); 390 | var AvgTempParams = retrieveParams("AvgTempValue", AvgTempValueQueryTime); 391 | var MinTempParams = retrieveParams("MinTempValue", MinTempValueQueryTime); 392 | var MaxTempParams = retrieveParams("MaxTempValue", MaxTempValueQueryTime); 393 | var AvgConnTimeParams = retrieveParams("AvgConnTime", AvgConnTimeQueryTime); 394 | var AvgDisConnTimeParams = retrieveParams("AvgDisconnTime", AvgDisConnTimeQueryTime); 395 | var anomalyParams = retrieveParams("DeviceTempAnomalyScore", anomalyScoreCurrentTime); 396 | 397 | var docClient = new AWS.DynamoDB.DocumentClient(); 398 | 399 | docClient.query(PerDeviceMaxTempParams, function(err, data) { 400 | if (err) console.log(err); 401 | else { 402 | maxTempPerDeviceQueryTime = updateHorizontalBarChart(data, 20, maxTempPerDeviceChart, maxTempPerDeviceQueryTime, splitFunc); 403 | } 404 | }); 405 | 406 | docClient.query(PerDeviceMinTempParams, function(err, data) { 407 | if (err) console.log(err); 408 | else { 409 | minTempPerDeviceQueryTime = updateHorizontalBarChart(data, 20, minTempPerDeviceChart, minTempPerDeviceQueryTime, splitFunc); 410 | } 411 | }); 412 | 413 | docClient.query(PerDeviceAvgTempParams, function(err, data) { 414 | if (err) console.log(err); 415 | else { 416 | avgTempPerDeviceQueryTime = updateHorizontalBarChart(data, 20, avgTempPerDeviceChart, avgTempPerDeviceQueryTime, splitFunc); 417 | } 418 | }); 419 | 420 | docClient.query(AvgConnTimeParams, function(err, data) { 421 | if (err) console.log(err); 422 | else { 423 | AvgConnTimeQueryTime = updateLineChart(data, AvgConnTimeCallLabels, AvgConnTimeMap, AvgConnTimeCallChart, AvgConnTimeQueryTime, splitFunc) ; 424 | } 425 | }); 426 | 427 | docClient.query(AvgDisConnTimeParams, function(err, data) { 428 | if (err) console.log(err); 429 | else { 430 | AvgDisConnTimeQueryTime = updateLineChart(data, AvgDisConnTimeCallLabels, AvgDisConnTimeMap, AvgDisConnTimeCallChart, AvgDisConnTimeQueryTime, splitFunc) ; 431 | } 432 | }); 433 | 434 | docClient.query(AvgTempParams, function(err, data) { 435 | if (err) console.log(err); 436 | else { 437 | AvgTempValueQueryTime = updateLineChart(data, AvgTempCallLabels, AvgTempCallMap, AvgTempCallChart, AvgTempValueQueryTime, splitFunc) ; 438 | } 439 | }); 440 | 441 | docClient.query(MinTempParams, function(err, data) { 442 | if (err) console.log(err); 443 | else { 444 | MinTempValueQueryTime = updateLineChart(data, MinTempCallLabels, MinTempCallMap, MinTempCallChart, MinTempValueQueryTime, splitFunc) ; 445 | } 446 | }); 447 | 448 | docClient.query(MaxTempParams, function(err, data) { 449 | if (err) console.log(err); 450 | else { 451 | MaxTempValueQueryTime = updateLineChart(data, MaxTempCallLabels, MaxTempCallMap, MaxTempCallChart, MaxTempValueQueryTime, splitFunc) ; 452 | } 453 | }); 454 | 455 | docClient.query(anomalyParams, function(err, data) { 456 | if (err) console.log(err); 457 | else { 458 | var items = data.Items; 459 | console.log(`anomalyScore data: ${data}`) 460 | for (let i = 0; i < items.length; i++) { 461 | console.log(`anomalyscore item: ${items[i]}`); 462 | anomalyCallLabels.push(splitLabel(items[i].EventTime)); 463 | ddbItem = JSON.parse(items[i].Data); 464 | anomaly_score_value = Object.values(ddbItem); 465 | var sum = anomaly_score_value.reduce((previous, current) => current += previous); 466 | var avg = sum / anomaly_score_value.length; 467 | anomalyCallMap["Average Anomaly Score"].push(parseFloat(avg)); 468 | } 469 | if (items.length>0) { 470 | anomalyScoreCurrentTime = items[items.length-1].EventTime; 471 | updateData(anomalyChart, anomalyCallLabels, Object.values(anomalyCallMap), Object.keys(anomalyCallMap), true); 472 | } 473 | } 474 | }); 475 | 476 | docClient.query(params, function(err, data) { 477 | if (err) console.log(err); 478 | else { 479 | 480 | var items = data.Items; 481 | for (var i = 0; i < items.length; i++) { 482 | totalConnectedDevices = parseInt((items[i].Data).split(':')[1]); 483 | } 484 | var callTime; 485 | if (items.length > 0) callTime = items[items.length-1].EventTime; 486 | else callTime = new Date(new Date().getTime() - 200).toISOString().replace('T',' ').replace('Z',''); 487 | totalCallCtx.innerHTML = "

CountConnectedDevices: " + totalConnectedDevices + "

"; 488 | totalCallTimeCtx.innerHTML = "

Last Updated: " + callTime.split(' ')[1] + "

"; 489 | } 490 | }); 491 | 492 | setTimeout( function() { 493 | getLatestRecord(); 494 | }, 15000); 495 | } 496 | var cognitoAuth = function() { 497 | 498 | $("#logoutLink").click( function() { 499 | cognitoUser.signOut(); 500 | 501 | $("#password").val(""); 502 | $("#loginForm").removeClass("hidden"); 503 | $("#logoutLink").addClass("hidden"); 504 | $("#unauthMessage").removeClass("hidden"); 505 | $("#dashboard_content").addClass("hidden"); 506 | }); 507 | 508 | $("#btnSaveConfiguration").click(function (e) { 509 | 510 | var clientId = $("#clientId").val(), 511 | userPoolId = $("#userPoolId").val(), 512 | identityPoolId = $("#identityPoolId").val(), 513 | userPoolRegion = $("#userPoolRegion").val(); 514 | 515 | if (clientId && userPoolId && identityPoolId && userPoolRegion) { 516 | $("#configErr").addClass("hidden"); 517 | localStorage.setItem(clientIdParamName, clientId); 518 | localStorage.setItem(userPoolIdParamName, userPoolId); 519 | localStorage.setItem(identityPoolIdParamName, identityPoolId); 520 | localStorage.setItem(cognitoRegionParamName, userPoolRegion); 521 | $("#cognitoModal").modal("hide"); 522 | } 523 | else { 524 | $("#configErr").removeClass("hidden"); 525 | } 526 | }); 527 | 528 | $("#newPasswordForm").submit(function (e) { 529 | var newPassword = $("#newPassword").val(); 530 | 531 | // If new password meets the criteria, 532 | if (newPassword.length >= 8 && newPassword.match(/[a-z]/) 533 | && newPassword.match(/[A-Z]/) && newPassword.match(/[0-9]/) 534 | && newPassword == $("#newPassword2").val()) 535 | { 536 | $("#newPasswordModal").modal("hide"); 537 | $("#newPasswordErr").addClass("hidden"); 538 | $("#newPasswordMatchErr").addClass("hidden"); 539 | $("#newPasswordComplexityErr").addClass("hidden"); 540 | 541 | var userName = $("#userName").val(); 542 | var password = $("#password").val(); 543 | 544 | var authData = { 545 | UserName: userName, 546 | Password: password 547 | }; 548 | 549 | var authDetails = new AmazonCognitoIdentity.AuthenticationDetails(authData); 550 | 551 | var poolData = { 552 | UserPoolId: cognitoUserPoolId, 553 | ClientId: cognitoAppClientId 554 | }; 555 | 556 | var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData); 557 | var userData = { 558 | Username: userName, 559 | Pool: userPool 560 | }; 561 | 562 | cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); 563 | 564 | cognitoUser.authenticateUser(authDetails, cognitoAuthFunctions); 565 | 566 | } else { 567 | $("#newPasswordErr").removeClass("hidden"); 568 | 569 | if (newPassword != $("#newPassword2").val()) { 570 | $("#newPasswordMatchErr").removeClass("hidden"); 571 | } 572 | else { 573 | $("#newPasswordMatchErr").addClass("hidden"); 574 | } 575 | 576 | if (newPassword.length < 8 || !newPassword.match(/[a-z]/) 577 | || !newPassword.match(/[A-Z]/) || !newPassword.match(/[0-9]/)) { 578 | 579 | $("#newPasswordComplexityErr").removeClass("hidden"); 580 | 581 | // Must be longer than 8 characters 582 | if (newPassword.length < 8 ) { 583 | $("#newPasswordLengthErr").removeClass("hidden"); 584 | } 585 | else { 586 | $("#newPasswordLengthErr").addClass("hidden"); 587 | } 588 | 589 | // Must contain a lowercase error. 590 | if (!newPassword.match(/[a-z]/)) { 591 | $("#newPasswordLowerErr").removeClass("hidden"); 592 | } 593 | else { 594 | $("#newPasswordLowerErr").addClass("hidden"); 595 | } 596 | 597 | // Must contain an uppercase letter. 598 | if (!newPassword.match(/[A-Z]/)) { 599 | $("#newPasswordUpperErr").removeClass("hidden"); 600 | } 601 | else { 602 | $("#newPasswordUpperErr").addClass("hidden"); 603 | } 604 | 605 | // Must contain a number. 606 | if (!newPassword.match(/[0-9]/)) { 607 | $("#newPasswordNumberErr").removeClass("hidden"); 608 | } 609 | else { 610 | $("#newPasswordNumberErr").addClass("hidden"); 611 | } 612 | 613 | } 614 | else { 615 | $("#newPasswordComplexityErr").addClass("hidden"); 616 | } 617 | } 618 | }); 619 | 620 | $("#loginForm").submit(function() { 621 | 622 | // validate that the Cognito configuration parameters have been set 623 | if (!cognitoAppClientId || !cognitoUserPoolId || !cognitoIdentityPoolId || !cognitoRegion) { 624 | console.log("not present") 625 | $("#configErr").removeClass("hidden"); 626 | $("#configureLink").trigger("click"); 627 | return; 628 | } 629 | 630 | // update ui 631 | $("#loginForm").addClass("hidden"); 632 | $("#signInSpinner").removeClass("hidden"); 633 | 634 | var userName = $("#userName").val(); 635 | var password = $("#password").val(); 636 | 637 | var authData = { 638 | UserName: userName, 639 | Password: password 640 | }; 641 | 642 | var authDetails = new AmazonCognitoIdentity.AuthenticationDetails(authData); 643 | 644 | var poolData = { 645 | UserPoolId: cognitoUserPoolId, 646 | ClientId: cognitoAppClientId 647 | }; 648 | 649 | var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData); 650 | var userData = { 651 | Username: userName, 652 | Pool: userPool 653 | }; 654 | 655 | cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); 656 | cognitoUser.authenticateUser(authDetails, cognitoAuthFunctions); 657 | }); 658 | } 659 | 660 | cognitoAuth(); 661 | 662 | function timeNow() { 663 | var d = new Date(), 664 | h = (d.getHours()<10?'0':'') + d.getHours(), 665 | m = (d.getMinutes()<10?'0':'') + d.getMinutes(), 666 | s = (d.getSeconds()<10?'0':'') + d.getSeconds(); 667 | 668 | return h + ':' + m + ':' + s; 669 | } 670 | 671 | let cognitoAuthFunctions = { 672 | onSuccess: function(result) { 673 | console.log('access token + ' + result.getAccessToken().getJwtToken()); 674 | 675 | var logins = {}; 676 | logins["cognito-idp." + cognitoRegion + ".amazonaws.com/" + cognitoUserPoolId] = result.getIdToken().getJwtToken(); 677 | var params = { 678 | IdentityPoolId: cognitoIdentityPoolId, 679 | Logins: logins 680 | }; 681 | 682 | AWS.config.region = cognitoRegion; 683 | AWSCognito.config.region = cognitoRegion; 684 | 685 | AWS.config.credentials = new AWS.CognitoIdentityCredentials(params); 686 | 687 | AWS.config.credentials.get(function(refreshErr) { 688 | if (refreshErr) { 689 | console.error(refreshErr); 690 | } 691 | else { 692 | $("#unauthMessage").addClass("hidden"); 693 | $("#logoutLink").removeClass("hidden"); 694 | $("#dashboard_content").removeClass("hidden"); 695 | $("#signInSpinner").addClass("hidden"); 696 | getLatestRecord(); 697 | } 698 | }); 699 | }, 700 | onFailure: function(err) { 701 | $("#logoutLink").addClass("hidden"); 702 | $("#loginForm").removeClass("hidden"); 703 | $("#signInSpinner").addClass("hidden"); 704 | 705 | alert(err); 706 | }, 707 | newPasswordRequired: function(userAttributes, requiredAttributes) { 708 | // User was signed up by an admin and must provide new 709 | // password and required attributes, if any, to complete 710 | // authentication. 711 | console.log("New Password Required"); 712 | var newPassword = $("#newPassword").val(); 713 | 714 | var attributesData = {}; 715 | if (newPassword.length >= 8 && newPassword.match(/[a-z]/) 716 | && newPassword.match(/[A-Z]/) && newPassword.match(/[0-9]/) 717 | && newPassword == $("#newPassword2").val()) 718 | { 719 | cognitoUser.completeNewPasswordChallenge(newPassword, attributesData, this); 720 | } else { 721 | $("#newPasswordModal").modal("show"); 722 | } 723 | } 724 | }; 725 | 726 | } 727 | --------------------------------------------------------------------------------