├── .gitignore ├── LICENSE ├── README.md ├── config.example.yml ├── lambda ├── dynamodb │ ├── LambdaChatDynamoDBPolicy.json │ ├── code │ │ ├── LambdaChatDynamoDB.js │ │ └── README │ ├── config.yml │ └── input.json └── sns │ ├── LambdaChatPolicy.json │ ├── config.yml │ ├── dynamodb_table.json │ ├── input.json │ └── lambdachat.js ├── presentation ├── example.html ├── imgs │ ├── dynamic-dashboards.png │ ├── kinesis-pull-10.png │ ├── lambda-chat.png │ ├── push-s3-example-10.png │ └── vote-app.png ├── index.html ├── public ├── remark-latest.min.js └── remark.language.js ├── publish-presentation.sh ├── requirements.txt ├── resources.py ├── s3-website ├── public │ ├── error.html │ ├── index.html │ ├── lambda-chat.css │ └── lambda-chat.js └── update.sh └── yaml2shell.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # node-waf configuration 20 | .lock-wscript 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 27 | node_modules 28 | 29 | # Ignore the config file as it has secrets in it 30 | config.yml 31 | s3-website/public/config.js 32 | 33 | # Ignore compiled Python files 34 | *.pyc 35 | 36 | # Ignore Emacs backup files 37 | *~ 38 | 39 | # Ignore the data file 40 | s3-website/public/data.json 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015 CloudNative, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lambda Chat 2 | A chat application without servers - using only AWS Lambda, S3, DynamoDB and SNS 3 | 4 | 5 | ## Live Demo 6 | 7 | http://lambda-chat.s3-website-us-west-2.amazonaws.com/ 8 | 9 | Please don't send a million messages through here - it does cost us money and we will turn it off if it is abused. 10 | 11 | 12 | ## How it works 13 | 14 | 15 |
    ◎ ◎
 16 |      ◡
 17 | 
 18 |      │(1)
 19 |      │                       ┏━━━━━━━━━━━━━━━━━━┓
 20 |      │                       ┃                  ┃
 21 |      │        (2)            ┃  Google OAuth2   ┃           (4)
 22 |      │        ┌─────────────▶┃       API        ┃◀────────────┐
 23 |      │        │              ┃                  ┃             │
 24 |      │        │              ┗━━━━━━━━━━━━━━━━━━┛             │
 25 |      ▼        ▼                                     ┏━━━━━━━━━━━━━━━━━━┓
 26 |     ┏━━━━━━━━━━━━━━━━━━┓                            ┃                  ┃
 27 |     ┃                  ┃ (3)                        ┃     AWS STS      ┃
 28 |  ┌─▶┃     Website      ┃◀──────────────────────────▶┃  AWS Web ID Fed  ┃
 29 |  │  ┃                  ┃                            ┃                  ┃
 30 |  │  ┗━━━━━━━━━━━━━━━━━━┛                            ┗━━━━━━━━━━━━━━━━━━┛
 31 |  │            │
 32 |  │            │        ┏━━━━━━━━━━━━━━━━━━┓
 33 |  │            │        ┃                  ┃
 34 |  │            └───────▶┃    SNS Topic     ┃
 35 |  │            (5)      ┃                  ┃
 36 |  │                     ┗━━━━━━━━━━━━━━━━━━┛
 37 |  │                               │
 38 |  │                               │       ┏━━━━━━━━━━━━━━━━━━┓
 39 |  │                               │       ┃                  ┃
 40 |  │                               └──────▶┃    Lambda fn1    ┃
 41 |  │                               (6)     ┃                  ┃
 42 |  │                                       ┗━━━━━━━━━━━━━━━━━━┛
 43 |  │                                                 │
 44 |  │                                                 │      ┏━━━━━━━━━━━━━━━━━━┓
 45 |  │                                                 │      ┃                  ┃
 46 |  │                                                 └─────▶┃  DynamoDB Table  ┃
 47 |  │                                                 (7)    ┃                  ┃
 48 |  │                                                        ┗━━━━━━━━━━━━━━━━━━┛
 49 |  │                                                                  │
 50 |  │                                    ┏━━━━━━━━━━━━━━━━━━┓          │
 51 |  │                                    ┃                  ┃          │
 52 |  │                                    ┃    Lambda fn2    ┃◀─────────┘
 53 |  │                                    ┃                  ┃        (8)
 54 |  │                                    ┗━━━━━━━━━━━━━━━━━━┛
 55 |  │                                              │
 56 |  │            ┏━━━━━━━━━━━━━━━━━━┓              │
 57 |  │            ┃                  ┃              │
 58 |  └────────────┃    S3 Object     ┃◀─────────────┘
 59 |  (10)         ┃                  ┃            (9)
 60 |               ┗━━━━━━━━━━━━━━━━━━┛
 61 | 
 62 | 
 63 | Created with Monodraw
 64 | 
