├── .DS_Store ├── .github └── PULL_REQUEST_TEMPLATE.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── images ├── xray-segment-info-1024x776.jpeg ├── xray-servicemap-1024x403.jpeg ├── xray-sidecar.jpeg ├── xray-trace-1024x337.jpeg └── xray-traffic-flow.jpeg └── src ├── .DS_Store ├── README.md ├── ecs-trust-pol.json ├── service-a-taskdef.json ├── service-a ├── Dockerfile ├── buildspec.yml ├── docker-compose.yml-template ├── ecs-params.yml-template ├── package.json └── server.js ├── service-b-taskdef.json ├── service-b ├── Dockerfile ├── docker-compose.yml-template ├── ecs-params.yml-template ├── package.json └── server.js ├── xray-daemon ├── Dockerfile ├── buildspec.yml └── xray-k8s-daemonset.yaml └── xray-pol.json /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-xray-fargate/1b74080aa9155db90b69114d539e38ba4bee13e9/.DS_Store -------------------------------------------------------------------------------- /.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 my contribution is made under the terms of the Apache 2.0 license. 7 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/aws-samples/aws-xray-fargate/issues), or [recently closed](https://github.com/aws-samples/aws-xray-fargate/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws-samples/aws-xray-fargate/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/aws-samples/aws-xray-fargate/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Application Tracing on Fargate 2 | Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Application Tracing on Fargate with AWS X-Ray 2 | 3 | This is a continuation of an earlier [post](https://aws.amazon.com/de/blogs/compute/application-tracing-on-kubernetes-with-aws-x-ray/) on application tracking on Kubernetes with AWS X-Ray. 4 | 5 | As microservices proliferate, the ability to trace calls between different different services becomes increasingly important. This can be accomplished using AWS X-Ray, a managed service that provides distributed application tracing functionality. X-Ray was built to help you understand how your services are interacting with each other by surfacing information such as call latency and exceptions, which together, helps you analyze, debug, and resolve issues faster. 6 | 7 | Containers have become a popular vehicle for packaging and deploying microservices because they’re lightweight, polyglot, and run consistently as they’re moved across different environments. It’s not unusual for these types of applications to be deployed using a container orchestration platform like ECS. ECS simplifies running containers by providing a managed control plane for managing cluster resources and scheduling your containers onto a fleet of EC2 instances. These instances, however, are still your responsibility. Since managing a large fleet of hosts can be complex, we built Fargate, a managed service that removes “undifferentiated heavy lifting” that often accompanies management of a fleet of container instances. Fargate allows you to concentrate on building and operating your application, rather than infrastructure and gives you yet another option for running your microservices applications. 8 | 9 | ## Running X-Ray on Fargate 10 | 11 | The remainder of this post explains how to run X-Ray as a sidecar container in a Fargate task. By doing this, you will be able to provide application tracing capabilities to services running on Fargate. 12 | 13 | The code, including a simple Node.js based demo application is available in the [src](https://github.com/aws-samples/aws-xray-fargate/tree/master/src) folder, so you can quickly get started with X-Ray. 14 | 15 | The sample application within the repository consists of two simple microservices, Service-A and Service-B. The following diagram illustrates how each service is deployed with 2 Fargate services: 16 | 17 | ![xray-traffic-flow](/images/xray-traffic-flow.jpeg) 18 | 19 | 20 | * Requests are sent to the Service-A from clients. 21 | * Service-A then contacts Service-B. 22 | * The requests are serviced by Service-B. 23 | * Service-B adds a random delay to each request to show different response times in X-Ray. 24 | 25 | 26 | To test out the sample applications on your own ECS/Fargate cluster use the Dockerfiles provided in the GitHub repository, then follow the steps in the README file. 27 | 28 | ## Prerequisites 29 | 30 | If you do not have an ECS cluster running within your AWS environment, create it now using the following command: 31 | 32 | `aws ecs create-cluster --cluster-name --region us-east-1` 33 | 34 | *NOTE:* At present, you can only create Fargate tasks in us-east-1, us-east-2, us-west-2 and eu-west-1. 35 | 36 | ## Deploy X-Ray as a sidecar container 37 | 38 | In Christoph Kassen’s blog post, he describes how to deploy the X-Ray pod as a Kubernetes daemonset. A daemonset is a special type of deployment strategy that places one instance of a pod onto each instance in the cluster. It will also deploy an instance of that pod onto Kubernetes workers as they’re added to the cluster. Since Fargate doesn’t yet have support for daemonsets, you have to deploy X-Ray as a sidecar container. A sidecar container is a container that runs alongside another container in the same Fargate task. 39 | 40 | ![xray-sidecar](/images/xray-sidecar.jpeg) 41 | 42 | The task definitions in the GitHub repository are already configured to run X-Ray as a sidecar container. 43 | 44 | ## Connecting to the X-Ray daemon 45 | 46 | To integrate application tracing with your applications, use the X-Ray SDK for one of the supported programming languages: 47 | 48 | 49 | * Java 50 | * Node.js 51 | * .NET (Framework and Core) 52 | * Go 53 | * Python 54 | 55 | 56 | The SDKs provide classes and methods for generating and sending trace data to the X-Ray daemon. Trace data includes information about incoming HTTP requests served by the application, and calls that the application makes to downstream services using the AWS SDK or HTTP clients. 57 | 58 | By default, the X-Ray SDK expects the daemon to be available on 127.0.0.1:2000. Since we’re running X-Ray as a sidecar container, no changes are necessary. 59 | 60 | ## Sending tracing information to AWS X-Ray 61 | 62 | Sending tracing information from your application is straightforward with the X-Ray SDKs. The example code below serves as a starting point to instrument your application with traces. Take a look at the two sample applications in the GitHub repository to see how to send traces from Service A to Service B. The diagram below visualizes the flow of requests between the services. 63 | 64 | Since Fargate is a service that manages the instances your tasks run on, access to the underlying host is prohibited. Consequently, the ECSPlugin and EC2Plugins for X-Ray will not work. 65 | 66 | ``` 67 | var app = express(); 68 | 69 | //... 70 | 71 | var AWSXRay = require('aws-xray-sdk'); 72 | 73 | app.use(AWSXRay.express.openSegment('defaultName')); //required at the start of your routes 74 | 75 | app.get('/', function (req, res) { 76 | res.render('index'); 77 | }); 78 | 79 | app.use(AWSXRay.express.closeSegment()); //required at the end of your routes / first in error handling routes 80 | ``` 81 | 82 | For more information about all options and possibilities to instrument your application code, see the X-Ray [documentation](https://aws.amazon.com/documentation/xray/) page for the corresponding SDK information. 83 | 84 | The image below shows the resulting service map that provides insights into the flow of requests through the microservice landscape. You can drill down here into individual traces and see which path each request has taken. 85 | 86 | ![xray-service-map](/images/xray-servicemap-1024x403.jpeg) 87 | 88 | From the service map, you can drill down into individual requests and see where they originated from and how much time was spent in each service processing the request. 89 | 90 | ![xray-trace](/images/xray-trace-1024x337.jpeg) 91 | 92 | You can also view details about every individual segment of the trace by clicking on it. This displays gives more details. 93 | 94 | ![xray-segment](/images/xray-segment-info-1024x776.jpeg) 95 | 96 | ## Summary 97 | 98 | In this post I shared how to deploy and run X-Ray running as a sidecar container in a Fargate task. By using X-Ray for distributed tracing you can get insights into how well your applications are performing and spot issues early before them become real problems. 99 | 100 | ## License 101 | 102 | This library is licensed under the Apache 2.0 License. 103 | -------------------------------------------------------------------------------- /images/xray-segment-info-1024x776.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-xray-fargate/1b74080aa9155db90b69114d539e38ba4bee13e9/images/xray-segment-info-1024x776.jpeg -------------------------------------------------------------------------------- /images/xray-servicemap-1024x403.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-xray-fargate/1b74080aa9155db90b69114d539e38ba4bee13e9/images/xray-servicemap-1024x403.jpeg -------------------------------------------------------------------------------- /images/xray-sidecar.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-xray-fargate/1b74080aa9155db90b69114d539e38ba4bee13e9/images/xray-sidecar.jpeg -------------------------------------------------------------------------------- /images/xray-trace-1024x337.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-xray-fargate/1b74080aa9155db90b69114d539e38ba4bee13e9/images/xray-trace-1024x337.jpeg -------------------------------------------------------------------------------- /images/xray-traffic-flow.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-xray-fargate/1b74080aa9155db90b69114d539e38ba4bee13e9/images/xray-traffic-flow.jpeg -------------------------------------------------------------------------------- /src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-xray-fargate/1b74080aa9155db90b69114d539e38ba4bee13e9/src/.DS_Store -------------------------------------------------------------------------------- /src/README.md: -------------------------------------------------------------------------------- 1 | Create a task role that allows the task to write traces to AWS X-Ray. Replace ** with your role name. 2 | 3 | ``` 4 | export TASK_ROLE_NAME=$(aws iam create-role --role-name --assume-role-policy-document file://ecs-trust-pol.json | jq -r '.Role.RoleName') 5 | export XRAY_POLICY_ARN=$(aws iam create-policy --policy-name --policy-document file://xray-pol.json | jq -r '.Policy.Arn') 6 | aws iam attach-role-policy --role-name $TASK_ROLE_NAME --policy-arn $XRAY_POLICY_ARN 7 | ``` 8 | 9 | If this is your first time using ECS you will need to create the ECS Task Execution Role. 10 | 11 | ``` 12 | aws iam create-role --role-name ecsTaskExecutionRole --assume-role-policy-document file://ecs-trust-pol.json 13 | export ECS_EXECUTION_POLICY_ARN=$(aws iam list-policies --scope AWS --query 'Policies[?PolicyName==`AmazonECSTaskExecutionRolePolicy`].Arn' | jq -r '.[]') 14 | aws iam attach-role-policy --role-name ecsTaskExecutionRole --policy-arn $ECS_EXECUTION_POLICY_ARN 15 | ``` 16 | 17 | Export the Arns of the task role and the task execution role. 18 | 19 | ``` 20 | export TASK_ROLE_ARN=$(aws iam get-role --role-name --query "Role.Arn" --output text) 21 | export TASK_EXECUTION_ROLE_ARN=$(aws iam get-role --role-name ecsTaskExecutionRole --query "Role.Arn" --output text) 22 | ``` 23 | 24 | Get a list of subnets in a VPC. Replace ** with the vpc id of the vpc where you intend to deploy the services. 25 | 26 | ``` 27 | aws ec2 describe-subnets --query 'Subnets[?VpcId==``].SubnetId' 28 | ``` 29 | 30 | Choose at least 2 subnets to set as environment variables. These will be used to populate the ecs-params.yml file. 31 | 32 | ``` 33 | export SUBNET_ID_1= 34 | export SUBNET_ID_2= 35 | ``` 36 | 37 | Create a security group. Replace **, **, and ** with the appropriate values. The ** should match the vpc id you used earlier. 38 | 39 | ``` 40 | export SG_ID=$(aws ec2 create-security-group --group-name --description --vpc-id | jq -r '.GroupId') 41 | ``` 42 | 43 | Add the following inbound rules to the security group. 44 | 45 | ``` 46 | aws ec2 authorize-security-group-ingress --group-id $SG_ID --protocol tcp --port 80 --cidr 0.0.0.0/0 47 | aws ec2 authorize-security-group-ingress --group-id $SG_ID --protocol all --port all --source-group $SG_ID 48 | ``` 49 | 50 | Create an Application Load Balancer (ALB), listener, and target group for service B. 51 | 52 | ``` 53 | export LOAD_BALANCER_ARN=$(aws elbv2 create-load-balancer --name --subnets $SUBNET_ID_1 $SUBNET_ID_2 --security-groups $SG_ID --scheme internet-facing --type application | jq -r '.LoadBalancers[].LoadBalancerArn') 54 | export TARGET_GROUP_ARN=$(aws elbv2 create-target-group --name --protocol HTTP --port 8080 --vpc-id --target-type ip --health-check-path /health | jq -r '.TargetGroups[].TargetGroupArn') 55 | aws elbv2 create-listener --load-balancer-arn $LOAD_BALANCER_ARN --protocol HTTP --port 80 --default-actions Type=forward,TargetGroupArn=$TARGET_GROUP_ARN 56 | ``` 57 | 58 | Get the DNS name of the load balancer. 59 | 60 | ``` 61 | export SERVICE_B_ENDPOINT=$(aws elbv2 describe-load-balancers --load-balancer-arn $LOAD_BALANCER_ARN | jq -r '.LoadBalancers[].DNSName') 62 | ``` 63 | 64 | Build and push the containers to ECR. 65 | 66 | ``` 67 | cd ./service-b/ 68 | docker build -t service-b . 69 | ecs-cli push service-b 70 | cd ./service-a/ 71 | docker build -t service-a . 72 | ecs-cli push service-a 73 | ``` 74 | 75 | Set the registry URLs 76 | 77 | ``` 78 | export REGISTRY_URL_SERVICE_B=$(aws ecr describe-repositories --repository-name service-b | jq -r '.repositories[].repositoryUri') 79 | export REGISTRY_URL_SERVICE_A=$(aws ecr describe-repositories --repository-name service-a | jq -r '.repositories[].repositoryUri') 80 | ``` 81 | 82 | Create logs groups. 83 | 84 | ``` 85 | aws logs create-log-group --log-group-name /ecs/service-b 86 | aws logs create-log-group --log-group-name /ecs/service-a 87 | ``` 88 | 89 | Create service B. 90 | 91 | ``` 92 | cd ./service-b/ 93 | envsubst < docker-compose.yml-template > docker-compose.yml 94 | envsubst < ecs-params.yml-template > ecs-params.yml 95 | ecs-cli compose service up --deployment-max-percent 100 --deployment-min-healthy-percent 0 --target-group-arn $TARGET_GROUP_ARN --launch-type FARGATE --container-name service-b --container-port 8080 --cluster 96 | ``` 97 | 98 | Create an Application Load Balancer (ALB), listener, and target group for service A. 99 | 100 | ``` 101 | export LOAD_BALANCER_ARN=$(aws elbv2 create-load-balancer --name --subnets $SUBNET_ID_1 $SUBNET_ID_2 --security-groups $SG_ID --scheme internet-facing --type application | jq -r '.LoadBalancers[].LoadBalancerArn') 102 | export TARGET_GROUP_ARN=$(aws elbv2 create-target-group --name --protocol HTTP --port 8080 --vpc-id --target-type ip --health-check-path /health | jq -r '.TargetGroups[].TargetGroupArn') 103 | aws elbv2 create-listener --load-balancer-arn $LOAD_BALANCER_ARN --protocol HTTP --port 80 --default-actions Type=forward,TargetGroupArn=$TARGET_GROUP_ARN 104 | ``` 105 | 106 | Create service A. 107 | 108 | ``` 109 | cd ./service-a/ 110 | envsubst < docker-compose.yml-template > docker-compose.yml 111 | envsubst < ecs-params.yml-template > ecs-params.yml 112 | ecs-cli compose service up --deployment-max-percent 100 --deployment-min-healthy-percent 0 --target-group-arn $TARGET_GROUP_ARN --launch-type FARGATE --container-name service-a --container-port 8080 --cluster 113 | ``` 114 | 115 | Open the X-Ray console. 116 | -------------------------------------------------------------------------------- /src/ecs-trust-pol.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "", 6 | "Effect": "Allow", 7 | "Principal": { 8 | "Service": "ecs-tasks.amazonaws.com" 9 | }, 10 | "Action": "sts:AssumeRole" 11 | } 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /src/service-a-taskdef.json: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "memory": "512", 4 | "networkMode": "awsvpc", 5 | "family": "service-a", 6 | "placementConstraints": [], 7 | "cpu": "256", 8 | "executionRoleArn": "", 9 | "volumes": [], 10 | "requiresCompatibilities": [ 11 | "FARGATE" 12 | ], 13 | "taskRoleArn": "", 14 | "containerDefinitions": [ 15 | { 16 | "environment": [ 17 | { 18 | "name": "AWS_XRAY_DAEMON_ADDRESS", 19 | "value": "" 20 | }, 21 | { 22 | "name": "API_CNAME", 23 | "value": "" 24 | } 25 | ], 26 | "name": "service-a", 27 | "mountPoints": [], 28 | "image": "", 29 | "cpu": 0, 30 | "portMappings": [ 31 | { 32 | "protocol": "tcp", 33 | "containerPort": 8080, 34 | "hostPort": 8080 35 | } 36 | ], 37 | "logConfiguration": { 38 | "logDriver": "awslogs", 39 | "options": { 40 | "awslogs-region": "us-east-1", 41 | "awslogs-stream-prefix": "ecs", 42 | "awslogs-group": "/ecs/service-a" 43 | } 44 | }, 45 | "essential": true, 46 | "volumesFrom": [] 47 | }, 48 | { 49 | "environment": [], 50 | "name": "xray-sidecar", 51 | "mountPoints": [], 52 | "image": "", 53 | "cpu": 0, 54 | "portMappings": [ 55 | { 56 | "protocol": "udp", 57 | "containerPort": 2000, 58 | "hostPort": 2000 59 | } 60 | ], 61 | "logConfiguration": { 62 | "logDriver": "awslogs", 63 | "options": { 64 | "awslogs-region": "us-east-1", 65 | "awslogs-stream-prefix": "ecs", 66 | "awslogs-group": "/ecs/service-a" 67 | } 68 | }, 69 | "essential": true, 70 | "volumesFrom": [] 71 | } 72 | ] 73 | } 74 | -------------------------------------------------------------------------------- /src/service-a/Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). 4 | # You may not use this file except in compliance with the License. 5 | # A copy of the License is located at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # or in the "license" file accompanying this file. This file is distributed 10 | # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | # express or implied. See the License for the specific language governing 12 | # permissions and limitations under the License. 13 | 14 | FROM node:8-alpine 15 | 16 | # Create app directory 17 | RUN mkdir -p /usr/src/app 18 | WORKDIR /usr/src/app 19 | 20 | # Install app dependencies 21 | COPY package.json /usr/src/app/ 22 | RUN npm install 23 | 24 | # Bundle app source 25 | COPY . /usr/src/app 26 | 27 | EXPOSE 8080 28 | 29 | CMD [ "node", "server.js" ] 30 | -------------------------------------------------------------------------------- /src/service-a/buildspec.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). 4 | # You may not use this file except in compliance with the License. 5 | # A copy of the License is located at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # or in the "license" file accompanying this file. This file is distributed 10 | # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | # express or implied. See the License for the specific language governing 12 | # permissions and limitations under the License. 13 | 14 | version: 0.2 15 | 16 | phases: 17 | pre_build: 18 | commands: 19 | - echo Logging in to Amazon ECR... 20 | - $(aws ecr get-login --no-include-email --region $AWS_DEFAULT_REGION) 21 | build: 22 | commands: 23 | - echo Build started on `date` 24 | - echo Building the Docker image... 25 | - docker build -t $IMAGE_REPO_NAME:latest . 26 | - docker tag $IMAGE_REPO_NAME:latest $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:latest 27 | post_build: 28 | commands: 29 | - echo Build completed on `date` 30 | - echo Pushing the Docker image... 31 | - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:latest 32 | -------------------------------------------------------------------------------- /src/service-a/docker-compose.yml-template: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | service-a: 4 | image: ${REGISTRY_URL_SERVICE_A} 5 | ports: 6 | - 8080:8080 7 | environment: 8 | API_CNAME: ${SERVICE_B_ENDPOINT} 9 | AWS_XRAY_DAEMON_ADDRESS: 10 | logging: 11 | driver: awslogs 12 | options: 13 | awslogs-group: /ecs/service-a 14 | awslogs-region: us-east-1 15 | awslogs-stream-prefix: ecs 16 | x-ray: 17 | image: amazon/aws-xray-daemon 18 | ports: 19 | - 2000:2000/udp 20 | environment: 21 | AWS_XRAY_DAEMON_ADDRESS: 22 | logging: 23 | driver: awslogs 24 | options: 25 | awslogs-group: /ecs/service-a 26 | awslogs-region: us-east-1 27 | awslogs-stream-prefix: ecs 28 | -------------------------------------------------------------------------------- /src/service-a/ecs-params.yml-template: -------------------------------------------------------------------------------- 1 | version: 1 2 | task_definition: 3 | ecs_network_mode: awsvpc 4 | task_role_arn: ${TASK_ROLE_ARN} 5 | task_execution_role: ${TASK_EXECUTION_ROLE_ARN} 6 | task_size: 7 | cpu_limit: 256 8 | mem_limit: 512 9 | services: 10 | service-a: 11 | essential: true 12 | run_params: 13 | network_configuration: 14 | awsvpc_configuration: 15 | subnets: 16 | - ${SUBNET_ID_1} 17 | - ${SUBNET_ID_2} 18 | security_groups: 19 | - ${SG_ID} 20 | assign_public_ip: ENABLED 21 | -------------------------------------------------------------------------------- /src/service-a/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "xray-demo-service-a", 3 | "version": "1.0.0", 4 | "description": "Express application with X-Ray traces", 5 | "author": "Christoph Kassen ", 6 | "main": "server.js", 7 | "scripts": { 8 | "start": "node server.js" 9 | }, 10 | "dependencies": { 11 | "express": "latest", 12 | "aws-sdk": "latest", 13 | "aws-xray-sdk": "latest", 14 | "body-parser": "latest", 15 | "querystring": "latest" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/service-a/server.js: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). 4 | // You may not use this file except in compliance with the License. 5 | // A copy of the License is located at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | var XRay = require('aws-xray-sdk'); 15 | var AWS = XRay.captureAWS(require('aws-sdk')); 16 | var http = XRay.captureHTTPs(require('http')); 17 | 18 | const express = require('express'); 19 | var bodyParser = require('body-parser'); 20 | var queryString = require('querystring'); 21 | 22 | 23 | // Constants 24 | const PORT = 8080; 25 | const apiCNAME = process.env.API_CNAME || 'localhost'; 26 | 27 | // App 28 | const app = express(); 29 | 30 | XRay.config([XRay.plugins.ECSPlugin]); 31 | XRay.middleware.enableDynamicNaming(); 32 | 33 | app.use(bodyParser.urlencoded({extended: false})); 34 | app.use(XRay.express.openSegment('service-a')); 35 | 36 | app.get('/health', function(req, res) { 37 | res.status(200).send("Healthy"); 38 | }); 39 | 40 | app.get('/', function(req, res) { 41 | var seg = XRay.getSegment(); 42 | seg.addAnnotation('service', 'service-b-request'); 43 | 44 | var reqData = queryString.stringify(req.body); 45 | 46 | var options = { 47 | host: apiCNAME, 48 | port: '80', 49 | path: '/create', 50 | method: 'POST', 51 | headers: { 52 | 'Content-Type': 'application/x-www-form-urlencoded', 53 | 'Content-Length': Buffer.byteLength(reqData) 54 | } 55 | }; 56 | 57 | // Set up the request 58 | var remoteReq = http.request(options, function(remoteRes) { 59 | var body = ''; 60 | remoteRes.setEncoding('utf8'); 61 | 62 | remoteRes.on('data', function(chunk) { 63 | body += chunk; 64 | }); 65 | 66 | remoteRes.on('end', function() { 67 | res.status(200).send(body); 68 | }); 69 | }); 70 | 71 | remoteReq.on('error', function() { 72 | console.log('service-b request failed'); 73 | }); 74 | 75 | // post the data 76 | remoteReq.write(reqData); 77 | remoteReq.end(); 78 | }); 79 | 80 | app.use(XRay.express.closeSegment()); 81 | 82 | app.listen(PORT); 83 | console.log('Running on http://0.0.0.0:' + PORT); 84 | -------------------------------------------------------------------------------- /src/service-b-taskdef.json: -------------------------------------------------------------------------------- 1 | { 2 | "memory": "512", 3 | "networkMode": "awsvpc", 4 | "family": "service-b", 5 | "placementConstraints": [], 6 | "cpu": "256", 7 | "executionRoleArn": "", 8 | "volumes": [], 9 | "requiresCompatibilities": [ 10 | "FARGATE" 11 | ], 12 | "taskRoleArn": "", 13 | "containerDefinitions": [ 14 | { 15 | "environment": [ 16 | { 17 | "name": "AWS_XRAY_DAEMON_ADDRESS", 18 | "value": "" 19 | } 20 | ], 21 | "name": "service-b", 22 | "mountPoints": [], 23 | "image": "", 24 | "cpu": 0, 25 | "portMappings": [ 26 | { 27 | "protocol": "tcp", 28 | "containerPort": 8080, 29 | "hostPort": 8080 30 | } 31 | ], 32 | "logConfiguration": { 33 | "logDriver": "awslogs", 34 | "options": { 35 | "awslogs-region": "us-east-1", 36 | "awslogs-stream-prefix": "ecs", 37 | "awslogs-group": "/ecs/service-b" 38 | } 39 | }, 40 | "essential": true, 41 | "volumesFrom": [] 42 | }, 43 | { 44 | "environment": [], 45 | "name": "xray-sidecar", 46 | "mountPoints": [], 47 | "image": "", 48 | "cpu": 0, 49 | "portMappings": [ 50 | { 51 | "protocol": "udp", 52 | "containerPort": 2000, 53 | "hostPort": 2000 54 | } 55 | ], 56 | "logConfiguration": { 57 | "logDriver": "awslogs", 58 | "options": { 59 | "awslogs-region": "us-east-1", 60 | "awslogs-stream-prefix": "ecs", 61 | "awslogs-group": "/ecs/service-b" 62 | } 63 | }, 64 | "essential": true, 65 | "volumesFrom": [] 66 | } 67 | ] 68 | } 69 | -------------------------------------------------------------------------------- /src/service-b/Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). 4 | # You may not use this file except in compliance with the License. 5 | # A copy of the License is located at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # or in the "license" file accompanying this file. This file is distributed 10 | # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | # express or implied. See the License for the specific language governing 12 | # permissions and limitations under the License. 13 | 14 | FROM node:8-alpine 15 | 16 | # Create app directory 17 | RUN mkdir -p /usr/src/app 18 | WORKDIR /usr/src/app 19 | 20 | # Install app dependencies 21 | COPY package.json /usr/src/app/ 22 | RUN npm install 23 | 24 | # Bundle app source 25 | COPY . /usr/src/app 26 | 27 | EXPOSE 8080 28 | 29 | CMD [ "node", "server.js" ] 30 | -------------------------------------------------------------------------------- /src/service-b/docker-compose.yml-template: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | service-b: 4 | image: ${REGISTRY_URL_SERVICE_B} 5 | ports: 6 | - 8080:8080 7 | environment: 8 | AWS_XRAY_DAEMON_ADDRESS: 9 | logging: 10 | driver: awslogs 11 | options: 12 | awslogs-group: /ecs/service-b 13 | awslogs-region: us-east-1 14 | awslogs-stream-prefix: ecs 15 | x-ray: 16 | image: amazon/aws-xray-daemon 17 | ports: 18 | - 2000:2000/udp 19 | environment: 20 | AWS_XRAY_DAEMON_ADDRESS: 21 | logging: 22 | driver: awslogs 23 | options: 24 | awslogs-group: /ecs/service-b 25 | awslogs-region: us-east-1 26 | awslogs-stream-prefix: ecs 27 | -------------------------------------------------------------------------------- /src/service-b/ecs-params.yml-template: -------------------------------------------------------------------------------- 1 | version: 1 2 | task_definition: 3 | ecs_network_mode: awsvpc 4 | task_role_arn: ${TASK_ROLE_ARN} 5 | task_execution_role: ${TASK_EXECUTION_ROLE_ARN} 6 | task_size: 7 | cpu_limit: 256 8 | mem_limit: 512 9 | services: 10 | service-b: 11 | essential: true 12 | run_params: 13 | network_configuration: 14 | awsvpc_configuration: 15 | subnets: 16 | - ${SUBNET_ID_1} 17 | - ${SUBNET_ID_2} 18 | security_groups: 19 | - ${SG_ID} 20 | assign_public_ip: ENABLED 21 | -------------------------------------------------------------------------------- /src/service-b/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "xray-demo-service-b", 3 | "version": "1.0.0", 4 | "description": "Express microservice with X-Ray traces", 5 | "author": "Christoph Kassen ", 6 | "main": "server.js", 7 | "scripts": { 8 | "start": "node server.js" 9 | }, 10 | "dependencies": { 11 | "express": "latest", 12 | "aws-sdk": "latest", 13 | "aws-xray-sdk": "latest" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/service-b/server.js: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). 4 | // You may not use this file except in compliance with the License. 5 | // A copy of the License is located at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | var XRay = require('aws-xray-sdk'); 15 | var AWS = XRay.captureAWS(require('aws-sdk')); 16 | 17 | const express = require('express'); 18 | 19 | // Constants 20 | const PORT = 8080; 21 | 22 | // App 23 | const app = express(); 24 | 25 | XRay.config([XRay.plugins.ECSPlugin]); 26 | XRay.middleware.enableDynamicNaming(); 27 | 28 | app.use(XRay.express.openSegment('service-b')); 29 | 30 | function randomIntInc(low, high) { 31 | return Math.floor(Math.random() * (high - low + 1) + low); 32 | } 33 | 34 | function sleep(callback) { 35 | var now = new Date().getTime(); 36 | while (new Date().getTime() < now + randomIntInc(0, 1000)) { /* */ } 37 | callback(); 38 | } 39 | 40 | app.get('/health', function(req, res) { 41 | res.status(200).send("Healthy"); 42 | }); 43 | 44 | app.post('/create', function(req, res) { 45 | res.setHeader('Content-Type', 'application/json'); 46 | 47 | var r = randomIntInc(1, 10) 48 | var st = 0; 49 | if (r % 2 == 0) { 50 | st = 200; 51 | } else { 52 | st = 403; 53 | } 54 | 55 | var data = { 56 | request: randomIntInc(1, 10000), 57 | status: st, 58 | time: new Date().getTime() 59 | }; 60 | 61 | for (var i = 0; i < 5; i++) { 62 | sleep(function() {}); 63 | } 64 | 65 | if (st == 200) { 66 | res.json(data); 67 | } else { 68 | res.status(st).send(data); 69 | } 70 | 71 | }); 72 | 73 | app.use(XRay.express.closeSegment()); 74 | 75 | app.listen(PORT); 76 | console.log('Running on http://0.0.0.0:' + PORT); 77 | -------------------------------------------------------------------------------- /src/xray-daemon/Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). 4 | # You may not use this file except in compliance with the License. 5 | # A copy of the License is located at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # or in the "license" file accompanying this file. This file is distributed 10 | # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | # express or implied. See the License for the specific language governing 12 | # permissions and limitations under the License. 13 | 14 | FROM amazonlinux:1 15 | 16 | # Download latest 2.x release of X-Ray daemon 17 | # Unpack archive, by default unzip is not installed so do that beforehand 18 | RUN yum install -y unzip && \ 19 | cd /tmp/ && \ 20 | curl https://s3.dualstack.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray-daemon/aws-xray-daemon-linux-2.x.zip > aws-xray-daemon-linux-2.x.zip && \ 21 | unzip aws-xray-daemon-linux-2.x.zip && \ 22 | cp xray /usr/bin/xray && \ 23 | rm aws-xray-daemon-linux-2.x.zip && \ 24 | rm cfg.yaml 25 | 26 | # Expose port 2000 on udp 27 | EXPOSE 2000/udp 28 | 29 | ENTRYPOINT ["/usr/bin/xray", "-b", "0.0.0.0:2000"] 30 | 31 | # No cmd line parameters, use default configuration 32 | CMD [''] 33 | -------------------------------------------------------------------------------- /src/xray-daemon/buildspec.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). 4 | # You may not use this file except in compliance with the License. 5 | # A copy of the License is located at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # or in the "license" file accompanying this file. This file is distributed 10 | # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | # express or implied. See the License for the specific language governing 12 | # permissions and limitations under the License. 13 | 14 | version: 0.2 15 | 16 | phases: 17 | pre_build: 18 | commands: 19 | - echo Logging in to Amazon ECR... 20 | - $(aws ecr get-login --no-include-email --region $AWS_DEFAULT_REGION) 21 | build: 22 | commands: 23 | - echo Build started on `date` 24 | - echo Building the Docker image... 25 | - docker build -t xray:latest . 26 | - docker tag xray:latest $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/xray:latest 27 | post_build: 28 | commands: 29 | - echo Build completed on `date` 30 | - echo Pushing the Docker image... 31 | - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/xray:latest 32 | -------------------------------------------------------------------------------- /src/xray-daemon/xray-k8s-daemonset.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). 4 | # You may not use this file except in compliance with the License. 5 | # A copy of the License is located at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # or in the "license" file accompanying this file. This file is distributed 10 | # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | # express or implied. See the License for the specific language governing 12 | # permissions and limitations under the License. 13 | 14 | apiVersion: v1 15 | kind: ServiceAccount 16 | metadata: 17 | labels: 18 | app: xray-daemon 19 | name: xray-daemon 20 | namespace: default 21 | --- 22 | apiVersion: rbac.authorization.k8s.io/v1beta1 23 | kind: ClusterRoleBinding 24 | metadata: 25 | name: xray-daemon 26 | labels: 27 | app: xray-daemon 28 | roleRef: 29 | apiGroup: rbac.authorization.k8s.io 30 | kind: ClusterRole 31 | name: cluster-admin 32 | subjects: 33 | - kind: ServiceAccount 34 | name: xray-daemon 35 | namespace: default 36 | --- 37 | apiVersion: extensions/v1beta1 38 | kind: DaemonSet 39 | metadata: 40 | name: xray-daemon 41 | spec: 42 | updateStrategy: 43 | type: RollingUpdate 44 | template: 45 | metadata: 46 | labels: 47 | app: xray-daemon 48 | spec: 49 | volumes: 50 | - name: config-volume 51 | configMap: 52 | name: "xray-config" 53 | hostNetwork: true 54 | containers: 55 | - name: xray-daemon 56 | image: .dkr.ecr.eu-west-1.amazonaws.com/xray:latest 57 | imagePullPolicy: Always 58 | command: [ "/usr/bin/xray", "-c", "/aws/xray/config.yaml" ] 59 | resources: 60 | limits: 61 | memory: 24Mi 62 | ports: 63 | - name: xray-ingest 64 | containerPort: 2000 65 | hostPort: 2000 66 | protocol: UDP 67 | volumeMounts: 68 | - name: config-volume 69 | mountPath: /aws/xray 70 | readOnly: true 71 | --- 72 | # Configuration for AWS X-Ray daemon 73 | apiVersion: v1 74 | kind: ConfigMap 75 | metadata: 76 | name: xray-config 77 | data: 78 | config.yaml: |- 79 | # Maximum buffer size in MB (minimum 3). Choose 0 to use 1% of host memory. 80 | TotalBufferSizeMB: 0 81 | # Maximum number of concurrent calls to AWS X-Ray to upload segment documents. 82 | Concurrency: 8 83 | # Send segments to AWS X-Ray service in a specific region 84 | Region: "" 85 | # Change the X-Ray service endpoint to which the daemon sends segment documents. 86 | Endpoint: "" 87 | Socket: 88 | # Change the address and port on which the daemon listens for UDP packets containing segment documents. 89 | # Make sure we listen on all IP's by default for the k8s setup 90 | UDPAddress: "0.0.0.0:2000" 91 | Logging: 92 | LogRotation: true 93 | # Change the log level, from most verbose to least: dev, debug, info, warn, error, prod (default). 94 | LogLevel: "prod" 95 | # Output logs to the specified file path. 96 | LogPath: "" 97 | # Turn on local mode to skip EC2 instance metadata check. 98 | LocalMode: false 99 | # Amazon Resource Name (ARN) of the AWS resource running the daemon. 100 | ResourceARN: "" 101 | # Assume an IAM role to upload segments to a different account. 102 | RoleARN: "" 103 | # Disable TLS certificate verification. 104 | NoVerifySSL: false 105 | # Upload segments to AWS X-Ray through a proxy. 106 | ProxyAddress: "" 107 | # Daemon configuration file format version. 108 | Version: 1 109 | --- 110 | # k8s service definition for AWS X-Ray daemon headless service 111 | apiVersion: v1 112 | kind: Service 113 | metadata: 114 | name: xray-service 115 | spec: 116 | selector: 117 | app: xray-daemon 118 | clusterIP: None 119 | ports: 120 | - name: incoming 121 | port: 2000 122 | protocol: UDP 123 | -------------------------------------------------------------------------------- /src/xray-pol.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "xray:PutTraceSegments", 8 | "xray:PutTelemetryRecords" 9 | ], 10 | "Resource": [ 11 | "*" 12 | ] 13 | } 14 | ] 15 | } 16 | --------------------------------------------------------------------------------