65 | 66 | 1. The user opens their browser and go to the website which is hosted entirely on S3 67 | 2. The user signs in with their Google account and gets back an `id_token` 68 | 3. Using AWS Web Identity Federation in the Javascript SDK, the `id_token` is sent to get temporary AWS credentials from STS. 69 | 4. STS verifies the token with Google 70 | 5. The users types in a message, hits ENTER, and the website publishes the message to an SNS Topic. 71 | 6. A Lambda function is trigged by the SNS message, which gets the contents of the message, and... 72 | 7. Stores the message in a DynamoDB table 73 | 8. The process of adding a new chat message to the DynamoDB table triggers another Lambda function. This requires the currently-in-preview DynamoDB Streams feature. This second Lambda function reads the last 20 messages from DynamoDB, and... 74 | 9. Writes them to an S3 object in JSON format 75 | 10. The website polls the S3 object every second, and updates the chat box with any new messages it finds. 76 | 77 | 78 | ## Getting Started 79 | 80 | There is a lot involved here, but we have tried to make it as easy as possible for you to follow along. 81 | 82 | ### Get the code 83 | 84 | git clone git@github.com:cloudnative/lambda-chat.git 85 | cd lambda-chat 86 | 87 | ### Config 88 | 89 | cp config.example.yml config.yml 90 | 91 | The only thing to edit at this point is the name of the S3 bucket to put the website in as bucket names are globally unique. 92 | 93 | s3_bucket: my-lambda-chat-bucket 94 | 95 | ### Google OAuth 96 | 97 | To be able to use AWS Web Identity Federation, you will need to create a new Google Project and create credentials. 98 | 99 | 1. Go to: https://console.developers.google.com/project 100 | 1. Create a new project 101 | 1. Enable **Google+ API** 102 | 1. Create OAuth 2 credentials. Leave the Javascript Origin empty for now 103 | 1. Edit `config.yml` and set `google_oauth_client_id` to your Client ID 104 | 105 | ### AWS Resources 106 | 107 | #### Prerequisites 108 | 109 | You will need Python 2.7. On OSX using brew 110 | 111 | brew install python 112 | 113 | Now we need a few Python libraries 114 | 115 | pip install -r requirements.txt 116 | 117 | #### CloudFormation 118 | 119 | There is a script called `resources.py` which will generate a CloudFormation template to bring up the AWS resources needed to run Lambda Chat. 120 | 121 | You can see the template by running 122 | 123 | ./resources.py cf 124 | 125 | If you are happy with that, the script can also launch the CloudFormation Stack. To create it in N. Virginia, run: 126 | 127 | ./resources.py launch --region=us-east-1 128 | 129 | The script returns quickly because it is now up to CloudFormation to bring up the AWS resources. Login to the AWS Web Console and go to the CloudFormation section in that region. Select the `Lambda-Chat` stack, then click on the **Events** tab to see the progress and check for errors. 130 | 131 | Once the stack is complete, run: 132 | 133 | ./resources.py output --region=us-east-1 134 | 135 | and add these values to your `config.yml` file. 136 | 137 | #### Website 138 | 139 | The files needed to run the website need to be in S3. To get them there: 140 | 141 | cd s3-website 142 | ./update.sh 143 | 144 | You can run this command as many times as you like, particularly if you are editing the files to see what is happening. 145 | 146 | The script tells you the URL of the website. Open that up in your browser. 147 | 148 | #### Lambda functions 149 | 150 | To help with the AWS Lambda side of things, we are using 151 | [kappa](https://github.com/garnaat/kappa). Kappa is a CLI tool that helps with 152 | the details of creating and managing AWS Lambda applications. You must install 153 | kappa before proceeding. You can install it from PyPI using pip: 154 | 155 | % pip install kappa 156 | 157 | or you can clone the kappa repo and install locally: 158 | 159 | % git clone git@github.com:garnaat/kappa.git 160 | % cd kappa 161 | % pip install -r requirements.txt 162 | % python setup.py install 163 | 164 | Next, you must edit the config.yml files in the lambda/sns directory and the 165 | lambda/dynamodb directories. The config.yml files have comments which direct 166 | you to the parts that need to be changed. 167 | 168 | Now create the components required for the SNS->DynamoDB Lambda function: 169 | 170 | 1. cd lambda/sns 171 | 1. run ``kappa config.yml create`` 172 | 1. run ``kappa config.yml invoke``. This will call the AWS Lambda function 173 | synchronously with test data and return the log data to the console. 174 | 1. run ``kappa config.yml add_event_sources``. This will connect the SNS topic 175 | to your AWS Lambda function. 176 | 177 | Finally, you need to create the components requried for the DynamoDB->S3 Lambda 178 | function: 179 | 180 | 1. cd lambda/dynamodb 181 | 1. run ``kappa config.yml create`` 182 | 1. run ``kappa config.yml invoke``. This will call the AWS Lambda function 183 | synchronously with test data and return the log data to the console. 184 | 1. run ``kappa config.yml add_event_sources``. This will connect the DynamoDB 185 | stream to your AWS Lambda function. 186 | 187 | 188 | ### Usage 189 | 190 | 1. Go to the URL returned by the `update.sh` script, and login with your Google account. 191 | 1. Use like any other chat application :-) 192 | 193 | 194 | ## Updating 195 | 196 | You should feel free to mess around with this and update parts of it with your own code. If you do, please [let us know](https://twitter.com/intent/tweet?text=I%20am%20having%20fun%20with%20Lambda%20Chat.%20Thanks%20@CloudNativeIO). 197 | 198 | When you are making changes to the website, you can push them to S3 by running: 199 | 200 | cd s3-website 201 | ./update.sh 202 | 203 | For modifications to the AWS Lambda functions, run: 204 | 205 | % kappa config.yml update_code 206 | 207 | in the corresponding lambda directory. 208 | 209 | 210 | ## Clean up 211 | 212 | Delete the CloudFormation stack 213 | 214 | ./resources.py delete --region=us-east-1 215 | 216 | Delete the Lambda functions 217 | 218 | % kappa config.yml delete 219 | 220 | in the corresponding lambda directory. This will delete the AWS Lambda 221 | function, remove the event source mappings, and delete the IAM role. 222 | 223 | ## Reading, resources and other stuff 224 | 225 | - [The blog post that describes why we did this](https://cloudnative.io/blog/2015/05/lambda-chat/) 226 | - [AWS Web Identity Federation playground](https://web-identity-federation-playground.s3.amazonaws.com/index.html) 227 | - [Building Dynamic Dashboards Using Lambda and DynamoDB Streams: Part 1](https://medium.com/aws-activate-startup-blog/building-dynamic-dashboards-using-lambda-and-dynamodb-streams-part-1-217e2318ae17) 228 | - [Kappa](https://github.com/garnaat/kappa) 229 | - [Troposphere](https://github.com/cloudtools/troposphere) 230 | 231 | -------------------------------------------------------------------------------- /config.example.yml: -------------------------------------------------------------------------------- 1 | # Example configuration for Lambda Chat 2 | # Copy this file to `config.yml` and then set the values appropriately 3 | 4 | # The Google OAuth Client ID 5 | # Visit: https://console.developers.google.com/project 6 | # To create a project, enable the Google+ API, and create an ID 7 | # Set the Javascript Origin to the S3 bucket URL 8 | google_oauth_client_id: TODO 9 | 10 | # The AWS region to do everything in 11 | region: us-east-1 12 | 13 | # The name of the S3 bucket to use for the website 14 | # This must be unique across all AWS accounts 15 | s3_bucket: lambda-chat 16 | 17 | # The S3 object key for the chat data 18 | data_key: data.json 19 | 20 | # The ARN of the IAM role the website will assume to be able to send messages 21 | # using SNS 22 | website_iam_role_arn: arn:aws:iam::TODO 23 | 24 | # The ARN of the SNS topic to publish chat messages to, and for Lambda to read 25 | sns_topic_arn: arn:aws:sns::TODO 26 | -------------------------------------------------------------------------------- /lambda/dynamodb/LambdaChatDynamoDBPolicy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "lambda:InvokeFunction" 8 | ], 9 | "Resource": "*" 10 | }, 11 | { 12 | "Effect": "Allow", 13 | "Action": [ 14 | "dynamodb:*", 15 | "s3:*", 16 | "logs:*" 17 | ], 18 | "Resource": "*" 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /lambda/dynamodb/code/LambdaChatDynamoDB.js: -------------------------------------------------------------------------------- 1 | console.log('Loading function'); 2 | var async = require('async'); 3 | var aws = require('aws-sdk'); 4 | var ddb = new aws.DynamoDB( 5 | {endpoint: "https://dynamodb.us-west-2.amazonaws.com/", 6 | params: {TableName: "lambdachat"}}); 7 | var s3 = new aws.S3(); 8 | // change bucket name to match your bucket name 9 | var bucket = "lambda-chat"; 10 | var keyname = "data.json"; 11 | 12 | 13 | function escapeHtml(text) { 14 | var map = { 15 | '&': '&', 16 | '<': '<', 17 | '>': '>', 18 | '"': '"', 19 | "'": ''' 20 | }; 21 | 22 | return text.replace(/[&<>"']/g, function(m) { return map[m]; }); 23 | } 24 | 25 | 26 | exports.handler = function(event, context) { 27 | console.log('Handle DynamoDB Streams event'); 28 | console.log(JSON.stringify(event, null, 2)); 29 | var new_object = event.Records[0].dynamodb; 30 | var channel = "default"; 31 | if ('channel' in new_object.NewImage) { 32 | channel = new_object.NewImage.channel.S; 33 | } 34 | console.log("channel = " + channel); 35 | 36 | 37 | async.waterfall([ 38 | function getrecords(next) { 39 | var params = { 40 | "IndexName": "channel-timestamp-index", 41 | "KeyConditions": { 42 | "channel": { 43 | "AttributeValueList": [{ 44 | "S": channel 45 | }], 46 | "ComparisonOperator": "EQ" 47 | } 48 | 49 | }, 50 | "Limit": 20, 51 | "ScanIndexForward": false 52 | } 53 | console.log("Scanning the table"); 54 | ddb.query(params, next); 55 | }, 56 | function buildjson(response, next) { 57 | console.log("Building JSON file"); 58 | console.log(JSON.stringify(response)); 59 | var messageData = { 60 | messages: [] 61 | }; 62 | 63 | for (var i = response.Items.length - 1; i >= 0; i--) { 64 | ii = response.Items[i]; 65 | var message = {}; 66 | message['id'] = ii.message_id['S']; 67 | message['name'] = escapeHtml(ii.name['S']); 68 | message['message'] = escapeHtml(ii.message['S']); 69 | message['channel'] = ii.channel['S']; 70 | messageData.messages.push(message); 71 | } 72 | next(null, JSON.stringify(messageData)); 73 | }, 74 | function savetos3(jsonstring, next) { 75 | console.log(jsonstring); 76 | s3.putObject({ 77 | Bucket: bucket, 78 | Key: keyname, 79 | Body: jsonstring 80 | }, next); 81 | } 82 | ], function (err) { 83 | if (err) { 84 | console.log('got an error'); 85 | console.log(err, err.stack); 86 | } else { 87 | console.log('Saved Data to S3'); 88 | } 89 | context.done(err, ''); 90 | }); 91 | 92 | }; 93 | -------------------------------------------------------------------------------- /lambda/dynamodb/code/README: -------------------------------------------------------------------------------- 1 | This code requires the async nodejs package. Before uploading the function you 2 | should install that package here using: 3 | 4 | % npm install async -------------------------------------------------------------------------------- /lambda/dynamodb/config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # change profile and region to meet your needs 3 | profile: cloudnative-dev 4 | region: us-west-2 5 | resources: resources.json 6 | iam: 7 | policy: 8 | description: A policy used with the Kappa SNS->DynamoDB example 9 | name: LambdaChatDynamoDBPolicy 10 | document: LambdaChatDynamoDBPolicy.json 11 | role: 12 | name: LambdaChatDynamoDBRole 13 | lambda: 14 | name: LambdaChatDynamoDB 15 | zipfile_name: LambdaChatDynamoDB.zip 16 | description: A simple chat app with S3/SNS/DynamoDB/Lambda 17 | path: code/ 18 | handler: LambdaChatDynamoDB.handler 19 | runtime: nodejs 20 | memory_size: 128 21 | timeout: 3 22 | event_sources: 23 | - 24 | # Change this to point to your DynamoDB stream. 25 | # Note that you must be in the DynamoDB Streams preview. 26 | arn: arn:aws:dynamodb:us-west-2:860421987956:table/lambdachat/stream/2015-09-09T17:52:45.927 27 | batch_size: 1 28 | starting_position: LATEST 29 | enabled: true 30 | test_data: input.json 31 | -------------------------------------------------------------------------------- /lambda/dynamodb/input.json: -------------------------------------------------------------------------------- 1 | { 2 | "Records":[ 3 | { 4 | "EventName":"INSERT", 5 | "EventVersion":"1.0", 6 | "EventSource":"aws:dynamodb", 7 | "Dynamodb":{ 8 | "NewImage":{ 9 | "Message":{ 10 | "S":"New item!" 11 | }, 12 | "Id":{ 13 | "N":"101" 14 | } 15 | }, 16 | "SizeBytes":26, 17 | "StreamViewType":"NEW_AND_OLD_IMAGES", 18 | "SequenceNumber":"111", 19 | "Keys":{ 20 | "Id":{ 21 | "N":"101" 22 | } 23 | } 24 | }, 25 | "EventID":"1", 26 | "eventSourceARN":"arn:aws:dynamodb:us-east-1:acct-id:table/ExampleTableWithStream/stream/stream-id/", 27 | "AwsRegion":"us-east-1" 28 | }, 29 | { 30 | "EventName":"MODIFY", 31 | "EventVersion":"1.0", 32 | "EventSource":"aws:dynamodb", 33 | "Dynamodb":{ 34 | "NewImage":{ 35 | "Message":{ 36 | "S":"This item has changed" 37 | }, 38 | "Id":{ 39 | "N":"101" 40 | } 41 | }, 42 | "SizeBytes":59, 43 | "StreamViewType":"NEW_AND_OLD_IMAGES", 44 | "SequenceNumber":"222", 45 | "OldImage":{ 46 | "Message":{ 47 | "S":"New item!" 48 | }, 49 | "Id":{ 50 | "N":"101" 51 | } 52 | }, 53 | "Keys":{ 54 | "Id":{ 55 | "N":"101" 56 | } 57 | } 58 | }, 59 | "EventID":"2", 60 | "eventSourceARN":"arn:aws:dynamodb:us-east-1:acct-id:table/ExampleTableWithStream/stream/stream-id/", 61 | "AwsRegion":"us-east-1" 62 | }, 63 | { 64 | "EventName":"REMOVE", 65 | "EventVersion":"1.0", 66 | "EventSource":"aws:dynamodb", 67 | "Dynamodb":{ 68 | "SizeBytes":38, 69 | "StreamViewType":"NEW_AND_OLD_IMAGES", 70 | "SequenceNumber":"333", 71 | "OldImage":{ 72 | "Message":{ 73 | "S":"This item has changed" 74 | }, 75 | "Id":{ 76 | "N":"101" 77 | } 78 | }, 79 | "Keys":{ 80 | "Id":{ 81 | "N":"101" 82 | } 83 | } 84 | }, 85 | "EventID":"3", 86 | "eventSourceARN":"arn:aws:dynamodb:eu-west-1:acct-id:table/ExampleTableWithStream/stream/stream-id/", 87 | "AwsRegion":"eu-west-1" 88 | } 89 | ] 90 | } 91 | -------------------------------------------------------------------------------- /lambda/sns/LambdaChatPolicy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement":[ 4 | { 5 | "Sid":"Stmt1", 6 | "Effect":"Allow", 7 | "Action":["dynamodb:*"], 8 | "Resource":["arn:aws:dynamodb:us-west-2:860421987956:table/lambdachat"] 9 | }, 10 | { 11 | "Sid":"Stmt2", 12 | "Effect":"Allow", 13 | "Action":["logs:*"], 14 | "Resource":["arn:aws:logs:*:*:*"] 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /lambda/sns/config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # change profile and region to meet your needs 3 | profile: cloudnative-dev 4 | region: us-west-2 5 | iam: 6 | policy: 7 | description: A policy used with the Kappa SNS->DynamoDB example 8 | name: LambdaChatPolicy 9 | document: LambdaChatPolicy.json 10 | role: 11 | name: LambdaChatRole 12 | policy: LambdaChatPolicy 13 | lambda: 14 | name: LambdaChat 15 | zipfile_name: LambdaChat.zip 16 | description: A simple chat app with S3/SNS/DynamoDB/Lambda 17 | path: lambdachat.js 18 | handler: lambdachat.handler 19 | runtime: nodejs 20 | memory_size: 128 21 | timeout: 3 22 | permissions: 23 | - 24 | statement_id: sns_invoke 25 | action: lambda:invokeFunction 26 | principal: sns.amazonaws.com 27 | # change this to point to your SNS topic 28 | source_arn: arn:aws:sns:us-west-2:860421987956:lambda-chat 29 | event_sources: 30 | - 31 | # change this to point to your SNS topic 32 | arn: arn:aws:sns:us-west-2:860421987956:lambda-chat 33 | test_data: input.json 34 | -------------------------------------------------------------------------------- /lambda/sns/dynamodb_table.json: -------------------------------------------------------------------------------- 1 | { 2 | "TableName": "snslambda", 3 | "AttributeDefinitions": [ 4 | { 5 | "AttributeName": "SnsTopicArn", 6 | "AttributeType": "S" 7 | }, 8 | { 9 | "AttributeName": "SnsPublishTime", 10 | "AttributeType": "S" 11 | }, 12 | { 13 | "AttributeName": "SnsMessageId", 14 | "AttributeType": "S" 15 | } 16 | ], 17 | "KeySchema": [ 18 | { 19 | "AttributeName": "SnsTopicArn", 20 | "KeyType": "HASH" 21 | }, 22 | { 23 | "AttributeName": "SnsPublishTime", 24 | "KeyType": "RANGE" 25 | } 26 | ], 27 | "GlobalSecondaryIndexes": [ 28 | { 29 | "IndexName": "MesssageIndex", 30 | "KeySchema": [ 31 | { 32 | "AttributeName": "SnsMessageId", 33 | "KeyType": "HASH" 34 | } 35 | ], 36 | "Projection": { 37 | "ProjectionType": "ALL" 38 | }, 39 | "ProvisionedThroughput": { 40 | "ReadCapacityUnits": 5, 41 | "WriteCapacityUnits": 1 42 | } 43 | } 44 | ], 45 | "ProvisionedThroughput": { 46 | "ReadCapacityUnits": 5, 47 | "WriteCapacityUnits": 5 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /lambda/sns/input.json: -------------------------------------------------------------------------------- 1 | { 2 | "Records":[ 3 | { 4 | "EventSource":"aws:sns", 5 | "EventVersion": "1.0", 6 | "EventSubscriptionArn": "arn:aws:sns:us-east-1:123456789012:lambda_topic:0b6941c3-f04d-4d3e-a66d-b1df00e1e381", 7 | "Sns":{ 8 | "Type" : "Notification", 9 | "MessageId" : "e70fa8dd-0d77-5944-8862-e569494b48b5", 10 | "TopicArn" : "arn:aws:sns:us-east-1:658794617753:lambda-chat", 11 | "Message" : "{\"name\":\"Mitch Garnaat\",\"message\":\"just testing this out\"}", 12 | "Timestamp" : "2015-04-24T13:15:40.632Z", 13 | "Channel" : "foo", 14 | "SignatureVersion" : "1", 15 | "Signature" : "n0zU4mvKQT5vy6RbDK3BoiWQrFBirbaIGRQOVXE4Vx1XE0SrsXBo4mPm2eDMgjFboP0RJxRCvkFpN07mbnVOIoT2UWKVD2hU1vLdTlEPE4ppSSx17KzhABsOuA8XwijL3hm4cpVHmCmhNXcKekC+fGCryjf9cxr6ODm45PxxE4WLSak85uLzgWhfbAEgPqD2Q/Fa3NwJIyBkZWEdlpJCeaZb4gCzPauvcynRyzWS+e+76WpXMgInCU2y7lhtajDpHrDlZ13UvHOWAQONFRGJXsxFeP370tnzVKfdfMPNbmr4gb3dk+VP0+PsyrIakqp31cO5umUZwSeVZaXLQLewmg==", 16 | "SigningCertURL" : "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-d6d679a1d18e95c2f9ffcf11f4f9e198.pem", 17 | "UnsubscribeURL" : "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:658794617753:lambda-chat:f1bde0aa-11eb-4417-a9cf-6a00c6aac0a7" 18 | } 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /lambda/sns/lambdachat.js: -------------------------------------------------------------------------------- 1 | console.log('Loading event'); 2 | var aws = require('aws-sdk'); 3 | var ddb = new aws.DynamoDB( 4 | {endpoint: 'https://dynamodb.us-west-2.amazonaws.com/', 5 | params: {TableName: 'lambdachat'}}); 6 | 7 | exports.handler = function(event, context) { 8 | var message_id = event.Records[0].Sns.MessageId; 9 | var timestamp = event.Records[0].Sns.Timestamp; 10 | var payload = JSON.parse(event.Records[0].Sns.Message); 11 | var channel = 'default'; 12 | if ("channel" in payload) { 13 | channel = payload.channel; 14 | } 15 | var name = payload.name; 16 | var message = payload.message; 17 | var LambdaReceiveTime = new Date().toString(); 18 | var itemParams = {Item: {message_id: {S: message_id}, 19 | timestamp: {S: timestamp}, 20 | channel: {S: channel}, 21 | name: {S: name}, 22 | message: {S: message}}}; 23 | ddb.putItem(itemParams, function(err, data) { 24 | context.done(err,''); 25 | }); 26 | }; 27 | -------------------------------------------------------------------------------- /presentation/example.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Remark 8 | 122 | 123 | 124 | 464 | 465 | 466 | 469 | 470 | 476 | 477 | 478 | -------------------------------------------------------------------------------- /presentation/imgs/dynamic-dashboards.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudnative/lambda-chat/923e320a5acb2ac27c7675f461fda89e61eb6c6c/presentation/imgs/dynamic-dashboards.png -------------------------------------------------------------------------------- /presentation/imgs/kinesis-pull-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudnative/lambda-chat/923e320a5acb2ac27c7675f461fda89e61eb6c6c/presentation/imgs/kinesis-pull-10.png -------------------------------------------------------------------------------- /presentation/imgs/lambda-chat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudnative/lambda-chat/923e320a5acb2ac27c7675f461fda89e61eb6c6c/presentation/imgs/lambda-chat.png -------------------------------------------------------------------------------- /presentation/imgs/push-s3-example-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudnative/lambda-chat/923e320a5acb2ac27c7675f461fda89e61eb6c6c/presentation/imgs/push-s3-example-10.png -------------------------------------------------------------------------------- /presentation/imgs/vote-app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudnative/lambda-chat/923e320a5acb2ac27c7675f461fda89e61eb6c6c/presentation/imgs/vote-app.png -------------------------------------------------------------------------------- /presentation/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | AWS Lambda 8 | 155 | 156 | 157 | 948 | 949 | 950 | 953 | 954 | 960 | 961 | 962 | -------------------------------------------------------------------------------- /presentation/public: -------------------------------------------------------------------------------- 1 | . -------------------------------------------------------------------------------- /presentation/remark.language.js: -------------------------------------------------------------------------------- 1 | /* 2 | Language: remark markdown flavor 3 | Author: Ole Petter Bang 4 | */ 5 | 6 | hljs.registerLanguage('remark', function () { 7 | return { 8 | contains: [ 9 | { 10 | className: 'keyword', 11 | begin: '^#+[^\n]+', 12 | relevance: 10 13 | }, 14 | { 15 | className: 'comment', 16 | begin: '^---?' 17 | }, 18 | { 19 | className: 'string', 20 | begin: '^\\w+:' 21 | }, 22 | { 23 | className: 'literal', 24 | begin: '\\{\\{', end: '\\}\\}' 25 | }, 26 | { 27 | className: 'string', 28 | begin: '\\.\\w+' 29 | } 30 | ] 31 | }; 32 | }); 33 | -------------------------------------------------------------------------------- /publish-presentation.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2015 CloudNative, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | # Stop execution if something goes wrong 18 | set -e 19 | 20 | # Read configuration details and set them as environment variables 21 | echo "Loading configuration file: ./config.yml" 22 | source ./yaml2shell.sh 23 | eval $(parse_yaml ./config.yml) 24 | echo "Configuration loaded" 25 | 26 | echo "Uploading the presentation files to S3..." 27 | aws s3 sync --profile ${profile} --region ${region} --exclude "*public*" --no-follow-symlinks presentation/ s3://${s3_bucket}/presentation/ 28 | 29 | echo "-- DONE --" 30 | echo "Go to: http://${s3_bucket}.s3-website-${region}.amazonaws.com/presentation/" 31 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | awacs==0.5.0 2 | boto==2.38.0 3 | docopt==0.6.2 4 | PyYAML==3.11 5 | troposphere==0.7.2 6 | -------------------------------------------------------------------------------- /resources.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Script to generate a CloudFormation Template that brings up all of the AWS 4 | resources needed to run lambda-chat 5 | 6 | This requires Python 2.7. To get the required libraries: 7 | sudo pip install docopt boto troposphere awacs pyyaml --upgrade 8 | 9 | Usage: 10 | resources.py cf 11 | resources.py launch --region= --profile= 12 | resources.py update --region= --profile= 13 | resources.py delete --region= --profile= 14 | resources.py output --region= --profile= 15 | 16 | Options: 17 | -h --help Show this screen. 18 | --version Show version. 19 | --region= The AWS region to use 20 | --profile= The AWS credential profile to use 21 | 22 | License: 23 | Copyright 2015 CloudNative, Inc. 24 | https://cloudnative.io/ 25 | 26 | Licensed under the Apache License, Version 2.0 (the "License"); 27 | you may not use this file except in compliance with the License. 28 | You may obtain a copy of the License at 29 | 30 | http://www.apache.org/licenses/LICENSE-2.0 31 | 32 | Unless required by applicable law or agreed to in writing, software 33 | distributed under the License is distributed on an "AS IS" BASIS, 34 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 35 | See the License for the specific language governing permissions and 36 | limitations under the License. 37 | 38 | """ 39 | 40 | # Import all the goodness 41 | import sys 42 | from docopt import docopt 43 | import yaml 44 | from boto import cloudformation 45 | from troposphere import Template, Parameter, Output 46 | from troposphere import GetAtt, Ref, Join 47 | import troposphere.iam as iam 48 | import troposphere.sns as sns 49 | import troposphere.s3 as s3 50 | from awacs.aws import Action, Allow, Policy, Statement, Principal, Condition, StringEquals, AWSPrincipal 51 | 52 | 53 | def default_config(): 54 | """ 55 | Returns a dict with the default configuration 56 | """ 57 | return { 58 | 'stack_name': 'Lambda-Chat', 59 | 'tags': { 60 | 'Name': 'Lambda Chat', 61 | 'Creator': 'CloudNative' 62 | } 63 | } 64 | 65 | 66 | def load_config(): 67 | """ 68 | Returns the default config merged with the what is in the config.yml file 69 | """ 70 | try: 71 | # Attempt to load configuration file 72 | stream = file('config.yml', 'r') 73 | config = yaml.load(stream) 74 | config['loaded'] = True 75 | except IOError: 76 | config = {} 77 | config['loaded'] = False 78 | 79 | # Merge with default 80 | return dict(default_config().items() + config.items()) 81 | 82 | 83 | def assert_config_loaded(): 84 | """ 85 | Stops execution and displays an error message if the settings have not 86 | been loaded from config.yml 87 | """ 88 | if not config['loaded']: 89 | print('ERROR: Could not load file: config.yml') 90 | sys.exit(1) 91 | 92 | 93 | def cf_params(): 94 | """ 95 | Returns the parameters needed to create or update the CloudFormation 96 | stack 97 | """ 98 | assert_config_loaded() 99 | return [ 100 | ('GoogleOAuthClientID', config['google_oauth_client_id']), 101 | ('WebsiteS3BucketName', config['s3_bucket']), 102 | ] 103 | 104 | 105 | def generate_cf_template(): 106 | """ 107 | Returns an entire CloudFormation stack by using troposphere to construct 108 | each piece 109 | """ 110 | # Header of CloudFormation template 111 | t = Template() 112 | t.add_version("2010-09-09") 113 | t.add_description("Lambda Chat AWS Resources") 114 | # Paramters 115 | description = "should match [0-9]+-[a-z0-9]+.apps.googleusercontent.com" 116 | google_oauth_client_id = t.add_parameter(Parameter( 117 | "GoogleOAuthClientID", 118 | AllowedPattern="[0-9]+-[a-z0-9]+.apps.googleusercontent.com", 119 | Type="String", 120 | Description="The Client ID of your Google project", 121 | ConstraintDescription=description 122 | )) 123 | 124 | website_s3_bucket_name = t.add_parameter(Parameter( 125 | "WebsiteS3BucketName", 126 | AllowedPattern="[a-zA-Z0-9\-]*", 127 | Type="String", 128 | Description="Name of S3 bucket to store the website in", 129 | ConstraintDescription="can contain only alphanumeric characters and dashes.", 130 | )) 131 | 132 | # The SNS topic the website will publish chat messages to 133 | website_sns_topic = t.add_resource(sns.Topic( 134 | 'WebsiteSnsTopic', 135 | TopicName='lambda-chat', 136 | DisplayName='Lambda Chat' 137 | )) 138 | t.add_output(Output( 139 | "WebsiteSnsTopic", 140 | Description="sns_topic_arn", 141 | Value=Ref(website_sns_topic), 142 | )) 143 | 144 | # The IAM Role and Policy the website will assume to publish to SNS 145 | website_role = t.add_resource(iam.Role( 146 | "WebsiteRole", 147 | Path="/", 148 | AssumeRolePolicyDocument=Policy( 149 | Statement=[ 150 | Statement( 151 | Effect=Allow, 152 | Action=[Action("sts", "AssumeRoleWithWebIdentity")], 153 | Principal=Principal("Federated", "accounts.google.com"), 154 | Condition=Condition( 155 | StringEquals( 156 | "accounts.google.com:aud", 157 | Ref(google_oauth_client_id) 158 | ) 159 | ), 160 | ), 161 | ], 162 | ), 163 | )) 164 | t.add_resource(iam.PolicyType( 165 | "WebsitePolicy", 166 | PolicyName="lambda-chat-website-policy", 167 | Roles=[Ref(website_role)], 168 | PolicyDocument=Policy( 169 | Version="2012-10-17", 170 | Statement=[ 171 | Statement( 172 | Effect=Allow, 173 | Action=[Action("sns", "Publish")], 174 | Resource=[ 175 | Ref(website_sns_topic) 176 | ], 177 | ), 178 | ], 179 | ) 180 | )) 181 | t.add_output(Output( 182 | "WebsiteRole", 183 | Description="website_iam_role_arn", 184 | Value=GetAtt(website_role, "Arn"), 185 | )) 186 | 187 | website_bucket = t.add_resource(s3.Bucket( 188 | 'WebsiteS3Bucket', 189 | BucketName=Ref(website_s3_bucket_name), 190 | WebsiteConfiguration=s3.WebsiteConfiguration( 191 | ErrorDocument="error.html", 192 | IndexDocument="index.html" 193 | ) 194 | )) 195 | t.add_output(Output( 196 | "S3Bucket", 197 | Description="s3_bucket", 198 | Value=Ref(website_bucket), 199 | )) 200 | t.add_resource(s3.BucketPolicy( 201 | 'WebsiteS3BucketPolicy', 202 | Bucket=Ref(website_bucket), 203 | PolicyDocument={ 204 | "Version": "2012-10-17", 205 | "Statement": [ 206 | { 207 | "Sid": "PublicAccess", 208 | "Effect": "Allow", 209 | "Principal": "*", 210 | "Action": ["s3:GetObject"], 211 | "Resource": [{ 212 | "Fn::Join": [ 213 | "", 214 | [ 215 | "arn:aws:s3:::", 216 | { 217 | "Ref": "WebsiteS3Bucket", 218 | }, 219 | "/*" 220 | ] 221 | ] 222 | }] 223 | } 224 | ] 225 | } 226 | )) 227 | 228 | return t 229 | 230 | 231 | def launch(args, config, cf_conn, template): 232 | """ 233 | Create new CloudFormation Stack from the template 234 | """ 235 | print("Creating CloudFormation Stack %s..." % config['stack_name']) 236 | stack_id = cf_conn.create_stack( 237 | config['stack_name'], 238 | template_body=template.to_json(), 239 | parameters=cf_params(), 240 | tags=config['tags'], 241 | capabilities=['CAPABILITY_IAM'] 242 | ) 243 | print('Created ' + stack_id) 244 | 245 | 246 | def update(args, config, cf_conn, template): 247 | """ 248 | Update an existing CloudFormation Stack 249 | """ 250 | print("Updating CloudFormation Stack %s..." % config['stack_name']) 251 | stack_id = cf_conn.update_stack( 252 | config['stack_name'], 253 | template_body=template.to_json(), 254 | parameters=cf_params(), 255 | tags=config['tags'], 256 | capabilities=['CAPABILITY_IAM'] 257 | ) 258 | print('Updated ' + stack_id) 259 | 260 | 261 | def delete(args, config, cf_conn): 262 | """ 263 | Deletes an existing CloudFormation Stack 264 | """ 265 | # Delete an existing CloudFormation Stack with same name 266 | print("Deleting CloudFormation Stack %s..." % config['stack_name']) 267 | resp = cf_conn.delete_stack( 268 | config['stack_name'], 269 | ) 270 | print(resp) 271 | 272 | 273 | def output(args, config, cf_conn): 274 | """ 275 | Describes a CloudFormation Stack and prints the outputs 276 | """ 277 | print("Describing CloudFormation Stack %s..." % config['stack_name']) 278 | resp = conn.describe_stacks( 279 | config['stack_name'] 280 | ) 281 | print('---'); 282 | print('region: %s' % args['--region']) 283 | for output in resp[0].outputs: 284 | print("%s: %s" % (output.description, output.value)) 285 | 286 | 287 | if __name__ == '__main__': 288 | args = docopt(__doc__, version='Lambda Chat AWS Resources 0.2') 289 | config = load_config() 290 | 291 | print_cf_template = args['cf'] or args['launch'] 292 | 293 | try: 294 | if print_cf_template: 295 | template = generate_cf_template() 296 | print(template.to_json()) 297 | if (args['cf']): 298 | sys.exit(1) 299 | 300 | # Get a connection to AWS CloudFormation in the given region 301 | conn = cloudformation.connect_to_region( 302 | args['--region'], profile_name=args['--profile']) 303 | 304 | if (args['launch']): 305 | launch(args, config, conn, template) 306 | 307 | elif (args['update']): 308 | update(args, config, conn, template) 309 | 310 | elif (args['delete']): 311 | delete(args, config, conn) 312 | 313 | elif (args['output']): 314 | output(args, config, conn) 315 | 316 | 317 | except Exception, e: 318 | print('ERROR') 319 | print(e) 320 | print(e.message) 321 | -------------------------------------------------------------------------------- /s3-website/public/error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ERROR 8 | 9 | 10 | 11 |
12 |
13 |

ERROR

14 |

I don't know what you were looking for, but it's not here.

15 |

Go back to Lambda Chat

16 |
17 |
18 | 19 | -------------------------------------------------------------------------------- /s3-website/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Lambda Chat 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 64 | 65 | 66 |
67 |

A simple chat application using AWS Lambda, SNS, DynamoDB and hosted on S3.

68 | 69 |
70 |

Please sign in so we can assign you temporary AWS credentials.

71 | 72 |
73 |
74 |
75 | 76 |
77 | 78 |
79 |
80 |
Conversation
81 |
82 |
83 |
84 |
85 | 92 |
93 | 94 |
95 | 96 |
97 |
98 | 99 |
100 | 101 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /s3-website/public/lambda-chat.css: -------------------------------------------------------------------------------- 1 | html { 2 | position: relative; 3 | min-height: 100%; 4 | } 5 | 6 | body { 7 | /* Margin bottom by footer height */ 8 | margin-bottom: 60px; 9 | } 10 | 11 | body > .container { 12 | padding: 60px 15px 0; 13 | } 14 | 15 | .footer { 16 | position: absolute; 17 | bottom: 0; 18 | width: 100%; 19 | /* Set the fixed height of the footer here */ 20 | height: 60px; 21 | background-color: #f5f5f5; 22 | } 23 | 24 | .footer > .container { 25 | padding-right: 15px; 26 | padding-left: 15px; 27 | } 28 | 29 | .footer > .container > p { 30 | margin: 20px 0; 31 | } 32 | 33 | .chatbox > .panel-footer > .form > .form-group { 34 | margin-bottom: 0px; 35 | } 36 | 37 | #chat-body { 38 | overflow-y: scroll; 39 | height:400px; 40 | padding-right:20px; 41 | } -------------------------------------------------------------------------------- /s3-website/public/lambda-chat.js: -------------------------------------------------------------------------------- 1 | var webIdentityToken = null; 2 | var sns = null; 3 | var chatUpdateId = null; 4 | var displayedMessages = []; 5 | var username = 'Anonymous'; 6 | 7 | function setStateSignedOut() { 8 | // Toggle state to signed out 9 | $('#signout-button').addClass('hidden'); 10 | $('#signed-out').show(); 11 | $('#signed-in').hide(); 12 | 13 | // Stop reading chat messages 14 | if (chatUpdateId) { 15 | clearInterval(chatUpdateId) 16 | chatUpdateId = null; 17 | } 18 | } 19 | 20 | function setStateSignedIn() { 21 | // Toggle state to signed in 22 | $('#signout-button').removeClass('hidden'); 23 | $('#signed-out').hide(); 24 | $('#signed-in').show(); 25 | 26 | // Start reading the chat messages 27 | chatUpdateId = setInterval(updateChat, 1000); 28 | } 29 | 30 | function showSigninButton() { 31 | var options = { 32 | 'callback' : signinCallback, 33 | 'approvalprompt' : 'force', 34 | 'scope' : 'profile', 35 | 'cookiepolicy' : 'single_host_origin', 36 | 'clientid' : google_oauth_client_id, 37 | }; 38 | gapi.signin.render('renderMe', options); 39 | } 40 | 41 | 42 | function signinCallback(authResult) { 43 | if (authResult['status']['signed_in']) { 44 | console.log('User is signed in!'); 45 | 46 | // Toggle state to signed in 47 | setStateSignedIn(); 48 | 49 | // Get the profile details about the user 50 | gapi.client.load('plus', 'v1', getUserProfile) 51 | 52 | // Save the token 53 | webIdentityToken = authResult['id_token'] 54 | 55 | setAwsConfig(); 56 | 57 | } else { 58 | // Update the app to reflect a signed out user 59 | // Possible error values: 60 | // "user_signed_out" - User is signed-out 61 | // "access_denied" - User denied access to your app 62 | // "immediate_failed" - Could not automatically log in the user 63 | console.log('Sign-in state: ' + authResult['error']); 64 | 65 | console.log('User is signed out'); 66 | 67 | 68 | // Toggle state to signed out 69 | setStateSignedOut(); 70 | } 71 | } 72 | 73 | function signOut() { 74 | gapi.auth.signOut(); 75 | 76 | setStateSignedOut(); 77 | } 78 | 79 | 80 | function setAwsConfig() { 81 | AWS.config.region = region 82 | AWS.config.credentials = new AWS.WebIdentityCredentials({ 83 | RoleArn: website_iam_role_arn, 84 | RoleSessionName: 'lambda-chat', 85 | WebIdentityToken: webIdentityToken 86 | }); 87 | 88 | // Also create an SNS 89 | sns = new AWS.SNS(); 90 | } 91 | 92 | 93 | function getUserProfile() { 94 | gapi.client.plus.people.get({userId: 'me'}).execute(function(resp) { 95 | console.log('Got user details') 96 | console.log(resp); 97 | username = resp.displayName; 98 | setStatusBar('Welcome ' + username); 99 | }); 100 | } 101 | 102 | function sendMessage(input) { 103 | message = input.val(); 104 | if (message.length > 0) { 105 | var payload = { 106 | name: username, 107 | message: message, 108 | } 109 | 110 | var params = { 111 | Message: JSON.stringify(payload), 112 | TargetArn: sns_topic_arn 113 | }; 114 | 115 | setStatusBar('Sending message to SNS'); 116 | sns.publish(params, function(err, data) { 117 | if (err) { 118 | // an error occurred 119 | console.log(err, err.stack); 120 | setStatusBar(err); 121 | } else { 122 | // successful response 123 | console.log(data); 124 | setStatusBar('Message sent to SNS successfully'); 125 | } 126 | }); 127 | } 128 | 129 | // Reset the input box for the next message 130 | input.val(''); 131 | } 132 | 133 | 134 | function updateChat() { 135 | getData().done(function(data) { 136 | var messageList = data['messages']; 137 | 138 | // Get the last message displayed 139 | if (displayedMessages.length > 0) { 140 | lastMessage = displayedMessages[displayedMessages.length - 1]; 141 | console.log('The last message is: '); 142 | console.log(lastMessage); 143 | } else { 144 | lastMessage = {}; 145 | } 146 | 147 | // Figure out which messages from the data to add 148 | msgsToAdd = []; 149 | for (var i = messageList.length - 1; i >= 0; i--) { 150 | var message = messageList[i]; 151 | if (areMessagesEqual(message, lastMessage)) { 152 | break; 153 | } 154 | 155 | msgsToAdd.unshift(message); 156 | } 157 | 158 | // Now actually display the messages 159 | chatBody = $('#chat-body'); 160 | for (var i = 0; i < msgsToAdd.length; i++) { 161 | message = msgsToAdd[i]; 162 | 163 | msgHtml = '
'; 164 | msgHtml += '
'; 165 | msgHtml += ' ' + message['name'] + ''; 166 | msgHtml += '
'; 167 | msgHtml += '
' + message['message'] + '
'; 168 | msgHtml += '
'; 169 | 170 | chatBody.append(msgHtml); 171 | chatBody.animate({ 172 | scrollTop: "+=" + 20 + "px" 173 | }); 174 | 175 | displayedMessages.push(message); 176 | } 177 | }); 178 | } 179 | 180 | 181 | function areMessagesEqual(msg1, msg2) { 182 | return msg1['name'] == msg2['name'] 183 | && msg1['message'] == msg2['message']; 184 | } 185 | 186 | 187 | /** 188 | * Makes a call to a data file to set a data object for the chart 189 | * @return {JSON object} 190 | */ 191 | function getData() { 192 | return $.getJSON(data_key).then( 193 | function(data) { 194 | console.log('Data loaded'); 195 | console.log(data); 196 | return data; 197 | } 198 | , function(jqXHR, textStatus, errorThrown) { 199 | console.log("ERROR: " + errorThrown); 200 | console.log(jqXHR); 201 | } 202 | ); 203 | } 204 | 205 | 206 | function setStatusBar(text) { 207 | $('#status-bar').text(text); 208 | } 209 | 210 | // Load 211 | $(function() { 212 | // Set initial state to signed out 213 | setStateSignedOut(); 214 | 215 | // Add listener for signout button clicks 216 | $('#signout-button').click(signOut); 217 | 218 | // Show the sign in button 219 | showSigninButton(); 220 | 221 | // Add a listener for the ENTER key on the chat message box 222 | $('#chat-message').keypress(function(e) { 223 | if (e.which == 13) { 224 | sendMessage($('#chat-message')); 225 | } 226 | }); 227 | 228 | // Always get the data 229 | $.ajaxSetup({ cache: false }); 230 | }); 231 | -------------------------------------------------------------------------------- /s3-website/update.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2015 CloudNative, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | # Stop execution if something goes wrong 18 | set -e 19 | 20 | # Read configuration details and set them as environment variables 21 | echo "Loading configuration file: ../config.yml" 22 | source ../yaml2shell.sh 23 | eval $(parse_yaml ../config.yml) 24 | echo "Configuration loaded" 25 | 26 | echo "Writing Javascript config file..." 27 | cat > public/config.js < indent) {delete vname[i]}} 15 | if (length($3) > 0) { 16 | vn=""; for (i=0; i