id
stringlengths 8
78
| source
stringclasses 743
values | chunk_id
int64 1
5.05k
| text
stringlengths 593
49.7k
|
---|---|---|---|
xray-guide-051 | xray-guide.pdf | 51 | "xray:GetSamplingTargets" ], "Resource": "*", "Condition": { "StringEquals": { "aws:SourceAccount": "account-id" }, "StringLike": { "aws:SourceArn": "arn:partition:sns:region:account-id:topic-name" } } } ] }' To use these examples, replace partition, region, account-id, and topic-name with your specific AWS partition, region, account ID, and Amazon SNS topic name. To give all Amazon SNS topics permission to send trace data to X-Ray, replace the topic name with *. How AWS X-Ray works with IAM 168 AWS X-Ray Developer Guide Authorization based on X-Ray tags You can attach tags to X-Ray groups or sampling rules, or pass tags in a request to X-Ray. To control access based on tags, you provide tag information in the condition element of a policy using the xray:ResourceTag/key-name, aws:RequestTag/key-name, or aws:TagKeys condition keys. For more information about tagging X-Ray resources, see Tagging X-Ray sampling rules and groups. To view an example identity-based policy for limiting access to a resource based on the tags on that resource, see Managing access to X-Ray groups and sampling rules based on tags. Running your application locally Your instrumented application sends trace data to the X-Ray daemon. The daemon buffers segment documents and uploads them to the X-Ray service in batches. The daemon needs write permissions to upload trace data and telemetry to the X-Ray service. When you run the daemon locally, create an IAM role, assume the role and store temporary credentials in environment variables, or in a file named credentials within a folder named .aws in your user folder. See using temporary security credentials with the AWS CLI for more information. Example ~/.aws/credentials [default] aws_access_key_id={access key ID} aws_secret_access_key={access key} aws_session_token={AWS session token} If you already configured credentials for use with the AWS SDK or AWS CLI, the daemon can use those. If multiple profiles are available, the daemon uses the default profile. Running your application in AWS When you run your application on AWS, use a role to grant permission to the Amazon EC2 instance or Lambda function that runs the daemon. • Amazon Elastic Compute Cloud (Amazon EC2) – Create an IAM role and attach it to the EC2 instance as an instance profile. How AWS X-Ray works with IAM 169 AWS X-Ray Developer Guide • Amazon Elastic Container Service (Amazon ECS) – Create an IAM role and attach it to container instances as a container instance IAM role. • AWS Elastic Beanstalk (Elastic Beanstalk) – Elastic Beanstalk includes X-Ray permissions in its default instance profile. You can use the default instance profile, or add write permissions to a custom instance profile. • AWS Lambda (Lambda) – Add write permissions to your function's execution role. To create a role for use with X-Ray 1. Open the IAM console. 2. Choose Roles. 3. Choose Create New Role. 4. 5. For Role Name, type xray-application. Choose Next Step. For Role Type, choose Amazon EC2. 6. Attach the following managed policy to give your application access to AWS services: • AWSXRayDaemonWriteAccess – Gives the X-Ray daemon permission to upload trace data. If your application uses the AWS SDK to access other services, add policies that grant access to those services. 7. Choose Next Step. 8. Choose Create Role. User permissions for encryption X-Ray encrypts all trace data and by default, and you can configure it to use a key that you manage. If you choose a AWS Key Management Service customer managed key, you need to ensure that the key's access policy lets you grant permission to X-Ray to use it to encrypt. Other users in your account also need access to the key to view encrypted trace data in the X-Ray console. For a customer managed key, configure your key with an access policy that allows the following actions: • User who configures the key in X-Ray has permission to call kms:CreateGrant and kms:DescribeKey. How AWS X-Ray works with IAM 170 AWS X-Ray Developer Guide • Users who can access encrypted trace data have permission to call kms:Decrypt. When you add a user to the Key users group in the key configuration section of the IAM console, they have permission for both of these operations. Permission only needs to be set on the key policy, so you don't need any AWS KMS permissions on your users, groups, or roles. For more information, see Using Key Policies in the AWS KMS Developer Guide. For default encryption, or if you choose the AWS managed CMK (aws/xray), permission is based on who has access to X-Ray APIs. Anyone with access to PutEncryptionConfig, included in AWSXrayFullAccess, can change the encryption configuration. To prevent a user from changing the encryption key, do not give them permission to use PutEncryptionConfig. AWS X-Ray identity-based policy examples By default, users and roles don't have permission to create or modify X-Ray resources. They also can't perform tasks using the AWS Management Console, AWS CLI, or |
xray-guide-052 | xray-guide.pdf | 52 | groups, or roles. For more information, see Using Key Policies in the AWS KMS Developer Guide. For default encryption, or if you choose the AWS managed CMK (aws/xray), permission is based on who has access to X-Ray APIs. Anyone with access to PutEncryptionConfig, included in AWSXrayFullAccess, can change the encryption configuration. To prevent a user from changing the encryption key, do not give them permission to use PutEncryptionConfig. AWS X-Ray identity-based policy examples By default, users and roles don't have permission to create or modify X-Ray resources. They also can't perform tasks using the AWS Management Console, AWS CLI, or AWS API. An administrator must create IAM policies that grant users and roles permission to perform specific API operations on the specified resources they need. The administrator must then attach those policies to the users or groups that require those permissions. To learn how to create an IAM identity-based policy using these example JSON policy documents, see Creating Policies on the JSON Tab in the IAM User Guide. Topics • Policy best practices • Using the X-Ray console • Allow users to view their own permissions • Managing access to X-Ray groups and sampling rules based on tags • IAM managed policies for X-Ray • X-Ray updates to AWS managed policies • Specifying a resource within an IAM policy Policy best practices Identity-based policies determine whether someone can create, access, or delete X-Ray resources in your account. These actions can incur costs for your AWS account. When you create or edit identity- based policies, follow these guidelines and recommendations: Identity-based policy examples 171 AWS X-Ray Developer Guide • Get started with AWS managed policies and move toward least-privilege permissions – To get started granting permissions to your users and workloads, use the AWS managed policies that grant permissions for many common use cases. They are available in your AWS account. We recommend that you reduce permissions further by defining AWS customer managed policies that are specific to your use cases. For more information, see AWS managed policies or AWS managed policies for job functions in the IAM User Guide. • Apply least-privilege permissions – When you set permissions with IAM policies, grant only the permissions required to perform a task. You do this by defining the actions that can be taken on specific resources under specific conditions, also known as least-privilege permissions. For more information about using IAM to apply permissions, see Policies and permissions in IAM in the IAM User Guide. • Use conditions in IAM policies to further restrict access – You can add a condition to your policies to limit access to actions and resources. For example, you can write a policy condition to specify that all requests must be sent using SSL. You can also use conditions to grant access to service actions if they are used through a specific AWS service, such as AWS CloudFormation. For more information, see IAM JSON policy elements: Condition in the IAM User Guide. • Use IAM Access Analyzer to validate your IAM policies to ensure secure and functional permissions – IAM Access Analyzer validates new and existing policies so that the policies adhere to the IAM policy language (JSON) and IAM best practices. IAM Access Analyzer provides more than 100 policy checks and actionable recommendations to help you author secure and functional policies. For more information, see Validate policies with IAM Access Analyzer in the IAM User Guide. • Require multi-factor authentication (MFA) – If you have a scenario that requires IAM users or a root user in your AWS account, turn on MFA for additional security. To require MFA when API operations are called, add MFA conditions to your policies. For more information, see Secure API access with MFA in the IAM User Guide. For more information about best practices in IAM, see Security best practices in IAM in the IAM User Guide. Using the X-Ray console To access the AWS X-Ray console, you must have a minimum set of permissions. These permissions must allow you to list and view details about the X-Ray resources in your AWS account. If you create an identity-based policy that is more restrictive than the minimum required permissions, the console won't function as intended for entities (users or roles) with that policy. Identity-based policy examples 172 AWS X-Ray Developer Guide To ensure that those entities can still use the X-Ray console, attach the AWSXRayReadOnlyAccess AWS managed policy to the entities. This policy is described in more detail in IAM managed policies for X-Ray. For more information, see Adding Permissions to a User in the IAM User Guide. You don't need to allow minimum console permissions for users that are making calls only to the AWS CLI or the AWS API. Instead, allow access to only the actions that match the API operation |
xray-guide-053 | xray-guide.pdf | 53 | as intended for entities (users or roles) with that policy. Identity-based policy examples 172 AWS X-Ray Developer Guide To ensure that those entities can still use the X-Ray console, attach the AWSXRayReadOnlyAccess AWS managed policy to the entities. This policy is described in more detail in IAM managed policies for X-Ray. For more information, see Adding Permissions to a User in the IAM User Guide. You don't need to allow minimum console permissions for users that are making calls only to the AWS CLI or the AWS API. Instead, allow access to only the actions that match the API operation that you're trying to perform. Allow users to view their own permissions This example shows how you might create a policy that allows IAM users to view the inline and managed policies that are attached to their user identity. This policy includes permissions to complete this action on the console or programmatically using the AWS CLI or AWS API. { "Version": "2012-10-17", "Statement": [ { "Sid": "ViewOwnUserInfo", "Effect": "Allow", "Action": [ "iam:GetUserPolicy", "iam:ListGroupsForUser", "iam:ListAttachedUserPolicies", "iam:ListUserPolicies", "iam:GetUser" ], "Resource": ["arn:aws:iam::*:user/${aws:username}"] }, { "Sid": "NavigateInConsole", "Effect": "Allow", "Action": [ "iam:GetGroupPolicy", "iam:GetPolicyVersion", "iam:GetPolicy", "iam:ListAttachedGroupPolicies", "iam:ListGroupPolicies", "iam:ListPolicyVersions", "iam:ListPolicies", "iam:ListUsers" ], "Resource": "*" Identity-based policy examples 173 AWS X-Ray } ] } Developer Guide Managing access to X-Ray groups and sampling rules based on tags You can use conditions in your identity-based policy to control access to X-Ray groups and sampling rules based on tags. The following example policy could be used to deny a user role the permissions to create, delete, or update groups with the tags stage:prod or stage:preprod. For more information about tagging X-Ray sampling rules and groups, see Tagging X-Ray sampling rules and groups. To deny a user access to create, update, or delete a group with a tag stage:prod or stage:preprod, assign the user a role with a policy similar to the following. { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAllXRay", "Effect": "Allow", "Action": "xray:*", "Resource": "*" }, { "Sid": "DenyCreateGroupWithStage", "Effect": "Deny", "Action": [ "xray:CreateGroup" ], "Resource": "*", "Condition": { "StringEquals": { "aws:RequestTag/stage": [ "preprod", "prod" ] } } }, { "Sid": "DenyUpdateGroupWithStage", Identity-based policy examples 174 AWS X-Ray Developer Guide "Effect": "Deny", "Action": [ "xray:UpdateGroup", "xray:DeleteGroup" ], "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/stage": [ "preprod", "prod" ] } } } ] } To deny the creation of a sampling rule, use aws:RequestTag to indicate tags that cannot be passed as part of a creation request. To deny the update or deletion of a sampling rule, use aws:ResourceTag to deny actions based on the tags on those resources. { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAllXRay", "Effect": "Allow", "Action": "xray:*", "Resource": "*" }, { "Sid": "DenyCreateSamplingRuleWithStage", "Effect": "Deny", "Action": "xray:CreateSamplingRule", "Resource": "*", "Condition": { "StringEquals": { "aws:RequestTag/stage": [ "preprod", "prod" ] } Identity-based policy examples 175 Developer Guide AWS X-Ray } }, { "Sid": "DenyUpdateSamplingRuleWithStage", "Effect": "Deny", "Action": [ "xray:UpdateSamplingRule", "xray:DeleteSamplingRule" ], "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/stage": [ "preprod", "prod" ] } } } ] } You can attach these policies (or combine them into a single policy, then attach the policy) to the users in your account. For the user to make changes to a group or sampling rule, the group or sampling rule must not be tagged stage=prepod or stage=prod. The condition tag key Stage matches both Stage and stage because condition key names are not case-sensitive. For more information about the condition block, see IAM JSON Policy Elements: Condition in the IAM User Guide. A user with a role that has the following policy attached cannot add the tag role:admin to resources, and cannot remove tags from a resource that has role:admin associated with it. { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAllXRay", "Effect": "Allow", "Action": "xray:*", "Resource": "*" }, { Identity-based policy examples 176 AWS X-Ray Developer Guide "Sid": "DenyRequestTagAdmin", "Effect": "Deny", "Action": "xray:TagResource", "Resource": "*", "Condition": { "StringEquals": { "aws:RequestTag/role": "admin" } } }, { "Sid": "DenyResourceTagAdmin", "Effect": "Deny", "Action": "xray:UntagResource", "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/role": "admin" } } } ] } IAM managed policies for X-Ray To make granting permissions easy, IAM supports managed policies for each service. A service can update these managed policies with new permissions when it releases new APIs. AWS X-Ray provides managed policies for read only, write only, and administrator use cases. • AWSXrayReadOnlyAccess – Read permissions for using the X-Ray console, AWS CLI, or AWS SDK to get trace data, trace maps, insights, and X-Ray configuration from the X-Ray API. Includes Observability Access Manager (OAM) oam:ListSinks and oam:ListAttachedSinks permissions to allow the console to view traces shared from source accounts as part of CloudWatch cross-account observability. The BatchGetTraceSummaryById and GetDistinctTraceGraphs API actions are not intended to be called by your code, and not included in the AWS CLI and AWS SDKs. { |
xray-guide-054 | xray-guide.pdf | 54 | when it releases new APIs. AWS X-Ray provides managed policies for read only, write only, and administrator use cases. • AWSXrayReadOnlyAccess – Read permissions for using the X-Ray console, AWS CLI, or AWS SDK to get trace data, trace maps, insights, and X-Ray configuration from the X-Ray API. Includes Observability Access Manager (OAM) oam:ListSinks and oam:ListAttachedSinks permissions to allow the console to view traces shared from source accounts as part of CloudWatch cross-account observability. The BatchGetTraceSummaryById and GetDistinctTraceGraphs API actions are not intended to be called by your code, and not included in the AWS CLI and AWS SDKs. { "Version": "2012-10-17", "Statement": [ { Identity-based policy examples 177 AWS X-Ray Developer Guide "Effect": "Allow", "Action": [ "xray:GetSamplingRules", "xray:GetSamplingTargets", "xray:GetSamplingStatisticSummaries", "xray:BatchGetTraces", "xray:BatchGetTraceSummaryById", "xray:GetDistinctTraceGraphs", "xray:GetServiceGraph", "xray:GetTraceGraph", "xray:GetTraceSummaries", "xray:GetGroups", "xray:GetGroup", "xray:ListTagsForResource", "xray:ListResourcePolicies", "xray:GetTimeSeriesServiceStatistics", "xray:GetInsightSummaries", "xray:GetInsight", "xray:GetInsightEvents", "xray:GetInsightImpactGraph", "oam:ListSinks" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Action": [ "oam:ListAttachedLinks" ], "Resource": "arn:aws:oam:*:*:sink/*" } } • AWSXRayDaemonWriteAccess – Write permissions for using the X-Ray daemon, AWS CLI, or AWS SDK to upload segment documents and telemetry to the X-Ray API. Includes read permissions to get sampling rules and report sampling results. { "Version": "2012-10-17", "Statement": [ Identity-based policy examples 178 Developer Guide AWS X-Ray { "Effect": "Allow", "Action": [ "xray:PutTraceSegments", "xray:PutTelemetryRecords", "xray:GetSamplingRules", "xray:GetSamplingTargets", "xray:GetSamplingStatisticSummaries" ], "Resource": [ "*" ] } ] } • AWSXrayCrossAccountSharingConfiguration – Grants permissions to create, manage, and view Observability Access Manager links for sharing X-Ray resources between accounts. Used to enable CloudWatch cross-account observability between source and monitoring accounts. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "xray:Link", "oam:ListLinks" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "oam:DeleteLink", "oam:GetLink", "oam:TagResource" ], "Resource": "arn:aws:oam:*:*:link/*" }, { "Effect": "Allow", "Action": [ Identity-based policy examples 179 AWS X-Ray Developer Guide "oam:CreateLink", "oam:UpdateLink" ], "Resource": [ "arn:aws:oam:*:*:link/*", "arn:aws:oam:*:*:sink/*" ] } ] } • AWSXrayFullAccess – Permission to use all X-Ray APIs, including read permissions, write permissions, and permission to configure encryption key settings and sampling rules. Includes Observability Access Manager (OAM) oam:ListSinks and oam:ListAttachedSinks permissions to allow the console to view traces shared from source accounts as part of CloudWatch cross-account observability. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "xray:*", "oam:ListSinks" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Action": [ "oam:ListAttachedLinks" ], "Resource": "arn:aws:oam:*:*:sink/*" } ] } Identity-based policy examples 180 AWS X-Ray Developer Guide To add a managed policy to an IAM user, group, or role 1. Open the IAM console. 2. Open the role associated with your instance profile, an IAM user, or an IAM group. 3. Under Permissions, attach the managed policy. X-Ray updates to AWS managed policies View details about updates to AWS managed policies for X-Ray since this service began tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the X-Ray Document history page. Change Description Date IAM managed policies for X- Ray – Added new AWSXrayCr ossAccountSharingC , and onfiguration updated AWSXrayRe and adOnlyAccess AWSXrayFullAccess policies. November 27, 2022 X-Ray added Observabi lity Access Manager (OAM) permissions oam:ListS inks and oam:ListA ttachedSinks policies to allow the console to these to view traces shared from source accounts as part of CloudWatch cross-account observability. IAM managed policies for X- X-Ray added an API action, November 15, 2022 Ray – Update to AWSXrayRe ListResourcePolicies . adOnlyAccess policy. Using the X-Ray console X-Ray added two new November 11, 2022 – Update to AWSXrayRe policy adOnlyAccess API actions, BatchGetT raceSummaryById and GetDistinctTraceGr aphs . These actions are not intended to be called by your Identity-based policy examples 181 AWS X-Ray Change Developer Guide Description Date code. Therefore, these API actions are not included in the AWS CLI and AWS SDKs. Specifying a resource within an IAM policy You can control access to resources by using an IAM policy. For actions that support resource-level permissions, you use an Amazon Resource Name (ARN) to identify the resource that the policy applies to. All X-Ray actions can be used in an IAM policy to grant or deny users permission to use that action. However, not all X-Ray actions support resource-level permissions, which enable you to specify the resources on which an action can be performed. For actions that don't support resource-level permissions, you must use "*" as the resource. The following X-Ray actions support resource-level permissions: • CreateGroup • GetGroup • UpdateGroup • DeleteGroup • CreateSamplingRule • UpdateSamplingRule • DeleteSamplingRule The following is an example of an identity-based permissions policy for a CreateGroup action. The example shows the use of an ARN relating to Group name local-users with the unique ID as a wildcard. The unique ID is generated when the group is created, and so it can't be predicted in the policy in advance. When using GetGroup, UpdateGroup, or DeleteGroup, you can define this as either a |
xray-guide-055 | xray-guide.pdf | 55 | don't support resource-level permissions, you must use "*" as the resource. The following X-Ray actions support resource-level permissions: • CreateGroup • GetGroup • UpdateGroup • DeleteGroup • CreateSamplingRule • UpdateSamplingRule • DeleteSamplingRule The following is an example of an identity-based permissions policy for a CreateGroup action. The example shows the use of an ARN relating to Group name local-users with the unique ID as a wildcard. The unique ID is generated when the group is created, and so it can't be predicted in the policy in advance. When using GetGroup, UpdateGroup, or DeleteGroup, you can define this as either a wildcard or the exact ARN, including ID. { "Version": "2012-10-17", Identity-based policy examples 182 AWS X-Ray Developer Guide "Statement": [ { "Effect": "Allow", "Action": [ "xray:CreateGroup" ], "Resource": [ "arn:aws:xray:eu-west-1:123456789012:group/local-users/*" ] } ] } The following is an example of an identity-based permissions policy for a CreateSamplingRule action. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "xray:CreateSamplingRule" ], "Resource": [ "arn:aws:xray:eu-west-1:123456789012:sampling-rule/base-scorekeep" ] } ] } Note The ARN of a sampling rule is defined by its name. Unlike group ARNs, sampling rules have no uniquely generated ID. Troubleshooting AWS X-Ray identity and access Use the following information to help you diagnose and fix common issues that you might encounter when working with X-Ray and IAM. Troubleshooting 183 AWS X-Ray Topics Developer Guide • I Am not authorized to perform an action in X-Ray • I Am not authorized to perform iam:PassRole • I'm an administrator and want to allow others to access X-Ray • I want to allow people outside of my AWS account to access my X-Ray resources I Am not authorized to perform an action in X-Ray If the AWS Management Console tells you that you're not authorized to perform an action, then you must contact your administrator for assistance. Your administrator is the person that provided you with your sign-in credentials. The following example error occurs when the mateojackson user tries to use the console to view details about a sampling rule but does not have xray:GetSamplingRules permissions. User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: xray:GetSamplingRules on resource: arn:${Partition}:xray:${Region}: ${Account}:sampling-rule/${SamplingRuleName} In this case, Mateo asks his administrator to update his policies to allow him to access the sampling rule resource using the xray:GetSamplingRules action. I Am not authorized to perform iam:PassRole If you receive an error that you're not authorized to perform the iam:PassRole action, your policies must be updated to allow you to pass a role to X-Ray. Some AWS services allow you to pass an existing role to that service instead of creating a new service role or service-linked role. To do this, you must have permissions to pass the role to the service. The following example error occurs when an IAM user named marymajor tries to use the console to perform an action in X-Ray. However, the action requires the service to have permissions that are granted by a service role. Mary does not have permissions to pass the role to the service. User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole Troubleshooting 184 AWS X-Ray Developer Guide In this case, Mary's policies must be updated to allow her to perform the iam:PassRole action. If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials. I'm an administrator and want to allow others to access X-Ray To allow others to access X-Ray, you must grant permission to the people or applications that need access. If you are using AWS IAM Identity Center to manage people and applications, you assign permission sets to users or groups to define their level of access. Permission sets automatically create and assign IAM policies to IAM roles that are associated with the person or application. For more information, see Permission sets in the AWS IAM Identity Center User Guide. If you are not using IAM Identity Center, you must create IAM entities (users or roles) for the people or applications that need access. You must then attach a policy to the entity that grants them the correct permissions in X-Ray. After the permissions are granted, provide the credentials to the user or application developer. They will use those credentials to access AWS. To learn more about creating IAM users, groups, policies, and permissions, see IAM Identities and Policies and permissions in IAM in the IAM User Guide. I want to allow people outside of my AWS account to access my X-Ray resources You can create a role that users in other accounts or people outside of your organization can use to access your resources. You can specify who is trusted to assume the role. For services that support resource-based policies or access control lists (ACLs), you can use those policies to grant people access to your resources. To learn |
xray-guide-056 | xray-guide.pdf | 56 | to access AWS. To learn more about creating IAM users, groups, policies, and permissions, see IAM Identities and Policies and permissions in IAM in the IAM User Guide. I want to allow people outside of my AWS account to access my X-Ray resources You can create a role that users in other accounts or people outside of your organization can use to access your resources. You can specify who is trusted to assume the role. For services that support resource-based policies or access control lists (ACLs), you can use those policies to grant people access to your resources. To learn more, consult the following: • To learn whether X-Ray supports these features, see How AWS X-Ray works with IAM. • To learn how to provide access to your resources across AWS accounts that you own, see Providing access to an IAM user in another AWS account that you own in the IAM User Guide. • To learn how to provide access to your resources to third-party AWS accounts, see Providing access to AWS accounts owned by third parties in the IAM User Guide. • To learn how to provide access through identity federation, see Providing access to externally authenticated users (identity federation) in the IAM User Guide. • To learn the difference between using roles and resource-based policies for cross-account access, see Cross account resource access in IAM in the IAM User Guide. Troubleshooting 185 AWS X-Ray Developer Guide Logging and monitoring in AWS X-Ray Monitoring is an important part of maintaining the reliability, availability, and performance of your AWS solutions. You should collect monitoring data from all of the parts of your AWS solution so that you can more easily debug a multi-point failure if one occurs. AWS provides several tools for monitoring your X-Ray resources and responding to potential incidents: AWS CloudTrail Logs AWS X-Ray integrates with AWS CloudTrail to record API actions made by a user, a role, or an AWS service in X-Ray. You can use CloudTrail to monitor X-Ray API requests in real time and store logs in Amazon S3, Amazon CloudWatch Logs, and Amazon CloudWatch Events. For more information, see Logging X-Ray API calls with AWS CloudTrail. AWS Config Tracking AWS X-Ray integrates with AWS Config to record configuration changes made to your X-Ray encryption resources. You can use AWS Config to inventory X-Ray encryption resources, audit the X-Ray configuration history, and send notifications based on resource changes. For more information, see Tracking X-Ray encryption configuration changes with AWS Config. Amazon CloudWatch Monitoring You can use the X-Ray SDK for Java to publish unsampled Amazon CloudWatch metrics from your collected X-Ray segments. These metrics are derived from the segment’s start and end time, and the error, fault and throttled status flags. Use these trace metrics to expose retries and dependency issues within subsegments. For more information, see AWS X-Ray metrics for the X-Ray SDK for Java. Compliance validation for AWS X-Ray To learn whether an AWS service is within the scope of specific compliance programs, see AWS services in Scope by Compliance Program and choose the compliance program that you are interested in. For general information, see AWS Compliance Programs. You can download third-party audit reports using AWS Artifact. For more information, see Downloading Reports in AWS Artifact. Logging and monitoring 186 AWS X-Ray Developer Guide Your compliance responsibility when using AWS services is determined by the sensitivity of your data, your company's compliance objectives, and applicable laws and regulations. AWS provides the following resources to help with compliance: • Security Compliance & Governance – These solution implementation guides discuss architectural considerations and provide steps for deploying security and compliance features. • HIPAA Eligible Services Reference – Lists HIPAA eligible services. Not all AWS services are HIPAA eligible. • AWS Compliance Resources – This collection of workbooks and guides might apply to your industry and location. • AWS Customer Compliance Guides – Understand the shared responsibility model through the lens of compliance. The guides summarize the best practices for securing AWS services and map the guidance to security controls across multiple frameworks (including National Institute of Standards and Technology (NIST), Payment Card Industry Security Standards Council (PCI), and International Organization for Standardization (ISO)). • Evaluating Resources with Rules in the AWS Config Developer Guide – The AWS Config service assesses how well your resource configurations comply with internal practices, industry guidelines, and regulations. • AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS. Security Hub uses security controls to evaluate your AWS resources and to check your compliance against security industry standards and best practices. For a list of supported services and controls, see Security Hub controls reference. • Amazon GuardDuty – This AWS service detects potential threats to your AWS accounts, workloads, containers, and data |
xray-guide-057 | xray-guide.pdf | 57 | Evaluating Resources with Rules in the AWS Config Developer Guide – The AWS Config service assesses how well your resource configurations comply with internal practices, industry guidelines, and regulations. • AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS. Security Hub uses security controls to evaluate your AWS resources and to check your compliance against security industry standards and best practices. For a list of supported services and controls, see Security Hub controls reference. • Amazon GuardDuty – This AWS service detects potential threats to your AWS accounts, workloads, containers, and data by monitoring your environment for suspicious and malicious activities. GuardDuty can help you address various compliance requirements, like PCI DSS, by meeting intrusion detection requirements mandated by certain compliance frameworks. • AWS Audit Manager – This AWS service helps you continuously audit your AWS usage to simplify how you manage risk and compliance with regulations and industry standards. Resilience in AWS X-Ray The AWS global infrastructure is built around AWS Regions and Availability Zones. AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected with low-latency, high-throughput, and highly redundant networking. With Availability Zones, you can design and operate applications and databases that automatically fail over between Availability Resilience 187 AWS X-Ray Developer Guide Zones without interruption. Availability Zones are more highly available, fault tolerant, and scalable than traditional single or multiple data center infrastructures. For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure. Infrastructure security in AWS X-Ray As a managed service, AWS X-Ray is protected by AWS global network security. For information about AWS security services and how AWS protects infrastructure, see AWS Cloud Security. To design your AWS environment using the best practices for infrastructure security, see Infrastructure Protection in Security Pillar AWS Well‐Architected Framework. You use AWS published API calls to access X-Ray through the network. Clients must support the following: • Transport Layer Security (TLS). We require TLS 1.2 and recommend TLS 1.3. • Cipher suites with perfect forward secrecy (PFS) such as DHE (Ephemeral Diffie-Hellman) or ECDHE (Elliptic Curve Ephemeral Diffie-Hellman). Most modern systems such as Java 7 and later support these modes. Additionally, requests must be signed by using an access key ID and a secret access key that is associated with an IAM principal. Or you can use the AWS Security Token Service (AWS STS) to generate temporary security credentials to sign requests. Using AWS X-Ray with VPC endpoints If you use Amazon Virtual Private Cloud (Amazon VPC) to host your AWS resources, you can establish a private connection between your VPC and X-Ray. This enables resources in your Amazon VPC to communicate with the X-Ray service without going through the public internet. Amazon VPC is an AWS service that you can use to launch AWS resources in a virtual network that you define. With a VPC, you have control over your network settings, such as the IP address range, subnets, route tables, and network gateways. To connect your VPC to X-Ray, you define an interface VPC endpoint. The endpoint provides reliable, scalable connectivity to X-Ray without requiring an internet gateway, network address translation (NAT) instance, or VPN connection. For more information, see What Is Amazon VPC in the Amazon VPC User Guide. Infrastructure security 188 AWS X-Ray Developer Guide Interface VPC endpoints are powered by AWS PrivateLink, an AWS technology that enables private communication between AWS services by using an elastic network interface with private IP addresses. For more information, see the New – AWS PrivateLink for AWS services blog post and Getting Started in the Amazon VPC User Guide. To ensure you can create a VPC endpoint for X-Ray in your chosen AWS Region, see Supported Regions. Creating a VPC endpoint for X-Ray To start using X-Ray with your VPC, create an interface VPC endpoint for X-Ray. 1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/. 2. Navigate to Endpoints within the navigation pane and choose Create Endpoint. 3. Search for and select the name of the AWS X-Ray service: com.amazonaws.region.xray. 4. Select the VPC you want and then select a subnet in your VPC to use the interface endpoint. An endpoint network interface is created in the selected subnet. You can specify more than one subnet in different Availability Zones (as supported by the service) to help ensure that your interface endpoint is resilient to Availability Zone failures. If you do so, an interface network interface is created in each subnet that you specify. Creating a VPC endpoint for X-Ray 189 AWS X-Ray Developer Guide 5. (Optional) Private DNS is enabled by default for the endpoint, so that you can make requests to X-Ray using its default DNS hostname. You can choose to disable it. 6. Specify the security groups to associate with |
xray-guide-058 | xray-guide.pdf | 58 | is created in the selected subnet. You can specify more than one subnet in different Availability Zones (as supported by the service) to help ensure that your interface endpoint is resilient to Availability Zone failures. If you do so, an interface network interface is created in each subnet that you specify. Creating a VPC endpoint for X-Ray 189 AWS X-Ray Developer Guide 5. (Optional) Private DNS is enabled by default for the endpoint, so that you can make requests to X-Ray using its default DNS hostname. You can choose to disable it. 6. Specify the security groups to associate with the endpoint network interface. 7. (Optional) Specify custom policy to control permissions to access the X-Ray service. By default, full access is allowed. Controlling access to your X-Ray VPC endpoint A VPC endpoint policy is an IAM resource policy that you attach to an endpoint when you create or modify the endpoint. If you don't attach a policy when you create an endpoint, Amazon VPC attaches a default policy for you that allows full access to the service. An endpoint policy doesn't override or replace IAM user policies or service-specific policies. It's a separate policy for controlling access from the endpoint to the specified service. Endpoint policies must be written in JSON Controlling access to your X-Ray VPC endpoint 190 AWS X-Ray Developer Guide format. For more information, see Controlling Access to Services with VPC Endpoints in the Amazon VPC User Guide. VPC endpoint policy enables you to control permissions to various X-Ray actions. For example, you can create a policy to allow only PutTraceSegment and deny all other actions. This restricts workloads and services in the VPC to send only trace data to X-Ray and deny any other action such as retrieve data, change encryption config, or create/update groups. The following is an example of an endpoint policy for X-Ray. This policy allows users connecting to X-Ray through the VPC to send segment data to X-Ray, and also prevents them from performing other X-Ray actions. {"Statement": [ {"Sid": "Allow PutTraceSegments", "Principal": "*", "Action": [ "xray:PutTraceSegments" ], "Effect": "Allow", "Resource": "*" } ] } To edit the VPC endpoint policy for X-Ray 1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/. 2. 3. 4. In the navigation pane, choose Endpoints. If you haven't already created the endpoint for X-Ray, follow the steps in Creating a VPC endpoint for X-Ray. Select the com.amazonaws.region.xray endpoint, and then choose the Policy tab. 5. Choose Edit Policy, and then make your changes. Supported Regions X-Ray currently supports VPC endpoints in the following AWS Regions: • US East (Ohio) • US East (N. Virginia) Supported Regions 191 Developer Guide AWS X-Ray • US West (N. California) • US West (Oregon) • Africa (Cape Town) • Asia Pacific (Hong Kong) • Asia Pacific (Mumbai) • Asia Pacific (Osaka) • Asia Pacific (Seoul) • Asia Pacific (Singapore) • Asia Pacific (Sydney) • Asia Pacific (Tokyo) • Canada (Central) • Europe (Frankfurt) • Europe (Ireland) • Europe (London) • Europe (Milan) • Europe (Paris) • Europe (Stockholm) • Middle East (Bahrain) • South America (São Paulo) • AWS GovCloud (US-East) • AWS GovCloud (US-West) Supported Regions 192 AWS X-Ray Developer Guide AWS X-Ray sample application The AWS X-Ray eb-java-scorekeep sample app, available on GitHub, shows the use of the AWS X- Ray SDK to instrument incoming HTTP calls, DynamoDB SDK clients, and HTTP clients. The sample app uses AWS CloudFormation to create DynamoDB tables, compile Java code on instance, and run the X-Ray daemon without any additional configuration. See the Scorekeep tutorial to start installing and using an instrumented sample application, using the AWS Management Console or the AWS CLI. The sample includes a front-end web app, the API that it calls, and the DynamoDB tables that it uses to store data. Basic instrumentation with filters, plugins, and instrumented AWS SDK clients is shown in the project's xray-gettingstarted branch. This is the branch that you deploy in the getting started tutorial. Because this branch only includes the basics, you can diff it against the master branch to quickly understand the basics. 193 AWS X-Ray Developer Guide The sample application shows basic instrumentation in these files: • HTTP request filter – WebConfig.java • AWS SDK client instrumentation – build.gradle 194 AWS X-Ray Developer Guide The xray branch of the application includes the use of HTTPClient, Annotations, SQL queries, custom subsegments, an instrumented AWS Lambda function, and instrumented initialization code and scripts. To support user log-in and AWS SDK for JavaScript use in the browser, the xray-cognito branch adds Amazon Cognito to support user authentication and authorization. With credentials retrieved from Amazon Cognito, the web app also sends trace data to X-Ray to record request information from the client's point of view. The browser client appears as its own node on |
xray-guide-059 | xray-guide.pdf | 59 | – WebConfig.java • AWS SDK client instrumentation – build.gradle 194 AWS X-Ray Developer Guide The xray branch of the application includes the use of HTTPClient, Annotations, SQL queries, custom subsegments, an instrumented AWS Lambda function, and instrumented initialization code and scripts. To support user log-in and AWS SDK for JavaScript use in the browser, the xray-cognito branch adds Amazon Cognito to support user authentication and authorization. With credentials retrieved from Amazon Cognito, the web app also sends trace data to X-Ray to record request information from the client's point of view. The browser client appears as its own node on the trace map, and records additional information, including the URL of the page that the user is viewing, and the user's ID. Finally, the xray-worker branch adds an instrumented Python Lambda function that runs independently, processing items from an Amazon SQS queue. Scorekeep adds an item to the queue each time a game ends. The Lambda worker, triggered by CloudWatch Events, pulls items from the queue every few minutes and processes them to store game records in Amazon S3 for analysis. Topics • Getting started with the Scorekeep sample application • Manually instrumenting AWS SDK clients • Creating additional subsegments • Recording annotations, metadata, and user IDs • Instrumenting outgoing HTTP calls • Instrumenting calls to a PostgreSQL database • Instrumenting AWS Lambda functions • Instrumenting startup code • Instrumenting scripts • Instrumenting a web app client • Using instrumented clients in worker threads Getting started with the Scorekeep sample application This tutorial uses the xray-gettingstarted branch of the Scorekeep sample application, which uses AWS CloudFormation to create and configure the resources that run the sample application and X-Ray daemon on Amazon ECS. The application uses the Spring framework to implement a Scorekeep tutorial 195 AWS X-Ray Developer Guide JSON web API and the AWS SDK for Java to persist data to Amazon DynamoDB. A servlet filter in the application instruments all incoming requests served by the application, and a request handler on the AWS SDK client instruments downstream calls to DynamoDB. You can follow this tutorial using either the AWS Management Console or the AWS CLI. Sections • Prerequisites • Install the Scorekeep application using CloudFormation • Generate trace data • View the trace map in the AWS Management Console • Configuring Amazon SNS notifications • Explore the sample application • Optional: Least privilege policy • Clean up • Next steps Prerequisites This tutorial uses AWS CloudFormation to create and configure the resources that run the sample application and X-Ray daemon. The following prerequisites are required to install and run through the tutorial: 1. If you use an IAM user with limited permissions, add the following user policies in the IAM console: • AWSCloudFormationFullAccess – to access and use CloudFormation • AmazonS3FullAccess – to upload a template file to CloudFormation using the AWS Management Console • IAMFullAccess – to create the Amazon ECS and Amazon EC2 instance roles • AmazonEC2FullAccess – to create the Amazon EC2 resources • AmazonDynamoDBFullAccess – to create the DynamoDB tables • AmazonECS_FullAccess – to create Amazon ECS resources • AmazonSNSFullAccess – to create the Amazon SNS topic Prerequisites 196 AWS X-Ray Developer Guide • AWSXrayReadOnlyAccess – for permission to view the trace map and traces in the X-Ray console 2. To run through the tutorial using the AWS CLI, install the CLI version 2.7.9 or later, and configure the CLI with the user from the previous step. Make sure the region is configured when configuring the AWS CLI with the user. If a region is not configured, you will need to append --region AWS-REGION to every CLI command. 3. Ensure that Git is installed, in order to clone the sample application repo. 4. Use the following code example to clone the xray-gettingstarted branch of the Scorekeep repository: git clone https://github.com/aws-samples/eb-java-scorekeep.git xray-scorekeep -b xray-gettingstarted Install the Scorekeep application using CloudFormation AWS Management Console Install the sample application using the AWS Management Console 1. Open the CloudFormation console 2. Choose Create stack and then choose With new resources from the drop-down menu. 3. 4. In the Specify template section, choose Upload a template file. Select Choose file, navigate to the xray-scorekeep/cloudformation folder that was created when you cloned the git repo, and choose the cf-resources.yaml file. 5. Choose Next to continue. 6. 7. 8. Enter scorekeep into the Stack name textbox, and then choose Next at the bottom of the page to continue. Note that the rest of this tutorial assumes the stack is named scorekeep. Scroll to the bottom of the Configure stack options page and choose Next to continue. Scroll to the bottom of the Review page, choose the check-box acknowledging that CloudFormation may create IAM resources with custom names, and choose Create stack. 9. The CloudFormation stack is now being created. The stack |
xray-guide-060 | xray-guide.pdf | 60 | you cloned the git repo, and choose the cf-resources.yaml file. 5. Choose Next to continue. 6. 7. 8. Enter scorekeep into the Stack name textbox, and then choose Next at the bottom of the page to continue. Note that the rest of this tutorial assumes the stack is named scorekeep. Scroll to the bottom of the Configure stack options page and choose Next to continue. Scroll to the bottom of the Review page, choose the check-box acknowledging that CloudFormation may create IAM resources with custom names, and choose Create stack. 9. The CloudFormation stack is now being created. The stack status will be CREATE_IN_PROGRESS for about five minutes before changing to CREATE_COMPLETE. The status will refresh periodically, or you can refresh the page. Install the Scorekeep application using CloudFormation 197 AWS X-Ray AWS CLI Developer Guide Install the sample application using the AWS CLI 1. Navigate to the cloudformation folder of the xray-scorekeep repository that you cloned earlier in the tutorial: cd xray-scorekeep/cloudformation/ 2. Enter the following AWS CLI command to create the CloudFormation stack: aws cloudformation create-stack --stack-name scorekeep --capabilities "CAPABILITY_NAMED_IAM" --template-body file://cf-resources.yaml 3. Wait until the CloudFormation stack status is CREATE_COMPLETE, which will take about five minutes. Use the following AWS CLI command to check on the status: aws cloudformation describe-stacks --stack-name scorekeep --query "Stacks[0].StackStatus" Generate trace data The sample application includes a front-end web app. Use the web app to generate traffic to the API and send trace data to X-Ray. First, retrieve the web app URL using the AWS Management Console or the AWS CLI: AWS Management Console Find the application URL using the AWS Management Console 1. Open the CloudFormation console 2. Choose the scorekeep stack from the list. 3. Choose the Outputs tab on the scorekeep stack page, and choose the LoadBalancerUrl URL link to open the web application. Generate trace data 198 AWS X-Ray AWS CLI Developer Guide Find the application URL using the AWS CLI 1. Use the following command to display the URL of the web application: aws cloudformation describe-stacks --stack-name scorekeep --query "Stacks[0].Outputs[0].OutputValue" 2. Copy this URL and open in a browser to display the Scorekeep web application. Use the web application to generate trace data 1. Choose Create to create a user and session. 2. Type a game name, set the Rules to Tic Tac Toe, and then choose Create to create a game. 3. Choose Play to start the game. 4. Choose a tile to make a move and change the game state. Each of these steps generates HTTP requests to the API, and downstream calls to DynamoDB to read and write user, session, game, move, and state data. View the trace map in the AWS Management Console You can see the trace map and traces generated by the sample application in the X-Ray and CloudWatch consoles. X-Ray console Use the X-Ray console 1. Open the trace map page of the X-Ray console. 2. The console shows a representation of the service graph that X-Ray generates from the trace data sent by the application. Be sure to adjust the time period of the trace map if needed, to make sure that it will display all traces since you first started the web application. View the trace map in the AWS Management Console 199 AWS X-Ray Developer Guide The trace map shows the web app client, the API running in Amazon ECS, and each DynamoDB table that the application uses. Every request to the application, up to a configurable maximum number of requests per second, is traced as it hits the API, generates requests to downstream services, and completes. You can choose any node in the service graph to view traces for requests that generated traffic to that node. Currently, the Amazon SNS node is yellow. Drill down to find out why. View the trace map in the AWS Management Console 200 AWS X-Ray Developer Guide To find the cause of the error 1. Choose the node named SNS. The node details panel is displayed. 2. Choose View traces to access the Trace overview screen. 3. Choose the trace from the Trace list. This trace doesn't have a method or URL because it was recorded during startup instead of in response to an incoming request. View the trace map in the AWS Management Console 201 AWS X-Ray Developer Guide 4. Choose the error status icon within the Amazon SNS segment at the bottom of the page, to open the Exceptions page for the SNS subsegment. View the trace map in the AWS Management Console 202 AWS X-Ray Developer Guide 5. The X-Ray SDK automatically captures exceptions thrown by instrumented AWS SDK clients and records the stack trace. CloudWatch console Use the CloudWatch console 1. Open the X-Ray trace map page of the CloudWatch console. 2. The console shows a |
xray-guide-061 | xray-guide.pdf | 61 | in response to an incoming request. View the trace map in the AWS Management Console 201 AWS X-Ray Developer Guide 4. Choose the error status icon within the Amazon SNS segment at the bottom of the page, to open the Exceptions page for the SNS subsegment. View the trace map in the AWS Management Console 202 AWS X-Ray Developer Guide 5. The X-Ray SDK automatically captures exceptions thrown by instrumented AWS SDK clients and records the stack trace. CloudWatch console Use the CloudWatch console 1. Open the X-Ray trace map page of the CloudWatch console. 2. The console shows a representation of the service graph that X-Ray generates from the trace data sent by the application. Be sure to adjust the time period of the trace View the trace map in the AWS Management Console 203 AWS X-Ray Developer Guide map if needed, to make sure that it will display all traces since you first started the web application. The trace map shows the web app client, the API running in Amazon EC2, and each DynamoDB table that the application uses. Every request to the application, up to a configurable maximum number of requests per second, is traced as it hits the API, generates requests to downstream services, and completes. You can choose any node in the service graph to view traces for requests that generated traffic to that node. Currently, the Amazon SNS node is orange. Drill down to find out why. View the trace map in the AWS Management Console 204 AWS X-Ray Developer Guide View the trace map in the AWS Management Console 205 AWS X-Ray Developer Guide To find the cause of the error 1. Choose the node named SNS. The SNS node details panel is displayed below the map. 2. Choose View traces to access the Traces page. 3. Add the bottom of the page, choose the trace from the Traces list. This trace doesn't have a method or URL because it was recorded during startup instead of in response to an incoming request. 4. Choose the Amazon SNS subsegment at the bottom of the segments timeline, and choose the Exceptions tab for the SNS subsegment to view the exception details. View the trace map in the AWS Management Console 206 AWS X-Ray Developer Guide The cause indicates that the email address provided in a call to createSubscription made in the WebConfig class was invalid. In the next section, we'll fix that. Configuring Amazon SNS notifications Scorekeep uses Amazon SNS to send notifications when users complete a game. When the application starts up, it tries to create a subscription for an email address defined in a CloudFormation stack parameter. That call is currently failing. Configure a notification email to enable notifications, and resolve the failures highlighted in the trace map. AWS Management Console To configure Amazon SNS notifications using the AWS Management Console 1. Open the CloudFormation console 2. Choose the radio button next to the scorekeep stack name in the list, and then choose Update. 3. Make sure that Use current template is chosen, and then click Next on the Update stack page. 4. Find the Email parameter in the list, and replace the default value with a valid email address. 5. 6. Scroll to the bottom of the page and choose Next. Scroll to the bottom of the Review page, choose the check-box acknowledging that CloudFormation may create IAM resources with custom names, and choose Update stack. 7. The CloudFormation stack is now being updated. The stack status will be UPDATE_IN_PROGRESS for about five minutes before changing to UPDATE_COMPLETE. The status will refresh periodically, or you can refresh the page. Configuring Amazon SNS notifications 207 AWS X-Ray AWS CLI Developer Guide To configure Amazon SNS notifications using the AWS CLI 1. Navigate to the xray-scorekeep/cloudformation/ folder you previously created, and open the cf-resources.yaml file in a text editor. 2. Find the Default value within the Email parameter and change it from UPDATE_ME to a valid email address. Parameters: Email: Type: String Default: UPDATE_ME # <- change to a valid abc@def.xyz email address 3. From the cloudformation folder, update the CloudFormation stack with the following AWS CLI command: aws cloudformation update-stack --stack-name scorekeep --capabilities "CAPABILITY_NAMED_IAM" --template-body file://cf-resources.yaml 4. Wait until the CloudFormation stack status is UPDATE_COMPLETE, which will take a few minutes. Use the following AWS CLI command to check on the status: aws cloudformation describe-stacks --stack-name scorekeep --query "Stacks[0].StackStatus" When the update completes, Scorekeep restarts and creates a subscription to the SNS topic. Check your email and confirm the subscription to see updates when you complete a game. Open the trace map to verify that the calls to SNS are no longer failing. Explore the sample application The sample application is an HTTP web API in Java that is configured to use the |
xray-guide-062 | xray-guide.pdf | 62 | "CAPABILITY_NAMED_IAM" --template-body file://cf-resources.yaml 4. Wait until the CloudFormation stack status is UPDATE_COMPLETE, which will take a few minutes. Use the following AWS CLI command to check on the status: aws cloudformation describe-stacks --stack-name scorekeep --query "Stacks[0].StackStatus" When the update completes, Scorekeep restarts and creates a subscription to the SNS topic. Check your email and confirm the subscription to see updates when you complete a game. Open the trace map to verify that the calls to SNS are no longer failing. Explore the sample application The sample application is an HTTP web API in Java that is configured to use the X-Ray SDK for Java. When you deploy the application with the CloudFormation template, it creates the DynamoDB tables, Amazon ECS Cluster, and other services required to run Scorekeep on ECS. A task definition file for ECS is created through CloudFormation. This file defines the container images used per task in an ECS cluster. These images are obtained from the official X-Ray public ECR. The scorekeep API container image has the API compiled with Gradle. The container image of the Scorekeep frontend Explore the sample application 208 AWS X-Ray Developer Guide container serves the frontend using the nginx proxy server. This server routes requests to paths starting with /api to the API. To instrument incoming HTTP requests, the application adds the TracingFilter provided by the SDK. Example src/main/java/scorekeep/WebConfig.java - servlet filter import javax.servlet.Filter; import com.amazonaws.xray.javax.servlet.AWSXRayServletFilter; ... @Configuration public class WebConfig { @Bean public Filter TracingFilter() { return new AWSXRayServletFilter("Scorekeep"); } ... This filter sends trace data about all incoming requests that the application serves, including request URL, method, response status, start time, and end time. The application also makes downstream calls to DynamoDB using the AWS SDK for Java. To instrument these calls, the application simply takes the AWS SDK-related submodules as dependencies, and the X-Ray SDK for Java automatically instruments all AWS SDK clients. The application uses Docker to build the source code on-instance with the Gradle Docker Image and the Scorekeep API Dockerfile file to run the executable JAR that Gradle generates at its ENTRYPOINT. Example use of Docker to build via Gradle Docker Image docker run --rm -v /PATH/TO/SCOREKEEP_REPO/home/gradle/project -w /home/gradle/project gradle:4.3 gradle build Example Dockerfile ENTRYPOINT ENTRYPOINT [ "sh", "-c", "java -Dserver.port=5000 -jar scorekeep-api-1.0.0.jar" ] Explore the sample application 209 AWS X-Ray Developer Guide The build.gradle file downloads the SDK submodules from Maven during compilation by declaring them as dependencies. Example build.gradle -- dependencies ... dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile('org.springframework.boot:spring-boot-starter-test') compile('com.amazonaws:aws-java-sdk-dynamodb') compile("com.amazonaws:aws-xray-recorder-sdk-core") compile("com.amazonaws:aws-xray-recorder-sdk-aws-sdk") compile("com.amazonaws:aws-xray-recorder-sdk-aws-sdk-instrumentor") ... } dependencyManagement { imports { mavenBom("com.amazonaws:aws-java-sdk-bom:1.11.67") mavenBom("com.amazonaws:aws-xray-recorder-sdk-bom:2.11.0") } } The core, AWS SDK, and AWS SDK Instrumentor submodules are all that's required to automatically instrument any downstream calls made with the AWS SDK. To relay the raw segment data to the X-Ray API, the X-Ray daemon is required to listen for traffic on UDP port 2000. To do so, the application has the X-Ray daemon run in a container that is deployed alongside the Scorekeep application on ECS as a sidecar container. Check out the X-Ray daemon topic for more information. Example X-Ray Daemon Container Definition in an ECS Task Definition ... Resources: ScorekeepTaskDefinition: Type: AWS::ECS::TaskDefinition Properties: ContainerDefinitions: ... - Cpu: '256' Essential: true Explore the sample application 210 AWS X-Ray Developer Guide Image: amazon/aws-xray-daemon MemoryReservation: '128' Name: xray-daemon PortMappings: - ContainerPort: '2000' HostPort: '2000' Protocol: udp ... The X-Ray SDK for Java provides a class named AWSXRay that provides the global recorder, a TracingHandler that you can use to instrument your code. You can configure the global recorder to customize the AWSXRayServletFilter that creates segments for incoming HTTP calls. The sample includes a static block in the WebConfig class that configures the global recorder with plugins and sampling rules. Example src/main/java/scorekeep/WebConfig.java - recorder import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorderBuilder; import com.amazonaws.xray.javax.servlet.AWSXRayServletFilter; import com.amazonaws.xray.plugins.ECSPlugin; import com.amazonaws.xray.plugins.EC2Plugin; import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy; ... @Configuration public class WebConfig { ... static { AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard().withPlugin(new ECSPlugin()).withPlugin(new EC2Plugin()); URL ruleFile = WebConfig.class.getResource("/sampling-rules.json"); builder.withSamplingStrategy(new LocalizedSamplingStrategy(ruleFile)); AWSXRay.setGlobalRecorder(builder.build()); ... } } Explore the sample application 211 AWS X-Ray Developer Guide This example uses the builder to load sampling rules from a file named sampling-rules.json. Sampling rules determine the rate at which the SDK records segments for incoming requests. Example src/main/java/resources/sampling-rules.json { "version": 1, "rules": [ { "description": "Resource creation.", "service_name": "*", "http_method": "POST", "url_path": "/api/*", "fixed_target": 1, "rate": 1.0 }, { "description": "Session polling.", "service_name": "*", "http_method": "GET", "url_path": "/api/session/*", "fixed_target": 0, "rate": 0.05 }, { "description": "Game polling.", "service_name": "*", "http_method": "GET", "url_path": "/api/game/*/*", "fixed_target": 0, "rate": 0.05 }, { "description": "State polling.", "service_name": "*", "http_method": "GET", "url_path": "/api/state/*/*/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 Explore the sample application 212 AWS X-Ray } } Developer Guide The sampling rules file defines four custom sampling rules and the default rule. For each incoming request, the SDK evaluates |
xray-guide-063 | xray-guide.pdf | 63 | "rules": [ { "description": "Resource creation.", "service_name": "*", "http_method": "POST", "url_path": "/api/*", "fixed_target": 1, "rate": 1.0 }, { "description": "Session polling.", "service_name": "*", "http_method": "GET", "url_path": "/api/session/*", "fixed_target": 0, "rate": 0.05 }, { "description": "Game polling.", "service_name": "*", "http_method": "GET", "url_path": "/api/game/*/*", "fixed_target": 0, "rate": 0.05 }, { "description": "State polling.", "service_name": "*", "http_method": "GET", "url_path": "/api/state/*/*/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 Explore the sample application 212 AWS X-Ray } } Developer Guide The sampling rules file defines four custom sampling rules and the default rule. For each incoming request, the SDK evaluates the custom rules in the order in which they are defined. The SDK applies the first rule that matches the request's method, path, and service name. For Scorekeep, the first rule catches all POST requests (resource creation calls) by applying a fixed target of one request per second and a rate of 1.0, or 100 percent of requests after the fixed target is satisfied. The other three custom rules apply a five percent rate with no fixed target to session, game, and state reads (GET requests). This minimizes the number of traces for periodic calls that the front end makes automatically every few seconds to ensure the content is up to date. For all other requests, the file defines a default rate of one request per second and a rate of 10 percent. The sample application also shows how to use advanced features such as manual SDK client instrumentation, creating additional subsegments, and outgoing HTTP calls. For more information, see AWS X-Ray sample application. Optional: Least privilege policy The Scorekeep ECS containers access resources using full access policies, such as AmazonSNSFullAccess and AmazonDynamoDBFullAccess. Using full access policies is not the best practice for production applications. The following example updates the DynamoDB IAM policy to improve the security of the application. To learn more about security best practices in IAM policies, see Identity and access management for AWS X-Ray. Example cf-resources.yaml template ECSTaskRole definition ECSTaskRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Principal: Service: - "ecs-tasks.amazonaws.com" Action: Optional: Least privilege policy 213 AWS X-Ray Developer Guide - "sts:AssumeRole" ManagedPolicyArns: - "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess" - "arn:aws:iam::aws:policy/AmazonSNSFullAccess" - "arn:aws:iam::aws:policy/AWSXrayFullAccess" RoleName: "scorekeepRole" To update your policy, first you identify the ARN of your DynamoDB resources. Then you use the ARN in a custom IAM policy. Finally, you apply that policy to your instance profile. To identify the ARN of your DynamoDB resource: 1. Open the DynamoDB console. 2. Choose Tables from the left navigation bar. 3. Choose any of the scorekeep-* to display the table detail page. 4. Under the Overview tab, choose Additional info to expand the section and view the Amazon Resource Name (ARN). Copy this value. 5. Insert the ARN into the following IAM policy, replacing the AWS_REGION and AWS_ACCOUNT_ID values with your specific region and account ID. This new policy allows only the actions specified, instead of the AmazonDynamoDBFullAccess policy which allows any action. Example { "Version": "2012-10-17", "Statement": [ { "Sid": "ScorekeepDynamoDB", "Effect": "Allow", "Action": [ "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:Scan", "dynamodb:Query" ], "Resource": "arn:aws:dynamodb:<AWS_REGION>:<AWS_ACCOUNT_ID>:table/ scorekeep-*" Optional: Least privilege policy 214 AWS X-Ray } ] } Developer Guide The tables that the application creates follow a consistent naming convention. You can use the scorekeep-* format to indicate all Scorekeep tables. Change your IAM policy 1. Open the Scorekeep task role (scorekeepRole) from the IAM console. 2. Choose the check box next to the AmazonDynamoDBFullAccess policy and choose Remove to remove this policy. 3. Choose Add permissions, and then Attach policies, and finally Create policy. 4. Choose the JSON tab and paste in the policy created above. 5. Choose Next: Tags at the bottom of the page. 6. Choose Next: Review at the bottom of the page. 7. For Name, assign a name for the policy. 8. Choose Create policy at the bottom of the page. 9. Attach the newly created policy to the scorekeepRole role. It may take a few minutes for the attached policy to take effect. If you have attached the new policy to the scorekeepRole role, you must detach it before deleting the CloudFormation stack, since this attached policy will block the stack from being deleted. The policy can be automatically detached by deleting the policy. Remove your custom IAM policy 1. Open the IAM console. 2. Choose Policies from the left navigation bar. 3. Search for the custom policy name you created earlier in this section, and choose the radio button next to the policy name to highlight it. 4. Choose the Actions drop-down and then choose Delete. 5. Type the name of the custom policy and then choose Delete to confirm deletion . This will automatically detach the policy from the scorekeepRole role. Optional: Least privilege policy 215 AWS X-Ray Clean up Developer |
xray-guide-064 | xray-guide.pdf | 64 | deleted. The policy can be automatically detached by deleting the policy. Remove your custom IAM policy 1. Open the IAM console. 2. Choose Policies from the left navigation bar. 3. Search for the custom policy name you created earlier in this section, and choose the radio button next to the policy name to highlight it. 4. Choose the Actions drop-down and then choose Delete. 5. Type the name of the custom policy and then choose Delete to confirm deletion . This will automatically detach the policy from the scorekeepRole role. Optional: Least privilege policy 215 AWS X-Ray Clean up Developer Guide Follow these steps to delete the Scorekeep application resources: Note If you created and attached custom policies using the prior section of this tutorial, you must remove the policy from the scorekeepRole before deleting the CloudFormation stack. AWS Management Console Delete the sample application using the AWS Management Console 1. Open the CloudFormation console 2. Choose the radio button next to the scorekeep stack name in the list, and then choose Delete. 3. The CloudFormation stack is now being deleted. The stack status will be DELETE_IN_PROGRESS for a few minutes until all resources are deleted. The status will refresh periodically, or you can refresh the page. AWS CLI Delete the sample application using the AWS CLI 1. Enter the following AWS CLI command to delete the CloudFormation stack: aws cloudformation delete-stack --stack-name scorekeep 2. Wait until the CloudFormation stack no longer exists, which will take about five minutes. Use the following AWS CLI command to check on the status: aws cloudformation describe-stacks --stack-name scorekeep --query "Stacks[0].StackStatus" Clean up 216 AWS X-Ray Next steps Developer Guide Learn more about X-Ray in the next chapter, AWS X-Ray concepts. To instrument your own app, learn more about the X-Ray SDK for Java or one of the other X-Ray SDKs: • X-Ray SDK for Java – AWS X-Ray SDK for Java • X-Ray SDK for Node.js – AWS X-Ray SDK for Node.js • X-Ray SDK for .NET – AWS X-Ray SDK for .NET To run the X-Ray daemon locally or on AWS, see AWS X-Ray daemon. To contribute to the sample application on GitHub, see eb-java-scorekeep. Manually instrumenting AWS SDK clients The X-Ray SDK for Java automatically instruments all AWS SDK clients when you include the AWS SDK Instrumentor submodule in your build dependencies. You can disable automatic client instrumentation by removing the Instrumentor submodule. This enables you to instrument some clients manually while ignoring others, or use different tracing handlers on different clients. To illustrate support for instrumenting specific AWS SDK clients, the application passes a tracing handler to AmazonDynamoDBClientBuilder as a request handler in the user, game, and session model. This code change tells the SDK to instrument all calls to DynamoDB using those clients. Example src/main/java/scorekeep/SessionModel.java – Manual AWS SDK client instrumentation import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.handlers.TracingHandler; public class SessionModel { private AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() .withRegion(Constants.REGION) .withRequestHandlers(new TracingHandler(AWSXRay.getGlobalRecorder())) .build(); private DynamoDBMapper mapper = new DynamoDBMapper(client); Next steps 217 AWS X-Ray Developer Guide If you remove the AWS SDK Instrumentor submodule from project dependencies, only the manually instrumented AWS SDK clients appear in the trace map. Creating additional subsegments In the user model class, the application manually creates subsegments to group all downstream calls made within the saveUser function and adds metadata. Example src/main/java/scorekeep/UserModel.java - Custom subsegments import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Subsegment; ... public void saveUser(User user) { // Wrap in subsegment Subsegment subsegment = AWSXRay.beginSubsegment("## UserModel.saveUser"); try { mapper.save(user); } catch (Exception e) { subsegment.addException(e); throw e; } finally { AWSXRay.endSubsegment(); } } Recording annotations, metadata, and user IDs In the game model class, the application records Game objects in a metadata block each time it saves a game in DynamoDB. Separately, the application records game IDs in annotations for use with filter expressions. Example src/main/java/scorekeep/GameModel.java – Annotations and metadata import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; ... public void saveGame(Game game) throws SessionNotFoundException { // wrap in subsegment Subsegment subsegment = AWSXRay.beginSubsegment("## GameModel.saveGame"); Custom subsegments 218 Developer Guide AWS X-Ray try { // check session String sessionId = game.getSession(); if (sessionModel.loadSession(sessionId) == null ) { throw new SessionNotFoundException(sessionId); } Segment segment = AWSXRay.getCurrentSegment(); subsegment.putMetadata("resources", "game", game); segment.putAnnotation("gameid", game.getId()); mapper.save(game); } catch (Exception e) { subsegment.addException(e); throw e; } finally { AWSXRay.endSubsegment(); } } In the move controller, the application records user IDs with setUser. User IDs are recorded in a separate field on segments and are indexed for use with search. Example src/main/java/scorekeep/MoveController.java – User ID import com.amazonaws.xray.AWSXRay; ... @RequestMapping(value="/{userId}", method=RequestMethod.POST) public Move newMove(@PathVariable String sessionId, @PathVariable String gameId, @PathVariable String userId, @RequestBody String move) throws SessionNotFoundException, GameNotFoundException, StateNotFoundException, RulesException { AWSXRay.getCurrentSegment().setUser(userId); return moveFactory.newMove(sessionId, gameId, userId, move); } Instrumenting outgoing HTTP calls The user factory class shows how the application uses the X-Ray SDK for Java's version of HTTPClientBuilder to instrument |
xray-guide-065 | xray-guide.pdf | 65 | (Exception e) { subsegment.addException(e); throw e; } finally { AWSXRay.endSubsegment(); } } In the move controller, the application records user IDs with setUser. User IDs are recorded in a separate field on segments and are indexed for use with search. Example src/main/java/scorekeep/MoveController.java – User ID import com.amazonaws.xray.AWSXRay; ... @RequestMapping(value="/{userId}", method=RequestMethod.POST) public Move newMove(@PathVariable String sessionId, @PathVariable String gameId, @PathVariable String userId, @RequestBody String move) throws SessionNotFoundException, GameNotFoundException, StateNotFoundException, RulesException { AWSXRay.getCurrentSegment().setUser(userId); return moveFactory.newMove(sessionId, gameId, userId, move); } Instrumenting outgoing HTTP calls The user factory class shows how the application uses the X-Ray SDK for Java's version of HTTPClientBuilder to instrument outgoing HTTP calls. Example src/main/java/scorekeep/UserFactory.java – HTTPClient instrumentation import com.amazonaws.xray.proxies.apache.http.HttpClientBuilder; HTTP clients 219 AWS X-Ray Developer Guide public String randomName() throws IOException { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet("http://uinames.com/api/"); CloseableHttpResponse response = httpclient.execute(httpGet); try { HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ObjectMapper mapper = new ObjectMapper(); Map<String, String> jsonMap = mapper.readValue(inputStream, Map.class); String name = jsonMap.get("name"); EntityUtils.consume(entity); return name; } finally { response.close(); } } If you currently use org.apache.http.impl.client.HttpClientBuilder, you can simply swap out the import statement for that class with one for com.amazonaws.xray.proxies.apache.http.HttpClientBuilder. Instrumenting calls to a PostgreSQL database The application-pgsql.properties file adds the X-Ray PostgreSQL tracing interceptor to the data source created in RdsWebConfig.java. Example application-pgsql.properties – PostgreSQL database instrumentation spring.datasource.continue-on-error=true spring.jpa.show-sql=false spring.jpa.hibernate.ddl-auto=create-drop spring.datasource.jdbc-interceptors=com.amazonaws.xray.sql.postgres.TracingInterceptor spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL94Dialect Note See Configuring Databases with Elastic Beanstalk in the AWS Elastic Beanstalk Developer Guide for details on how to add a PostgreSQL database to the application environment. SQL clients 220 AWS X-Ray Developer Guide The X-Ray demo page in the xray branch includes a demo that uses the instrumented data source to generate traces that show information about the SQL queries that it generates. Navigate to the /#/xray path in the running application or choose Powered by AWS X-Ray in the navigation bar to see the demo page. SQL clients 221 AWS X-Ray Developer Guide SQL clients 222 AWS X-Ray Developer Guide Choose Trace SQL queries to simulate game sessions and store the results in the attached database. Then, choose View traces in AWS X-Ray to see a filtered list of traces that hit the API's / api/history route. Choose one of the traces from the list to see the timeline, including the SQL query. Instrumenting AWS Lambda functions Scorekeep uses two AWS Lambda functions. The first is a Node.js function from the lambda branch that generates random names for new users. When a user creates a session without entering a name, the application calls a function named random-name with the AWS SDK for Java. The X- Ray SDK for Java records information about the call to Lambda in a subsegment like any other call made with an instrumented AWS SDK client. Note Running the random-name Lambda function requires the creation of additional resources outside of the Elastic Beanstalk environment. See the readme for more information and instructions: AWS Lambda Integration. The second function, scorekeep-worker, is a Python function that runs independently of the Scorekeep API. When a game ends, the API writes the session ID and game ID to an SQS queue. The worker function reads items from the queue, and calls the Scorekeep API to construct complete records of each game session for storage in Amazon S3. Scorekeep includes AWS CloudFormation templates and scripts to create both functions. Because you need to bundle the X-Ray SDK with the function code, the templates create the AWS Lambda functions 223 AWS X-Ray Developer Guide functions without any code. When you deploy Scorekeep, a configuration file included in the .ebextensions folder creates a source bundle that includes the SDK, and updates the function code and configuration with the AWS Command Line Interface. Functions • Random name • Worker Random name Scorekeep calls the random name function when a user starts a game session without signing in or specifying a user name. When Lambda processes the call to random-name, it reads the tracing header, which contains the trace ID and sampling decision written by the X-Ray SDK for Java. For each sampled request, Lambda runs the X-Ray daemon and writes two segments. The first segment records information about the call to Lambda that invokes the function. This segment contains the same information as the subsegment recorded by Scorekeep, but from the Lambda point of view. The second segment represents the work that the function does. Lambda passes the function segment to the X-Ray SDK through the function context. When you instrument a Lambda function, you don't use the SDK to create a segment for incoming requests. Lambda provides the segment, and you use the SDK to instrument clients and write subsegments. Random name 224 AWS X-Ray Developer Guide The random-name function is implemented in Node.js. It uses the SDK for JavaScript in Node.js to send notifications with Amazon SNS, |
xray-guide-066 | xray-guide.pdf | 66 | the same information as the subsegment recorded by Scorekeep, but from the Lambda point of view. The second segment represents the work that the function does. Lambda passes the function segment to the X-Ray SDK through the function context. When you instrument a Lambda function, you don't use the SDK to create a segment for incoming requests. Lambda provides the segment, and you use the SDK to instrument clients and write subsegments. Random name 224 AWS X-Ray Developer Guide The random-name function is implemented in Node.js. It uses the SDK for JavaScript in Node.js to send notifications with Amazon SNS, and the X-Ray SDK for Node.js to instrument the AWS SDK client. To write annotations, the function creates a custom subsegment with AWSXRay.captureFunc, and writes annotations in the instrumented function. In Lambda, you can't write annotations directly to the function segment, only to a subsegment that you create. Example function/index.js -- Random name Lambda function var AWSXRay = require('aws-xray-sdk-core'); var AWS = AWSXRay.captureAWS(require('aws-sdk')); AWS.config.update({region: process.env.AWS_REGION}); var Chance = require('chance'); var myFunction = function(event, context, callback) { var sns = new AWS.SNS(); var chance = new Chance(); var userid = event.userid; var name = chance.first(); AWSXRay.captureFunc('annotations', function(subsegment){ Random name 225 AWS X-Ray Developer Guide subsegment.addAnnotation('Name', name); subsegment.addAnnotation('UserID', event.userid); }); // Notify var params = { Message: 'Created randon name "' + name + '"" for user "' + userid + '".', Subject: 'New user: ' + name, TopicArn: process.env.TOPIC_ARN }; sns.publish(params, function(err, data) { if (err) { console.log(err, err.stack); callback(err); } else { console.log(data); callback(null, {"name": name}); } }); }; exports.handler = myFunction; This function is created automatically when you deploy the sample application to Elastic Beanstalk. The xray branch includes a script to create a blank Lambda function. Configuration files in the .ebextensions folder build the function package with npm install during deployment, and then update the Lambda function with the AWS CLI. Worker The instrumented worker function is provided in its own branch, xray-worker, as it cannot run unless you create the worker function and related resources first. See the branch readme for instructions. The function is triggered by a bundled Amazon CloudWatch Events event every 5 minutes. When it runs, the function pulls an item from an Amazon SQS queue that Scorekeep manages. Each message contains information about a completed game. The worker pulls the game record and documents from other tables that the game record references. For example, the game record in DynamoDB includes a list of moves that were executed Worker 226 AWS X-Ray Developer Guide during the game. The list does not contain the moves themselves, but rather IDs of moves that are stored in a separate table. Sessions, and states are stored as references as well. This keeps the entries in the game table from being too large, but requires additional calls to get all of the information about the game. The worker dereferences all of these entries and constructs a complete record of the game as a single document in Amazon S3. When you want to do analytics on the data, you can run queries on it directly in Amazon S3 with Amazon Athena without running read-heavy data migrations to get your data out of DynamoDB. The worker function has active tracing enabled in its configuration in AWS Lambda. Unlike the random name function, the worker does not receive a request from an instrumented application, so AWS Lambda doesn't receive a tracing header. With active tracing, Lambda creates the trace ID and makes sampling decisions. The X-Ray SDK for Python is just a few lines at the top of the function that import the SDK and run its patch_all function to patch the AWS SDK for Python (Boto) and HTTclients that it uses to call Amazon SQS and Amazon S3. When the worker calls the Scorekeep API, the SDK adds the tracing header to the request to trace calls through the API. Worker 227 AWS X-Ray Developer Guide Example _lambda/scorekeep-worker/scorekeep-worker.py -- Worker Lambda function import os import boto3 import json import requests import time from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core import patch_all patch_all() queue_url = os.environ['WORKER_QUEUE'] def lambda_handler(event, context): # Create SQS client sqs = boto3.client('sqs') s3client = boto3.client('s3') # Receive message from SQS queue response = sqs.receive_message( QueueUrl=queue_url, AttributeNames=[ 'SentTimestamp' ], MaxNumberOfMessages=1, MessageAttributeNames=[ 'All' ], VisibilityTimeout=0, WaitTimeSeconds=0 ) ... Instrumenting startup code The X-Ray SDK for Java automatically creates segments for incoming requests. As long as a request is in scope, you can use instrumented clients and record subsegments without issue. If you try to use an instrumented client in startup code, though, you'll get a SegmentNotFoundException. Startup code runs outside of the standard request/response flow of a web application, so you need to create segments manually to instrument it. Scorekeep shows the instrumentation of startup code in its WebConfig files. Scorekeep |
xray-guide-067 | xray-guide.pdf | 67 | SQS queue response = sqs.receive_message( QueueUrl=queue_url, AttributeNames=[ 'SentTimestamp' ], MaxNumberOfMessages=1, MessageAttributeNames=[ 'All' ], VisibilityTimeout=0, WaitTimeSeconds=0 ) ... Instrumenting startup code The X-Ray SDK for Java automatically creates segments for incoming requests. As long as a request is in scope, you can use instrumented clients and record subsegments without issue. If you try to use an instrumented client in startup code, though, you'll get a SegmentNotFoundException. Startup code runs outside of the standard request/response flow of a web application, so you need to create segments manually to instrument it. Scorekeep shows the instrumentation of startup code in its WebConfig files. Scorekeep calls an SQL database and Amazon SNS during startup. Instrumenting startup code 228 AWS X-Ray Developer Guide The default WebConfig class creates an Amazon SNS subscription for notifications. To provide a segment for the X-Ray SDK to write to when the Amazon SNS client is used, Scorekeep calls beginSegment and endSegment on the global recorder. Example src/main/java/scorekeep/WebConfig.java – Instrumented AWS SDK client in startup code AWSXRay.beginSegment("Scorekeep-init"); if ( System.getenv("NOTIFICATION_EMAIL") != null ){ try { Sns.createSubscription(); } catch (Exception e ) { logger.warn("Failed to create subscription for email "+ System.getenv("NOTIFICATION_EMAIL")); } } AWSXRay.endSegment(); Instrumenting startup code 229 AWS X-Ray Developer Guide In RdsWebConfig, which Scorekeep uses when an Amazon RDS database is connected, the configuration also creates a segment for the SQL client that Hibernate uses when it applies the database schema during startup. Example src/main/java/scorekeep/RdsWebConfig.java – Instrumented SQL database client in startup code @PostConstruct public void schemaExport() { EntityManagerFactoryImpl entityManagerFactoryImpl = (EntityManagerFactoryImpl) localContainerEntityManagerFactoryBean.getNativeEntityManagerFactory(); SessionFactoryImplementor sessionFactoryImplementor = entityManagerFactoryImpl.getSessionFactory(); StandardServiceRegistry standardServiceRegistry = sessionFactoryImplementor.getSessionFactoryOptions().getServiceRegistry(); MetadataSources metadataSources = new MetadataSources(new BootstrapServiceRegistryBuilder().build()); metadataSources.addAnnotatedClass(GameHistory.class); MetadataImplementor metadataImplementor = (MetadataImplementor) metadataSources.buildMetadata(standardServiceRegistry); SchemaExport schemaExport = new SchemaExport(standardServiceRegistry, metadataImplementor); AWSXRay.beginSegment("Scorekeep-init"); schemaExport.create(true, true); AWSXRay.endSegment(); } SchemaExport runs automatically and uses an SQL client. Since the client is instrumented, Scorekeep must override the default implementation and provide a segment for the SDK to use when the client is invoked. Instrumenting scripts You can also instrument code that isn't part of your application. When the X-Ray daemon is running, it will relay any segments that it receives to X-Ray, even if they are not generated by the X-Ray SDK. Scorekeep uses its own scripts to instrument the build that compiles the application during deployment. Instrumenting scripts 230 AWS X-Ray Developer Guide Example bin/build.sh – Instrumented build script SEGMENT=$(python bin/xray_start.py) gradle build --quiet --stacktrace &> /var/log/gradle.log; GRADLE_RETURN=$? if (( GRADLE_RETURN != 0 )); then echo "Gradle failed with exit status $GRADLE_RETURN" >&2 python bin/xray_error.py "$SEGMENT" "$(cat /var/log/gradle.log)" exit 1 fi python bin/xray_success.py "$SEGMENT" xray_start.py, xray_error.py and xray_success.py are simple Python scripts that construct segment objects, convert them to JSON documents, and send them to the daemon over UDP. If the Gradle build fails, you can find the error message by clicking on the scorekeep-build node in the X-Ray console trace map. Instrumenting scripts 231 AWS X-Ray Developer Guide Instrumenting a web app client In the xray-cognito branch, Scorekeep uses Amazon Cognito to enable users to create an account and sign in with it to retrieve their user information from an Amazon Cognito user pool. When a user signs in, Scorekeep uses an Amazon Cognito identity pool to get temporary AWS credentials for use with the AWS SDK for JavaScript. The identity pool is configured to let signed-in users write trace data to AWS X-Ray. The web app uses these credentials to record the signed-in user's ID, the browser path, and the client's view of calls to the Scorekeep API. Most of the work is done in a service class named xray. This service class provides methods for generating the required identifiers, creating in-progress segments, finalizing segments, and sending segment documents to the X-Ray API. Example public/xray.js – Record and upload segments ... service.beginSegment = function() { var segment = {}; var traceId = '1-' + service.getHexTime() + '-' + service.getHexId(24); Instrumenting web clients 232 AWS X-Ray Developer Guide var id = service.getHexId(16); var startTime = service.getEpochTime(); segment.trace_id = traceId; segment.id = id; segment.start_time = startTime; segment.name = 'Scorekeep-client'; segment.in_progress = true; segment.user = sessionStorage['userid']; segment.http = { request: { url: window.location.href } }; var documents = []; documents[0] = JSON.stringify(segment); service.putDocuments(documents); return segment; } service.endSegment = function(segment) { var endTime = service.getEpochTime(); segment.end_time = endTime; segment.in_progress = false; var documents = []; documents[0] = JSON.stringify(segment); service.putDocuments(documents); } service.putDocuments = function(documents) { var xray = new AWS.XRay(); var params = { TraceSegmentDocuments: documents }; xray.putTraceSegments(params, function(err, data) { if (err) { console.log(err, err.stack); } else { console.log(data); } }) Instrumenting web clients 233 AWS X-Ray } Developer Guide These methods are called in header and transformResponse functions in the resource services that the web app uses to call the Scorekeep API. To include the client segment in the same trace as the segment that the API generates, the web app must include the trace ID |
xray-guide-068 | xray-guide.pdf | 68 | endTime; segment.in_progress = false; var documents = []; documents[0] = JSON.stringify(segment); service.putDocuments(documents); } service.putDocuments = function(documents) { var xray = new AWS.XRay(); var params = { TraceSegmentDocuments: documents }; xray.putTraceSegments(params, function(err, data) { if (err) { console.log(err, err.stack); } else { console.log(data); } }) Instrumenting web clients 233 AWS X-Ray } Developer Guide These methods are called in header and transformResponse functions in the resource services that the web app uses to call the Scorekeep API. To include the client segment in the same trace as the segment that the API generates, the web app must include the trace ID and segment ID in a tracing header (X-Amzn-Trace-Id) that the X-Ray SDK can read. When the instrumented Java application receives a request with this header, the X-Ray SDK for Java uses the same trace ID and makes the segment from the web app client the parent of its segment. Example public/app/services.js – Recording segments for angular resource calls and writing tracing headers var module = angular.module('scorekeep'); module.factory('SessionService', function($resource, api, XRay) { return $resource(api + 'session/:id', { id: '@_id' }, { segment: {}, get: { method: 'GET', headers: { 'X-Amzn-Trace-Id': function(config) { segment = XRay.beginSegment(); return XRay.getTraceHeader(segment); } }, transformResponse: function(data) { XRay.endSegment(segment); return angular.fromJson(data); }, }, ... The resulting trace map includes a node for the web app client. Instrumenting web clients 234 AWS X-Ray Developer Guide Traces that include segments from the web app show the URL that the user sees in the browser (paths starting with /#/). Without client instrumentation, you only get the URL of the API resource that the web app calls (paths starting with /api/). Instrumenting web clients 235 AWS X-Ray Developer Guide Using instrumented clients in worker threads Scorekeep uses a worker thread to publish a notification to Amazon SNS when a user wins a game. Publishing the notification takes longer than the rest of the request operations combined, and doesn't affect the client or user. Therefore, performing the task asynchronously is a good way to improve response time. However, the X-Ray SDK for Java doesn't know which segment was active when the thread is created. As a result, when you try to use the instrumented AWS SDK for Java client within the thread, it throws a SegmentNotFoundException, crashing the thread. Example Web-1.error.log Exception in thread "Thread-2" com.amazonaws.xray.exceptions.SegmentNotFoundException: Failed to begin subsegment named 'AmazonSNS': segment cannot be found. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ... To fix this, the application uses GetTraceEntity to get a reference to the segment in the main thread, and Entity.run() to safely run the worker thread code with access to the segment's context. Example src/main/java/scorekeep/MoveFactory.java – Passing trace context to a worker thread import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.entities.Entity; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; ... Entity segment = recorder.getTraceEntity(); Thread comm = new Thread() { public void run() { segment.run(() -> { Subsegment subsegment = AWSXRay.beginSubsegment("## Send notification"); Sns.sendNotification("Scorekeep game completed", "Winner: " + userId); Worker threads 236 AWS X-Ray Developer Guide AWSXRay.endSubsegment(); } } Because the request is now resolved before the call to Amazon SNS, the application creates a separate subsegment for the thread. This prevents the X-Ray SDK from closing the segment before it records the response from Amazon SNS. If no subsegment is open when Scorekeep resolved the request, the response from Amazon SNS could be lost. See Passing segment context between threads in a multithreaded application for more information about multithreading. Worker threads 237 AWS X-Ray Developer Guide AWS X-Ray daemon Note You can now use the CloudWatch agent to collect metrics, logs and traces from Amazon EC2 instances and on-premise servers. CloudWatch agent version 1.300025.0 and later can collect traces from OpenTelemetry or X-Ray client SDKs, and send them to X-Ray. Using the CloudWatch agent instead of the AWS Distro for OpenTelemetry (ADOT) Collector or X-Ray daemon to collect traces can help you reduce the number of agents that you manage. See the CloudWatch agent topic in the CloudWatch User Guide for more information. The AWS X-Ray daemon is a software application that listens for traffic on UDP port 2000, gathers raw segment data, and relays it to the AWS X-Ray API. The daemon works in conjunction with the AWS X-Ray SDKs and must be running so that data sent by the SDKs can reach the X-Ray service. The X-Ray daemon is an open source project. You can follow the project and submit issues and pull requests on GitHub: github.com/aws/aws-xray-daemon On AWS Lambda and AWS Elastic Beanstalk, use those services' integration with X-Ray to run the daemon. Lambda runs the daemon automatically any time a function is invoked for a sampled request. On Elastic Beanstalk, use the XRayEnabled configuration option to run the daemon on the instances in your environment. For more information, see To run the X-Ray daemon locally, on-premises, or on |
xray-guide-069 | xray-guide.pdf | 69 | must be running so that data sent by the SDKs can reach the X-Ray service. The X-Ray daemon is an open source project. You can follow the project and submit issues and pull requests on GitHub: github.com/aws/aws-xray-daemon On AWS Lambda and AWS Elastic Beanstalk, use those services' integration with X-Ray to run the daemon. Lambda runs the daemon automatically any time a function is invoked for a sampled request. On Elastic Beanstalk, use the XRayEnabled configuration option to run the daemon on the instances in your environment. For more information, see To run the X-Ray daemon locally, on-premises, or on other AWS services, download it, run it, and then give it permission to upload segment documents to X-Ray. Downloading the daemon You can download the daemon from Amazon S3, Amazon ECR, or Docker Hub, and then run it locally, or install it on an Amazon EC2 instance on launch. Amazon S3 X-Ray daemon installers and executables • Linux (executable) – aws-xray-daemon-linux-3.x.zip (sig) • Linux (RPM installer) – aws-xray-daemon-3.x.rpm Downloading the daemon 238 AWS X-Ray Developer Guide • Linux (DEB installer) – aws-xray-daemon-3.x.deb • Linux (ARM64, executable) – aws-xray-daemon-linux-arm64-3.x.zip (sig) • Linux (ARM64, RPM installer) – aws-xray-daemon-arm64-3.x.rpm • Linux (ARM64, DEB installer) – aws-xray-daemon-arm64-3.x.deb • OS X (executable) – aws-xray-daemon-macos-3.x.zip (sig) • Windows (executable) – aws-xray-daemon-windows-process-3.x.zip (sig) • Windows (service) – aws-xray-daemon-windows-service-3.x.zip (sig) These links always point to the latest 3.x release of the daemon. To download a specific release, do the following: • If you want to download a release prior to version 3.3.0, replace 3.x with the version number. For example, 2.1.0. Prior to version 3.3.0, the only available architecture is arm64. For example, 2.1.0 and arm64. • If you want to download a release after version 3.3.0, replace 3.x with the version number and arch with the architecture type. X-Ray assets are replicated to buckets in every supported region. To use the bucket closest to you or your AWS resources, replace the region in the above links with your region. https://s3.us-west-2.amazonaws.com/aws-xray-assets.us-west-2/xray-daemon/aws-xray- daemon-3.x.rpm Amazon ECR As of version 3.2.0 the daemon can be found on Amazon ECR. Before pulling an image you should authenticate your docker client to the Amazon ECR public registry. Pull the latest released 3.x version tag by running the following command: docker pull public.ecr.aws/xray/aws-xray-daemon:3.x Prior or alpha releases can be downloaded by replacing 3.x with alpha or a specific version number. It is not recommended to use a daemon image with an alpha tag in a production environment. Downloading the daemon 239 AWS X-Ray Docker Hub Developer Guide The daemon can be found on Docker Hub. To download the latest released 3.x version, run the following command: docker pull amazon/aws-xray-daemon:3.x Prior releases of the daemon can be released by replacing 3.x with the desired version. Verifying the daemon archive's signature GPG signature files are included for daemon assets compressed in ZIP archives. The public key is here: aws-xray.gpg. You can use the public key to verify that the daemon's ZIP archive is original and unmodified. First, import the public key with GnuPG. To import the public key 1. Download the public key. $ BUCKETURL=https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2 $ wget $BUCKETURL/xray-daemon/aws-xray.gpg 2. Import the public key into your keyring. $ gpg --import aws-xray.gpg gpg: /Users/me/.gnupg/trustdb.gpg: trustdb created gpg: key 7BFE036BFE6157D3: public key "AWS X-Ray <aws-xray@amazon.com>" imported gpg: Total number processed: 1 gpg: imported: 1 Use the imported key to verify the signature of the daemon's ZIP archive. To verify an archive's signature 1. Download the archive and signature file. $ BUCKETURL=https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2 Verifying the daemon archive's signature 240 AWS X-Ray Developer Guide $ wget $BUCKETURL/xray-daemon/aws-xray-daemon-linux-3.x.zip $ wget $BUCKETURL/xray-daemon/aws-xray-daemon-linux-3.x.zip.sig 2. Run gpg --verify to verify the signature. $ gpg --verify aws-xray-daemon-linux-3.x.zip.sig aws-xray-daemon-linux-3.x.zip gpg: Signature made Wed 19 Apr 2017 05:06:31 AM UTC using RSA key ID FE6157D3 gpg: Good signature from "AWS X-Ray <aws-xray@amazon.com>" gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: EA6D 9271 FBF3 6990 277F 4B87 7BFE 036B FE61 57D3 Note the warning about trust. A key is only trusted if you or someone you trust has signed it. This does not mean that the signature is invalid, only that you have not verified the public key. Running the daemon Run the daemon locally from the command line. Use the -o option to run in local mode, and -n to set the region. ~/Downloads$ ./xray -o -n us-east-2 For detailed platform-specific instructions, see the following topics: • Linux (local) – Running the X-Ray daemon on Linux • Windows (local) – Running the X-Ray daemon on Windows • Elastic Beanstalk – Running the X-Ray daemon on AWS Elastic Beanstalk • Amazon EC2 – Running the X-Ray daemon on Amazon EC2 • Amazon ECS – Running the X-Ray daemon on Amazon ECS You |
xray-guide-070 | xray-guide.pdf | 70 | have not verified the public key. Running the daemon Run the daemon locally from the command line. Use the -o option to run in local mode, and -n to set the region. ~/Downloads$ ./xray -o -n us-east-2 For detailed platform-specific instructions, see the following topics: • Linux (local) – Running the X-Ray daemon on Linux • Windows (local) – Running the X-Ray daemon on Windows • Elastic Beanstalk – Running the X-Ray daemon on AWS Elastic Beanstalk • Amazon EC2 – Running the X-Ray daemon on Amazon EC2 • Amazon ECS – Running the X-Ray daemon on Amazon ECS You can customize the daemon's behavior further by using command line options or a configuration file. See Configuring the AWS X-Ray daemon for details. Giving the daemon permission to send data to X-Ray The X-Ray daemon uses the AWS SDK to upload trace data to X-Ray, and it needs AWS credentials with permission to do that. Running the daemon 241 AWS X-Ray Developer Guide On Amazon EC2, the daemon uses the instance's instance profile role automatically. For information about credentials required to run the daemon locally, see running your application locally. If you specify credentials in more than one location (credentials file, instance profile, or environment variables), the SDK provider chain determines which credentials are used. For more information about providing credentials to the SDK, see Specifying Credentials in the AWS SDK for Go Developer Guide. The IAM role or user that the daemon's credentials belong to must have permission to write data to the service on your behalf. • To use the daemon on Amazon EC2, create a new instance profile role or add the managed policy to an existing one. • To use the daemon on Elastic Beanstalk, add the managed policy to the Elastic Beanstalk default instance profile role. • To run the daemon locally, see running your application locally. For more information, see Identity and access management for AWS X-Ray. X-Ray daemon logs The daemon outputs information about its current configuration and segments that it sends to AWS X-Ray. 2016-11-24T06:07:06Z [Info] Initializing AWS X-Ray daemon 2.1.0 2016-11-24T06:07:06Z [Info] Using memory limit of 49 MB 2016-11-24T06:07:06Z [Info] 313 segment buffers allocated 2016-11-24T06:07:08Z [Info] Successfully sent batch of 1 segments (0.123 seconds) 2016-11-24T06:07:09Z [Info] Successfully sent batch of 1 segments (0.006 seconds) By default, the daemon outputs logs to STDOUT. If you run the daemon in the background, use the --log-file command line option or a configuration file to set the log file path. You can also set the log level and disable log rotation. See Configuring the AWS X-Ray daemon for instructions. On Elastic Beanstalk, the platform sets the location of the daemon logs. See Running the X-Ray daemon on AWS Elastic Beanstalk for details. X-Ray daemon logs 242 AWS X-Ray Developer Guide Configuring the AWS X-Ray daemon You can use command line options or a configuration file to customize the X-Ray daemon's behavior. Most options are available using both methods, but some are only available in configuration files and some only at the command line. To get started, the only option that you need to know is -n or --region, which you use to set the region that the daemon uses to send trace data to X-Ray. ~/xray-daemon$ ./xray -n us-east-2 If you are running the daemon locally, that is, not on Amazon EC2, you can add the -o option to skip checking for instance profile credentials so the daemon will become ready more quickly. ~/xray-daemon$ ./xray -o -n us-east-2 The rest of the command line options let you configure logging, listen on a different port, limit the amount of memory that the daemon can use, or assume a role to send trace data to a different account. You can pass a configuration file to the daemon to access advanced configuration options and do things like limit the number of concurrent calls to X-Ray, disable log rotation, and send traffic to a proxy. Sections • Supported environment variables • Using command line options • Using a configuration file Supported environment variables The X-Ray daemon supports the following environment variables: • AWS_REGION – Specifies the AWS Region of the X-Ray service endpoint. • HTTPS_PROXY – Specifies a proxy address for the daemon to upload segments through. This can be either the DNS domain names or IP addresses and port numbers used by your proxy servers. Configuration 243 AWS X-Ray Developer Guide Using command line options Pass these options to the daemon when you run it locally or with a user data script. Command Line Options • -b, --bind – Listen for segment documents on a different UDP port. --bind "127.0.0.1:3000" Default – 2000. • -t, --bind-tcp – Listen for calls to the X-Ray service on a different TCP port. -bind-tcp "127.0.0.1:3000" Default – 2000. • -c, --config – |
xray-guide-071 | xray-guide.pdf | 71 | address for the daemon to upload segments through. This can be either the DNS domain names or IP addresses and port numbers used by your proxy servers. Configuration 243 AWS X-Ray Developer Guide Using command line options Pass these options to the daemon when you run it locally or with a user data script. Command Line Options • -b, --bind – Listen for segment documents on a different UDP port. --bind "127.0.0.1:3000" Default – 2000. • -t, --bind-tcp – Listen for calls to the X-Ray service on a different TCP port. -bind-tcp "127.0.0.1:3000" Default – 2000. • -c, --config – Load a configuration file from the specified path. --config "/home/ec2-user/xray-daemon.yaml" • -f, --log-file – Output logs to the specified file path. --log-file "/var/log/xray-daemon.log" • -l, --log-level – Log level, from most verbose to least: dev, debug, info, warn, error, prod. --log-level warn Default – prod • -m, --buffer-memory – Change the amount of memory in MB that buffers can use (minimum 3). --buffer-memory 50 Default – 1% of available memory. • -o, --local-mode – Don't check for EC2 instance metadata. • -r, --role-arn – Assume the specified IAM role to upload segments to a different account. Using command line options 244 AWS X-Ray Developer Guide --role-arn "arn:aws:iam::123456789012:role/xray-cross-account" • -a, --resource-arn – Amazon Resource Name (ARN) of the AWS resource running the daemon. • -p, --proxy-address – Upload segments to AWS X-Ray through a proxy. The proxy server's protocol must be specified. --proxy-address "http://192.0.2.0:3000" • -n, --region – Send segments to X-Ray service in a specific region. • -v, --version – Show AWS X-Ray daemon version. • -h, --help – Show the help screen. Using a configuration file You can also use a YAML format file to configure the daemon. Pass the configuration file to the daemon by using the -c option. ~$ ./xray -c ~/xray-daemon.yaml Configuration file options • TotalBufferSizeMB – Maximum buffer size in MB (minimum 3). Choose 0 to use 1% of host memory. • Concurrency – Maximum number of concurrent calls to AWS X-Ray to upload segment documents. • Region – Send segments to AWS X-Ray service in a specific region. • Socket – Configure the daemon's binding. • UDPAddress – Change the port on which the daemon listens. • TCPAddress – Listen for calls to the X-Ray service on a different TCP port. • Logging – Configure logging behavior. • LogRotation – Set to false to disable log rotation. • LogLevel – Change the log level, from most verbose to least: dev, debug, info or prod, warn, error, prod. The default is prod, which is equivalent to info. Using a configuration file 245 AWS X-Ray Developer Guide • LogPath – Output logs to the specified file path. • LocalMode – Set to true to skip checking for EC2 instance metadata. • ResourceARN – Amazon Resource Name (ARN) of the AWS resource running the daemon. • RoleARN – Assume the specified IAM role to upload segments to a different account. • ProxyAddress – Upload segments to AWS X-Ray through a proxy. • Endpoint – Change the X-Ray service endpoint to which the daemon sends segment documents. • NoVerifySSL – Disable TLS certificate verification. • Version – Daemon configuration file format version. The file format version is a required field. Example Xray-daemon.yaml This configuration file changes the daemon's listening port to 3000, turns off checks for instance metadata, sets a role to use for uploading segments, and changes region and logging options. Socket: UDPAddress: "127.0.0.1:3000" TCPAddress: "127.0.0.1:3000" Region: "us-west-2" Logging: LogLevel: "warn" LogPath: "/var/log/xray-daemon.log" LocalMode: true RoleARN: "arn:aws:iam::123456789012:role/xray-cross-account" Version: 2 Running the X-Ray daemon locally You can run the AWS X-Ray daemon locally on Linux, MacOS, Windows, or in a Docker container. Run the daemon to relay trace data to X-Ray when you are developing and testing your instrumented application. Download and extract the daemon by using the instructions here. When running locally, the daemon can read credentials from an AWS SDK credentials file (.aws/ credentials in your user directory) or from environment variables. For more information, see Giving the daemon permission to send data to X-Ray. Run the daemon locally 246 AWS X-Ray Developer Guide The daemon listens for UDP data on port 2000. You can change the port and other options by using a configuration file and command line options. For more information, see Configuring the AWS X-Ray daemon. Running the X-Ray daemon on Linux You can run the daemon executable from the command line. Use the -o option to run in local mode, and -n to set the region. ~/xray-daemon$ ./xray -o -n us-east-2 To run the daemon in the background, use &. ~/xray-daemon$ ./xray -o -n us-east-2 & Terminate a daemon process running in the background with pkill. ~$ pkill xray Running the X-Ray daemon in a Docker container To run the daemon locally |
xray-guide-072 | xray-guide.pdf | 72 | the port and other options by using a configuration file and command line options. For more information, see Configuring the AWS X-Ray daemon. Running the X-Ray daemon on Linux You can run the daemon executable from the command line. Use the -o option to run in local mode, and -n to set the region. ~/xray-daemon$ ./xray -o -n us-east-2 To run the daemon in the background, use &. ~/xray-daemon$ ./xray -o -n us-east-2 & Terminate a daemon process running in the background with pkill. ~$ pkill xray Running the X-Ray daemon in a Docker container To run the daemon locally in a Docker container, save the following text to a file named Dockerfile. Download the complete example image on Amazon ECR. See downloading the daemon for more information. Example Dockerfile – Amazon Linux FROM amazonlinux RUN yum install -y unzip RUN curl -o daemon.zip https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/ xray-daemon/aws-xray-daemon-linux-3.x.zip RUN unzip daemon.zip && cp xray /usr/bin/xray ENTRYPOINT ["/usr/bin/xray", "-t", "0.0.0.0:2000", "-b", "0.0.0.0:2000"] EXPOSE 2000/udp EXPOSE 2000/tcp Build the container image with docker build. ~/xray-daemon$ docker build -t xray-daemon . Running the X-Ray daemon on Linux 247 AWS X-Ray Developer Guide Run the image in a container with docker run. ~/xray-daemon$ docker run \ --attach STDOUT \ -v ~/.aws/:/root/.aws/:ro \ --net=host \ -e AWS_REGION=us-east-2 \ --name xray-daemon \ -p 2000:2000/udp \ xray-daemon -o This command uses the following options: • --attach STDOUT – View output from the daemon in the terminal. • -v ~/.aws/:/root/.aws/:ro – Give the container read-only access to the .aws directory to let it read your AWS SDK credentials. • AWS_REGION=us-east-2 – Set the AWS_REGION environment variable to tell the daemon which region to use. • --net=host – Attach the container to the host network. Containers on the host network can communicate with each other without publishing ports. • -p 2000:2000/udp – Map UDP port 2000 on your machine to the same port on the container. This is not required for containers on the same network to communicate, but it does let you send segments to the daemon from the command line or from an application not running in Docker. • --name xray-daemon – Name the container xray-daemon instead of generating a random name. • -o (after the image name) – Append the -o option to the entry point that runs the daemon within the container. This option tells the daemon to run in local mode to prevent it from trying to read Amazon EC2 instance metadata. To stop the daemon, use docker stop. If you make changes to the Dockerfile and build a new image, you need to delete the existing container before you can create another one with the same name. Use docker rm to delete the container. $ docker stop xray-daemon $ docker rm xray-daemon Running the X-Ray daemon in a Docker container 248 AWS X-Ray Developer Guide Running the X-Ray daemon on Windows You can run the daemon executable from the command line. Use the -o option to run in local mode, and -n to set the region. > .\xray_windows.exe -o -n us-east-2 Use a PowerShell script to create and run a service for the daemon. Example PowerShell script - Windows if ( Get-Service "AWSXRayDaemon" -ErrorAction SilentlyContinue ){ sc.exe stop AWSXRayDaemon sc.exe delete AWSXRayDaemon } if ( Get-Item -path aws-xray-daemon -ErrorAction SilentlyContinue ) { Remove-Item -Recurse -Force aws-xray-daemon } $currentLocation = Get-Location $zipFileName = "aws-xray-daemon-windows-service-3.x.zip" $zipPath = "$currentLocation\$zipFileName" $destPath = "$currentLocation\aws-xray-daemon" $daemonPath = "$destPath\xray.exe" $daemonLogPath = "C:\inetpub\wwwroot\xray-daemon.log" $url = "https://s3.dualstack.us-west-2.amazonaws.com/aws-xray-assets.us-west-2/xray- daemon/aws-xray-daemon-windows-service-3.x.zip" Invoke-WebRequest -Uri $url -OutFile $zipPath Add-Type -Assembly "System.IO.Compression.Filesystem" [io.compression.zipfile]::ExtractToDirectory($zipPath, $destPath) sc.exe create AWSXRayDaemon binPath= "$daemonPath -f $daemonLogPath" sc.exe start AWSXRayDaemon Running the X-Ray daemon on OS X You can run the daemon executable from the command line. Use the -o option to run in local mode, and -n to set the region. ~/xray-daemon$ ./xray_mac -o -n us-east-2 Running the X-Ray daemon on Windows 249 AWS X-Ray Developer Guide To run the daemon in the background, use &. ~/xray-daemon$ ./xray_mac -o -n us-east-2 & Use nohup to prevent the daemon from terminating when the terminal is closed. ~/xray-daemon$ nohup ./xray_mac & Running the X-Ray daemon on AWS Elastic Beanstalk To relay trace data from your application to AWS X-Ray, you can run the X-Ray daemon on your Elastic Beanstalk environment's Amazon EC2 instances. For a list of supported platforms, see Configuring AWS X-Ray Debugging in the AWS Elastic Beanstalk Developer Guide. Note The daemon uses your environment's instance profile for permissions. For instructions about adding permissions to the Elastic Beanstalk instance profile, see Giving the daemon permission to send data to X-Ray. Elastic Beanstalk platforms provide a configuration option that you can set to run the daemon automatically. You can enable the daemon in a configuration file in your source code or by choosing an option in the Elastic Beanstalk console. When you enable the configuration option, |
xray-guide-073 | xray-guide.pdf | 73 | Elastic Beanstalk environment's Amazon EC2 instances. For a list of supported platforms, see Configuring AWS X-Ray Debugging in the AWS Elastic Beanstalk Developer Guide. Note The daemon uses your environment's instance profile for permissions. For instructions about adding permissions to the Elastic Beanstalk instance profile, see Giving the daemon permission to send data to X-Ray. Elastic Beanstalk platforms provide a configuration option that you can set to run the daemon automatically. You can enable the daemon in a configuration file in your source code or by choosing an option in the Elastic Beanstalk console. When you enable the configuration option, the daemon is installed on the instance and runs as a service. The version included on Elastic Beanstalk platforms might not be the latest version. See the Supported Platforms topic to find out the version of the daemon that is available for your platform configuration. Elastic Beanstalk does not provide the X-Ray daemon on the Multicontainer Docker (Amazon ECS) platform. Using the Elastic Beanstalk X-Ray integration to run the X-Ray daemon Use the console to turn on X-Ray integration, or configure it in your application source code with a configuration file. On Elastic Beanstalk 250 AWS X-Ray Developer Guide To enable the X-Ray daemon in the Elastic Beanstalk console 1. Open the Elastic Beanstalk console. 2. Navigate to the management console for your environment. 3. Choose Configuration. 4. Choose Software Settings. 5. For X-Ray daemon, choose Enabled. 6. Choose Apply. You can include a configuration file in your source code to make your configuration portable between environments. Example .ebextensions/xray-daemon.config option_settings: aws:elasticbeanstalk:xray: XRayEnabled: true Elastic Beanstalk passes a configuration file to the daemon and outputs logs to a standard location. On Windows Server Platforms • Configuration file – C:\Program Files\Amazon\XRay\cfg.yaml • Logs – c:\Program Files\Amazon\XRay\logs\xray-service.log On Linux Platforms • Configuration file – /etc/amazon/xray/cfg.yaml • Logs – /var/log/xray/xray.log Elastic Beanstalk provides tools for pulling instance logs from the AWS Management Console or command line. You can tell Elastic Beanstalk to include the X-Ray daemon logs by adding a task with a configuration file. Example .ebextensions/xray-logs.config - Linux files: Using the Elastic Beanstalk X-Ray integration to run the X-Ray daemon 251 AWS X-Ray Developer Guide "/opt/elasticbeanstalk/tasks/taillogs.d/xray-daemon.conf" : mode: "000644" owner: root group: root content: | /var/log/xray/xray.log Example .ebextensions/xray-logs.config - Windows server files: "c:/Program Files/Amazon/ElasticBeanstalk/config/taillogs.d/xray-daemon.conf" : mode: "000644" owner: root group: root content: | c:\Progam Files\Amazon\XRay\logs\xray-service.log See Viewing Logs from Your Elastic Beanstalk Environment's Amazon EC2 Instances in the AWS Elastic Beanstalk Developer Guide for more information. Downloading and running the X-Ray daemon manually (advanced) If the X-Ray daemon isn't available for your platform configuration, you can download it from Amazon S3 and run it with a configuration file. Use an Elastic Beanstalk configuration file to download and run the daemon. Example .ebextensions/xray.config - Linux commands: 01-stop-tracing: command: yum remove -y xray ignoreErrors: true 02-copy-tracing: command: curl https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray- daemon/aws-xray-daemon-3.x.rpm -o /home/ec2-user/xray.rpm 03-start-tracing: command: yum install -y /home/ec2-user/xray.rpm files: "/opt/elasticbeanstalk/tasks/taillogs.d/xray-daemon.conf" : mode: "000644" owner: root Downloading and running the X-Ray daemon manually (advanced) 252 AWS X-Ray Developer Guide group: root content: | /var/log/xray/xray.log "/etc/amazon/xray/cfg.yaml" : mode: "000644" owner: root group: root content: | Logging: LogLevel: "debug" Version: 2 Example .ebextensions/xray.config - Windows server container_commands: 01-execute-config-script: command: Powershell.exe -ExecutionPolicy Bypass -File c:\\temp\\installDaemon.ps1 waitAfterCompletion: 0 files: "c:/temp/installDaemon.ps1": content: | if ( Get-Service "AWSXRayDaemon" -ErrorAction SilentlyContinue ) { sc.exe stop AWSXRayDaemon sc.exe delete AWSXRayDaemon } $targetLocation = "C:\Program Files\Amazon\XRay" if ((Test-Path $targetLocation) -eq 0) { mkdir $targetLocation } $zipFileName = "aws-xray-daemon-windows-service-3.x.zip" $zipPath = "$targetLocation\$zipFileName" $destPath = "$targetLocation\aws-xray-daemon" if ((Test-Path $destPath) -eq 1) { Remove-Item -Recurse -Force $destPath } $daemonPath = "$destPath\xray.exe" $daemonLogPath = "$targetLocation\xray-daemon.log" $url = "https://s3.dualstack.us-west-2.amazonaws.com/aws-xray-assets.us-west-2/ xray-daemon/aws-xray-daemon-windows-service-3.x.zip" Downloading and running the X-Ray daemon manually (advanced) 253 AWS X-Ray Developer Guide Invoke-WebRequest -Uri $url -OutFile $zipPath Add-Type -Assembly "System.IO.Compression.Filesystem" [io.compression.zipfile]::ExtractToDirectory($zipPath, $destPath) New-Service -Name "AWSXRayDaemon" -StartupType Automatic -BinaryPathName "`"$daemonPath`" -f `"$daemonLogPath`"" sc.exe start AWSXRayDaemon encoding: plain "c:/Program Files/Amazon/ElasticBeanstalk/config/taillogs.d/xray-daemon.conf" : mode: "000644" owner: root group: root content: | C:\Program Files\Amazon\XRay\xray-daemon.log These examples also add the daemon's log file to the Elastic Beanstalk tail logs task, so that it's included when you request logs with the console or Elastic Beanstalk Command Line Interface (EB CLI). Running the X-Ray daemon on Amazon EC2 You can run the X-Ray daemon on the following operating systems on Amazon EC2: • Amazon Linux • Ubuntu • Windows Server (2012 R2 and newer) Use an instance profile to grant the daemon permission to upload trace data to X-Ray. For more information, see Giving the daemon permission to send data to X-Ray. Use a user data script to run the daemon automatically when you launch the instance. Example User data script - Linux #!/bin/bash curl https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray-daemon/aws-xray- daemon-3.x.rpm -o /home/ec2-user/xray.rpm yum install -y /home/ec2-user/xray.rpm On Amazon EC2 254 AWS X-Ray Developer Guide Example User data script - Windows server <powershell> if ( Get-Service "AWSXRayDaemon" -ErrorAction SilentlyContinue ) { |
xray-guide-074 | xray-guide.pdf | 74 | operating systems on Amazon EC2: • Amazon Linux • Ubuntu • Windows Server (2012 R2 and newer) Use an instance profile to grant the daemon permission to upload trace data to X-Ray. For more information, see Giving the daemon permission to send data to X-Ray. Use a user data script to run the daemon automatically when you launch the instance. Example User data script - Linux #!/bin/bash curl https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray-daemon/aws-xray- daemon-3.x.rpm -o /home/ec2-user/xray.rpm yum install -y /home/ec2-user/xray.rpm On Amazon EC2 254 AWS X-Ray Developer Guide Example User data script - Windows server <powershell> if ( Get-Service "AWSXRayDaemon" -ErrorAction SilentlyContinue ) { sc.exe stop AWSXRayDaemon sc.exe delete AWSXRayDaemon } $targetLocation = "C:\Program Files\Amazon\XRay" if ((Test-Path $targetLocation) -eq 0) { mkdir $targetLocation } $zipFileName = "aws-xray-daemon-windows-service-3.x.zip" $zipPath = "$targetLocation\$zipFileName" $destPath = "$targetLocation\aws-xray-daemon" if ((Test-Path $destPath) -eq 1) { Remove-Item -Recurse -Force $destPath } $daemonPath = "$destPath\xray.exe" $daemonLogPath = "$targetLocation\xray-daemon.log" $url = "https://s3.dualstack.us-west-2.amazonaws.com/aws-xray-assets.us-west-2/xray- daemon/aws-xray-daemon-windows-service-3.x.zip" Invoke-WebRequest -Uri $url -OutFile $zipPath Add-Type -Assembly "System.IO.Compression.Filesystem" [io.compression.zipfile]::ExtractToDirectory($zipPath, $destPath) New-Service -Name "AWSXRayDaemon" -StartupType Automatic -BinaryPathName "`"$daemonPath`" -f `"$daemonLogPath`"" sc.exe start AWSXRayDaemon </powershell> Running the X-Ray daemon on Amazon ECS In Amazon ECS, create a Docker image that runs the X-Ray daemon, upload it to a Docker image repository, and then deploy it to your Amazon ECS cluster. You can use port mappings and network mode settings in your task definition file to allow your application to communicate with the daemon container. On Amazon ECS 255 AWS X-Ray Developer Guide Using the official Docker image X-Ray provides a Docker container image on Amazon ECR that you can deploy alongside your application. See downloading the daemon for more information. Example Task definition { "name": "xray-daemon", "image": "amazon/aws-xray-daemon", "cpu": 32, "memoryReservation": 256, "portMappings" : [ { "hostPort": 0, "containerPort": 2000, "protocol": "udp" } ] } Create and build a Docker image For custom configuration, you may need to define your own Docker image. Add managed policies to your task role to grant the daemon permission to upload trace data to X- Ray. For more information, see Giving the daemon permission to send data to X-Ray. Use one of the following Dockerfiles to create an image that runs the daemon. Example Dockerfile – Amazon Linux FROM amazonlinux RUN yum install -y unzip RUN curl -o daemon.zip https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/ xray-daemon/aws-xray-daemon-linux-3.x.zip RUN unzip daemon.zip && cp xray /usr/bin/xray ENTRYPOINT ["/usr/bin/xray", "-t", "0.0.0.0:2000", "-b", "0.0.0.0:2000"] EXPOSE 2000/udp EXPOSE 2000/tcp Using the official Docker image 256 AWS X-Ray Note Developer Guide Flags -t and -b are required to specify a binding address to listen to the loopback of a multi-container environment. Example Dockerfile – Ubuntu For Debian derivatives, you also need to install certificate authority (CA) certificates to avoid issues when downloading the installer. FROM ubuntu:16.04 RUN apt-get update && apt-get install -y --force-yes --no-install-recommends apt- transport-https curl ca-certificates wget && apt-get clean && apt-get autoremove && rm -rf /var/lib/apt/lists/* RUN wget https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray-daemon/aws- xray-daemon-3.x.deb RUN dpkg -i aws-xray-daemon-3.x.deb ENTRYPOINT ["/usr/bin/xray", "--bind=0.0.0.0:2000", "--bind-tcp=0.0.0.0:2000"] EXPOSE 2000/udp EXPOSE 2000/tcp In your task definition, the configuration depends on the networking mode that you use. Bridge networking is the default and can be used in your default VPC. In a bridge network, set the AWS_XRAY_DAEMON_ADDRESS environment variable to tell the X-Ray SDK which container-port to reference and set the host port. For example, you could publish UDP port 2000, and create a link from your application container to the daemon container. Example Task definition { "name": "xray-daemon", "image": "123456789012.dkr.ecr.us-east-2.amazonaws.com/xray-daemon", "cpu": 32, "memoryReservation": 256, "portMappings" : [ { "hostPort": 0, "containerPort": 2000, "protocol": "udp" Create and build a Docker image 257 Developer Guide AWS X-Ray } ] }, { "name": "scorekeep-api", "image": "123456789012.dkr.ecr.us-east-2.amazonaws.com/scorekeep-api", "cpu": 192, "memoryReservation": 512, "environment": [ { "name" : "AWS_REGION", "value" : "us-east-2" }, { "name" : "NOTIFICATION_TOPIC", "value" : "arn:aws:sns:us- east-2:123456789012:scorekeep-notifications" }, { "name" : "AWS_XRAY_DAEMON_ADDRESS", "value" : "xray-daemon:2000" } ], "portMappings" : [ { "hostPort": 5000, "containerPort": 5000 } ], "links": [ "xray-daemon" ] } If you run your cluster in the private subnet of a VPC, you can use the awsvpc network mode to attach an elastic network interface (ENI) to your containers. This enables you to avoid using links. Omit the host port in the port mappings, the link, and the AWS_XRAY_DAEMON_ADDRESS environment variable. Example VPC task definition { "family": "scorekeep", "networkMode":"awsvpc", "containerDefinitions": [ { "name": "xray-daemon", "image": "123456789012.dkr.ecr.us-east-2.amazonaws.com/xray-daemon", "cpu": 32, "memoryReservation": 256, "portMappings" : [ { Create and build a Docker image 258 AWS X-Ray Developer Guide "containerPort": 2000, "protocol": "udp" } ] }, { "name": "scorekeep-api", "image": "123456789012.dkr.ecr.us-east-2.amazonaws.com/scorekeep-api", "cpu": 192, "memoryReservation": 512, "environment": [ { "name" : "AWS_REGION", "value" : "us-east-2" }, { "name" : "NOTIFICATION_TOPIC", "value" : "arn:aws:sns:us- east-2:123456789012:scorekeep-notifications" } ], "portMappings" : [ { "containerPort": 5000 } ] } ] } Configure command line options in the Amazon ECS console Command line options override any conflicting values in your image's config file. Command |
xray-guide-075 | xray-guide.pdf | 75 | definition { "family": "scorekeep", "networkMode":"awsvpc", "containerDefinitions": [ { "name": "xray-daemon", "image": "123456789012.dkr.ecr.us-east-2.amazonaws.com/xray-daemon", "cpu": 32, "memoryReservation": 256, "portMappings" : [ { Create and build a Docker image 258 AWS X-Ray Developer Guide "containerPort": 2000, "protocol": "udp" } ] }, { "name": "scorekeep-api", "image": "123456789012.dkr.ecr.us-east-2.amazonaws.com/scorekeep-api", "cpu": 192, "memoryReservation": 512, "environment": [ { "name" : "AWS_REGION", "value" : "us-east-2" }, { "name" : "NOTIFICATION_TOPIC", "value" : "arn:aws:sns:us- east-2:123456789012:scorekeep-notifications" } ], "portMappings" : [ { "containerPort": 5000 } ] } ] } Configure command line options in the Amazon ECS console Command line options override any conflicting values in your image's config file. Command line options are typically used for local testing, but can also be used for convenience while setting environment variables, or to control the startup process. By adding command line options, you are updating the Docker CMD that is passed to the container. For more information, see the Docker run reference. To set a command line option 1. Open the Amazon ECS classic console at https://console.aws.amazon.com/ecs/. 2. 3. From the navigation bar, choose the region that contains your task definition. In the navigation pane, choose Task Definitions. 4. On the Task Definitions page, select the box to the left of the task definition to revise and choose Create new revision. 5. On the Create new revision of Task Definition page, select the container. Configure command line options in the Amazon ECS console 259 AWS X-Ray Developer Guide 6. In the ENVIRONMENT section, add your comma-separated list of command line options to the Command field. 7. Choose Update. 8. Verify the information and choose Create. The following example shows how to write a comma-separated command line option for the RoleARN option. The RoleARN option assumes the specified IAM role to upload segments to a different account. Example --role-arn, arn:aws:iam::123456789012:role/xray-cross-account To learn more about the available command line options in X-Ray, see Configuring the AWS X-Ray Daemon. Configure command line options in the Amazon ECS console 260 AWS X-Ray Developer Guide Integrating AWS X-Ray with other AWS services Many AWS services provide varying levels of X-Ray integration, including sampling and adding headers to incoming requests, running the X-Ray daemon, and automatically sending trace data to X-Ray. Integration with X-Ray can include the following: • Active instrumentation – Samples and instruments incoming requests • Passive instrumentation – Instruments requests that have been sampled by another service • Request tracing – Adds a tracing header to all incoming requests and propagates it downstream • Tooling – Runs the X-Ray daemon to receive segments from the X-Ray SDK Note The X-Ray SDKs include plugins for additional integration with AWS services. For example, you can use the X-Ray SDK for Java Elastic Beanstalk plugin to add information about the Elastic Beanstalk environment that runs your application, including the environment name and ID. Here are some examples of AWS services that are integrated with X-Ray: • AWS Distro for OpenTelemetry (ADOT) – With ADOT, engineers can instrument their applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, Amazon OpenSearch Service, and Amazon Managed Service for Prometheus. • AWS Lambda – Active and passive instrumentation of incoming requests on all runtimes. AWS Lambda adds two nodes to your trace map, one for the AWS Lambda service, and one for the function. When you enable instrumentation, AWS Lambda also runs the X-Ray daemon on Java and Node.js runtimes for use with the X-Ray SDK. • Amazon API Gateway – Active and passive instrumentation. API Gateway uses sampling rules to determine which requests to record, and adds a node for the gateway stage to your service map. • AWS Elastic Beanstalk – Tooling. Elastic Beanstalk includes the X-Ray daemon on the following platforms: • Java SE – 2.3.0 and later configurations • Tomcat – 2.4.0 and later configurations 261 AWS X-Ray Developer Guide • Node.js – 3.2.0 and later configurations • Windows Server – All configurations other than Windows Server Core that have been released after December 9th, 2016 You can use the Elastic Beanstalk console to tell Elastic Beanstalk to run the daemon on these platforms, or use the XRayEnabled option in the aws:elasticbeanstalk:xray namespace. • Elastic Load Balancing – Request tracing on Application Load Balancers. The Application Load Balancer adds the trace ID to the request header before sending it to a target group. • Amazon EventBridge – Passive instrumentation. If a service that publishes events to EventBridge is instrumented with the X-Ray SDK, event targets will receive the tracing header and can continue to propagate the original trace ID. • Amazon Simple Notification Service – Passive instrumentation. If an Amazon SNS publisher traces its client with the X-Ray SDK, subscribers can retrieve the tracing header and continue to propagate the original trace from the publisher with the same trace |
xray-guide-076 | xray-guide.pdf | 76 | tracing on Application Load Balancers. The Application Load Balancer adds the trace ID to the request header before sending it to a target group. • Amazon EventBridge – Passive instrumentation. If a service that publishes events to EventBridge is instrumented with the X-Ray SDK, event targets will receive the tracing header and can continue to propagate the original trace ID. • Amazon Simple Notification Service – Passive instrumentation. If an Amazon SNS publisher traces its client with the X-Ray SDK, subscribers can retrieve the tracing header and continue to propagate the original trace from the publisher with the same trace ID. • Amazon Simple Queue Service – Passive instrumentation. If a service traces requests by using the X-Ray SDK, Amazon SQS can send the tracing header and continue to propagate the original trace from the sender to the consumer with a consistent trace ID. Choose from the following topics to explore the full set of integrated AWS services. Topics • AWS Distro for OpenTelemetry and AWS X-Ray • Amazon API Gateway active tracing support for AWS X-Ray • Amazon EC2 and AWS App Mesh • AWS App Runner and X-Ray • AWS AppSync and AWS X-Ray • Logging X-Ray API calls with AWS CloudTrail • CloudWatch integration with X-Ray • Tracking X-Ray encryption configuration changes with AWS Config • Amazon Elastic Compute Cloud and AWS X-Ray • AWS Elastic Beanstalk and AWS X-Ray • Elastic Load Balancing and AWS X-Ray • Amazon EventBridge and AWS X-Ray 262 AWS X-Ray • AWS Lambda and AWS X-Ray • Amazon SNS and AWS X-Ray • AWS Step Functions and AWS X-Ray • Amazon SQS and AWS X-Ray • Amazon S3 and AWS X-Ray Developer Guide AWS Distro for OpenTelemetry and AWS X-Ray Use the AWS Distro for OpenTelemetry (ADOT) to collect and send metrics and traces to AWS X- Ray and other monitoring solutions, such as Amazon CloudWatch, Amazon OpenSearch Service, and Amazon Managed Service for Prometheus. AWS Distro for OpenTelemetry The AWS Distro for OpenTelemetry (ADOT) is an AWS distribution based on the Cloud Native Computing Foundation (CNCF) OpenTelemetry project. OpenTelemetry provides a single set of open source APIs, libraries, and agents to collect distributed traces and metrics. This toolkit is a distribution of upstream OpenTelemetry components including SDKs, auto-instrumentation agents, and collectors that are tested, optimized, secured, and supported by AWS. With ADOT, engineers can instrument their applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, Amazon OpenSearch Service, and Amazon Managed Service for Prometheus. ADOT is integrated with a growing number of AWS services to simplify sending traces and metrics to monitoring solutions such as X-Ray. Some examples of services integrated with ADOT include: • AWS Lambda – AWS managed Lambda layers for ADOT provides a plug-and-play user experience by automatically instrumenting a Lambda function, packaging OpenTelemetry together with an out-of-the-box configuration for AWS Lambda and X-Ray in an easy to setup layer. Users can enable and disable OpenTelemetry for their Lambda function without changing code. For more information, see AWS Distro for OpenTelemetry Lambda • Amazon Elastic Container Service (ECS) – Collect metrics and traces from Amazon ECS applications using the AWS Distro for OpenTelemetry Collector, to send to X-Ray and other monitoring solutions. For more information, see Collecting application trace data in the Amazon ECS developer guide. AWS Distro for OpenTelemetry 263 AWS X-Ray Developer Guide • AWS App Runner – App Runner supports sending traces to X-Ray using the AWS Distro for OpenTelemetry (ADOT). Use ADOT SDKs to collect trace data for your containerized applications, and use X-Ray to analyze and gain insights into your instrumented application. For more information, see AWS App Runner and X-Ray. For more information about the AWS Distro for OpenTelemetry, including integration with additional AWS services, see the AWS Distro for OpenTelemetry Documentation. For more information about instrumenting your application with AWS Distro for OpenTelemetry and X-Ray, see Instrumenting your application with the AWS Distro for OpenTelemetry. Amazon API Gateway active tracing support for AWS X-Ray You can use X-Ray to trace and analyze user requests as they travel through your Amazon API Gateway APIs to the underlying services. API Gateway supports X-Ray tracing for all API Gateway endpoint types: Regional, edge-optimized, and private. You can use X-Ray with Amazon API Gateway in all AWS Regions where X-Ray is available. For more information, see Trace API Gateway API Execution with AWS X-Ray in the Amazon API Gateway Developer Guide. Note X-Ray only supports tracing for REST APIs through API Gateway. Amazon API Gateway provides active tracing support for AWS X-Ray. Enable active tracing on your API stages to sample incoming requests and send traces to X-Ray. To enable active tracing on an API stage 1. Open the API Gateway console at https://console.aws.amazon.com/apigateway/. 2. |
xray-guide-077 | xray-guide.pdf | 77 | tracing for all API Gateway endpoint types: Regional, edge-optimized, and private. You can use X-Ray with Amazon API Gateway in all AWS Regions where X-Ray is available. For more information, see Trace API Gateway API Execution with AWS X-Ray in the Amazon API Gateway Developer Guide. Note X-Ray only supports tracing for REST APIs through API Gateway. Amazon API Gateway provides active tracing support for AWS X-Ray. Enable active tracing on your API stages to sample incoming requests and send traces to X-Ray. To enable active tracing on an API stage 1. Open the API Gateway console at https://console.aws.amazon.com/apigateway/. 2. Choose an API. 3. Choose a stage. 4. On the Logs/Tracing tab, choose Enable X-Ray Tracing and then choose Save Changes. 5. Choose Resources in the left side navigation panel. 6. To redeploy the API with the new settings, choose the Actions dropdown, and then choose Deploy API. API Gateway 264 AWS X-Ray Developer Guide API Gateway uses sampling rules that you define in the X-Ray console to determine which requests to record. You can create rules that only apply to APIs, or that apply only to requests that contain certain headers. API Gateway records headers in attributes on the segment, along with details about the stage and request. For more information, see Configuring sampling rules. Note When tracing REST APIs with API Gateway HTTP integration, each segment's service name is set to the request URL path from API Gateway to your HTTP integration endpoint, resulting in a service node on the X-Ray trace map for each unique URL path. A large number of URL paths may cause the trace map to exceed the limit of 10,000 nodes, resulting in an error. To minimize the number of service nodes created by API Gateway, consider passing parameters within the URL query string or in the request body via POST. Either approach will ensure parameters are not part of the URL path, which may result in fewer distinct URL paths and service nodes. For all incoming requests, API Gateway adds a tracing header to incoming HTTP requests that don't already have one. X-Amzn-Trace-Id: Root=1-5759e988-bd862e3fe1be46a994272793 X-Ray trace ID format An X-Ray trace_id consists of three numbers separated by hyphens. For example, 1-58406520- a006649127e371903a2de979. This includes: • The version number, which is 1. • The time of the original request in Unix epoch time using 8 hexadecimal digits. For example, 10:00AM December 1st, 2016 PST in epoch time is 1480615200 seconds or 58406520 in hexadecimal digits. • A globally unique 96-bit identifier for the trace in 24 hexadecimal digits. If active tracing is disabled, the stage still records a segment if the request comes from a service that sampled the request and started a trace. For example, an instrumented web application can API Gateway 265 AWS X-Ray Developer Guide call an API Gateway API with an HTTP client. When you instrument an HTTP client with the X-Ray SDK, it adds a tracing header to the outgoing request that contains the sampling decision. API Gateway reads the tracing header and creates a segment for sampled requests. If you use API Gateway to generate a Java SDK for your API, you can instrument the SDK client by adding a request handler with the client builder, in the same way that you would manually instrument an AWS SDK client. See Tracing AWS SDK calls with the X-Ray SDK for Java for instructions. Amazon EC2 and AWS App Mesh AWS X-Ray integrates with AWS App Mesh to manage Envoy proxies for microservices. App Mesh provides a version of Envoy that you can configure to send trace data to the X-Ray daemon running in a container of the same task or pod. X-Ray supports tracing with the following App Mesh compatible services: • Amazon Elastic Container Service (Amazon ECS) • Amazon Elastic Kubernetes Service (Amazon EKS) • Amazon Elastic Compute Cloud (Amazon EC2) Use the following instructions to learn how to enable X-Ray tracing through App Mesh. App Mesh 266 AWS X-Ray Developer Guide To configure the Envoy proxy to send data to X-Ray, set the ENABLE_ENVOY_XRAY_TRACING environment variable in its container definition. Note The App Mesh version of Envoy does not currently send traces based on configured sampling rules. Instead, it uses a fixed sampling rate of 5% for Envoy version 1.16.3 or newer, or a 50% sampling rate for Envoy versions prior to 1.16.3. App Mesh 267 AWS X-Ray Developer Guide Example Envoy container definition for Amazon ECS { "name": "envoy", "image": "public.ecr.aws/appmesh/aws-appmesh-envoy:envoy-version", "essential": true, "environment": [ { "name": "APPMESH_VIRTUAL_NODE_NAME", "value": "mesh/myMesh/virtualNode/myNode" }, { "name": "ENABLE_ENVOY_XRAY_TRACING", "value": "1" } ], "healthCheck": { "command": [ "CMD-SHELL", "curl -s http://localhost:9901/server_info | cut -d' ' -f3 | grep -q live" ], "startPeriod": 10, "interval": 5, "timeout": 2, "retries": 3 } Note To learn more about available Envoy region addresses, see |
xray-guide-078 | xray-guide.pdf | 78 | rules. Instead, it uses a fixed sampling rate of 5% for Envoy version 1.16.3 or newer, or a 50% sampling rate for Envoy versions prior to 1.16.3. App Mesh 267 AWS X-Ray Developer Guide Example Envoy container definition for Amazon ECS { "name": "envoy", "image": "public.ecr.aws/appmesh/aws-appmesh-envoy:envoy-version", "essential": true, "environment": [ { "name": "APPMESH_VIRTUAL_NODE_NAME", "value": "mesh/myMesh/virtualNode/myNode" }, { "name": "ENABLE_ENVOY_XRAY_TRACING", "value": "1" } ], "healthCheck": { "command": [ "CMD-SHELL", "curl -s http://localhost:9901/server_info | cut -d' ' -f3 | grep -q live" ], "startPeriod": 10, "interval": 5, "timeout": 2, "retries": 3 } Note To learn more about available Envoy region addresses, see Envoy image in the AWS App Mesh User Guide. For details on running the X-Ray daemon in a container, see Running the X-Ray daemon on Amazon ECS. For a sample application that includes a service mesh, microservice, Envoy proxy, and X-Ray daemon, deploy the colorapp sample in the App Mesh Examples GitHub repository. Learn More • Getting Started with AWS App Mesh • Getting Started with AWS App Mesh and Amazon ECS App Mesh 268 AWS X-Ray Developer Guide AWS App Runner and X-Ray AWS App Runner is an AWS service that provides a fast, simple, and cost-effective way to deploy from source code or a container image directly to a scalable and secure web application in the AWS Cloud. You don't need to learn new technologies, decide which compute service to use, or know how to provision and configure AWS resources. See What is AWS App Runner for more information. AWS App Runner sends traces to X-Ray by integrating with the AWS Distro for OpenTelemetry (ADOT). Use ADOT SDKs to collect trace data for your containerized applications, and use X-Ray to analyze and gain insights into your instrumented application. For more information, see Tracing for your App Runner application with X-Ray. AWS AppSync and AWS X-Ray You can enable and trace requests for AWS AppSync. For more information, see Tracing with AWS X-Ray for instructions. When X-Ray tracing is enabled for an AWS AppSync API, an AWS Identity and Access Management service-linked role is automatically created in your account with the appropriate permissions. This allows AWS AppSync to send traces to X-Ray in a secure way. Logging X-Ray API calls with AWS CloudTrail AWS X-Ray is integrated with AWS CloudTrail, a service that provides a record of actions taken by a user, role, or an AWS service. CloudTrail captures all API calls for X-Ray as events. The calls captured include calls from the X-Ray console and code calls to the X-Ray API operations. Using the information collected by CloudTrail, you can determine the request that was made to X-Ray, the IP address from which the request was made, when it was made, and additional details. Every event or log entry contains information about who generated the request. The identity information helps you determine the following: • Whether the request was made with root user or user credentials. • Whether the request was made on behalf of an IAM Identity Center user. • Whether the request was made with temporary security credentials for a role or federated user. • Whether the request was made by another AWS service. App Runner 269 AWS X-Ray Developer Guide CloudTrail is active in your AWS account when you create the account and you automatically have access to the CloudTrail Event history. The CloudTrail Event history provides a viewable, searchable, downloadable, and immutable record of the past 90 days of recorded management events in an AWS Region. For more information, see Working with CloudTrail Event history in the AWS CloudTrail User Guide. There are no CloudTrail charges for viewing the Event history. For an ongoing record of events in your AWS account past 90 days, create a trail or a CloudTrail Lake event data store. CloudTrail trails A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. All trails created using the AWS Management Console are multi-Region. You can create a single-Region or a multi-Region trail by using the AWS CLI. Creating a multi-Region trail is recommended because you capture activity in all AWS Regions in your account. If you create a single-Region trail, you can view only the events logged in the trail's AWS Region. For more information about trails, see Creating a trail for your AWS account and Creating a trail for an organization in the AWS CloudTrail User Guide. You can deliver one copy of your ongoing management events to your Amazon S3 bucket at no charge from CloudTrail by creating a trail, however, there are Amazon S3 storage charges. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. For information about Amazon S3 pricing, see Amazon S3 Pricing. CloudTrail Lake event data stores CloudTrail Lake lets you run SQL-based queries on your events. CloudTrail Lake converts existing |
xray-guide-079 | xray-guide.pdf | 79 | the trail's AWS Region. For more information about trails, see Creating a trail for your AWS account and Creating a trail for an organization in the AWS CloudTrail User Guide. You can deliver one copy of your ongoing management events to your Amazon S3 bucket at no charge from CloudTrail by creating a trail, however, there are Amazon S3 storage charges. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. For information about Amazon S3 pricing, see Amazon S3 Pricing. CloudTrail Lake event data stores CloudTrail Lake lets you run SQL-based queries on your events. CloudTrail Lake converts existing events in row-based JSON format to Apache ORC format. ORC is a columnar storage format that is optimized for fast retrieval of data. Events are aggregated into event data stores, which are immutable collections of events based on criteria that you select by applying advanced event selectors. The selectors that you apply to an event data store control which events persist and are available for you to query. For more information about CloudTrail Lake, see Working with AWS CloudTrail Lake in the AWS CloudTrail User Guide. CloudTrail Lake event data stores and queries incur costs. When you create an event data store, you choose the pricing option you want to use for the event data store. The pricing option determines the cost for ingesting and storing events, and the default and maximum retention period for the event data store. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. CloudTrail 270 AWS X-Ray Topics • X-Ray management events in CloudTrail • X-Ray data events in CloudTrail • X-Ray event examples Developer Guide X-Ray management events in CloudTrail AWS X-Ray integrates with AWS CloudTrail to record API actions made by a user, a role, or an AWS service in X-Ray. You can use CloudTrail to monitor X-Ray API requests in real time and store logs in Amazon S3, Amazon CloudWatch Logs, and Amazon CloudWatch Events. X-Ray supports logging the following actions as events in CloudTrail log files: Supported API Actions • PutEncryptionConfig • GetEncryptionConfig • CreateGroup • UpdateGroup • DeleteGroup • GetGroup • GetGroups • GetInsight • GetInsightEvents • GetInsightImpactGraph • GetInsightSummaries • GetSamplingStatisticSummaries X-Ray data events in CloudTrail Data events provide information about the resource operations performed on or in a resource (for example, PutTraceSegments, which uploads segment documents to X-Ray). These are also known as data plane operations. Data events are often high-volume activities. By default, CloudTrail doesn’t log data events. The CloudTrail Event history doesn't record data events. X-Ray management events in CloudTrail 271 AWS X-Ray Developer Guide Additional charges apply for data events. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. You can log data events for the X-Ray resource types by using the CloudTrail console, AWS CLI, or CloudTrail API operations. For more information about how to log data events, see Logging data events with the AWS Management Console and Logging data events with the AWS Command Line Interface in the AWS CloudTrail User Guide. The following table lists the X-Ray resource types for which you can log data events. The Data event type (console) column shows the value to choose from the Data event type list on the CloudTrail console. The resources.type value column shows the resources.type value, which you would specify when configuring advanced event selectors using the AWS CLI or CloudTrail APIs. The Data APIs logged to CloudTrail column shows the API calls logged to CloudTrail for the resource type. Data event type (console) resources.type value Data APIs logged to CloudTrail X-Ray trace AWS::XRay::Trace • PutTraceSegments • GetTraceSummaries • GetTraceGraph • GetServiceGraph • BatchGetTraces • GetTimeSeriesServi ceStatistics • PutTelemetryRecords • GetSamplingTargets You can configure advanced event selectors to filter on the eventName and readOnly fields to log only those events that are important to you. However, you cannot select events by adding the resources.ARN field selector, because X-Ray traces do not have ARNs. For more information about these fields, see AdvancedFieldSelector in the AWS CloudTrail API Reference. The following is an example of how to run the put-event-selectors AWS CLI command to log data events on a CloudTrail trail. You must run the command in or specify the Region in which the trail was created; otherwise, the operation returns an InvalidHomeRegionException exception. X-Ray data events in CloudTrail 272 AWS X-Ray Developer Guide aws cloudtrail put-event-selectors --trail-name myTrail --advanced-event-selectors \ '{ "AdvancedEventSelectors": [ { "FieldSelectors": [ { "Field": "eventCategory", "Equals": ["Data"] }, { "Field": "resources.type", "Equals": ["AWS::XRay::Trace"] }, { "Field": "eventName", "Equals": ["PutTraceSegments","GetSamplingTargets"] } ], "Name": "Log X-Ray PutTraceSegments and GetSamplingTargets data events" } ] }' X-Ray event examples Management event example, GetEncryptionConfig The following is an example of the X-Ray GetEncryptionConfig log entry in CloudTrail. Example { "eventVersion"=>"1.05", "userIdentity"=>{ "type"=>"AssumedRole", "principalId"=>"AROAJVHBZWD3DN6CI2MHM:MyName", "arn"=>"arn:aws:sts::123456789012:assumed-role/MyRole/MyName", "accountId"=>"123456789012", "accessKeyId"=>"AKIAIOSFODNN7EXAMPLE", "sessionContext"=>{ "attributes"=>{ "mfaAuthenticated"=>"false", "creationDate"=>"2023-7-01T00:24:36Z" }, "sessionIssuer"=>{ "type"=>"Role", |
xray-guide-080 | xray-guide.pdf | 80 | the trail was created; otherwise, the operation returns an InvalidHomeRegionException exception. X-Ray data events in CloudTrail 272 AWS X-Ray Developer Guide aws cloudtrail put-event-selectors --trail-name myTrail --advanced-event-selectors \ '{ "AdvancedEventSelectors": [ { "FieldSelectors": [ { "Field": "eventCategory", "Equals": ["Data"] }, { "Field": "resources.type", "Equals": ["AWS::XRay::Trace"] }, { "Field": "eventName", "Equals": ["PutTraceSegments","GetSamplingTargets"] } ], "Name": "Log X-Ray PutTraceSegments and GetSamplingTargets data events" } ] }' X-Ray event examples Management event example, GetEncryptionConfig The following is an example of the X-Ray GetEncryptionConfig log entry in CloudTrail. Example { "eventVersion"=>"1.05", "userIdentity"=>{ "type"=>"AssumedRole", "principalId"=>"AROAJVHBZWD3DN6CI2MHM:MyName", "arn"=>"arn:aws:sts::123456789012:assumed-role/MyRole/MyName", "accountId"=>"123456789012", "accessKeyId"=>"AKIAIOSFODNN7EXAMPLE", "sessionContext"=>{ "attributes"=>{ "mfaAuthenticated"=>"false", "creationDate"=>"2023-7-01T00:24:36Z" }, "sessionIssuer"=>{ "type"=>"Role", "principalId"=>"AROAJVHBZWD3DN6CI2MHM", "arn"=>"arn:aws:iam::123456789012:role/MyRole", "accountId"=>"123456789012", "userName"=>"MyRole" } X-Ray event examples 273 Developer Guide AWS X-Ray } }, "eventTime"=>"2023-7-01T00:24:36Z", "eventSource"=>"xray.amazonaws.com", "eventName"=>"GetEncryptionConfig", "awsRegion"=>"us-east-2", "sourceIPAddress"=>"33.255.33.255", "userAgent"=>"aws-sdk-ruby2/2.11.19 ruby/2.3.1 x86_64-linux", "requestParameters"=>nil, "responseElements"=>nil, "requestID"=>"3fda699a-32e7-4c20-37af-edc2be5acbdb", "eventID"=>"039c3d45-6baa-11e3-2f3e-e5a036343c9f", "eventType"=>"AwsApiCall", "recipientAccountId"=>"123456789012" } Data event example, PutTraceSegments The following is an example of the X-Ray PutTraceSegments data event log entry in CloudTrail. Example { "eventVersion": "1.09", "userIdentity": { "type": "AssumedRole", "principalId": "AROAWYXPW54Y4NEXAMPLE:i-0dzz2ac111c83zz0z", "arn": "arn:aws:sts::012345678910:assumed-role/my-service-role/ i-0dzz2ac111c83zz0z", "accountId": "012345678910", "accessKeyId": "AKIAIOSFODNN7EXAMPLE", "sessionContext": { "sessionIssuer": { "type": "Role", "principalId": "AROAWYXPW54Y4NEXAMPLE", "arn": "arn:aws:iam::012345678910:role/service-role/my-service-role", "accountId": "012345678910", "userName": "my-service-role" }, "attributes": { "creationDate": "2024-01-22T17:34:11Z", "mfaAuthenticated": "false" }, X-Ray event examples 274 AWS X-Ray Developer Guide "ec2RoleDelivery": "2.0" } }, "eventTime": "2024-01-22T18:22:05Z", "eventSource": "xray.amazonaws.com", "eventName": "PutTraceSegments", "awsRegion": "us-west-2", "sourceIPAddress": "198.51.100.0", "userAgent": "aws-sdk-ruby3/3.190.0 md/internal ua/2.0 api/xray#1.0.0 os/linux md/ x86_64 lang/ruby#2.7.8 md/2.7.8 cfg/retry-mode#legacy", "requestParameters": { "traceSegmentDocuments": [ "trace_id:1-00zzz24z-EXAMPLE4f4e41754c77d0000", "trace_id:1-00zzz24z-EXAMPLE4f4e41754c77d0000", "trace_id:1-00zzz24z-EXAMPLE4f4e41754c77d0001", "trace_id:1-00zzz24z-EXAMPLE4f4e41754c77d0002" ] }, "responseElements": { "unprocessedTraceSegments": [] }, "requestID": "5zzzzz64-acbd-46ff-z544-451a3ebcb2f8", "eventID": "4zz51z7z-77f9-44zz-9bd7-6c8327740f2e", "readOnly": false, "resources": [ { "type": "AWS::XRay::Trace" } ], "eventType": "AwsApiCall", "managementEvent": false, "recipientAccountId": "012345678910", "eventCategory": "Data", "tlsDetails": { "tlsVersion": "TLSv1.2", "cipherSuite": "ZZZZZ-RSA-AAA128-GCM-SHA256", "clientProvidedHostHeader": "example.us-west-2.xray.cloudwatch.aws.dev" } } X-Ray event examples 275 AWS X-Ray Developer Guide CloudWatch integration with X-Ray AWS X-Ray integrates with CloudWatch Application Signals, CloudWatch RUM, and CloudWatch Synthetics to make it easier to monitor the health of your applications. Enable your application for Application Signals to monitor and troubleshoot the operational health of your services, client pages, Synthetics canaries, and service dependencies. By correlating CloudWatch metrics, logs, and X-Ray traces, the X-Ray trace map provides an end- to-end view of your services to help you quickly pinpoint performance bottlenecks and identify impacted users. With CloudWatch RUM, you can perform real user monitoring to collect and view client-side data about your web application performance from actual user sessions in near-real time. With AWS X- Ray and CloudWatch RUM, you can analyze and debug the request path starting from end users of your application through downstream AWS managed services. This helps you identify latency trends and errors that impact your end users. Topics • CloudWatch RUM and AWS X-Ray • Debugging CloudWatch synthetics canaries using X-Ray CloudWatch RUM and AWS X-Ray With Amazon CloudWatch RUM, you can perform real user monitoring to collect and view client- side data about your web application performance from actual user sessions in near-real time. With AWS X-Ray and CloudWatch RUM, you can analyze and debug the request path starting from end users of your application through downstream AWS managed services. This helps you identify latency trends and errors that impact your end users. After you turn on X-Ray tracing of user sessions, CloudWatch RUM adds an X-Ray trace header to allowed HTTP requests, and records an X-Ray segment for allowed HTTP requests. You can then see traces and segments from these user sessions in the X-Ray and CloudWatch consoles, including the X-Ray trace map. Note CloudWatch RUM doesn't integrate with X-Ray sampling rules. Instead, choose a sampling percentage when you set up your application to use CloudWatch RUM. Traces sent from CloudWatch 276 AWS X-Ray Developer Guide CloudWatch RUM might incur additional costs. For more information, see AWS X-Ray pricing. By default, client-side traces sent from CloudWatch RUM aren't connected to server-side traces. To connect client-side traces with server-side traces, configure the CloudWatch RUM web client to add an X-Ray trace header to these HTTP requests. Warning Configuring the CloudWatch RUM web client to add an X-Ray trace header to HTTP requests can cause cross-origin resource sharing (CORS) to fail. To avoid this, add the X- Amzn-Trace-Id HTTP header to the list of allowed headers on your downstream service's CORS configuration. If you are using API Gateway as your downstream, see Enabling CORS for a REST API resource. We strongly recommend that you test your application before adding a client-side X-Ray trace header in a production environment. For more information, see the CloudWatch RUM web client documentation. For more information about real user monitoring in CloudWatch, see Use CloudWatch RUM. To set up your application to use CloudWatch RUM, including tracing user sessions with X-Ray, see Set up an application to use CloudWatch RUM. Debugging CloudWatch synthetics canaries using X-Ray CloudWatch Synthetics is a fully managed service that enables you to monitor your endpoints and APIs using scripted canaries that run 24 hours |
xray-guide-081 | xray-guide.pdf | 81 | for a REST API resource. We strongly recommend that you test your application before adding a client-side X-Ray trace header in a production environment. For more information, see the CloudWatch RUM web client documentation. For more information about real user monitoring in CloudWatch, see Use CloudWatch RUM. To set up your application to use CloudWatch RUM, including tracing user sessions with X-Ray, see Set up an application to use CloudWatch RUM. Debugging CloudWatch synthetics canaries using X-Ray CloudWatch Synthetics is a fully managed service that enables you to monitor your endpoints and APIs using scripted canaries that run 24 hours per day, once per minute. You can customize canary scripts to check for changes in: • Availability • Latency • Transactions • Broken or dead links • Step-by-step task completions • Page load errors • Load Latencies for UI assets CloudWatch Synthetics 277 AWS X-Ray • Complex wizard flows • Checkout flows in your application Developer Guide Canaries follow the same routes and perform the same actions and behaviors as your customers, and continually verify the customer experience. To learn more about setting up Synthetics tests, see Using Synthetics to Create and Manage Canaries. The following examples show common use cases for debugging issues that your Synthetics canaries raise. Each example demonstrates a key strategy for debugging using either the trace map or the X-Ray Analytics console. CloudWatch Synthetics 278 AWS X-Ray Developer Guide For more information about how to read and interact with the trace map, see Viewing the Service Map. For more information about how to read and interact with the X-Ray Analytics console, see Interacting with the AWS X-Ray Analytics Console. Topics • View canaries with increased error reporting in the trace map • Use trace details maps for individual traces to view each request in detail • Determine the root cause of ongoing failures in upstream and downstream services • Identify performance bottlenecks and trends • Compare latency and error or fault rates before and after changes • Determine the required canary coverage for all APIs and URLs • Use groups to focus on synthetics tests View canaries with increased error reporting in the trace map To see which canaries have an increase in errors, faults, throttling rates, or slow response times within your X-Ray trace map, you can highlight Synthetics canary client nodes using the Client::Synthetic filter. Clicking a node displays the response time distribution of the entire request. Clicking an edge between two nodes shows details about the requests that traveled that connection. You can also view "remote" inferred nodes for related downstream services in your trace map. When you click the Synthetics node, there is a View in Synthetics button on side panel which redirects you to the Synthetics console where you can check the canary details. CloudWatch Synthetics 279 AWS X-Ray Developer Guide Use trace details maps for individual traces to view each request in detail To determine which service results in the most latency or is causing an error, invoke the trace details map by selecting the trace in the trace map. Individual trace details maps display the end- to-end path of a single request. Use this to understand the services invoked, and visualize the upstream and downstream services. CloudWatch Synthetics 280 AWS X-Ray Developer Guide Determine the root cause of ongoing failures in upstream and downstream services Once you receive a CloudWatch alarm for failures in a Synthetics canary, use the statistical modeling on trace data in X-Ray to determine the probable root cause of the issue within the X-Ray Analytics console. In the Analytics console, the Response Time Root Cause table shows recorded entity paths. X-Ray determines which path in your trace is the most likely cause for the response time. The format indicates a hierarchy of entities that are encountered, ending in a response time root cause. The following example shows that the Synthetics test for API “XXX” running on API Gateway is failing due to a throughput capacity exception from the Amazon DynamoDB table. CloudWatch Synthetics 281 AWS X-Ray Developer Guide CloudWatch Synthetics 282 AWS X-Ray Developer Guide Identify performance bottlenecks and trends You can view trends in the performance of your endpoint over time using continuous traffic from your Synthetics canaries to populate a trace details map over a period of time. Compare latency and error or fault rates before and after changes Pinpoint the time a change occurred to correlate that change to an increase in issues caught by your canaries. Use the X-Ray Analytics console to define the before and after time ranges as different trace sets, creating a visual differentiation in the response time distribution. CloudWatch Synthetics 283 AWS X-Ray Developer Guide Determine the required canary coverage for all APIs and URLs Use X-Ray Analytics to compare the experience of canaries with the |
xray-guide-082 | xray-guide.pdf | 82 | traffic from your Synthetics canaries to populate a trace details map over a period of time. Compare latency and error or fault rates before and after changes Pinpoint the time a change occurred to correlate that change to an increase in issues caught by your canaries. Use the X-Ray Analytics console to define the before and after time ranges as different trace sets, creating a visual differentiation in the response time distribution. CloudWatch Synthetics 283 AWS X-Ray Developer Guide Determine the required canary coverage for all APIs and URLs Use X-Ray Analytics to compare the experience of canaries with the users. The UI below shows a blue trend line for canaries and a green line for the users. You can also identify that two out of the three URLs don’t have canary tests. CloudWatch Synthetics 284 AWS X-Ray Developer Guide Use groups to focus on synthetics tests You can create an X-Ray group using a filter expression to focus on a certain set of workflows, such as a Synthetics tests for application “www” running on AWS Elastic Beanstalk. Use the complex keywords service() and edge() to filter through services and edges. Example Group filter expression "edge(id(name: "www", type: "client::Synthetics"), id(name: "www", type: "AWS::ElasticBeanstalk::Environment"))" CloudWatch Synthetics 285 AWS X-Ray Developer Guide Tracking X-Ray encryption configuration changes with AWS Config AWS X-Ray integrates with AWS Config to record configuration changes made to your X-Ray encryption resources. You can use AWS Config to inventory X-Ray encryption resources, audit the X-Ray configuration history, and send notifications based on resource changes. AWS Config supports logging the following X-Ray encryption resource changes as events: AWS Config 286 AWS X-Ray Developer Guide • Configuration changes – Changing or adding an encryption key, or reverting to the default X- Ray encryption setting. Use the following instructions to learn how to create a basic connection between X-Ray and AWS Config. Creating a Lambda function trigger You must have the ARN of a custom AWS Lambda function before you can generate a custom AWS Config rule. Follow these instructions to create a basic function with Node.js that returns a compliant or non-compliant value back to AWS Config based on the state of the XrayEncryptionConfig resource. To create a Lambda function with an AWS::XrayEncryptionConfig change trigger 1. Open the Lambda console. Choose Create function. 2. Choose Blueprints, and then filter the blueprints library for the config-rule-change-triggered blueprint. Either click the link in the blueprint's name or choose Configure to continue. 3. Define the following fields to configure the blueprint: • For Name, type a name. • For Role, choose Create new role from template(s). • For Role name, type a name. • For Policy templates, choose AWS Config Rules permissions. 4. Choose Create function to create and display your function in the AWS Lambda console. 5. Edit your function code to replace AWS::EC2::Instance with AWS::XrayEncryptionConfig. You can also update the description field to reflect this change. Default Code if (configurationItem.resourceType !== 'AWS::EC2::Instance') { return 'NOT_APPLICABLE'; } else if (ruleParameters.desiredInstanceType === configurationItem.configuration.instanceType) { return 'COMPLIANT'; } Creating a Lambda function trigger 287 AWS X-Ray Developer Guide return 'NON_COMPLIANT'; Updated Code if (configurationItem.resourceType !== 'AWS::XRay::EncryptionConfig') { return 'NOT_APPLICABLE'; } else if (ruleParameters.desiredInstanceType === configurationItem.configuration.instanceType) { return 'COMPLIANT'; } return 'NON_COMPLIANT'; 6. Add the following to your execution role in IAM for access to X-Ray. These permissions allow read-only access to your X-Ray resources. Failure to provide access to the appropriate resources will result in an out of scope message from AWS Config when it evaluates the Lambda function associated with the rule. { "Sid": "Stmt1529350291539", "Action": [ "xray:GetEncryptionConfig" ], "Effect": "Allow", "Resource": "*" } Creating a custom AWS Config rule for x-ray When the Lambda function is created, note the function's ARN, and go to the AWS Config console to create your custom rule. To create an AWS Config rule for X-Ray 1. Open the Rules page of the AWS Config console. 2. Choose Add rule, and then choose Add custom rule. 3. In AWS Lambda Function ARN, insert the ARN associated with the Lambda function you want to use. 4. Choose the type of trigger to set: Creating a custom AWS Config rule for x-ray 288 AWS X-Ray Developer Guide • Configuration changes – AWS Config triggers the evaluation when any resource that matches the rule's scope changes in configuration. The evaluation runs after AWS Config sends a configuration item change notification. • Periodic – AWS Config runs evaluations for the rule at a frequency that you choose (for example, every 24 hours). 5. For Resource type, choose EncryptionConfig in the X-Ray section. 6. Choose Save. The AWS Config console begins to evaluate the rule's compliance immediately. The evaluation can take several minutes to complete. Now that this rule is compliant, AWS Config can begin to compile an audit history. AWS Config |
xray-guide-083 | xray-guide.pdf | 83 | changes – AWS Config triggers the evaluation when any resource that matches the rule's scope changes in configuration. The evaluation runs after AWS Config sends a configuration item change notification. • Periodic – AWS Config runs evaluations for the rule at a frequency that you choose (for example, every 24 hours). 5. For Resource type, choose EncryptionConfig in the X-Ray section. 6. Choose Save. The AWS Config console begins to evaluate the rule's compliance immediately. The evaluation can take several minutes to complete. Now that this rule is compliant, AWS Config can begin to compile an audit history. AWS Config records resource changes in the form of a timeline. For each change in the timeline of events, AWS Config generates a table in a from/to format to show what changed in the JSON representation of the encryption key. The two field changes associated with EncryptionConfig are Configuration.type and Configuration.keyID. Example results Following is an example of an AWS Config timeline showing changes made at specific dates and times. Following is an example of an AWS Config change entry. The from/to format illustrates what changed. This example shows that the default X-Ray encryption settings were changed to a defined encryption key. Example results 289 AWS X-Ray Developer Guide Amazon SNS notifications To be notified of configuration changes, set AWS Config to publish Amazon SNS notifications. For more information, see Monitoring AWS Config Resource Changes by Email. Amazon Elastic Compute Cloud and AWS X-Ray You can install and run the X-Ray daemon on an Amazon EC2 instance with a user data script. See Running the X-Ray daemon on Amazon EC2 for instructions. Use an instance profile to grant the daemon permission to upload trace data to X-Ray. For more information, see Giving the daemon permission to send data to X-Ray. AWS Elastic Beanstalk and AWS X-Ray AWS Elastic Beanstalk platforms include the X-Ray daemon. You can run the daemon by setting an option in the Elastic Beanstalk console or with a configuration file. On the Java SE platform, you can use a Buildfile file to build your application with Maven or Gradle on-instance. The X-Ray SDK for Java and AWS SDK for Java are available from Maven, so you can deploy only your application code and build on-instance to avoid bundling and uploading all of your dependencies. You can use Elastic Beanstalk environment properties to configure the X-Ray SDK. The method that Elastic Beanstalk uses to pass environment properties to your application varies by platform. Use the X-Ray SDK's environment variables or system properties depending on your platform. • Node.js platform – Use environment variables • Java SE platform – Use environment variables • Tomcat platform – Use system properties Amazon SNS notifications 290 AWS X-Ray Developer Guide For more information, see Configuring AWS X-Ray Debugging in the AWS Elastic Beanstalk Developer Guide. Elastic Load Balancing and AWS X-Ray Elastic Load Balancing application load balancers add a trace ID to incoming HTTP requests in a header named X-Amzn-Trace-Id. X-Amzn-Trace-Id: Root=1-5759e988-bd862e3fe1be46a994272793 X-Ray trace ID format An X-Ray trace_id consists of three numbers separated by hyphens. For example, 1-58406520- a006649127e371903a2de979. This includes: • The version number, which is 1. • The time of the original request in Unix epoch time using 8 hexadecimal digits. For example, 10:00AM December 1st, 2016 PST in epoch time is 1480615200 seconds or 58406520 in hexadecimal digits. • A globally unique 96-bit identifier for the trace in 24 hexadecimal digits. Load balancers do not send data to X-Ray, and do not appear as a node on your service map. For more information, see Request Tracing for Your Application Load Balancer in the Elastic Load Balancing Developer Guide. Amazon EventBridge and AWS X-Ray AWS X-Ray integrates with Amazon EventBridge to trace events that are passed through EventBridge. If a service that is instrumented with the X-Ray SDK sends events to EventBridge, the trace context is propagated to downstream event targets within the tracing header. The X-Ray SDK automatically picks up the tracing header and applies it to any subsequent instrumentation. This continuity enables users to trace, analyze, and debug throughout downstream services and provides a more complete view of their system. For more information, see EventBridge X-Ray Integration in the EventBridge User Guide. Elastic Load Balancing 291 AWS X-Ray Developer Guide Viewing source and targets on the X-Ray service map The X-Ray trace map displays an EventBridge event node that connects source and target services, as in the following example: Propagate the trace context to event targets The X-Ray SDK enables the EventBridge event source to propagate trace context to downstream event targets. The following language-specific examples demonstrate calling EventBridge from a Lambda function on which active tracing is enabled: Java Add the necessary dependencies for X-Ray: • AWS X-Ray SDK for Java • AWS X-Ray Recorder SDK for Java |
xray-guide-084 | xray-guide.pdf | 84 | EventBridge User Guide. Elastic Load Balancing 291 AWS X-Ray Developer Guide Viewing source and targets on the X-Ray service map The X-Ray trace map displays an EventBridge event node that connects source and target services, as in the following example: Propagate the trace context to event targets The X-Ray SDK enables the EventBridge event source to propagate trace context to downstream event targets. The following language-specific examples demonstrate calling EventBridge from a Lambda function on which active tracing is enabled: Java Add the necessary dependencies for X-Ray: • AWS X-Ray SDK for Java • AWS X-Ray Recorder SDK for Java package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.amazonaws.xray.AWSXRay; import com.amazonaws.services.eventbridge.AmazonEventBridge; import com.amazonaws.services.eventbridge.AmazonEventBridgeClientBuilder; import com.amazonaws.services.eventbridge.model.PutEventsRequest; import com.amazonaws.services.eventbridge.model.PutEventsRequestEntry; import com.amazonaws.services.eventbridge.model.PutEventsResult; Viewing source and targets on the X-Ray service map 292 AWS X-Ray Developer Guide import com.amazonaws.services.eventbridge.model.PutEventsResultEntry; import com.amazonaws.xray.handlers.TracingHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.StringBuilder; import java.util.Map; import java.util.List; import java.util.Date; import java.util.Collections; /* Add the necessary dependencies for XRay: https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-xray https://mvnrepository.com/artifact/com.amazonaws/aws-xray-recorder-sdk-aws-sdk */ public class Handler implements RequestHandler<SQSEvent, String>{ private static final Logger logger = LoggerFactory.getLogger(Handler.class); /* build EventBridge client */ private static final AmazonEventBridge eventsClient = AmazonEventBridgeClientBuilder .standard() // instrument the EventBridge client with the XRay Tracing Handler. // the AWSXRay globalRecorder will retrieve the tracing-context // from the lambda function and inject it into the HTTP header. // be sure to enable 'active tracing' on the lambda function. .withRequestHandlers(new TracingHandler(AWSXRay.getGlobalRecorder())) .build(); @Override public String handleRequest(SQSEvent event, Context context) { PutEventsRequestEntry putEventsRequestEntry0 = new PutEventsRequestEntry(); putEventsRequestEntry0.setTime(new Date()); putEventsRequestEntry0.setSource("my-lambda-function"); putEventsRequestEntry0.setDetailType("my-lambda-event"); putEventsRequestEntry0.setDetail("{\"lambda-source\":\"sqs\"}"); PutEventsRequest putEventsRequest = new PutEventsRequest(); putEventsRequest.setEntries(Collections.singletonList(putEventsRequestEntry0)); // send the event(s) to EventBridge Propagate the trace context to event targets 293 AWS X-Ray Developer Guide PutEventsResult putEventsResult = eventsClient.putEvents(putEventsRequest); try { logger.info("Put Events Result: {}", putEventsResult); } catch(Exception e) { e.getStackTrace(); } return "success"; } } Python Add the following dependency to your requirements.txt file: aws-xray-sdk==2.4.3 import boto3 from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core import patch_all # apply the XRay handler to all clients. patch_all() client = boto3.client('events') def lambda_handler(event, context): response = client.put_events( Entries=[ { 'Source': 'foo', 'DetailType': 'foo', 'Detail': '{\"foo\": \"foo\"}' }, ] ) return response Go package main import ( "context" Propagate the trace context to event targets 294 AWS X-Ray Developer Guide "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-xray-sdk-go/xray" "github.com/aws/aws-sdk-go/service/eventbridge" "fmt" ) var client = eventbridge.New(session.New()) func main() { //Wrap the eventbridge client in the AWS XRay tracer xray.AWS(client.Client) lambda.Start(handleRequest) } func handleRequest(ctx context.Context, event events.SQSEvent) (string, error) { _, err := callEventBridge(ctx) if err != nil { return "ERROR", err } return "success", nil } func callEventBridge(ctx context.Context) (string, error) { entries := make([]*eventbridge.PutEventsRequestEntry, 1) detail := "{ \"foo\": \"foo\"}" detailType := "foo" source := "foo" entries[0] = &eventbridge.PutEventsRequestEntry{ Detail: &detail, DetailType: &detailType, Source: &source, } input := &eventbridge.PutEventsInput{ Entries: entries, } // Example sending a request using the PutEventsRequest method. resp, err := client.PutEventsWithContext(ctx, input) Propagate the trace context to event targets 295 AWS X-Ray Developer Guide success := "yes" if err == nil { // resp is now filled success = "no" fmt.Println(resp) } return success, err } Node.js const AWSXRay = require('aws-xray-sdk') //Wrap the aws-sdk client in the AWS XRay tracer const AWS = AWSXRay.captureAWS(require('aws-sdk')) const eventBridge = new AWS.EventBridge() exports.handler = async (event) => { let myDetail = { "name": "Alice" } const myEvent = { Entries: [{ Detail: JSON.stringify({ myDetail }), DetailType: 'myDetailType', Source: 'myApplication', Time: new Date }] } // Send to EventBridge const result = await eventBridge.putEvents(myEvent).promise() // Log the result console.log('Result: ', JSON.stringify(result, null, 2)) } C# Add the following X-Ray packages to your C# dependencies: <PackageReference Include="AWSXRayRecorder.Core" Version="2.6.2" /> <PackageReference Include="AWSXRayRecorder.Handlers.AwsSdk" Version="2.7.2" /> Propagate the trace context to event targets 296 AWS X-Ray Developer Guide using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon; using Amazon.Util; using Amazon.Lambda; using Amazon.Lambda.Model; using Amazon.Lambda.Core; using Amazon.EventBridge; using Amazon.EventBridge.Model; using Amazon.Lambda.SQSEvents; using Amazon.XRay.Recorder.Core; using Amazon.XRay.Recorder.Handlers.AwsSdk; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace blankCsharp { public class Function { private static AmazonEventBridgeClient eventClient; static Function() { initialize(); } static async void initialize() { //Wrap the AWS SDK clients in the AWS XRay tracer AWSSDKHandler.RegisterXRayForAllServices(); eventClient = new AmazonEventBridgeClient(); } public async Task<PutEventsResponse> FunctionHandler(SQSEvent invocationEvent, ILambdaContext context) { PutEventsResponse response; try { response = await callEventBridge(); Propagate the trace context to event targets 297 AWS X-Ray } catch (AmazonLambdaException ex) { throw ex; } return response; } Developer Guide public static async Task<PutEventsResponse> callEventBridge() { var request = new PutEventsRequest(); var entry = new PutEventsRequestEntry(); entry.DetailType = "foo"; entry.Source = "foo"; entry.Detail = "{\"instance_id\":\"A\"}"; List<PutEventsRequestEntry> entries = new List<PutEventsRequestEntry>(); entries.Add(entry); request.Entries = entries; var response = await eventClient.PutEventsAsync(request); return response; } } } AWS Lambda and AWS X-Ray You can use AWS X-Ray to trace your AWS Lambda functions. Lambda runs the X-Ray daemon and records a segment with details about invoking and running the function. For further instrumentation, you can bundle the X-Ray |
xray-guide-085 | xray-guide.pdf | 85 | AWS X-Ray } catch (AmazonLambdaException ex) { throw ex; } return response; } Developer Guide public static async Task<PutEventsResponse> callEventBridge() { var request = new PutEventsRequest(); var entry = new PutEventsRequestEntry(); entry.DetailType = "foo"; entry.Source = "foo"; entry.Detail = "{\"instance_id\":\"A\"}"; List<PutEventsRequestEntry> entries = new List<PutEventsRequestEntry>(); entries.Add(entry); request.Entries = entries; var response = await eventClient.PutEventsAsync(request); return response; } } } AWS Lambda and AWS X-Ray You can use AWS X-Ray to trace your AWS Lambda functions. Lambda runs the X-Ray daemon and records a segment with details about invoking and running the function. For further instrumentation, you can bundle the X-Ray SDK with your function to record outgoing calls and add annotations and metadata. If your Lambda function is called by another instrumented service, Lambda traces requests that have already been sampled without any additional configuration. The upstream service can be an instrumented web application or another Lambda function. Your service can invoke the function directly with an instrumented AWS SDK client, or by calling an API Gateway API with an instrumented HTTP client. AWS X-Ray supports tracing event-driven applications using AWS Lambda and Amazon SQS. Use the CloudWatch console to see a connected view of each request as it's queued with Amazon SQS and processed by a downstream Lambda function. Traces from upstream message producers are Lambda 298 AWS X-Ray Developer Guide automatically linked to traces from downstream Lambda consumer nodes, creating an end-to-end view of the application. For more information, see tracing event-driven applications. Note If you have traces enabled for a downstream Lambda function, you must also have traces enabled for the root Lambda function that calls the downstream function in order for the downstream function to generate traces. If your Lambda function runs on a schedule, or is invoked by a service that is not instrumented, you can configure Lambda to sample and record invocations with active tracing. To configure X-Ray integration on an AWS Lambda function 1. Open the AWS Lambda console. 2. Select Functions from the left navigation bar. 3. Choose your function. 4. On the Configuration tab, scroll down to the Additional monitoring tools card. You can also find this card by selecting Monitoring and operations tools on the left navigation pane. 5. Select Edit. 6. Under AWS X-Ray, enable Active tracing. On runtimes with a corresponding X-Ray SDK, Lambda also runs the X-Ray daemon. X-Ray SDKs on Lambda • X-Ray SDK for Go – Go 1.7 and newer runtimes • X-Ray SDK for Java – Java 8 runtime • X-Ray SDK for Node.js – Node.js 4.3 and newer runtimes • X-Ray SDK for Python – Python 2.7, Python 3.6, and newer runtimes • X-Ray SDK for .NET – .NET Core 2.0 and newer runtimes To use the X-Ray SDK on Lambda, bundle it with your function code each time you create a new version. You can instrument your Lambda functions with the same methods that you use to Lambda 299 AWS X-Ray Developer Guide instrument applications running on other services. The primary difference is that you don't use the SDK to instrument incoming requests, make sampling decisions, and create segments. The other difference between instrumenting Lambda functions and web applications is that the segment that Lambda creates and sends to X-Ray can't be modified by your function code. You can create subsegments and record annotations and metadata on them, but you can't add annotations and metadata to the parent segment. For more information, see Using AWS X-Ray in the AWS Lambda Developer Guide. Amazon SNS and AWS X-Ray You can use AWS X-Ray with Amazon Simple Notification Service (Amazon SNS) to trace and analyze requests as they travel through your SNS topics to your SNS-supported subscription services. Use X-Ray tracing with Amazon SNS to analyze latencies in your messages and their back-end services, such as how long a request spends in a topic, and how long it takes to deliver the message to each of the topic’s subscriptions. Amazon SNS supports X-Ray tracing for both standard and FIFO topics. If you publish to an Amazon SNS topic from a service that’s already instrumented with X-Ray, Amazon SNS passes the trace context from publisher to subscribers. In addition, you can turn on active tracing to send segment data about your Amazon SNS subscriptions to X-Ray for messages published from an instrumented SNS client. Turn on active tracing for an Amazon SNS topic by using the Amazon SNS console, or by using the Amazon SNS API or CLI. See Instrumenting your application for more information about instrumenting your SNS clients. Configure Amazon SNS active tracing You can use the Amazon SNS console or the AWS CLI or SDK to configure Amazon SNS active tracing. When you use the Amazon SNS console, Amazon SNS attempts to create the necessary permissions for SNS to call X-Ray. The |
xray-guide-086 | xray-guide.pdf | 86 | to send segment data about your Amazon SNS subscriptions to X-Ray for messages published from an instrumented SNS client. Turn on active tracing for an Amazon SNS topic by using the Amazon SNS console, or by using the Amazon SNS API or CLI. See Instrumenting your application for more information about instrumenting your SNS clients. Configure Amazon SNS active tracing You can use the Amazon SNS console or the AWS CLI or SDK to configure Amazon SNS active tracing. When you use the Amazon SNS console, Amazon SNS attempts to create the necessary permissions for SNS to call X-Ray. The attempt can be rejected if you don't have sufficient permissions to modify X-Ray resource policies. For more information about these permissions, see Identity and access management in Amazon SNS and Example cases for Amazon SNS access control in the Amazon Simple Notification Service Developer Guide. For more information about turning on active tracing using the Amazon SNS console, see Enabling active tracing on an Amazon SNS topic in the Amazon Simple Notification Service Developer Guide. Amazon SNS 300 AWS X-Ray Developer Guide When using the AWS CLI or SDK to turn on active tracing, you must manually configure the permissions using resource-based policies. Use PutResourcePolicy to configure X-Ray with the necessary resource-based policy to allow Amazon SNS to send traces to X-Ray. Example Example X-Ray resource-based policy for Amazon SNS active tracing This example policy document specifies the permissions that Amazon SNS needs to send trace data to X-Ray: { Version: "2012-10-17", Statement: [ { Sid: "SNSAccess", Effect: Allow, Principal: { Service: "sns.amazonaws.com", }, Action: [ "xray:PutTraceSegments", "xray:GetSamplingRules", "xray:GetSamplingTargets" ], Resource: "*", Condition: { StringEquals: { "aws:SourceAccount": "account-id" }, StringLike: { "aws:SourceArn": "arn:partition:sns:region:account-id:topic-name" } } } ] } Use the CLI to create a resource-based policy that gives Amazon SNS permissions to send trace data to X-Ray: aws xray put-resource-policy --policy-name MyResourcePolicy --policy-document '{ "Version": "2012-10-17", "Statement": [ { "Sid": "SNSAccess", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": [ "xray:PutTraceSegments", "xray:GetSamplingRules", "xray:GetSamplingTargets" ], "Resource": "*", Configure Amazon SNS active tracing 301 AWS X-Ray Developer Guide "Condition": { "StringEquals": { "aws:SourceAccount": "account-id" }, "StringLike": { "aws:SourceArn": "arn:partition:sns:region:account-id:topic-name" } } } ] }' To use these examples, replace partition, region, account-id, and topic-name with your specific AWS partition, region, account ID, and Amazon SNS topic name. To give all Amazon SNS topics permission to send trace data to X-Ray, replace the topic name with *. View Amazon SNS publisher and subscriber traces in the X-Ray console Use the X-Ray console to view a trace map and trace details that display a connected view of Amazon SNS publishers and subscribers. When Amazon SNS active tracing is turned on for a topic, the X-Ray trace map and trace details map displays connected nodes for Amazon SNS publishers, the Amazon SNS topic, and downstream subscribers: After choosing a trace that spans an Amazon SNS publisher and subscriber, the X-Ray trace details page displays a trace details map and segment timeline. Example Example timeline with Amazon SNS publisher and subscriber This example shows a timeline that includes an Amazon SNS publisher that sends a message to an Amazon SNS topic, which is processed by an Amazon SQS subscriber. View Amazon SNS publisher and subscriber traces in the X-Ray console 302 AWS X-Ray Developer Guide The example timeline above provides details about the Amazon SNS message flow: • The SNS segment represents the round-trip duration of the Publish API call from the client. • The myTopic segment represents the latency of the Amazon SNS response to the publish request. • The SQS subsegment represents the round-trip time it takes Amazon SNS to publish the message to an Amazon SQS queue. • The time between the myTopic segment and the SQS subsegment represents the time that the message spends in the Amazon SNS system. Example Example timeline with batched Amazon SNS messages If multiple Amazon SNS messages are batched within a single trace, the segment timeline displays segments that represent each message that's processed. AWS Step Functions and AWS X-Ray AWS X-Ray integrates with AWS Step Functions to trace and analyze requests for Step Functions. You can visualize the components of your state machine, identify performance bottlenecks, and Step Functions 303 AWS X-Ray Developer Guide troubleshoot requests that resulted in an error. For more information, see AWS X-Ray and Step Functions in the AWS Step Functions Developer Guide. To enable X-Ray tracing when creating a new state machine 1. Open the Step Functions console at https://console.aws.amazon.com/states/. 2. Choose Create a state machine. 3. On the Define state machine page, choose either Author with code snippets or Start with a template. If you choose to run a sample project, you can't enable X-Ray tracing during creation. Instead, enable X-Ray tracing after you create your state machine. 4. Choose |
xray-guide-087 | xray-guide.pdf | 87 | and Step Functions 303 AWS X-Ray Developer Guide troubleshoot requests that resulted in an error. For more information, see AWS X-Ray and Step Functions in the AWS Step Functions Developer Guide. To enable X-Ray tracing when creating a new state machine 1. Open the Step Functions console at https://console.aws.amazon.com/states/. 2. Choose Create a state machine. 3. On the Define state machine page, choose either Author with code snippets or Start with a template. If you choose to run a sample project, you can't enable X-Ray tracing during creation. Instead, enable X-Ray tracing after you create your state machine. 4. Choose Next. 5. On the Specify details page, configure your state machine. 6. Choose Enable X-Ray tracing. To enable X-Ray tracing in an existing state machine 1. In the Step Functions console, select the state machine for which you want to enable tracing. 2. Choose Edit. 3. Choose Enable X-Ray tracing. 4. (Optional) Auto-generate a new role for your state machine to include X-Ray permissions by choosing Create new role from the Permissions window. 5. Choose Save. Note When you create a new state machine, it's automatically traced if the request is sampled and tracing is enabled in an upstream service such as Amazon API Gateway or AWS Lambda. For any existing state machine not configured through the console, for example Step Functions 304 AWS X-Ray Developer Guide through an AWS CloudFormation template, check that you have an IAM policy that grants sufficient permissions to enable X-Ray traces. Amazon SQS and AWS X-Ray AWS X-Ray integrates with Amazon Simple Queue Service (Amazon SQS) to trace messages that are passed through an Amazon SQS queue. If a service traces requests by using the X-Ray SDK, Amazon SQS can send the tracing header and continue to propagate the original trace from the sender to the consumer with a consistent trace ID. Trace continuity enables users to track, analyze, and debug throughout downstream services. AWS X-Ray supports tracing event-driven applications using Amazon SQS and AWS Lambda. Use the CloudWatch console to see a connected view of each request as it's queued with Amazon SQS and processed by a downstream Lambda function. Traces from upstream message producers are automatically linked to traces from downstream Lambda consumer nodes, creating an end-to-end view of the application. For more information, see tracing event-driven applications. Amazon SQS supports the following tracing header instrumentation: • Default HTTP Header – The X-Ray SDK automatically populates the trace header as an HTTP header when you call Amazon SQS through the AWS SDK. The default trace header is carried by X-Amzn-Trace-Id and corresponds to all messages included in a SendMessage or SendMessageBatch request. To learn more about the default HTTP header, see Tracing header. • AWSTraceHeader System Attribute – The AWSTraceHeader is a message system attribute reserved by Amazon SQS to carry the X-Ray trace header with messages in the queue. AWSTraceHeader is available for use even when auto-instrumentation through the X-Ray Amazon SQS 305 AWS X-Ray Developer Guide SDK is not, for example when building a tracing SDK for a new language. When both header instrumentations are set, the message system attribute overrides the HTTP trace header. When running on Amazon EC2, Amazon SQS supports processing one message at a time. This applies when running on an on-premises host, and when using container services, such as AWS Fargate, Amazon ECS, or AWS App Mesh. The trace header is excluded from both Amazon SQS message size and message attribute quotas. Enabling X-Ray tracing will not exceed your Amazon SQS quotas. To learn more about AWS quotas, see Amazon SQS Quotas. Send the HTTP trace header Sender components in Amazon SQS can send the trace header automatically through the SendMessageBatch or SendMessage call. When AWS SDK clients are instrumented, they can be automatically tracked through all languages supported through the X-Ray SDK. Traced AWS services and resources that you access within those services (for example, an Amazon S3 bucket or Amazon SQS queue), appear as downstream nodes on the trace map in the X-Ray console. To learn how to trace AWS SDK calls with your preferred language, see the following topics in the supported SDKs: • Go – Tracing AWS SDK calls with the X-Ray SDK for Go • Java – Tracing AWS SDK calls with the X-Ray SDK for Java • Node.js – Tracing AWS SDK calls with the X-Ray SDK for Node.js • Python – Tracing AWS SDK calls with the X-Ray SDK for Python • Ruby – Tracing AWS SDK calls with the X-Ray SDK for Ruby • .NET – Tracing AWS SDK calls with the X-Ray SDK for .NET Retrieve the trace header and recover trace context If you are using a Lambda downstream consumer, trace context propagation is automatic. To continue context propagation with other Amazon SQS consumers, you |
xray-guide-088 | xray-guide.pdf | 88 | X-Ray SDK for Go • Java – Tracing AWS SDK calls with the X-Ray SDK for Java • Node.js – Tracing AWS SDK calls with the X-Ray SDK for Node.js • Python – Tracing AWS SDK calls with the X-Ray SDK for Python • Ruby – Tracing AWS SDK calls with the X-Ray SDK for Ruby • .NET – Tracing AWS SDK calls with the X-Ray SDK for .NET Retrieve the trace header and recover trace context If you are using a Lambda downstream consumer, trace context propagation is automatic. To continue context propagation with other Amazon SQS consumers, you must manually instrument the handoff to the receiver component. There are three main steps to recovering the trace context: Send the HTTP trace header 306 AWS X-Ray Developer Guide • Receive the message from the queue for the AWSTraceHeader attribute by calling the ReceiveMessage API. • Retrieve the trace header from the attribute. • Recover the trace ID from the header. Optionally, add more metrics to the segment. The following is an example implementation written with the X-Ray SDK for Java. Example : Retrieve the trace header and recover trace context // Receive the message from the queue, specifying the "AWSTraceHeader" ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest() .withQueueUrl(QUEUE_URL) .withAttributeNames("AWSTraceHeader"); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); if (!messages.isEmpty()) { Message message = messages.get(0); // Retrieve the trace header from the AWSTraceHeader message system attribute String traceHeaderStr = message.getAttributes().get("AWSTraceHeader"); if (traceHeaderStr != null) { TraceHeader traceHeader = TraceHeader.fromString(traceHeaderStr); // Recover the trace context from the trace header Segment segment = AWSXRay.getCurrentSegment(); segment.setTraceId(traceHeader.getRootTraceId()); segment.setParentId(traceHeader.getParentId()); segment.setSampled(traceHeader.getSampled().equals(TraceHeader.SampleDecision.SAMPLED)); } } Amazon S3 and AWS X-Ray AWS X-Ray integrates with Amazon S3 to trace upstream requests to update your application's S3 buckets. If a service traces requests by using the X-Ray SDK, Amazon S3 can send the tracing headers to downstream event subscribers such as AWS Lambda, Amazon SQS, and Amazon SNS. X- Ray enables trace messages for Amazon S3 event notifications. Amazon S3 307 AWS X-Ray Developer Guide You can use the X-Ray trace map to view the connections between Amazon S3 and other services that your application uses. You can also use the console to view metrics such as average latency and failure rates. For more information about the X-Ray console, see Use the X-Ray console. Amazon S3 supports the default http header instrumentation. The X-Ray SDK automatically populates the trace header as an HTTP header when you call Amazon S3 through the AWS SDK. The default trace header is carried by X-Amzn-Trace-Id. To learn more about tracing headers, see Tracing header on the concept page. Amazon S3 trace context propagation supports the following subscribers: Lambda, SQS and SNS. Because SQS and SNS don't emit segment data themselves, they won't appear in your trace or trace map when triggered by S3, even though they will propagate the tracing header to downstream services. Configure Amazon S3 event notifications With the Amazon S3 notification feature, you receive notifications when certain events happen in your bucket. These notifications can then be propagated to the following destinations within your application: • Amazon Simple Notification Service (Amazon SNS) • Amazon Simple Queue Service (Amazon SQS) • AWS Lambda For a list of supported events, see Supported event types in the Amazon S3 developer guide. Amazon SNS and Amazon SQS To publish notifications to an SNS topic or an SQS queue, you must first grant Amazon S3 permissions. To grant these permissions, you attach an AWS Identity and Access Management (IAM) policy to the destination SNS topic or SQS queue. To learn more about the IAM policies required, see Granting permissions to publish messages to an SNS topic or an SQS queue. For information about integrating SNS and SQS with X-Ray see, Amazon SNS and AWS X-Ray and Amazon SQS and AWS X-Ray. AWS Lambda When you use the Amazon S3 console to configure event notifications on an S3 bucket for a Lambda function, the console sets up the necessary permissions on the Lambda function so that Configure Amazon S3 event notifications 308 AWS X-Ray Developer Guide Amazon S3 has permissions to invoke the function from the bucket. For more information, see How Do I Enable and Configure Event Notifications for an S3 Bucket? in the Amazon Simple Storage Service Console User Guide. You can also grant Amazon S3 permissions from AWS Lambda to invoke your Lambda function. For more information, see Tutorial: Using AWS Lambda with Amazon S3 in the AWS Lambda Developer Guide. For more information about integrating Lambda with X-Ray, see Instrumenting Java code in AWS Lambda. Configure Amazon S3 event notifications 309 AWS X-Ray Developer Guide Instrumenting your application for AWS X-Ray Instrumenting your application involves sending trace data for incoming and outbound requests and other events within your application, along with metadata about each request. There are several different |
xray-guide-089 | xray-guide.pdf | 89 | in the Amazon Simple Storage Service Console User Guide. You can also grant Amazon S3 permissions from AWS Lambda to invoke your Lambda function. For more information, see Tutorial: Using AWS Lambda with Amazon S3 in the AWS Lambda Developer Guide. For more information about integrating Lambda with X-Ray, see Instrumenting Java code in AWS Lambda. Configure Amazon S3 event notifications 309 AWS X-Ray Developer Guide Instrumenting your application for AWS X-Ray Instrumenting your application involves sending trace data for incoming and outbound requests and other events within your application, along with metadata about each request. There are several different instrumentation options you can choose from or combine, based on your particular requirements: • Auto instrumentation – instrument your application with zero code changes, typically via configuration changes, adding an auto-instrumentation agent, or other mechanisms. • Library instrumentation – make minimal application code changes to add pre-built instrumentation targeting specific libraries or frameworks, such as the AWS SDK, Apache HTTP clients, or SQL clients. • Manual instrumentation – add instrumentation code to your application at each location where you want to send trace information. There are several SDKs, agents, and tools that can be used to instrument your application for X-Ray tracing. Topics • Instrumenting your application with the AWS Distro for OpenTelemetry • Instrumenting your application with AWS X-Ray SDKs • Choosing between the AWS Distro for OpenTelemetry and X-Ray SDKs Instrumenting your application with the AWS Distro for OpenTelemetry The AWS Distro for OpenTelemetry (ADOT) is an AWS distribution based on the Cloud Native Computing Foundation (CNCF) OpenTelemetry project. OpenTelemetry provides a single set of open source APIs, libraries, and agents to collect distributed traces and metrics. This toolkit is a distribution of upstream OpenTelemetry components including SDKs, auto-instrumentation agents, and collectors that are tested, optimized, secured, and supported by AWS. With ADOT, engineers can instrument their applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Instrumenting your application with the AWS Distro for OpenTelemetry 310 AWS X-Ray Developer Guide Using X-Ray with ADOT requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. For more information about using the AWS Distro for OpenTelemetry with AWS X-Ray and other AWS services, see the AWS Distro for OpenTelemetry Documentation. For more information about language support and usage, see AWS Observability on GitHub. Note You can now use the CloudWatch agent to collect metrics, logs and traces from Amazon EC2 instances and on-premise servers. CloudWatch agent version 1.300025.0 and later can collect traces from OpenTelemetry or X-Ray client SDKs, and send them to X-Ray. Using the CloudWatch agent instead of the AWS Distro for OpenTelemetry (ADOT) Collector or X-Ray daemon to collect traces can help you reduce the number of agents that you manage. See the CloudWatch agent topic in the CloudWatch User Guide for more information. ADOT includes the following: • AWS Distro for OpenTelemetry Go • AWS Distro for OpenTelemetry Java • AWS Distro for OpenTelemetry JavaScript • AWS Distro for OpenTelemetry Python • AWS Distro for OpenTelemetry .NET ADOT currently includes auto-instrumentation support for Java and Python. In addition, ADOT enables auto-instrumentation of AWS Lambda functions and their downstream requests using Java, Node.js, and Python runtimes, via ADOT Managed Lambda Layers. ADOT SDKs for Java and Go support X-Ray centralized sampling rules. If you need support for X- Ray sampling rules in other languages, consider using an AWS X-Ray SDK. Note You can send now send W3C trace IDs to X-Ray. By default, traces that are created with OpenTelemetry have a trace ID format that's based on the W3C Trace Context specification. This is different from the format for trace IDs that are created using an X-Ray SDK or by Instrumenting your application with the AWS Distro for OpenTelemetry 311 AWS X-Ray Developer Guide AWS services that are integrated with X-Ray. To ensure that trace IDs in W3C format are accepted by X-Ray, you must use AWS X-Ray Exporter version 0.86.0 or later, which is included with ADOT Collector version 0.34.0 and later. Previous versions of the exporter validate trace ID timestamps, which might cause W3C trace IDs to be rejected. Instrumenting your application with AWS X-Ray SDKs AWS X-Ray includes a set of language-specific SDKs for instrumenting your application to send traces to X-Ray. Each X-Ray SDK provides the following: • Interceptors to add to your code to trace incoming HTTP requests • Client handlers to instrument AWS SDK clients that your application uses to call other AWS services • An HTTP client to instrument calls to other internal and external HTTP web services X-Ray SDKs also support instrumenting calls to SQL databases, automatic AWS SDK client instrumentation, and other |
xray-guide-090 | xray-guide.pdf | 90 | timestamps, which might cause W3C trace IDs to be rejected. Instrumenting your application with AWS X-Ray SDKs AWS X-Ray includes a set of language-specific SDKs for instrumenting your application to send traces to X-Ray. Each X-Ray SDK provides the following: • Interceptors to add to your code to trace incoming HTTP requests • Client handlers to instrument AWS SDK clients that your application uses to call other AWS services • An HTTP client to instrument calls to other internal and external HTTP web services X-Ray SDKs also support instrumenting calls to SQL databases, automatic AWS SDK client instrumentation, and other features. Instead of sending trace data directly to X-Ray, the SDK sends JSON segment documents to a daemon process listening for UDP traffic. The X-Ray daemon buffers segments in a queue and uploads them to X-Ray in batches. The following language-specific SDKs are provided: • AWS X-Ray SDK for Go • AWS X-Ray SDK for Java • AWS X-Ray SDK for Node.js • AWS X-Ray SDK for Python • AWS X-Ray SDK for .NET • AWS X-Ray SDK for Ruby X-Ray currently includes auto-instrumentation support for Java. Instrumenting your application with AWS X-Ray SDKs 312 AWS X-Ray Developer Guide Choosing between the AWS Distro for OpenTelemetry and X- Ray SDKs The SDKs included with X-Ray are part of a tightly integrated instrumentation solution offered by AWS. The AWS Distro for OpenTelemetry is part of a broader industry solution in which X-Ray is only one of many tracing solutions. You can implement end-to-end tracing in X-Ray using either approach, but it’s important to understand the differences in order to determine the most useful approach for you. We recommend instrumenting your application with the AWS Distro for OpenTelemetry if you need the following: • The ability to send traces to multiple different tracing back ends without having to re-instrument your code • Support for a large number of library instrumentations for each language, maintained by the OpenTelemetry community • Fully managed Lambda layers that package everything you need to collect telemetry data, without requiring code changes when using Java, Python, or Node.js Note AWS Distro for OpenTelemetry offers a simpler getting started experience for instrumenting your Lambda functions. However, due to the flexibility OpenTelemetry offers, your Lambda function will require additional memory and invocations may experience cold start latency increases, which can lead to additional charges. If you're optimizing for low-latency and do not require OpenTelemetry's advanced capabilities such as dynamically configurable back end destinations, you may want to use the AWS X- Ray SDK to instrument your application. We recommend choosing an X-Ray SDK for instrumenting your application if you need the following: • A tightly integrated single-vendor solution • Integration with X-Ray centralized sampling rules, including the ability to configure sampling rules from the X-Ray console and automatically use them across multiple hosts, when using Node.js, Python, Ruby, or .NET Choosing between the AWS Distro for OpenTelemetry and X-Ray SDKs 313 AWS X-Ray Developer Guide Transaction Search Transaction Search is an interactive analytics experience you can use to get complete visibility of your application transaction spans. Spans are the fundamental units of operation in a distributed trace and represent specific actions or tasks in an application or system. Every span records details about a particular segment of the transaction. These details include start and end times, duration, and associated metadata, which can include business attributes like customer IDs and order IDs. Spans are arranged in a parent-child hierarchy. This heirarchy forms a complete trace mapping the flow of a transaction across different components or services. For more information, see Transaction Search. 314 AWS X-Ray Developer Guide OpenTelemetry Protocol (OTLP) Endpoint OpenTelemetry is an open-source observability framework that provides IT teams with standardized protocols and tools for collecting and routing telemetry data. It delivers a unified format for instrumenting, generating, gathering, and exporting application telemetry data, such as metrics, logs, and traces to monitoring platforms for analysis and insights. By using OpenTelemetry, teams can avoid vendor lock-in, ensuring flexibility in their observability solutions. You can use OpenTelemetry to directly send traces to an OpenTelemetry Protocol (OTLP) endpoint, and get out-of-the box application performance monitoring experiences in CloudWatch Application Signals. For more information, see OpenTelemetry. 315 AWS X-Ray Developer Guide Working with Go There are two ways to instrument your Go application to send traces to X-Ray: • AWS Distro for OpenTelemetry Go – An AWS distribution that provides a set of open source libraries for sending correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service, via the AWS Distro for OpenTelemetry Collector. • AWS X-Ray SDK for Go – A set of libraries for generating and sending traces to X-Ray via the X- Ray daemon. For more information, see Choosing between the |
xray-guide-091 | xray-guide.pdf | 91 | information, see OpenTelemetry. 315 AWS X-Ray Developer Guide Working with Go There are two ways to instrument your Go application to send traces to X-Ray: • AWS Distro for OpenTelemetry Go – An AWS distribution that provides a set of open source libraries for sending correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service, via the AWS Distro for OpenTelemetry Collector. • AWS X-Ray SDK for Go – A set of libraries for generating and sending traces to X-Ray via the X- Ray daemon. For more information, see Choosing between the AWS Distro for OpenTelemetry and X-Ray SDKs. AWS Distro for OpenTelemetry Go With the AWS Distro for OpenTelemetry Go, you can instrument your applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Using X-Ray with AWS Distro for OpenTelemetry requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. To get started, see the AWS Distro for OpenTelemetry Go documentation. For more information about using the AWS Distro for OpenTelemetry with AWS X-Ray and other AWS services, see AWS Distro for OpenTelemetry or the AWS Distro for OpenTelemetry Documentation. For more information about language support and usage, see AWS Observability on GitHub. AWS X-Ray SDK for Go The X-Ray SDK for Go is a set of libraries for Go applications that 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, HTTP clients, or an SQL database connector. You can also create segments manually and add debug information in annotations and metadata. AWS Distro for OpenTelemetry Go 316 AWS X-Ray Developer Guide Download the SDK from its GitHub repository with go get: $ go get -u github.com/aws/aws-xray-sdk-go/... For web applications, start by using the xray.Handler function to trace incoming requests. The message handler creates a segment for each traced request, and completes the segment when the response is sent. While the segment is open you can use the SDK client's methods to add information to the segment and create subsegments to trace downstream calls. The SDK also automatically records exceptions that your application throws while the segment is open. For Lambda functions called by an instrumented application or service, Lambda reads the tracing header and traces sampled requests automatically. For other functions, you can configure Lambda to sample and trace incoming requests. In either case, Lambda creates the segment and provides it to the X-Ray SDK. Note On Lambda, the X-Ray SDK is optional. If you don't use it in your function, your service map will still include a node for the Lambda service, and one for each Lambda function. By adding the SDK, you can instrument your function code to add subsegments to the function segment recorded by Lambda. See AWS Lambda and AWS X-Ray for more information. Next, wrap your client with a call to the AWS function. This step ensures that X-Ray instruments calls to any client methods. You can also instrument calls to SQL databases. After you start using the SDK, customize its behavior by configuring the recorder and middleware. You can add plugins to record data about the compute resources running your application, customize sampling behavior by defining sampling rules, and set the log level to see more or less information from the SDK in your application logs. Record additional information about requests and the work that your application does in annotations and metadata. Annotations are simple key-value pairs that are indexed for use with filter expressions, so that you can search for traces that contain specific data. Metadata entries are less restrictive and can record entire objects and arrays — anything that can be serialized into JSON. X-Ray SDK for Go 317 AWS X-Ray Developer Guide Annotations and Metadata Annotations and metadata are arbitrary text that you add to segments with the X-Ray SDK. Annotations are indexed for use with filter expressions. Metadata are not indexed, but can be viewed in the raw segment with the X-Ray console or API. Anyone that you grant read access to X-Ray can view this data. When you have a lot of instrumented clients in your code, a single request segment can contain a large number of subsegments, one for each call made with an instrumented client. You can organize and group subsegments by wrapping client calls in custom subsegments. You can create a custom subsegment for an entire function or any section of code, and record metadata and annotations on the subsegment instead of writing everything on the parent segment. Requirements The |
xray-guide-092 | xray-guide.pdf | 92 | viewed in the raw segment with the X-Ray console or API. Anyone that you grant read access to X-Ray can view this data. When you have a lot of instrumented clients in your code, a single request segment can contain a large number of subsegments, one for each call made with an instrumented client. You can organize and group subsegments by wrapping client calls in custom subsegments. You can create a custom subsegment for an entire function or any section of code, and record metadata and annotations on the subsegment instead of writing everything on the parent segment. Requirements The X-Ray SDK for Go requires Go 1.9 or later. The SDK depends on the following libraries at compile and runtime: • AWS SDK for Go version 1.10.0 or newer These dependencies are declared in the SDK's README.md file. Reference documentation Once you have downloaded the SDK, build and host the documentation locally to view it in a web browser. To view the reference documentation 1. Navigating to the $GOPATH/src/github.com/aws/aws-xray-sdk-go (Linux or Mac) directory or the %GOPATH%\src\github.com\aws\aws-xray-sdk-go (Windows) folder 2. Run the godoc command. $ godoc -http=:6060 3. Opening a browser at http://localhost:6060/pkg/github.com/aws/aws-xray-sdk- go/. Requirements 318 AWS X-Ray Developer Guide Configuring the X-Ray SDK for Go You can specify the configuration for X-Ray SDK for Go through environment variables, by calling Configure with a Config object, or by assuming default values. Environment variables take precedence over Config values, which take precedence over any default value. Sections • Service plugins • Sampling rules • Logging • Environment variables • Using configure Service plugins Use plugins to record information about the service hosting your application. Plugins • Amazon EC2 – EC2Plugin adds the instance ID, Availability Zone, and the CloudWatch Logs Group. • Elastic Beanstalk – ElasticBeanstalkPlugin adds the environment name, version label, and deployment ID. • Amazon ECS – ECSPlugin adds the container ID. Configuration 319 AWS X-Ray Developer Guide To use a plugin, import one of the following packages. "github.com/aws/aws-xray-sdk-go/awsplugins/ec2" "github.com/aws/aws-xray-sdk-go/awsplugins/ecs" "github.com/aws/aws-xray-sdk-go/awsplugins/beanstalk" Each plugin has an explicit Init() function call that loads the plugin. Example ec2.Init() import ( "os" "github.com/aws/aws-xray-sdk-go/awsplugins/ec2" "github.com/aws/aws-xray-sdk-go/xray" ) func init() { Configuration 320 AWS X-Ray Developer Guide // conditionally load plugin if os.Getenv("ENVIRONMENT") == "production" { ec2.Init() } xray.Configure(xray.Config{ ServiceVersion: "1.2.3", }) } The SDK also uses plugin settings to set the origin field on the segment. This indicates the type of AWS resource that runs your application. When you use multiple plugins, the SDK uses the following resolution order to determine the origin: ElasticBeanstalk > EKS > ECS > EC2. Sampling rules The SDK uses the sampling rules you define in the X-Ray console to determine which requests to record. The default rule traces the first request each second, and five percent of any additional requests across all services sending traces to X-Ray. Create additional rules in the X-Ray console to customize the amount of data recorded for each of your applications. The SDK applies custom rules in the order in which they are defined. If a request matches multiple custom rules, the SDK applies only the first rule. Note If the SDK can't reach X-Ray to get sampling rules, it reverts to a default local rule of the first request each second, and five percent of any additional requests per host. This can occur if the host doesn't have permission to call sampling APIs, or can't connect to the X- Ray daemon, which acts as a TCP proxy for API calls made by the SDK. You can also configure the SDK to load sampling rules from a JSON document. The SDK can use local rules as a backup for cases where X-Ray sampling is unavailable, or use local rules exclusively. Example sampling-rules.json { "version": 2, "rules": [ Configuration 321 Developer Guide AWS X-Ray { "description": "Player moves.", "host": "*", "http_method": "*", "url_path": "/api/move/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 } } This example defines one custom rule and a default rule. The custom rule applies a five-percent sampling rate with no minimum number of requests to trace for paths under /api/move/. The default rule traces the first request each second and 10 percent of additional requests. The disadvantage of defining rules locally is that the fixed target is applied by each instance of the recorder independently, instead of being managed by the X-Ray service. As you deploy more hosts, the fixed rate is multiplied, making it harder to control the amount of data recorded. On AWS Lambda, you cannot modify the sampling rate. If your function is called by an instrumented service, calls that generated requests that were sampled by that service will be recorded by Lambda. If active tracing is enabled and no tracing header is present, Lambda makes the sampling decision. To provide backup rules, point to |
xray-guide-093 | xray-guide.pdf | 93 | defining rules locally is that the fixed target is applied by each instance of the recorder independently, instead of being managed by the X-Ray service. As you deploy more hosts, the fixed rate is multiplied, making it harder to control the amount of data recorded. On AWS Lambda, you cannot modify the sampling rate. If your function is called by an instrumented service, calls that generated requests that were sampled by that service will be recorded by Lambda. If active tracing is enabled and no tracing header is present, Lambda makes the sampling decision. To provide backup rules, point to the local sampling JSON file by using NewCentralizedStrategyWithFilePath. Example main.go – Local sampling rule s, _ := sampling.NewCentralizedStrategyWithFilePath("sampling.json") // path to local sampling json xray.Configure(xray.Config{SamplingStrategy: s}) To use only local rules, point to the local sampling JSON file by using NewLocalizedStrategyFromFilePath. Configuration 322 AWS X-Ray Developer Guide Example main.go – Disable sampling s, _ := sampling.NewLocalizedStrategyFromFilePath("sampling.json") // path to local sampling json xray.Configure(xray.Config{SamplingStrategy: s}) Logging Note The xray.Config{} fields LogLevel and LogFormat are deprecated starting with version 1.0.0-rc.10. X-Ray uses the following interface for logging. The default logger writes to stdout at LogLevelInfo and above. type Logger interface { Log(level LogLevel, msg fmt.Stringer) } const ( LogLevelDebug LogLevel = iota + 1 LogLevelInfo LogLevelWarn LogLevelError ) Example write to io.Writer xray.SetLogger(xraylog.NewDefaultLogger(os.Stderr, xraylog.LogLevelError)) Environment variables You can use environment variables to configure the X-Ray SDK for Go. The SDK supports the following variables. • AWS_XRAY_CONTEXT_MISSING – Set to RUNTIME_ERROR to throw exceptions when your instrumented code attempts to record data when no segment is open. Configuration 323 AWS X-Ray Valid Values • RUNTIME_ERROR – Throw a runtime exception. • LOG_ERROR – Log an error and continue (default). • IGNORE_ERROR – Ignore error and continue. Developer Guide Errors related to missing segments or subsegments can occur when you attempt to use an instrumented client in startup code that runs when no request is open, or in code that spawns a new thread. • AWS_XRAY_TRACING_NAME – Set the service name that the SDK uses for segments. • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener. By default, the SDK sends trace data to 127.0.0.1:2000. Use this variable if you have configured the daemon to listen on a different port or if it is running on a different host. • AWS_XRAY_CONTEXT_MISSING – Set the value to determine how the SDK handles missing context errors. Errors related to missing segments or subsegments can occur when you attempt to use an instrumented client in the startup code when no request is open, or in code that spawns a new thread. • RUNTIME_ERROR – By default, the SDK is set to throw a runtime exception. • LOG_ERROR – Set to log an error and continue. Environment variables override equivalent values set in code. Using configure You can also configure the X-Ray SDK for Go using the Configure method. Configure takes one argument, a Config object, with the following, optional fields. DaemonAddr This string specifies the host and port of the X-Ray daemon listener. If not specified, X-Ray uses the value of the AWS_XRAY_DAEMON_ADDRESS environment variable. If that value is not set, it uses "127.0.0.1:2000". ServiceVersion This string specifies the version of the service. If not specified, X-Ray uses the empty string (""). Configuration 324 AWS X-Ray SamplingStrategy Developer Guide This SamplingStrategy object specifies which of your application calls are traced. If not specified, X-Ray uses a LocalizedSamplingStrategy, which takes the strategy as defined in xray/resources/DefaultSamplingRules.json. StreamingStrategy This StreamingStrategy object specifies whether to stream a segment when RequiresStreaming returns true. If not specified, X-Ray uses a DefaultStreamingStrategy that streams a sampled segment if the number of subsegments is greater than 20. ExceptionFormattingStrategy This ExceptionFormattingStrategy object specifies how you want to handle various exceptions. If not specified, X-Ray uses a DefaultExceptionFormattingStrategy with an XrayError of type error, the error message, and stack trace. Instrumenting incoming HTTP requests with the X-Ray SDK for Go You can use the X-Ray SDK to trace incoming HTTP requests that your application serves on an EC2 instance in Amazon EC2, AWS Elastic Beanstalk, or Amazon ECS. Use xray.Handler to instrument incoming HTTP requests. The X-Ray SDK for Go implements the standard Go library http.Handler interface in the xray.Handler class to intercept web requests. The xray.Handler class wraps the provided http.Handler with xray.Capture using the request's context, parsing the incoming headers, adding response headers if needed, and sets HTTP-specific trace fields. When you use this class to handle HTTP requests and responses, the X-Ray SDK for Go creates a segment for each sampled request. This segment includes timing, method, and disposition of the HTTP request. Additional instrumentation creates subsegments on this segment. Note For AWS Lambda functions, Lambda creates a segment for each sampled request. See AWS Lambda and AWS X-Ray |
xray-guide-094 | xray-guide.pdf | 94 | standard Go library http.Handler interface in the xray.Handler class to intercept web requests. The xray.Handler class wraps the provided http.Handler with xray.Capture using the request's context, parsing the incoming headers, adding response headers if needed, and sets HTTP-specific trace fields. When you use this class to handle HTTP requests and responses, the X-Ray SDK for Go creates a segment for each sampled request. This segment includes timing, method, and disposition of the HTTP request. Additional instrumentation creates subsegments on this segment. Note For AWS Lambda functions, Lambda creates a segment for each sampled request. See AWS Lambda and AWS X-Ray for more information. The following example intercepts requests on port 8000 and returns "Hello!" as a response. It creates the segment myApp and instruments calls through any application. Incoming requests 325 Developer Guide AWS X-Ray Example main.go func main() { http.Handle("/", xray.Handler(xray.NewFixedSegmentNamer("MyApp"), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello!")) }))) http.ListenAndServe(":8000", nil) } Each segment has a name that identifies your application in the service map. The segment can be named statically, or you can configure the SDK to name it dynamically based on the host header in the incoming request. Dynamic naming lets you group traces based on the domain name in the request, and apply a default name if the name doesn't match an expected pattern (for example, if the host header is forged). Forwarded Requests If a load balancer or other intermediary forwards a request to your application, X-Ray takes the client IP from the X-Forwarded-For header in the request instead of from the source IP in the IP packet. The client IP that is recorded for a forwarded request can be forged, so it should not be trusted. When a request is forwarded, the SDK sets an additional field in the segment to indicate this. If the segment contains the field x_forwarded_for set to true, the client IP was taken from the X- Forwarded-For header in the HTTP request. The handler creates a segment for each incoming request with an http block that contains the following information: • HTTP method – GET, POST, PUT, DELETE, etc. • Client address – The IP address of the client that sent the request. • Response code – The HTTP response code for the completed request. • Timing – The start time (when the request was received) and end time (when the response was sent). • User agent — The user-agent from the request. Incoming requests 326 AWS X-Ray Developer Guide • Content length — The content-length from the response. Configuring a segment naming strategy AWS X-Ray uses a service name to identify your application and distinguish it from the other applications, databases, external APIs, and AWS resources that your application uses. When the X- Ray SDK generates segments for incoming requests, it records your application's service name in the segment's name field. The X-Ray SDK can name segments after the hostname in the HTTP request header. However, this header can be forged, which could result in unexpected nodes in your service map. To prevent the SDK from naming segments incorrectly due to requests with forged host headers, you must specify a default name for incoming requests. If your application serves requests for multiple domains, you can configure the SDK to use a dynamic naming strategy to reflect this in segment names. A dynamic naming strategy allows the SDK to use the hostname for requests that match an expected pattern, and apply the default name to requests that don't. For example, you might have a single application serving requests to three subdomains– www.example.com, api.example.com, and static.example.com. You can use a dynamic naming strategy with the pattern *.example.com to identify segments for each subdomain with a different name, resulting in three service nodes on the service map. If your application receives requests with a hostname that doesn't match the pattern, you will see a fourth node on the service map with a fallback name that you specify. To use the same name for all request segments, specify the name of your application when you create the handler, as shown in the previous section. Note You can override the default service name that you define in code with the AWS_XRAY_TRACING_NAME environment variable. A dynamic naming strategy defines a pattern that hostnames should match, and a default name to use if the hostname in the HTTP request doesn't match the pattern. To name segments dynamically, use NewDynamicSegmentNamer to configure the default name and pattern to match. Incoming requests 327 AWS X-Ray Example main.go Developer Guide If the hostname in the request matches the pattern *.example.com, use the hostname. Otherwise, use MyApp. func main() { http.Handle("/", xray.Handler(xray.NewDynamicSegmentNamer("MyApp", "*.example.com"), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello!")) }))) http.ListenAndServe(":8000", nil) } Tracing AWS SDK calls with the X-Ray SDK for Go When your application makes calls to AWS |
xray-guide-095 | xray-guide.pdf | 95 | dynamic naming strategy defines a pattern that hostnames should match, and a default name to use if the hostname in the HTTP request doesn't match the pattern. To name segments dynamically, use NewDynamicSegmentNamer to configure the default name and pattern to match. Incoming requests 327 AWS X-Ray Example main.go Developer Guide If the hostname in the request matches the pattern *.example.com, use the hostname. Otherwise, use MyApp. func main() { http.Handle("/", xray.Handler(xray.NewDynamicSegmentNamer("MyApp", "*.example.com"), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello!")) }))) http.ListenAndServe(":8000", nil) } Tracing AWS SDK calls with the X-Ray SDK for Go When your application makes calls to AWS services to store data, write to a queue, or send notifications, the X-Ray SDK for Go tracks the calls downstream in subsegments. Traced AWS services and resources that you access within those services (for example, an Amazon S3 bucket or Amazon SQS queue), appear as downstream nodes on the trace map in the X-Ray console. To trace AWS SDK clients, wrap the client object with the xray.AWS() call as shown in the following example. Example main.go var dynamo *dynamodb.DynamoDB func main() { dynamo = dynamodb.New(session.Must(session.NewSession())) xray.AWS(dynamo.Client) } Then, when you use the AWS SDK client, use the withContext version of the call method, and pass it the context from the http.Request object passed to the handler. Example main.go – AWS SDK call func listTablesWithContext(ctx context.Context) { output := dynamo.ListTablesWithContext(ctx, &dynamodb.ListTablesInput{}) doSomething(output) AWS SDK clients 328 AWS X-Ray } Developer Guide For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a separate node in the service map, with a generic DynamoDB node for calls that don't target a table. Example Subsegment for a call to DynamoDB to save an item { "id": "24756640c0d0978a", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "DynamoDB", "namespace": "aws", "http": { "response": { "content_length": 60, "status": 200 } }, "aws": { "table_name": "scorekeep-user", "operation": "UpdateItem", "request_id": "UBQNSO5AEM8T4FDA4RQDEB94OVTDRVV4K4HIRGVJF66Q9ASUAAJG", } } When you access named resources, calls to the following services create additional nodes in the service map. Calls that don't target specific resources create a generic node for the service. • Amazon DynamoDB – Table name • Amazon Simple Storage Service – Bucket and key name • Amazon Simple Queue Service – Queue name AWS SDK clients 329 AWS X-Ray Developer Guide Tracing calls to downstream HTTP web services with the X-Ray SDK for Go When your application makes calls to microservices or public HTTP APIs, you can use the xray.Client to instrument those calls as subsegments of your Go application, as shown in the following example, where http-client is an HTTP client. The client creates a shallow copy of the provided HTTP client, defaulting to http.DefaultClient, with roundtripper wrapped with xray.RoundTripper. Example <caption>main.go – HTTP client</caption> myClient := xray.Client(http-client) <caption>main.go – Trace downstream HTTP call with ctxhttp library</caption> The following example instruments the outgoing HTTP call with the ctxhttp library using xray.Client. ctx can be passed from the upstream call. This ensures that the existing segment context is used. For example, X-Ray does not allow a new segment to be created within a Lambda function, so the existing Lambda segment context should be used. resp, err := ctxhttp.Get(ctx, xray.Client(nil), url) Tracing SQL queries with the X-Ray SDK for Go To trace SQL calls to PostgreSQL or MySQL, replacing sql.Open calls to xray.SQLContext, as shown in the following example. Use URLs instead of configuration strings if possible. Example main.go func main() { db, err := xray.SQLContext("postgres", "postgres://user:password@host:port/db") row, err := db.QueryRowContext(ctx, "SELECT 1") // Use as normal } Outgoing HTTP calls 330 AWS X-Ray Developer Guide Generating custom subsegments with the X-Ray SDK for Go Subsegments extend a trace's segment with details about work done in order to serve a request. Each time you make a call with an instrumented client, the X-Ray SDK records the information generated in a subsegment. You can create additional subsegments to group other subsegments, to measure the performance of a section of code, or to record annotations and metadata. Use the Capture method to create a subsegment around a function. Example main.go – Custom subsegment func criticalSection(ctx context.Context) { //this is an example of a subsegment xray.Capture(ctx, "GameModel.saveGame", func(ctx1 context.Context) error { var err error section.Lock() result := someLockedResource.Go() section.Unlock() xray.AddMetadata(ctx1, "ResourceResult", result) }) The following screenshot shows an example of how the saveGame subsegment might appear in traces for the application Scorekeep. Add annotations and metadata to segments with the X-Ray SDK for Go You can record additional information about requests, |
xray-guide-096 | xray-guide.pdf | 96 | other subsegments, to measure the performance of a section of code, or to record annotations and metadata. Use the Capture method to create a subsegment around a function. Example main.go – Custom subsegment func criticalSection(ctx context.Context) { //this is an example of a subsegment xray.Capture(ctx, "GameModel.saveGame", func(ctx1 context.Context) error { var err error section.Lock() result := someLockedResource.Go() section.Unlock() xray.AddMetadata(ctx1, "ResourceResult", result) }) The following screenshot shows an example of how the saveGame subsegment might appear in traces for the application Scorekeep. Add annotations and metadata to segments with the X-Ray SDK for Go You can record additional information about requests, the environment, or your application with annotations and metadata. You can add annotations and metadata to the segments that the X-Ray SDK creates, or to custom subsegments that you create. Custom subsegments 331 AWS X-Ray Developer Guide Annotations are key-value pairs with string, number, or Boolean values. Annotations are indexed for use with filter expressions. Use annotations to record data that you want to use to group traces in the console, or when calling the GetTraceSummaries API. Metadata are key-value pairs that can have values of any type, including objects and lists, but are not indexed for use with filter expressions. Use metadata to record additional data that you want stored in the trace but don't need to use with search. In addition to annotations and metadata, you can also record user ID strings on segments. User IDs are recorded in a separate field on segments and are indexed for use with search. Sections • Recording annotations with the X-Ray SDK for Go • Recording metadata with the X-Ray SDK for Go • Recording user IDs with the X-Ray SDK for Go Recording annotations with the X-Ray SDK for Go Use annotations to record information on segments that you want indexed for search. Annotation Requirements • Keys – The key for an X-Ray annotation can have up to 500 alphanumeric characters. You cannot use spaces or symbols other than a dot or period ( . ) • Values – The value for an X-Ray annotation can have up to 1,000 Unicode characters. • The number of Annotations – You can use up to 50 annotations per trace. To record annotations, call AddAnnotation with a string containing the metadata you want to associate with the segment. xray.AddAnnotation(key string, value interface{}) The SDK records annotations as key-value pairs in an annotations object in the segment document. Calling AddAnnotation twice with the same key overwrites previously recorded values on the same segment. To find traces that have annotations with specific values, use the annotation[key] keyword in a filter expression. Annotations and metadata 332 AWS X-Ray Developer Guide Recording metadata with the X-Ray SDK for Go Use metadata to record information on segments that you don't need indexed for search. To record metadata, call AddMetadata with a string containing the metadata you want to associate with the segment. xray.AddMetadata(key string, value interface{}) Recording user IDs with the X-Ray SDK for Go Record user IDs on request segments to identify the user who sent the request. To record user IDs 1. Get a reference to the current segment from AWSXRay. import ( "context" "github.com/aws/aws-xray-sdk-go/xray" ) mySegment := xray.GetSegment(context) 2. Call setUser with a String ID of the user who sent the request. mySegment.User = "U12345" To find traces for a user ID, use the user keyword in a filter expression. Annotations and metadata 333 AWS X-Ray Developer Guide Working with Java There are two ways to instrument your Java application to send traces to X-Ray: • AWS Distro for OpenTelemetry Java – An AWS distribution that provides a set of open source libraries for sending correlated metrics and traces to multiple AWS monitoring solutions, including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service, via the AWS Distro for OpenTelemetry Collector. • AWS X-Ray SDK for Java – A set of libraries for generating and sending traces to X-Ray via the X- Ray daemon. For more information, see Choosing between the AWS Distro for OpenTelemetry and X-Ray SDKs. AWS Distro for OpenTelemetry Java With the AWS Distro for OpenTelemetry (ADOT) Java, you can instrument your applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Using X-Ray with ADOT requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. ADOT Java includes auto-instrumentation support, enabling your application to send traces without code changes. To get started, see the AWS Distro for OpenTelemetry Java documentation. For more information about using the AWS Distro for OpenTelemetry with AWS X-Ray and other AWS services, see AWS Distro for OpenTelemetry or the AWS Distro for OpenTelemetry Documentation. For more information about language support and usage, |
xray-guide-097 | xray-guide.pdf | 97 | monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Using X-Ray with ADOT requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. ADOT Java includes auto-instrumentation support, enabling your application to send traces without code changes. To get started, see the AWS Distro for OpenTelemetry Java documentation. For more information about using the AWS Distro for OpenTelemetry with AWS X-Ray and other AWS services, see AWS Distro for OpenTelemetry or the AWS Distro for OpenTelemetry Documentation. For more information about language support and usage, see AWS Observability on GitHub. AWS X-Ray SDK for Java The X-Ray SDK for Java is a set of libraries for Java web applications that 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, HTTP clients, or an SQL database connector. You can also create segments manually and add debug information in annotations and metadata. AWS Distro for OpenTelemetry Java 334 AWS X-Ray Developer Guide The X-Ray SDK for Java is an open source project. You can follow the project and submit issues and pull requests on GitHub: github.com/aws/aws-xray-sdk-java Start by adding AWSXRayServletFilter as a servlet filter to trace incoming requests. A servlet filter creates a segment. While the segment is open, you can use the SDK client's methods to add information to the segment and create subsegments to trace downstream calls. The SDK also automatically records exceptions that your application throws while the segment is open. Starting in release 1.3, you can instrument your application using aspect-oriented programming (AOP) in Spring. What this means is that you can instrument your application, while it is running on AWS, without adding any code to your application's runtime. Next, use the X-Ray SDK for Java to instrument your AWS SDK for Java clients by including the SDK Instrumentor submodule in your build configuration. Whenever you make a call to a downstream AWS service or resource with an instrumented client, the SDK records information about the call in a subsegment. AWS services and the resources that you access within the services appear as downstream nodes on the trace map to help you identify errors and throttling issues on individual connections. If you don't want to instrument all downstream calls to AWS services, you can leave out the Instrumentor submodule and choose which clients to instrument. Instrument individual clients by adding a TracingHandler to an AWS SDK service client. Other X-Ray SDK for Java submodules provide instrumentation for downstream calls to HTTP web APIs and SQL databases. You can use the X-Ray SDK for Java versions of HTTPClient and HTTPClientBuilder in the Apache HTTP submodule to instrument Apache HTTP clients. To instrument SQL queries, add the SDK's interceptor to your data source. After you start using the SDK, customize its behavior by configuring the recorder and servlet filter. You can add plugins to record data about the compute resources running your application, customize sampling behavior by defining sampling rules, and set the log level to see more or less information from the SDK in your application logs. Record additional information about requests and the work that your application does in annotations and metadata. Annotations are simple key-value pairs that are indexed for use with filter expressions, so that you can search for traces that contain specific data. Metadata entries are less restrictive and can record entire objects and arrays — anything that can be serialized into JSON. X-Ray SDK for Java 335 AWS X-Ray Developer Guide Annotations and Metadata Annotations and metadata are arbitrary text that you add to segments with the X-Ray SDK. Annotations are indexed for use with filter expressions. Metadata are not indexed, but can be viewed in the raw segment with the X-Ray console or API. Anyone that you grant read access to X-Ray can view this data. When you have a lot of instrumented clients in your code, a single request segment can contain many subsegments, one for each call made with an instrumented client. You can organize and group subsegments by wrapping client calls in custom subsegments. You can create a custom subsegment for an entire function or any section of code, and record metadata and annotations on the subsegment instead of writing everything on the parent segment. Submodules You can download the X-Ray SDK for Java from Maven. The X-Ray SDK for Java is split into submodules by use case, with a bill of materials for version management: • aws-xray-recorder-sdk-core (required) – Basic functionality for creating segments and transmitting segments. Includes AWSXRayServletFilter for instrumenting incoming requests. • aws-xray-recorder-sdk-aws-sdk – Instruments calls to AWS services made with AWS |
xray-guide-098 | xray-guide.pdf | 98 | group subsegments by wrapping client calls in custom subsegments. You can create a custom subsegment for an entire function or any section of code, and record metadata and annotations on the subsegment instead of writing everything on the parent segment. Submodules You can download the X-Ray SDK for Java from Maven. The X-Ray SDK for Java is split into submodules by use case, with a bill of materials for version management: • aws-xray-recorder-sdk-core (required) – Basic functionality for creating segments and transmitting segments. Includes AWSXRayServletFilter for instrumenting incoming requests. • aws-xray-recorder-sdk-aws-sdk – Instruments calls to AWS services made with AWS SDK for Java clients by adding a tracing client as a request handler. • aws-xray-recorder-sdk-aws-sdk-v2 – Instruments calls to AWS services made with AWS SDK for Java 2.2 and later clients by adding a tracing client as a request intereceptor. • aws-xray-recorder-sdk-aws-sdk-instrumentor – With aws-xray-recorder-sdk- aws-sdk, instruments all AWS SDK for Java clients automatically. • aws-xray-recorder-sdk-aws-sdk-v2-instrumentor – With aws-xray-recorder-sdk- aws-sdk-v2, instruments all AWS SDK for Java 2.2 and later clients automatically. • aws-xray-recorder-sdk-apache-http – Instruments outbound HTTP calls made with Apache HTTP clients. • aws-xray-recorder-sdk-spring – Provides interceptors for Spring AOP Framework applications. • aws-xray-recorder-sdk-sql-postgres – Instruments outbound calls to a PostgreSQL database made with JDBC. Submodules 336 AWS X-Ray Developer Guide • aws-xray-recorder-sdk-sql-mysql – Instruments outbound calls to a MySQL database made with JDBC. • aws-xray-recorder-sdk-bom – Provides a bill of materials that you can use to specify the version to use for all submodules. • aws-xray-recorder-sdk-metrics – Publish unsampled Amazon CloudWatch metrics from your collected X-Ray segments. If you use Maven or Gradle to build your application, add the X-Ray SDK for Java to your build configuration. For reference documentation of the SDK's classes and methods, see AWS X-Ray SDK for Java API Reference. Requirements The X-Ray SDK for Java requires Java 8 or later, Servlet API 3, the AWS SDK, and Jackson. The SDK depends on the following libraries at compile and runtime: • AWS SDK for Java version 1.11.398 or later • Servlet API 3.1.0 These dependencies are declared in the SDK's pom.xml file and are included automatically if you build using Maven or Gradle. If you use a library that is included in the X-Ray SDK for Java, you must use the included version. For example, if you already depend on Jackson at runtime and include JAR files in your deployment for that dependency, you must remove those JAR files because the SDK JAR includes its own versions of Jackson libraries. Dependency management The X-Ray SDK for Java is available from Maven: • Group – com.amazonaws • Artifact – aws-xray-recorder-sdk-bom • Version – 2.11.0 Requirements 337 AWS X-Ray Developer Guide If you use Maven to build your application, add the SDK as a dependency in your pom.xml file. Example pom.xml - dependencies <dependencyManagement> <dependencies> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-bom</artifactId> <version>2.11.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-core</artifactId> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-apache-http</artifactId> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-aws-sdk</artifactId> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-aws-sdk-instrumentor</artifactId> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-sql-postgres</artifactId> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-sql-mysql</artifactId> </dependency> </dependencies> For Gradle, add the SDK as a compile-time dependency in your build.gradle file. Dependency management 338 AWS X-Ray Developer Guide Example build.gradle - dependencies dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile("org.springframework.boot:spring-boot-starter-test") compile("com.amazonaws:aws-java-sdk-dynamodb") compile("com.amazonaws:aws-xray-recorder-sdk-core") compile("com.amazonaws:aws-xray-recorder-sdk-aws-sdk") compile("com.amazonaws:aws-xray-recorder-sdk-aws-sdk-instrumentor") compile("com.amazonaws:aws-xray-recorder-sdk-apache-http") compile("com.amazonaws:aws-xray-recorder-sdk-sql-postgres") compile("com.amazonaws:aws-xray-recorder-sdk-sql-mysql") testCompile("junit:junit:4.11") } dependencyManagement { imports { mavenBom('com.amazonaws:aws-java-sdk-bom:1.11.39') mavenBom('com.amazonaws:aws-xray-recorder-sdk-bom:2.11.0') } } If you use Elastic Beanstalk to deploy your application, you can use Maven or Gradle to build on- instance each time you deploy, instead of building and uploading a large archive that includes all of your dependencies. See the sample application for an example that uses Gradle. AWS X-Ray auto-instrumentation agent for Java The AWS X-Ray auto-instrumentation agent for Java is a tracing solution that instruments your Java web applications with minimal development effort. The agent enables tracing for servlet- based applications and all of the agent's downstream requests made with supported frameworks and libraries. This includes downstream Apache HTTP requests, AWS SDK requests, and SQL queries made using a JDBC driver. The agent propagates X-Ray context, including all active segments and subsegments, across threads. All of the configurations and versatility of the X-Ray SDK are still available with the Java agent. Suitable defaults were chosen to ensure that the agent works with minimal effort. The X-Ray agent solution is best suited for servlet-based, request-response Java web application servers. If your application uses an asynchronous framework, or is not well modeled as a request- response service, you might want to consider manual instrumentation with the SDK instead. Auto-instrumentation agent 339 AWS X-Ray Developer Guide The X-Ray agent is built using the Distributed Systems Comprehension toolkit, or DiSCo. DiSCo is an open source framework for building Java agents that can be used in distributed systems. While it is not necessary to understand DiSCo to use the X-Ray agent, you can learn more |
xray-guide-099 | xray-guide.pdf | 99 | works with minimal effort. The X-Ray agent solution is best suited for servlet-based, request-response Java web application servers. If your application uses an asynchronous framework, or is not well modeled as a request- response service, you might want to consider manual instrumentation with the SDK instead. Auto-instrumentation agent 339 AWS X-Ray Developer Guide The X-Ray agent is built using the Distributed Systems Comprehension toolkit, or DiSCo. DiSCo is an open source framework for building Java agents that can be used in distributed systems. While it is not necessary to understand DiSCo to use the X-Ray agent, you can learn more about the project by visiting its homepage on GitHub. The X-Ray agent is also fully open-sourced. To view the source code, make contributions, or raise issues about the agent, visit its repository on GitHub. Sample application The eb-java-scorekeep sample application is adapted to be instrumented with the X-Ray agent. This branch contains no servlet filter or recorder configuration, as these functions are done by the agent. To run the application locally or using AWS resources, follow the steps in the sample application's readme file. The instructions for using the sample app to generate X-Ray traces are in the sample app’s tutorial. Getting started To get started with the X-Ray auto-instrumentation Java agent in your own application, follow these steps. 1. Run the X-Ray daemon in your environment. For more information, see AWS X-Ray daemon. 2. Download the latest distribution of the agent. Unzip the archive and note its location in your file system. Its contents should look like the following. disco ### disco-java-agent.jar ### disco-plugins ### aws-xray-agent-plugin.jar ### disco-java-agent-aws-plugin.jar ### disco-java-agent-sql-plugin.jar ### disco-java-agent-web-plugin.jar 3. Modify the JVM arguments of your application to include the following, which enables the agent. Ensure the -javaagent argument is placed before the -jar argument if applicable. The process to modify JVM arguments varies depending on the tools and frameworks you use to launch your Java server. Consult the documentation of your server framework for specific guidance. -javaagent:/<path-to-disco>/disco-java-agent.jar=pluginPath=/<path-to-disco>/disco- plugins Auto-instrumentation agent 340 AWS X-Ray Developer Guide 4. To specify how the name of your application appears on the X-Ray console, set the AWS_XRAY_TRACING_NAME environment variable or the com.amazonaws.xray.strategy.tracingName system property. If no name is provided, a default name is used. 5. Restart your server or container. Incoming requests and their downstream calls are now traced. If you don’t see the expected results, see the section called “Troubleshooting”. Configuration The X-Ray agent is configured by an external, user-provided JSON file. By default, this file is at the root of the user’s classpath (for example, in their resources directory) named xray- agent.json. You can configure a custom location for the config file by setting the com.amazonaws.xray.configFile system property to the absolute filesystem path of your configuration file. An example configuration file is shown next. { "serviceName": "XRayInstrumentedService", "contextMissingStrategy": "LOG_ERROR", "daemonAddress": "127.0.0.1:2000", "tracingEnabled": true, "samplingStrategy": "CENTRAL", "traceIdInjectionPrefix": "prefix", "samplingRulesManifest": "/path/to/manifest", "awsServiceHandlerManifest": "/path/to/manifest", "awsSdkVersion": 2, "maxStackTraceLength": 50, "streamingThreshold": 100, "traceIdInjection": true, "pluginsEnabled": true, "collectSqlQueries": false } Configuration specification The following table describes valid values for each property. Property names are case sensitive, but their keys are not. For properties that can be overridden by environment variables and system properties, the order of priority is always environment variable, then system property, and then Auto-instrumentation agent 341 AWS X-Ray Developer Guide configuration file. For information about properties that you can override, see Environment variables. All fields are optional. Property name serviceNa me contextMi ssingStra tegy Type Valid values Descripti on Environme nt variable System property Default String Any string The name of your AWS_XRAY_ TRACING_N com.amazo naws.xray XRayInstr umentedSe instrumen AME .strategy rvice .tracingN ame ted service as it will appear in the X-Ray console. String LOG_ERROR , The action taken by AWS_XRAY_ CONTEXT_M com.amazo naws.xray LOG_ERROR IGNORE_ER the agent ISSING .strategy .contextM issingStr ategy daemonAdd ress String ROR Formatted IP address and port, or list of TCP and UDP address when it attempts to use the X-Ray segment context but none is present. The address the agent uses to communica te with the X-Ray daemon. 127.0.0.1 :2000 AWS_XRAY_ DAEMON_AD DRESS com.amazo naws.xray .emitter. daemonAdd ress Auto-instrumentation agent 342 AWS X-Ray Property name tracingEn abled Developer Guide Type Valid values Descripti on Environme nt variable System property Default Boolean True, False Enables instrumen AWS_XRAY_ TRACING_E com.amazo naws.xray TRUE tation by NABLED .tracingE the X-Ray agent. nabled samplingS trategy String CENTRAL, LOCAL, The sampling NONE, ALL strategy N/A N/A CENTRAL used by the agent. ALL captures all requests, NONE captures no requests. See sampling rules. Includes the provided prefix before injected trace IDs in logs. N/A N/A None (empty string) String Any string traceIdIn jectionPr efix Auto-instrumentation agent 343 AWS X-Ray Developer Guide Property name Type Valid values Descripti on Environme nt variable System property Default N/A N/A DefaultSa mplingRul es.json N/A N/A |
xray-guide-100 | xray-guide.pdf | 100 | Environme nt variable System property Default Boolean True, False Enables instrumen AWS_XRAY_ TRACING_E com.amazo naws.xray TRUE tation by NABLED .tracingE the X-Ray agent. nabled samplingS trategy String CENTRAL, LOCAL, The sampling NONE, ALL strategy N/A N/A CENTRAL used by the agent. ALL captures all requests, NONE captures no requests. See sampling rules. Includes the provided prefix before injected trace IDs in logs. N/A N/A None (empty string) String Any string traceIdIn jectionPr efix Auto-instrumentation agent 343 AWS X-Ray Developer Guide Property name Type Valid values Descripti on Environme nt variable System property Default N/A N/A DefaultSa mplingRul es.json N/A N/A DefaultOp erationPa rameterWh itelist.json String samplingR ulesManif est An absolute file path String awsServic eHandlerM anifest An absolute file path The path to a custom sampling rules file to be used as the source of sampling rules for the local sampling strategy, or the fallback rules for the central strategy. The path to a custom parameter allow list, which captures additiona l informati on from AWS SDK clients. Auto-instrumentation agent 344 AWS X-Ray Developer Guide Property name Type Valid values Descripti on Environme nt variable System property Default awsSdkVer sion Integer 1, 2 maxStackT raceLength Integer streaming Threshold Integer Non- negative integers Non- negative integers N/A N/A 2 N/A N/A 50 N/A N/A 100 Version of the AWS SDK for Java you’re using. Ignored if awsServic eHandlerM anifest is not also set. The maximum lines of a stack trace to record in a trace. After at least this many subsegmen ts are closed, they are streamed to the daemon out-of-ba nd to avoid chunks being too large. Auto-instrumentation agent 345 AWS X-Ray Property name traceIdIn jection Type Valid values Descripti on Environme nt variable System property Default Developer Guide Boolean True, False N/A N/A TRUE N/A N/A TRUE Enables X- Ray trace ID injection into logs if the dependenc ies and configura tion described in logging config are also added. Otherwise , does nothing. Enables plugins that record metadata about the AWS environme nts you’re operating in. See plugins. pluginsEn abled Boolean True, False Auto-instrumentation agent 346 AWS X-Ray Property name collectSq lQueries Type Valid values Descripti on Environme nt variable System property Default Developer Guide Boolean True, False contextPr opagation Boolean True, False N/A N/A FALSE N/A N/A TRUE Records SQL query strings in SQL subsegmen ts on a best-effort basis. Automatic ally propagate s X-Ray context between threads if true. Otherwise , uses Thread Local to store context and manual propagati on across threads is required. Logging configuration The X-Ray agent's log level can be configured in the same way as the X-Ray SDK for Java. See Logging for more information on configuring logging with the X-Ray SDK for Java. Auto-instrumentation agent 347 AWS X-Ray Manual instrumentation Developer Guide If you’d like to perform manual instrumentation in addition to the agent’s auto-instrumentation, add the X-Ray SDK as a dependency to your project. Note that the SDK's custom servlet filters mentioned in Tracing Incoming Requests are not compatible with the X-Ray agent. Note You must use the latest version of the X-Ray SDK to perform manual instrumentation while also using the agent. If you are working in a Maven project, add the following dependencies to your pom.xml file. <dependencies> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-core</artifactId> <version>2.11.0</version> </dependency> </dependencies> If you are working in a Gradle project, add the following dependencies to your build.gradle file. implementation 'com.amazonaws:aws-xray-recorder-sdk-core:2.11.0' You can add custom subsegments in addition to annotations, metadata, and user IDs while using the agent, just as you would with the normal SDK. The agent automatically propagates context across threads, so no workarounds to propagate context should be necessary when working with multithreaded applications. Troubleshooting Since the agent offers fully automatic instrumentation, it can be difficult to identify the root cause of a problem when you are experiencing issues. If the X-Ray agent is not working as expected for you, review the following problems and solutions. The X-Ray agent and SDK use Jakarta Commons Logging (JCL). To see the logging output, ensure that a bridge connecting JCL to your logging backend is on the classpath, as in the following example: log4j-jcl or jcl-over-slf4j. Auto-instrumentation agent 348 AWS X-Ray Developer Guide Problem: I’ve enabled the Java agent on my application but don’t see anything on the X-Ray console Is the X-Ray daemon running on the same machine? If not, see the X-Ray daemon documentation to set it up. In your application logs, do you see a message like "Initializing the X-Ray agent recorder"? If you have correctly added the agent to your application, this message is logged at INFO level when your application starts, before it starts taking requests. If this message is not there, then the Java agent is not running with your Java process. Make sure you’ve followed all the setup steps correctly |
xray-guide-101 | xray-guide.pdf | 101 | Java agent on my application but don’t see anything on the X-Ray console Is the X-Ray daemon running on the same machine? If not, see the X-Ray daemon documentation to set it up. In your application logs, do you see a message like "Initializing the X-Ray agent recorder"? If you have correctly added the agent to your application, this message is logged at INFO level when your application starts, before it starts taking requests. If this message is not there, then the Java agent is not running with your Java process. Make sure you’ve followed all the setup steps correctly with no typos. In your application logs, do you see several error messages saying something like "Suppressing AWS X-Ray context missing exception"? These errors occur because the agent is trying to instrument downstream requests, like AWS SDK requests or SQL queries, but the agent was unable to automatically create a segment. If you see many of these errors, the agent might not be the best tool for your use case and you might want to consider manual instrumentation with the X-Ray SDK instead. Alternatively, you can enable X-Ray SDK debug logs to see the stack trace of where the context-missing exceptions are occurring. You can wrap these portions of your code with custom segments, which should resolve these errors. For an example of wrapping downstream requests with custom segments, see the sample code in instrumenting startup code. Problem: Some of the segments I expect do not appear on the X-Ray console Does your application use multithreading? If some segments that you expect to be created are not appearing in your console, background threads in your application might be the cause. If your application performs tasks using background threads that are “fire and forget,” like making a one-off call to a Lambda function with the AWS SDK, or polling some HTTP endpoint periodically, that may confuse the agent while it is propagating context across threads. To verify this is your problem, enable X-Ray SDK debug logs and check for messages like: Not emitting segment named <NAME > as it parents in- progress subsegments. To work around this, you can try joining the background threads before your server returns to ensure all the work done in them is recorded. Or, you can set the agent’s contextPropagation configuration to false to disable context propagation in background threads. If you do this, you’ll have to manually instrument those threads with custom segments or ignore the context missing exceptions they produce. Auto-instrumentation agent 349 AWS X-Ray Developer Guide Have you set up sampling rules? If there are seemingly random or unexpected segments appearing on the X-Ray console, or the segments you expect to be on the console aren’t, you might be experiencing a sampling issue. The X-Ray agent applies centralized sampling to all segments it creates, using the rules from the X-Ray console. The default rule is 1 segment per second, plus 5% of segments afterward, are sampled. This means segments that are created rapidly with the agent might not be sampled. To resolve this, you should create custom sampling rules on the X-Ray console that appropriately sample the desired segments. For more information, see sampling. Configuring the X-Ray SDK for Java The X-Ray SDK for Java includes a class named AWSXRay that provides the global recorder. This is a TracingHandler that you can use to instrument your code. You can configure the global recorder to customize the AWSXRayServletFilter that creates segments for incoming HTTP calls. Sections • Service plugins • Sampling rules • Logging • Segment listeners • Environment variables • System properties Service plugins Use plugins to record information about the service hosting your application. Plugins • Amazon EC2 – EC2Plugin adds the instance ID, Availability Zone, and the CloudWatch Logs Group. • Elastic Beanstalk – ElasticBeanstalkPlugin adds the environment name, version label, and deployment ID. • Amazon ECS – ECSPlugin adds the container ID. • Amazon EKS – EKSPlugin adds the container ID, cluster name, pod ID, and the CloudWatch Logs Group. Configuration 350 AWS X-Ray Developer Guide To use a plugin, call withPlugin on your AWSXRayRecorderBuilder. Example src/main/java/scorekeep/WebConfig.java - recorder import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorderBuilder; import com.amazonaws.xray.plugins.EC2Plugin; import com.amazonaws.xray.plugins.ElasticBeanstalkPlugin; import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy; @Configuration public class WebConfig { ... static { AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard().withPlugin(new EC2Plugin()).withPlugin(new ElasticBeanstalkPlugin()); Configuration 351 AWS X-Ray Developer Guide URL ruleFile = WebConfig.class.getResource("/sampling-rules.json"); builder.withSamplingStrategy(new LocalizedSamplingStrategy(ruleFile)); AWSXRay.setGlobalRecorder(builder.build()); } } The SDK also uses plugin settings to set the origin field on the segment. This indicates the type of AWS resource that runs your application. When you use multiple plugins, the SDK uses the following resolution order to determine the origin: ElasticBeanstalk > EKS > ECS > EC2. Sampling rules The SDK uses the sampling rules you define in the X-Ray console to determine which requests to record. The default rule traces |
xray-guide-102 | xray-guide.pdf | 102 | public class WebConfig { ... static { AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard().withPlugin(new EC2Plugin()).withPlugin(new ElasticBeanstalkPlugin()); Configuration 351 AWS X-Ray Developer Guide URL ruleFile = WebConfig.class.getResource("/sampling-rules.json"); builder.withSamplingStrategy(new LocalizedSamplingStrategy(ruleFile)); AWSXRay.setGlobalRecorder(builder.build()); } } The SDK also uses plugin settings to set the origin field on the segment. This indicates the type of AWS resource that runs your application. When you use multiple plugins, the SDK uses the following resolution order to determine the origin: ElasticBeanstalk > EKS > ECS > EC2. Sampling rules The SDK uses the sampling rules you define in the X-Ray console to determine which requests to record. The default rule traces the first request each second, and five percent of any additional requests across all services sending traces to X-Ray. Create additional rules in the X-Ray console to customize the amount of data recorded for each of your applications. The SDK applies custom rules in the order in which they are defined. If a request matches multiple custom rules, the SDK applies only the first rule. Note If the SDK can't reach X-Ray to get sampling rules, it reverts to a default local rule of the first request each second, and five percent of any additional requests per host. This can occur if the host doesn't have permission to call sampling APIs, or can't connect to the X- Ray daemon, which acts as a TCP proxy for API calls made by the SDK. You can also configure the SDK to load sampling rules from a JSON document. The SDK can use local rules as a backup for cases where X-Ray sampling is unavailable, or use local rules exclusively. Example sampling-rules.json { "version": 2, "rules": [ { "description": "Player moves.", "host": "*", Configuration 352 AWS X-Ray Developer Guide "http_method": "*", "url_path": "/api/move/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 } } This example defines one custom rule and a default rule. The custom rule applies a five-percent sampling rate with no minimum number of requests to trace for paths under /api/move/. The default rule traces the first request each second and 10 percent of additional requests. The disadvantage of defining rules locally is that the fixed target is applied by each instance of the recorder independently, instead of being managed by the X-Ray service. As you deploy more hosts, the fixed rate is multiplied, making it harder to control the amount of data recorded. On AWS Lambda, you cannot modify the sampling rate. If your function is called by an instrumented service, calls that generated requests that were sampled by that service will be recorded by Lambda. If active tracing is enabled and no tracing header is present, Lambda makes the sampling decision. To provide backup rules in Spring, configure the global recorder with a CentralizedSamplingStrategy in a configuration class. Example src/main/java/myapp/WebConfig.java - recorder configuration import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorderBuilder; import com.amazonaws.xray.javax.servlet.AWSXRayServletFilter; import com.amazonaws.xray.plugins.EC2Plugin; import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy; @Configuration public class WebConfig { static { AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard().withPlugin(new EC2Plugin()); Configuration 353 AWS X-Ray Developer Guide URL ruleFile = WebConfig.class.getResource("/sampling-rules.json"); builder.withSamplingStrategy(new CentralizedSamplingStrategy(ruleFile)); AWSXRay.setGlobalRecorder(builder.build()); } For Tomcat, add a listener that extends ServletContextListener and register the listener in the deployment descriptor. Example src/com/myapp/web/Startup.java import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorderBuilder; import com.amazonaws.xray.plugins.EC2Plugin; import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy; import java.net.URL; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class Startup implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent event) { AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard().withPlugin(new EC2Plugin()); URL ruleFile = Startup.class.getResource("/sampling-rules.json"); builder.withSamplingStrategy(new CentralizedSamplingStrategy(ruleFile)); AWSXRay.setGlobalRecorder(builder.build()); } @Override public void contextDestroyed(ServletContextEvent event) { } } Example WEB-INF/web.xml ... <listener> <listener-class>com.myapp.web.Startup</listener-class> Configuration 354 AWS X-Ray </listener> Developer Guide To use local rules only, replace the CentralizedSamplingStrategy with a LocalizedSamplingStrategy. builder.withSamplingStrategy(new LocalizedSamplingStrategy(ruleFile)); Logging By default, the SDK outputs ERROR-level messages to your application logs. You can enable debug- level logging on the SDK to output more detailed logs to your application log file. Valid log levels are DEBUG, INFO, WARN, ERROR, and FATAL. FATAL log level silences all log messages because the SDK does not log at fatal level. Example application.properties Set the logging level with the logging.level.com.amazonaws.xray property. logging.level.com.amazonaws.xray = DEBUG Use debug logs to identify issues, such as unclosed subsegments, when you generate subsegments manually. Trace ID injection into logs To expose the current fully qualified trace ID to your log statements, you can inject the ID into the mapped diagnostic context (MDC). Using the SegmentListener interface, methods are called from the X-Ray recorder during segment lifecycle events. When a segment or subsegment begins, the qualified trace ID is injected into the MDC with the key AWS-XRAY-TRACE-ID. When that segment ends, the key is removed from the MDC. This exposes the trace ID to the logging library in use. When a subsegment ends, its parent ID is injected into the MDC. Example fully qualified trace ID The fully qualified ID is represented as TraceID@EntityID 1-5df42873-011e96598b447dfca814c156@541b3365be3dafc3 This feature works with Java applications instrumented with the AWS X-Ray |
xray-guide-103 | xray-guide.pdf | 103 | ID into the mapped diagnostic context (MDC). Using the SegmentListener interface, methods are called from the X-Ray recorder during segment lifecycle events. When a segment or subsegment begins, the qualified trace ID is injected into the MDC with the key AWS-XRAY-TRACE-ID. When that segment ends, the key is removed from the MDC. This exposes the trace ID to the logging library in use. When a subsegment ends, its parent ID is injected into the MDC. Example fully qualified trace ID The fully qualified ID is represented as TraceID@EntityID 1-5df42873-011e96598b447dfca814c156@541b3365be3dafc3 This feature works with Java applications instrumented with the AWS X-Ray SDK for Java, and supports the following logging configurations: Configuration 355 AWS X-Ray Developer Guide • SLF4J front-end API with Logback backend • SLF4J front-end API with Log4J2 backend • Log4J2 front-end API with Log4J2 backend See the following tabs for the needs of each front end and each backend. SLF4J Frontend 1. Add the following Maven dependency to your project. <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-slf4j</artifactId> <version>2.11.0</version> </dependency> 2. Include the withSegmentListener method when building the AWSXRayRecorder. This adds a SegmentListener class, which automatically injects new trace IDs into the SLF4J MDC. The SegmentListener takes an optional string as a parameter to configure the log statement prefix. The prefix can be configured in the following ways: • None – Uses the default AWS-XRAY-TRACE-ID prefix. • Empty – Uses an empty string (e.g. ""). • Custom – Uses a custom prefix as defined in the string. Example AWSXRayRecorderBuilder statement AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder .standard().withSegmentListener(new SLF4JSegmentListener("CUSTOM- PREFIX")); Log4J2 front end 1. Add the following Maven dependency to your project. <dependency> Configuration 356 AWS X-Ray Developer Guide <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-log4j</artifactId> <version>2.11.0</version> </dependency> 2. Include the withSegmentListener method when building the AWSXRayRecorder. This will add a SegmentListener class, which automatically injects new fully qualified trace IDs into the SLF4J MDC. The SegmentListener takes an optional string as a parameter to configure the log statement prefix. The prefix can be configured in the following ways: • None – Uses the default AWS-XRAY-TRACE-ID prefix. • Empty – Uses an empty string (e.g. "") and removes the prefix. • Custom – Uses the custom prefix defined in the string. Example AWSXRayRecorderBuilder statement AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder .standard().withSegmentListener(new Log4JSegmentListener("CUSTOM- PREFIX")); Logback backend To insert the trace ID into your log events, you must modify the logger's PatternLayout, which formats each logging statement. 1. 2. Find where the patternLayout is configured. You can do this programmatically, or through an XML configuration file. To learn more, see Logback configuration. Insert %X{AWS-XRAY-TRACE-ID} anywhere in the patternLayout to insert the trace ID in future logging statements. %X{} indicates that you are retrieving a value with the provided key from the MDC. To learn more about PatternLayouts in Logback, see PatternLayout. Log4J2 backend 1. Find where the patternLayout is configured. You can do this programmatically, or through a configuration file written in XML, JSON, YAML, or properties format. Configuration 357 AWS X-Ray Developer Guide To learn more about configuring Log4J2 through a configuration file, see Configuration. To learn more about configuring Log4J2 programmatically, see Programmatic Configuration. 2. Insert %X{AWS-XRAY-TRACE-ID} anywhere in the PatternLayout to insert the trace ID in future logging statements. %X{} indicates that you are retrieving a value with the provided key from the MDC. To learn more about PatternLayouts in Log4J2, see Pattern Layout. Trace ID Injection Example The following shows a PatternLayout string modified to include the trace ID. The trace ID is printed after the thread name (%t) and before the log level (%-5p). Example PatternLayout With ID injection %d{HH:mm:ss.SSS} [%t] %X{AWS-XRAY-TRACE-ID} %-5p %m%n AWS X-Ray automatically prints the key and the trace ID in the log statement for easy parsing. The following shows a log statement using the modified PatternLayout. Example Log statement with ID injection 2019-09-10 18:58:30.844 [nio-5000-exec-4] AWS-XRAY-TRACE-ID: 1-5d77f256-19f12e4eaa02e3f76c78f46a@1ce7df03252d99e1 WARN 1 - Your logging message here The logging message itself is housed in the pattern %m and is set when calling the logger. Segment listeners Segment listeners are an interface to intercept lifecycle events such as the beginning and ending of segments produced by the AWSXRayRecorder. Implementation of a segment listener event function might be to add the same annotation to all subsegments when they are created with onBeginSubsegment, log a message after each segment is sent to the daemon using afterEndSegment, or to record queries sent by the SQL interceptors using beforeEndSubsegment to verify if the subsegment represents an SQL query, adding additional metadata if so. Configuration 358 AWS X-Ray Developer Guide To see the full list of SegmentListener functions, visit the documentation for the AWS X-Ray Recorder SDK for Java API. The following example shows how to add a consistent annotation to all subsegments on creation with onBeginSubsegment and to print a log message at the end of each segment with afterEndSegment. Example MySegmentListener.java import com.amazonaws.xray.entities.Segment; |
xray-guide-104 | xray-guide.pdf | 104 | onBeginSubsegment, log a message after each segment is sent to the daemon using afterEndSegment, or to record queries sent by the SQL interceptors using beforeEndSubsegment to verify if the subsegment represents an SQL query, adding additional metadata if so. Configuration 358 AWS X-Ray Developer Guide To see the full list of SegmentListener functions, visit the documentation for the AWS X-Ray Recorder SDK for Java API. The following example shows how to add a consistent annotation to all subsegments on creation with onBeginSubsegment and to print a log message at the end of each segment with afterEndSegment. Example MySegmentListener.java import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; import com.amazonaws.xray.listeners.SegmentListener; public class MySegmentListener implements SegmentListener { ..... @Override public void onBeginSubsegment(Subsegment subsegment) { subsegment.putAnnotation("annotationKey", "annotationValue"); } @Override public void afterEndSegment(Segment segment) { // Be mindful not to mutate the segment logger.info("Segment with ID " + segment.getId()); } } This custom segment listener is then referenced when building the AWSXRayRecorder. Example AWSXRayRecorderBuilder statement AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder .standard().withSegmentListener(new MySegmentListener()); Environment variables You can use environment variables to configure the X-Ray SDK for Java. The SDK supports the following variables. • AWS_XRAY_CONTEXT_MISSING – Set to RUNTIME_ERROR to throw exceptions when your instrumented code attempts to record data when no segment is open. Configuration 359 AWS X-Ray Valid Values • RUNTIME_ERROR – Throw a runtime exception. • LOG_ERROR – Log an error and continue (default). • IGNORE_ERROR – Ignore error and continue. Developer Guide Errors related to missing segments or subsegments can occur when you attempt to use an instrumented client in startup code that runs when no request is open, or in code that spawns a new thread. • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener. By default, the SDK uses 127.0.0.1:2000 for both trace data (UDP) and sampling (TCP). Use this variable if you have configured the daemon to listen on a different port or if it is running on a different host. Format • Same port – address:port • Different ports – tcp:address:port udp:address:port • AWS_LOG_GROUP – Set the name of a log group to log group associated with your application. If your log group uses the same AWS account and region as your application, X-Ray will automatically search for your application's segment data using this specified log group. For more information about log groups, see Working with log groups and streams. • AWS_XRAY_TRACING_NAME – Set a service name that the SDK uses for segments. Overrides the service name that you set on the servlet filter's segment naming strategy. Environment variables override equivalent system properties and values set in code. System properties You can use system properties as a JVM-specific alternative to environment variables. The SDK supports the following properties: • com.amazonaws.xray.strategy.tracingName – Equivalent to AWS_XRAY_TRACING_NAME. • com.amazonaws.xray.emitters.daemonAddress – Equivalent to AWS_XRAY_DAEMON_ADDRESS. • com.amazonaws.xray.strategy.contextMissingStrategy – Equivalent to AWS_XRAY_CONTEXT_MISSING. Configuration 360 AWS X-Ray Developer Guide If both a system property and the equivalent environment variable are set, the environment variable value is used. Either method overrides values set in code. Tracing incoming requests with the X-Ray SDK for Java You can use the X-Ray SDK to trace incoming HTTP requests that your application serves on an EC2 instance in Amazon EC2, AWS Elastic Beanstalk, or Amazon ECS. Use a Filter to instrument incoming HTTP requests. When you add the X-Ray servlet filter to your application, the X-Ray SDK for Java creates a segment for each sampled request. This segment includes timing, method, and disposition of the HTTP request. Additional instrumentation creates subsegments on this segment. Note For AWS Lambda functions, Lambda creates a segment for each sampled request. See AWS Lambda and AWS X-Ray for more information. Each segment has a name that identifies your application in the service map. The segment can be named statically, or you can configure the SDK to name it dynamically based on the host header in the incoming request. Dynamic naming lets you group traces based on the domain name in the request, and apply a default name if the name doesn't match an expected pattern (for example, if the host header is forged). Forwarded Requests If a load balancer or other intermediary forwards a request to your application, X-Ray takes the client IP from the X-Forwarded-For header in the request instead of from the source IP in the IP packet. The client IP that is recorded for a forwarded request can be forged, so it should not be trusted. When a request is forwarded, the SDK sets an additional field in the segment to indicate this. If the segment contains the field x_forwarded_for set to true, the client IP was taken from the X- Forwarded-For header in the HTTP request. The message handler creates a segment for each incoming request with an http block that contains the following information: Incoming requests 361 AWS X-Ray Developer |
xray-guide-105 | xray-guide.pdf | 105 | X-Forwarded-For header in the request instead of from the source IP in the IP packet. The client IP that is recorded for a forwarded request can be forged, so it should not be trusted. When a request is forwarded, the SDK sets an additional field in the segment to indicate this. If the segment contains the field x_forwarded_for set to true, the client IP was taken from the X- Forwarded-For header in the HTTP request. The message handler creates a segment for each incoming request with an http block that contains the following information: Incoming requests 361 AWS X-Ray Developer Guide • HTTP method – GET, POST, PUT, DELETE, etc. • Client address – The IP address of the client that sent the request. • Response code – The HTTP response code for the completed request. • Timing – The start time (when the request was received) and end time (when the response was sent). • User agent — The user-agent from the request. • Content length — The content-length from the response. Sections • Adding a tracing filter to your application (Tomcat) • Adding a tracing filter to your application (spring) • Configuring a segment naming strategy Adding a tracing filter to your application (Tomcat) For Tomcat, add a <filter> to your project's web.xml file. Use the fixedName parameter to specify a service name to apply to segments created for incoming requests. Example WEB-INF/web.xml - Tomcat <filter> <filter-name>AWSXRayServletFilter</filter-name> <filter-class>com.amazonaws.xray.javax.servlet.AWSXRayServletFilter</filter-class> <init-param> <param-name>fixedName</param-name> <param-value>MyApp</param-value> </init-param> </filter> <filter-mapping> <filter-name>AWSXRayServletFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping> Adding a tracing filter to your application (spring) For Spring, add a Filter to your WebConfig class. Pass the segment name to the AWSXRayServletFilter constructor as a string. Incoming requests 362 AWS X-Ray Developer Guide Example src/main/java/myapp/WebConfig.java - spring package myapp; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean; import javax.servlet.Filter; import com.amazonaws.xray.javax.servlet.AWSXRayServletFilter; @Configuration public class WebConfig { @Bean public Filter TracingFilter() { return new AWSXRayServletFilter("Scorekeep"); } } Configuring a segment naming strategy AWS X-Ray uses a service name to identify your application and distinguish it from the other applications, databases, external APIs, and AWS resources that your application uses. When the X- Ray SDK generates segments for incoming requests, it records your application's service name in the segment's name field. The X-Ray SDK can name segments after the hostname in the HTTP request header. However, this header can be forged, which could result in unexpected nodes in your service map. To prevent the SDK from naming segments incorrectly due to requests with forged host headers, you must specify a default name for incoming requests. If your application serves requests for multiple domains, you can configure the SDK to use a dynamic naming strategy to reflect this in segment names. A dynamic naming strategy allows the SDK to use the hostname for requests that match an expected pattern, and apply the default name to requests that don't. For example, you might have a single application serving requests to three subdomains– www.example.com, api.example.com, and static.example.com. You can use a dynamic naming strategy with the pattern *.example.com to identify segments for each subdomain with a different name, resulting in three service nodes on the service map. If your application receives requests with a hostname that doesn't match the pattern, you will see a fourth node on the service map with a fallback name that you specify. Incoming requests 363 AWS X-Ray Developer Guide To use the same name for all request segments, specify the name of your application when you initialize the servlet filter, as shown in the previous section. This has the same effect as creating a fixed SegmentNamingStrategy by calling SegmentNamingStrategy.fixed() and passing it to the AWSXRayServletFilter constructor. Note You can override the default service name that you define in code with the AWS_XRAY_TRACING_NAME environment variable. A dynamic naming strategy defines a pattern that hostnames should match, and a default name to use if the hostname in the HTTP request does not match the pattern. To name segments dynamically in Tomcat, use the dynamicNamingRecognizedHosts and dynamicNamingFallbackName to define the pattern and default name, respectively. Example WEB-INF/web.xml - servlet filter with dynamic naming <filter> <filter-name>AWSXRayServletFilter</filter-name> <filter-class>com.amazonaws.xray.javax.servlet.AWSXRayServletFilter</filter-class> <init-param> <param-name>dynamicNamingRecognizedHosts</param-name> <param-value>*.example.com</param-value> </init-param> <init-param> <param-name>dynamicNamingFallbackName</param-name> <param-value>MyApp</param-value> </init-param> </filter> <filter-mapping> <filter-name>AWSXRayServletFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping> For Spring, create a dynamic SegmentNamingStrategy by calling SegmentNamingStrategy.dynamic(), and pass it to the AWSXRayServletFilter constructor. Example src/main/java/myapp/WebConfig.java - servlet filter with dynamic naming package myapp; Incoming requests 364 AWS X-Ray Developer Guide import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean; import javax.servlet.Filter; import com.amazonaws.xray.javax.servlet.AWSXRayServletFilter; import com.amazonaws.xray.strategy.SegmentNamingStrategy; @Configuration public class WebConfig { @Bean public Filter TracingFilter() { return new AWSXRayServletFilter(SegmentNamingStrategy.dynamic("MyApp", "*.example.com")); } } Tracing AWS SDK calls with the X-Ray SDK for Java When your application makes calls to AWS services to store data, write to a queue, or send notifications, the X-Ray SDK for Java tracks the calls downstream in subsegments. Traced AWS services and resources that you access within |
xray-guide-106 | xray-guide.pdf | 106 | calling SegmentNamingStrategy.dynamic(), and pass it to the AWSXRayServletFilter constructor. Example src/main/java/myapp/WebConfig.java - servlet filter with dynamic naming package myapp; Incoming requests 364 AWS X-Ray Developer Guide import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean; import javax.servlet.Filter; import com.amazonaws.xray.javax.servlet.AWSXRayServletFilter; import com.amazonaws.xray.strategy.SegmentNamingStrategy; @Configuration public class WebConfig { @Bean public Filter TracingFilter() { return new AWSXRayServletFilter(SegmentNamingStrategy.dynamic("MyApp", "*.example.com")); } } Tracing AWS SDK calls with the X-Ray SDK for Java When your application makes calls to AWS services to store data, write to a queue, or send notifications, the X-Ray SDK for Java tracks the calls downstream in subsegments. Traced AWS services and resources that you access within those services (for example, an Amazon S3 bucket or Amazon SQS queue), appear as downstream nodes on the trace map in the X-Ray console. The X-Ray SDK for Java automatically instruments all AWS SDK clients when you include the aws-sdk and an aws-sdk-instrumentor submodules in your build. If you don't include the Instrumentor submodule, you can choose to instrument some clients while excluding others. To instrument individual clients, remove the aws-sdk-instrumentor submodule from your build and add an XRayClient as a TracingHandler on your AWS SDK client using the service's client builder. For example, to instrument an AmazonDynamoDB client, pass a tracing handler to AmazonDynamoDBClientBuilder. Example MyModel.java - DynamoDB client import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.handlers.TracingHandler; ... public class MyModel { AWS SDK clients 365 AWS X-Ray Developer Guide private AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() .withRegion(Regions.fromName(System.getenv("AWS_REGION"))) .withRequestHandlers(new TracingHandler(AWSXRay.getGlobalRecorder())) .build(); ... For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a separate node in the service map, with a generic DynamoDB node for calls that don't target a table. Example Subsegment for a call to DynamoDB to save an item { "id": "24756640c0d0978a", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "DynamoDB", "namespace": "aws", "http": { "response": { "content_length": 60, "status": 200 } }, "aws": { "table_name": "scorekeep-user", "operation": "UpdateItem", "request_id": "UBQNSO5AEM8T4FDA4RQDEB94OVTDRVV4K4HIRGVJF66Q9ASUAAJG", } } When you access named resources, calls to the following services create additional nodes in the service map. Calls that don't target specific resources create a generic node for the service. • Amazon DynamoDB – Table name • Amazon Simple Storage Service – Bucket and key name • Amazon Simple Queue Service – Queue name AWS SDK clients 366 AWS X-Ray Developer Guide To instrument downstream calls to AWS services with AWS SDK for Java 2.2 and later, you can omit the aws-xray-recorder-sdk-aws-sdk-v2-instrumentor module from your build configuration. Include the aws-xray-recorder-sdk-aws-sdk-v2 module instead, then instrument individual clients by configuring them with a TracingInterceptor. Example AWS SDK for Java 2.2 and later - tracing interceptor import com.amazonaws.xray.interceptors.TracingInterceptor; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration import software.amazon.awssdk.services.dynamodb.DynamoDbClient; //... public class MyModel { private DynamoDbClient client = DynamoDbClient.builder() .region(Region.US_WEST_2) .overrideConfiguration(ClientOverrideConfiguration.builder() .addExecutionInterceptor(new TracingInterceptor()) .build() ) .build(); //... Tracing calls to downstream HTTP web services with the X-Ray SDK for Java When your application makes calls to microservices or public HTTP APIs, you can use the X-Ray SDK for Java's version of HttpClient to instrument those calls and add the API to the service graph as a downstream service. The X-Ray SDK for Java includes DefaultHttpClient and HttpClientBuilder classes that can be used in place of the Apache HttpComponents equivalents to instrument outgoing HTTP calls. • com.amazonaws.xray.proxies.apache.http.DefaultHttpClient - org.apache.http.impl.client.DefaultHttpClient • com.amazonaws.xray.proxies.apache.http.HttpClientBuilder - org.apache.http.impl.client.HttpClientBuilder These libraries are in the aws-xray-recorder-sdk-apache-http submodule. You can replace your existing import statements with the X-Ray equivalent to instrument all clients, or use the fully qualified name when you initialize a client to instrument specific clients. Outgoing HTTP calls 367 AWS X-Ray Example HttpClientBuilder Developer Guide import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import com.amazonaws.xray.proxies.apache.http.HttpClientBuilder; ... public String randomName() throws IOException { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet("http://names.example.com/api/"); CloseableHttpResponse response = httpclient.execute(httpGet); try { HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ObjectMapper mapper = new ObjectMapper(); Map<String, String> jsonMap = mapper.readValue(inputStream, Map.class); String name = jsonMap.get("name"); EntityUtils.consume(entity); return name; } finally { response.close(); } } When you instrument a call to a downstream web api, the X-Ray SDK for Java records a subsegment with information about the HTTP request and response. X-Ray uses the subsegment to generate an inferred segment for the remote API. Example Subsegment for a downstream HTTP call { "id": "004f72be19cddc2a", "start_time": 1484786387.131, "end_time": 1484786387.501, "name": "names.example.com", "namespace": "remote", "http": { "request": { "method": "GET", "url": "https://names.example.com/" Outgoing HTTP calls 368 Developer Guide AWS X-Ray }, "response": { "content_length": -1, "status": 200 } } } Example Inferred segment for a downstream HTTP call { "id": "168416dc2ea97781", |
xray-guide-107 | xray-guide.pdf | 107 | } finally { response.close(); } } When you instrument a call to a downstream web api, the X-Ray SDK for Java records a subsegment with information about the HTTP request and response. X-Ray uses the subsegment to generate an inferred segment for the remote API. Example Subsegment for a downstream HTTP call { "id": "004f72be19cddc2a", "start_time": 1484786387.131, "end_time": 1484786387.501, "name": "names.example.com", "namespace": "remote", "http": { "request": { "method": "GET", "url": "https://names.example.com/" Outgoing HTTP calls 368 Developer Guide AWS X-Ray }, "response": { "content_length": -1, "status": 200 } } } Example Inferred segment for a downstream HTTP call { "id": "168416dc2ea97781", "name": "names.example.com", "trace_id": "1-62be1272-1b71c4274f39f122afa64eab", "start_time": 1484786387.131, "end_time": 1484786387.501, "parent_id": "004f72be19cddc2a", "http": { "request": { "method": "GET", "url": "https://names.example.com/" }, "response": { "content_length": -1, "status": 200 } }, "inferred": true } Tracing SQL queries with the X-Ray SDK for Java SQL Interceptors Instrument SQL database queries by adding the X-Ray SDK for Java JDBC interceptor to your data source configuration. • PostgreSQL – com.amazonaws.xray.sql.postgres.TracingInterceptor • MySQL – com.amazonaws.xray.sql.mysql.TracingInterceptor SQL queries 369 AWS X-Ray Developer Guide These interceptors are in the aws-xray-recorder-sql-postgres and aws- xray-recorder-sql-mysql submodules, respectively. They implement org.apache.tomcat.jdbc.pool.JdbcInterceptor and are compatible with Tomcat connection pools. Note SQL interceptors do not record the SQL query itself within subsegments for security purposes. For Spring, add the interceptor in a properties file and build the data source with Spring Boot's DataSourceBuilder. Example src/main/java/resources/application.properties - PostgreSQL JDBC interceptor spring.datasource.continue-on-error=true spring.jpa.show-sql=false spring.jpa.hibernate.ddl-auto=create-drop spring.datasource.jdbc-interceptors=com.amazonaws.xray.sql.postgres.TracingInterceptor spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL94Dialect Example src/main/java/myapp/WebConfig.java - Data source import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import javax.servlet.Filter; import javax.sql.DataSource; import java.net.URL; @Configuration @EnableAutoConfiguration @EnableJpaRepositories("myapp") public class RdsWebConfig { SQL queries 370 AWS X-Ray Developer Guide @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { logger.info("Initializing PostgreSQL datasource"); return DataSourceBuilder.create() .driverClassName("org.postgresql.Driver") .url("jdbc:postgresql://" + System.getenv("RDS_HOSTNAME") + ":" + System.getenv("RDS_PORT") + "/ebdb") .username(System.getenv("RDS_USERNAME")) .password(System.getenv("RDS_PASSWORD")) .build(); } ... } For Tomcat, call setJdbcInterceptors on the JDBC data source with a reference to the X-Ray SDK for Java class. Example src/main/myapp/model.java - Data source import org.apache.tomcat.jdbc.pool.DataSource; ... DataSource source = new DataSource(); source.setUrl(url); source.setUsername(user); source.setPassword(password); source.setDriverClassName("com.mysql.jdbc.Driver"); source.setJdbcInterceptors("com.amazonaws.xray.sql.mysql.TracingInterceptor;"); The Tomcat JDBC Data Source library is included in the X-Ray SDK for Java, but you can declare it as a provided dependency to document that you use it. Example pom.xml - JDBC data source <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>8.0.36</version> <scope>provided</scope> </dependency> SQL queries 371 AWS X-Ray Developer Guide Native SQL Tracing Decorator • Add aws-xray-recorder-sdk-sql to your dependencies. • Decorate your database datasource, connection, or statement. dataSource = TracingDataSource.decorate(dataSource) connection = TracingConnection.decorate(connection) statement = TracingStatement.decorateStatement(statement) preparedStatement = TracingStatement.decoratePreparedStatement(preparedStatement, sql) callableStatement = TracingStatement.decorateCallableStatement(callableStatement, sql) Generating custom subsegments with the X-Ray SDK for Java Subsegments extend a trace's segment with details about work done in order to serve a request. Each time you make a call with an instrumented client, the X-Ray SDK records the information generated in a subsegment. You can create additional subsegments to group other subsegments, to measure the performance of a section of code, or to record annotations and metadata. To manage subsegments, use the beginSubsegment and endSubsegment methods. Example GameModel.java - custom subsegment import com.amazonaws.xray.AWSXRay; ... public void saveGame(Game game) throws SessionNotFoundException { // wrap in subsegment Subsegment subsegment = AWSXRay.beginSubsegment("Save Game"); try { // check session String sessionId = game.getSession(); if (sessionModel.loadSession(sessionId) == null ) { throw new SessionNotFoundException(sessionId); } mapper.save(game); } catch (Exception e) { subsegment.addException(e); throw e; } finally { AWSXRay.endSubsegment(); Custom subsegments 372 AWS X-Ray } } Developer Guide In this example, the code within the subsegment loads the game's session from DynamoDB with a method on the session model, and uses the AWS SDK for Java's DynamoDB mapper to save the game. Wrapping this code in a subsegment makes the calls DynamoDB children of the Save Game subsegment in the trace view in the console. If the code in your subsegment throws checked exceptions, wrap it in a try block and call AWSXRay.endSubsegment() in a finally block to ensure that the subsegment is always closed. If a subsegment is not closed, the parent segment cannot be completed and won't be sent to X- Ray. For code that doesn't throw checked exceptions, you can pass the code to AWSXRay.CreateSubsegment as a Lambda function. Example Subsegment Lambda function import com.amazonaws.xray.AWSXRay; AWSXRay.createSubsegment("getMovies", (subsegment) -> { // function code }); When you create a subsegment within a segment or another subsegment, the X-Ray SDK for Java generates an ID for it and records the start time and end time. Example Subsegment with metadata "subsegments": [{ "id": "6f1605cd8a07cb70", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, Custom subsegments 373 AWS X-Ray Developer Guide "name": "Custom subsegment for UserModel.saveUser function", "metadata": { "debug": { "test": "Metadata string from UserModel.saveUser" } }, For asynchronous and multi-threaded programming, you must manually pass the subsegment to the endSubsegment() method to ensure it is closed correctly because the X-Ray context may be modified during |
xray-guide-108 | xray-guide.pdf | 108 | -> { // function code }); When you create a subsegment within a segment or another subsegment, the X-Ray SDK for Java generates an ID for it and records the start time and end time. Example Subsegment with metadata "subsegments": [{ "id": "6f1605cd8a07cb70", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, Custom subsegments 373 AWS X-Ray Developer Guide "name": "Custom subsegment for UserModel.saveUser function", "metadata": { "debug": { "test": "Metadata string from UserModel.saveUser" } }, For asynchronous and multi-threaded programming, you must manually pass the subsegment to the endSubsegment() method to ensure it is closed correctly because the X-Ray context may be modified during async execution. If an asynchronous subsegment is closed after its parent segment is closed, this method will automatically stream the entire segment to the X-Ray daemon. Example Asynchronous Subsegment @GetMapping("/api") public ResponseEntity<?> api() { CompletableFuture.runAsync(() -> { Subsegment subsegment = AWSXRay.beginSubsegment("Async Work"); try { Thread.sleep(3000); } catch (InterruptedException e) { subsegment.addException(e); throw e; } finally { AWSXRay.endSubsegment(subsegment); } }); return ResponseEntity.ok().build(); } Add annotations and metadata to segments with the X-Ray SDK for Java You can record additional information about requests, the environment, or your application with annotations and metadata. You can add annotations and metadata to the segments that the X-Ray SDK creates, or to custom subsegments that you create. Annotations are key-value pairs with string, number, or Boolean values. Annotations are indexed for use with filter expressions. Use annotations to record data that you want to use to group traces in the console, or when calling the GetTraceSummaries API. Annotations and metadata 374 AWS X-Ray Developer Guide Metadata are key-value pairs that can have values of any type, including objects and lists, but are not indexed for use with filter expressions. Use metadata to record additional data that you want stored in the trace but don't need to use with search. In addition to annotations and metadata, you can also record user ID strings on segments. User IDs are recorded in a separate field on segments and are indexed for use with search. Sections • Recording annotations with the X-Ray SDK for Java • Recording metadata with the X-Ray SDK for Java • Recording user IDs with the X-Ray SDK for Java Recording annotations with the X-Ray SDK for Java Use annotations to record information on segments or subsegments that you want indexed for search. Annotation Requirements • Keys – The key for an X-Ray annotation can have up to 500 alphanumeric characters. You cannot use spaces or symbols other than a dot or period ( . ) • Values – The value for an X-Ray annotation can have up to 1,000 Unicode characters. • The number of Annotations – You can use up to 50 annotations per trace. To record annotations 1. Get a reference to the current segment or subsegment from AWSXRay. import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Segment; ... Segment document = AWSXRay.getCurrentSegment(); or import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Subsegment; ... Annotations and metadata 375 AWS X-Ray Developer Guide Subsegment document = AWSXRay.getCurrentSubsegment(); 2. Call putAnnotation with a String key, and a Boolean, Number, or String value. document.putAnnotation("mykey", "my value"); The following example shows how to call putAnnotation with a String key that includes a dot, and a Boolean, Number, or String value. document.putAnnotation("testkey.test", "my value"); The SDK records annotations as key-value pairs in an annotations object in the segment document. Calling putAnnotation twice with the same key overwrites previously recorded values on the same segment or subsegment. To find traces that have annotations with specific values, use the annotation[key] keyword in a filter expression. Example src/main/java/scorekeep/GameModel.java – Annotations and metadata import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; ... public void saveGame(Game game) throws SessionNotFoundException { // wrap in subsegment Subsegment subsegment = AWSXRay.beginSubsegment("## GameModel.saveGame"); try { // check session String sessionId = game.getSession(); if (sessionModel.loadSession(sessionId) == null ) { throw new SessionNotFoundException(sessionId); } Segment segment = AWSXRay.getCurrentSegment(); subsegment.putMetadata("resources", "game", game); segment.putAnnotation("gameid", game.getId()); mapper.save(game); } catch (Exception e) { subsegment.addException(e); throw e; } finally { Annotations and metadata 376 AWS X-Ray Developer Guide AWSXRay.endSubsegment(); } } Recording metadata with the X-Ray SDK for Java Use metadata to record information on segments or subsegments that you don't need indexed for search. Metadata values can be strings, numbers, Booleans, or any object that can be serialized into a JSON object or array. To record metadata 1. Get a reference to the current segment or subsegment from AWSXRay. import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Segment; ... Segment document = AWSXRay.getCurrentSegment(); or import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Subsegment; ... Subsegment document = AWSXRay.getCurrentSubsegment(); 2. Call putMetadata with a String namespace, String key, and a Boolean, Number, String, or Object value. document.putMetadata("my namespace", "my key", "my value"); or Call putMetadata with just a key and value. document.putMetadata("my key", "my value"); If you don't specify a namespace, the SDK uses default. Calling putMetadata twice with the same key overwrites previously recorded values |
xray-guide-109 | xray-guide.pdf | 109 | can be serialized into a JSON object or array. To record metadata 1. Get a reference to the current segment or subsegment from AWSXRay. import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Segment; ... Segment document = AWSXRay.getCurrentSegment(); or import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Subsegment; ... Subsegment document = AWSXRay.getCurrentSubsegment(); 2. Call putMetadata with a String namespace, String key, and a Boolean, Number, String, or Object value. document.putMetadata("my namespace", "my key", "my value"); or Call putMetadata with just a key and value. document.putMetadata("my key", "my value"); If you don't specify a namespace, the SDK uses default. Calling putMetadata twice with the same key overwrites previously recorded values on the same segment or subsegment. Annotations and metadata 377 AWS X-Ray Developer Guide Example src/main/java/scorekeep/GameModel.java – Annotations and metadata import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; ... public void saveGame(Game game) throws SessionNotFoundException { // wrap in subsegment Subsegment subsegment = AWSXRay.beginSubsegment("## GameModel.saveGame"); try { // check session String sessionId = game.getSession(); if (sessionModel.loadSession(sessionId) == null ) { throw new SessionNotFoundException(sessionId); } Segment segment = AWSXRay.getCurrentSegment(); subsegment.putMetadata("resources", "game", game); segment.putAnnotation("gameid", game.getId()); mapper.save(game); } catch (Exception e) { subsegment.addException(e); throw e; } finally { AWSXRay.endSubsegment(); } } Recording user IDs with the X-Ray SDK for Java Record user IDs on request segments to identify the user who sent the request. To record user IDs 1. Get a reference to the current segment from AWSXRay. import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Segment; ... Segment document = AWSXRay.getCurrentSegment(); 2. Call setUser with a string ID of the user who sent the request. Annotations and metadata 378 AWS X-Ray Developer Guide document.setUser("U12345"); You can call setUser in your controllers to record the user ID as soon as your application starts processing a request. If you will only use the segment to set the user ID, you can chain the calls in a single line. Example src/main/java/scorekeep/MoveController.java – User ID import com.amazonaws.xray.AWSXRay; ... @RequestMapping(value="/{userId}", method=RequestMethod.POST) public Move newMove(@PathVariable String sessionId, @PathVariable String gameId, @PathVariable String userId, @RequestBody String move) throws SessionNotFoundException, GameNotFoundException, StateNotFoundException, RulesException { AWSXRay.getCurrentSegment().setUser(userId); return moveFactory.newMove(sessionId, gameId, userId, move); } To find traces for a user ID, use the user keyword in a filter expression. AWS X-Ray metrics for the X-Ray SDK for Java This topic describes the AWS X-Ray namespace, metrics, and dimensions. You can use the X- Ray SDK for Java to publish unsampled Amazon CloudWatch metrics from your collected X-Ray segments. These metrics are derived from the segment’s start and end time, and the error, fault, and throttled status flags. Use these trace metrics to expose retries and dependency issues within subsegments. CloudWatch is a metrics repository. A metric is the fundamental concept in CloudWatch and represents a time-ordered set of data points. You (or AWS services) publish metrics data points into CloudWatch and you retrieve statistics about those data points as an ordered set of time-series data. Metrics are uniquely defined by a name, a namespace, and one or more dimensions. Each data point has a timestamp and, optionally, a unit of measure. When you request statistics, the returned data stream is identified by namespace, metric name, and dimension. For more information about CloudWatch, see the Amazon CloudWatch User Guide. Monitoring 379 AWS X-Ray X-Ray CloudWatch metrics Developer Guide The ServiceMetrics/SDK namespace includes the following metrics. Metric Latency Statistics available Description Units Average, Minimum, Maximum, Count The difference between the start Milliseconds ErrorRate Average, Sum FaultRate Average, Sum ThrottleRate Average, Sum OkRate Average, Sum and end time. Average, minimum, and maximum all describe operation al latency. Count describes call count. The rate of requests that failed with a 4xx Client Error status code, resulting in an error. The rate of traces that failed with a 5xx Server Error status code, resulting in a fault. The rate of throttled traces that return a 429 status code. This is a subset of the ErrorRate metric. The rate of traced requests resulting in an OK status code. Percent Percent Percent Percent Monitoring 380 AWS X-Ray Developer Guide X-Ray CloudWatch dimensions Use the dimensions in the following table to refine the metrics returned for your X-Ray instrumented Java applications. Dimension ServiceType Description The type of the service, for example, AWS::EC2::Instance known. or NONE, if not ServiceName The canonical name for the service. Enable X-Ray CloudWatch metrics Use the following procedure to enable trace metrics in your instrumented Java application. To configure trace metrics 1. Add the aws-xray-recorder-sdk-metrics package as an Apache Maven dependency. For more information, see X-Ray SDK for Java Submodules. 2. Enable a new MetricsSegmentListener() as part of the global recorder build. Example src/com/myapp/web/Startup.java import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorderBuilder; import com.amazonaws.xray.plugins.EC2Plugin; import com.amazonaws.xray.plugins.ElasticBeanstalkPlugin; import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy; @Configuration public class WebConfig { ... static { AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder .standard() .withPlugin(new EC2Plugin()) .withPlugin(new ElasticBeanstalkPlugin()) Monitoring 381 AWS X-Ray Developer Guide .withSegmentListener(new MetricsSegmentListener()); URL ruleFile = WebConfig.class.getResource("/sampling-rules.json"); builder.withSamplingStrategy(new LocalizedSamplingStrategy(ruleFile)); AWSXRay.setGlobalRecorder(builder.build()); } } 3. Deploy the CloudWatch agent to |
xray-guide-110 | xray-guide.pdf | 110 | Use the following procedure to enable trace metrics in your instrumented Java application. To configure trace metrics 1. Add the aws-xray-recorder-sdk-metrics package as an Apache Maven dependency. For more information, see X-Ray SDK for Java Submodules. 2. Enable a new MetricsSegmentListener() as part of the global recorder build. Example src/com/myapp/web/Startup.java import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorderBuilder; import com.amazonaws.xray.plugins.EC2Plugin; import com.amazonaws.xray.plugins.ElasticBeanstalkPlugin; import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy; @Configuration public class WebConfig { ... static { AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder .standard() .withPlugin(new EC2Plugin()) .withPlugin(new ElasticBeanstalkPlugin()) Monitoring 381 AWS X-Ray Developer Guide .withSegmentListener(new MetricsSegmentListener()); URL ruleFile = WebConfig.class.getResource("/sampling-rules.json"); builder.withSamplingStrategy(new LocalizedSamplingStrategy(ruleFile)); AWSXRay.setGlobalRecorder(builder.build()); } } 3. Deploy the CloudWatch agent to collect metrics using Amazon Elastic Compute Cloud (Amazon EC2), Amazon Elastic Container Service (Amazon ECS), or Amazon Elastic Kubernetes Service (Amazon EKS): • To configure Amazon EC2, see Installing the CloudWatch agent. • To configure Amazon ECS, see Monitor Amazon ECS containers using Container Insights. • To configure Amazon EKS, see Install the CloudWatch agent by using the Amazon CloudWatch Observability EKS add-on. 4. Configure the SDK to communicate with the CloudWatch agent. By default, the SDK communicates with the CloudWatch agent on the address 127.0.0.1. You can configure alternate addresses by setting the environment variable or Java property to address:port. Example Environment variable AWS_XRAY_METRICS_DAEMON_ADDRESS=address:port Example Java property com.amazonaws.xray.metrics.daemonAddress=address:port To validate configuration 1. Sign in to the AWS Management Console and open the CloudWatch console at https:// console.aws.amazon.com/cloudwatch/. 2. Open the Metrics tab to observe the influx of your metrics. 3. (Optional) In the CloudWatch console, on the Logs tab, open the ServiceMetricsSDK log group. Look for a log stream that matches the host metrics, and confirm the log messages. Monitoring 382 AWS X-Ray Developer Guide Passing segment context between threads in a multithreaded application When you create a new thread in your application, the AWSXRayRecorder doesn't maintain a reference to the current segment or subsegment Entity. If you use an instrumented client in the new thread, the SDK tries to write to a segment that doesn't exist, causing a SegmentNotFoundException. To avoid throwing exceptions during development, you can configure the recorder with a ContextMissingStrategy that tells it to log an error instead. You can configure the strategy in code with SetContextMissingStrategy, or configure equivalent options with an environment variable or system property. One way to address the error is to use a new segment by calling beginSegment when you start the thread and endSegment when you close it. This works if you are instrumenting code that doesn't run in response to an HTTP request, like code that runs when your application starts. If you use multiple threads to handle incoming requests, you can pass the current segment or subsegment to the new thread and provide it to the global recorder. This ensures that the information recorded within the new thread is associated with the same segment as the rest of the information recorded about that request. Once the segment is available in the new thread, you can execute any runnable with access to that segment's context using the segment.run(() -> { ... }) method. See Using instrumented clients in worker threads for an example. Using X-Ray with Asynchronous Programming The X-Ray SDK for Java can be used in asynchronous Java programs with SegmentContextExecutors. The SegmentContextExecutor implements the Executor interface, which means it can be passed into all asynchronous operations of a CompletableFuture. This ensures that any asynchronous operations will be executed with the correct segment in its context. Example Example App.java: Passing SegmentContextExecutor to CompletableFuture DynamoDbAsyncClient client = DynamoDbAsyncClient.create(); AWSXRay.beginSegment(); // ... Multithreading 383 AWS X-Ray Developer Guide client.getItem(request).thenComposeAsync(response -> { // If we did not provide the segment context executor, this request would not be traced correctly. return client.getItem(request2); }, SegmentContextExecutors.newSegmentContextExecutor()); AOP with Spring and the X-Ray SDK for Java This topic describes how to use the X-Ray SDK and the Spring Framework to instrument your application without changing its core logic. This means that there is now a non-invasive way to instrument your applications running remotely in AWS. To enable AOP in spring 1. Configure Spring 2. Add a tracing filter to your application 3. Annotate your code or implement an interface 4. Activate X-Ray in your application Configuring Spring You can use Maven or Gradle to configure Spring to use AOP to instrument your application. If you use Maven to build your application, add the following dependency in your pom.xml file. <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-spring</artifactId> <version>2.11.0</version> </dependency> For Gradle, add the following dependency in your build.gradle file. compile 'com.amazonaws:aws-xray-recorder-sdk-spring:2.11.0' Configuring Spring Boot In addition to the Spring dependency described in the previous section, if you’re using Spring Boot, add the following dependency if it’s not already on your classpath. AOP with Spring 384 Developer Guide AWS X-Ray Maven: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.5.2</version> </dependency> Gradle: compile 'org.springframework.boot:spring-boot-starter-aop:2.5.2' Adding a tracing filter to your application Add a Filter to |
xray-guide-111 | xray-guide.pdf | 111 | configure Spring to use AOP to instrument your application. If you use Maven to build your application, add the following dependency in your pom.xml file. <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-xray-recorder-sdk-spring</artifactId> <version>2.11.0</version> </dependency> For Gradle, add the following dependency in your build.gradle file. compile 'com.amazonaws:aws-xray-recorder-sdk-spring:2.11.0' Configuring Spring Boot In addition to the Spring dependency described in the previous section, if you’re using Spring Boot, add the following dependency if it’s not already on your classpath. AOP with Spring 384 Developer Guide AWS X-Ray Maven: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.5.2</version> </dependency> Gradle: compile 'org.springframework.boot:spring-boot-starter-aop:2.5.2' Adding a tracing filter to your application Add a Filter to your WebConfig class. Pass the segment name to the AWSXRayServletFilter constructor as a string. For more information about tracing filters and instrumenting incoming requests, see Tracing incoming requests with the X-Ray SDK for Java. Example src/main/java/myapp/WebConfig.java - spring package myapp; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean; import javax.servlet.Filter; import com.amazonaws.xray.javax.servlet.AWSXRayServletFilter; @Configuration public class WebConfig { @Bean public Filter TracingFilter() { return new AWSXRayServletFilter("Scorekeep"); } } Jakarta Support Spring 6 uses Jakarta instead of Javax for its Enterprise Edition. To support this new namespace, X- Ray has created a parallel set of classes that live in their own Jakarta namespace. For the filter classes, replace javax with jakarta. When configuring a segment naming strategy, add jakarta before the naming strategy class name, as in the following example: AOP with Spring 385 AWS X-Ray Developer Guide package myapp; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean; import jakarta.servlet.Filter; import com.amazonaws.xray.jakarta.servlet.AWSXRayServletFilter; import com.amazonaws.xray.strategy.jakarta.SegmentNamingStrategy; @Configuration public class WebConfig { @Bean public Filter TracingFilter() { return new AWSXRayServletFilter(SegmentNamingStrategy.dynamic("Scorekeep")); } } Annotating your code or implementing an interface Your classes must either be annotated with the @XRayEnabled annotation, or implement the XRayTraced interface. This tells the AOP system to wrap the functions of the affected class for X- Ray instrumentation. Activating X-Ray in your application To activate X-Ray tracing in your application, your code must extend the abstract class BaseAbstractXRayInterceptor by overriding the following methods. • generateMetadata—This function allows customization of the metadata attached to the current function’s trace. By default, the class name of the executing function is recorded in the metadata. You can add more data if you need additional information. • xrayEnabledClasses—This function is empty, and should remain so. It serves as the host for a pointcut instructing the interceptor about which methods to wrap. Define the pointcut by specifying which of the classes that are annotated with @XRayEnabled to trace. The following pointcut statement tells the interceptor to wrap all controller beans annotated with the @XRayEnabled annotation. @Pointcut(“@within(com.amazonaws.xray.spring.aop.XRayEnabled) && bean(*Controller)”) If your project is using Spring Data JPA, consider extending from AbstractXRayInterceptor instead of BaseAbstractXRayInterceptor. AOP with Spring 386 AWS X-Ray Example Developer Guide The following code extends the abstract class BaseAbstractXRayInterceptor. @Aspect @Component public class XRayInspector extends BaseAbstractXRayInterceptor { @Override protected Map<String, Map<String, Object>> generateMetadata(ProceedingJoinPoint proceedingJoinPoint, Subsegment subsegment) throws Exception { return super.generateMetadata(proceedingJoinPoint, subsegment); } @Override @Pointcut("@within(com.amazonaws.xray.spring.aop.XRayEnabled) && bean(*Controller)") public void xrayEnabledClasses() {} } The following code is a class that will be instrumented by X-Ray. @Service @XRayEnabled public class MyServiceImpl implements MyService { private final MyEntityRepository myEntityRepository; @Autowired public MyServiceImpl(MyEntityRepository myEntityRepository) { this.myEntityRepository = myEntityRepository; } @Transactional(readOnly = true) public List<MyEntity> getMyEntities(){ try(Stream<MyEntity> entityStream = this.myEntityRepository.streamAll()){ return entityStream.sorted().collect(Collectors.toList()); } } } AOP with Spring 387 AWS X-Ray Developer Guide If you've configured your application correctly, you should see the complete call stack of the application, from the controller down through the service calls, as shown in the following screen shot of the console. AOP with Spring 388 AWS X-Ray Developer Guide Working with Node.js There are two ways to instrument your Node.js application to send traces to X-Ray: • AWS Distro for OpenTelemetry JavaScript – An AWS distribution that provides a set of open source libraries for sending correlated metrics and traces to multiple AWS monitoring solutions, including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service, via the AWS Distro for OpenTelemetry Collector. • AWS X-Ray SDK for Node.js – A set of libraries for generating and sending traces to X-Ray via the X-Ray daemon. For more information, see Choosing between the AWS Distro for OpenTelemetry and X-Ray SDKs. AWS Distro for OpenTelemetry JavaScript With the AWS Distro for OpenTelemetry (ADOT) JavaScript, you can instrument your applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Using X-Ray with AWS Distro for OpenTelemetry requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. To get started, see the AWS Distro for OpenTelemetry JavaScript documentation. Note ADOT JavaScript is supported for all server-side Node.js applications. ADOT JavaScript is not able to export data to X-Ray from browser clients. For more information about using the AWS Distro for OpenTelemetry with AWS X-Ray and |
xray-guide-112 | xray-guide.pdf | 112 | applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Using X-Ray with AWS Distro for OpenTelemetry requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. To get started, see the AWS Distro for OpenTelemetry JavaScript documentation. Note ADOT JavaScript is supported for all server-side Node.js applications. ADOT JavaScript is not able to export data to X-Ray from browser clients. For more information about using the AWS Distro for OpenTelemetry with AWS X-Ray and other AWS services, see AWS Distro for OpenTelemetry or the AWS Distro for OpenTelemetry Documentation. For more information about language support and usage, see AWS Observability on GitHub. AWS Distro for OpenTelemetry JavaScript 389 AWS X-Ray Developer Guide AWS X-Ray SDK for Node.js The X-Ray SDK for Node.js is a library for Express web applications and Node.js Lambda functions that provides 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. Note The X-Ray SDK for Node.js is an open source project that is supported for Node.js versions 14.x and up. You can follow the project and submit issues and pull requests on GitHub: github.com/aws/aws-xray-sdk-node If you use Express, start by adding the SDK as middleware on your application server to trace incoming requests. The middleware creates a segment for each traced request, and completes the segment when the response is sent. While the segment is open you can use the SDK client's methods to add information to the segment and create subsegments to trace downstream calls. The SDK also automatically records exceptions that your application throws while the segment is open. For Lambda functions called by an instrumented application or service, Lambda reads the tracing header and traces sampled requests automatically. For other functions, you can configure Lambda to sample and trace incoming requests. In either case, Lambda creates the segment and provides it to the X-Ray SDK. Note On Lambda, the X-Ray SDK is optional. If you don't use it in your function, your service map will still include a node for the Lambda service, and one for each Lambda function. By adding the SDK, you can instrument your function code to add subsegments to the function segment recorded by Lambda. See AWS Lambda and AWS X-Ray for more information. Next, use the X-Ray SDK for Node.js to instrument your AWS SDK for JavaScript in Node.js clients. Whenever you make a call to a downstream AWS service or resource with an instrumented client, the SDK records information about the call in a subsegment. AWS services and the resources that X-Ray SDK for Node.js 390 AWS X-Ray Developer Guide you access within the services appear as downstream nodes on the trace map to help you identify errors and throttling issues on individual connections. The X-Ray SDK for Node.js also provides instrumentation for downstream calls to HTTP web APIs and SQL queries. Wrap your HTTP client in the SDK's capture method to record information about outgoing HTTP calls. For SQL clients, use the capture method for your database type. The middleware applies sampling rules to incoming requests to determine which requests to trace. You can configure the X-Ray SDK for Node.js to adjust the sampling behavior or to record information about the AWS compute resources on which your application runs. Record additional information about requests and the work that your application does in annotations and metadata. Annotations are simple key-value pairs that are indexed for use with filter expressions, so that you can search for traces that contain specific data. Metadata entries are less restrictive and can record entire objects and arrays — anything that can be serialized into JSON. Annotations and Metadata Annotations and metadata are arbitrary text that you add to segments with the X-Ray SDK. Annotations are indexed for use with filter expressions. Metadata are not indexed, but can be viewed in the raw segment with the X-Ray console or API. Anyone that you grant read access to X-Ray can view this data. When you have a lot of instrumented clients in your code, a single request segment can contain a large number of subsegments, one for each call made with an instrumented client. You can organize and group subsegments by wrapping client calls in custom subsegments. You can create a custom subsegment for an entire function or any section of code, and record metadata and annotations on the subsegment instead of writing everything on the parent segment. For reference documentation about the SDK's classes and methods, see the AWS X-Ray SDK for Node.js API Reference. |
xray-guide-113 | xray-guide.pdf | 113 | access to X-Ray can view this data. When you have a lot of instrumented clients in your code, a single request segment can contain a large number of subsegments, one for each call made with an instrumented client. You can organize and group subsegments by wrapping client calls in custom subsegments. You can create a custom subsegment for an entire function or any section of code, and record metadata and annotations on the subsegment instead of writing everything on the parent segment. For reference documentation about the SDK's classes and methods, see the AWS X-Ray SDK for Node.js API Reference. Requirements The X-Ray SDK for Node.js requires Node.js and the following libraries: • atomic-batcher – 1.0.2 • cls-hooked – 4.2.2 Requirements 391 AWS X-Ray • pkginfo – 0.4.0 • semver – 5.3.0 Developer Guide The SDK pulls these libraries in when you install it with NPM. To trace AWS SDK clients, the X-Ray SDK for Node.js requires a minimum version of the AWS SDK for JavaScript in Node.js. • aws-sdk – 2.7.15 Dependency management The X-Ray SDK for Node.js is available from NPM. • Package – aws-xray-sdk For local development, install the SDK in your project directory with npm. ~/nodejs-xray$ npm install aws-xray-sdk aws-xray-sdk@3.3.3 ### aws-xray-sdk-core@3.3.3 # ### @aws-sdk/service-error-classification@3.15.0 # ### @aws-sdk/types@3.15.0 # ### @types/cls-hooked@4.3.3 # # ### @types/node@15.3.0 # ### atomic-batcher@1.0.2 # ### cls-hooked@4.2.2 # # ### async-hook-jl@1.7.6 # # # ### stack-chain@1.3.7 # # ### emitter-listener@1.1.2 # # ### shimmer@1.2.1 # ### semver@5.7.1 ### aws-xray-sdk-express@3.3.3 ### aws-xray-sdk-mysql@3.3.3 ### aws-xray-sdk-postgres@3.3.3 Use the --save option to save the SDK as a dependency in your application's package.json. ~/nodejs-xray$ npm install aws-xray-sdk --save Dependency management 392 AWS X-Ray aws-xray-sdk@3.3.3 Developer Guide If your application has any dependencies whose versions conflict with the X-Ray SDK's dependencies, both versions will be installed to ensure compatibility. For more details, see the official NPM documentation for dependency resolution. Node.js samples Work with the AWS X-Ray SDK for Node.js to get an end-to-end view of requests as they travel through your Node.js applications. • Node.js sample application on GitHub. Configuring the X-Ray SDK for Node.js You can configure the X-Ray SDK for Node.js with plugins to include information about the service that your application runs on, modify the default sampling behavior, or add sampling rules that apply to requests to specific paths. Sections • Service plugins • Sampling rules • Logging • X-Ray daemon address • Environment variables Service plugins Use plugins to record information about the service hosting your application. Plugins • Amazon EC2 – EC2Plugin adds the instance ID, Availability Zone, and the CloudWatch Logs Group. • Elastic Beanstalk – ElasticBeanstalkPlugin adds the environment name, version label, and deployment ID. Node.js samples 393 AWS X-Ray Developer Guide • Amazon ECS – ECSPlugin adds the container ID. To use a plugin, configure the X-Ray SDK for Node.js client by using the config method. Example app.js - plugins var AWSXRay = require('aws-xray-sdk'); AWSXRay.config([AWSXRay.plugins.EC2Plugin,AWSXRay.plugins.ElasticBeanstalkPlugin]); The SDK also uses plugin settings to set the origin field on the segment. This indicates the type of AWS resource that runs your application. When you use multiple plugins, the SDK uses the following resolution order to determine the origin: ElasticBeanstalk > EKS > ECS > EC2. Sampling rules The SDK uses the sampling rules you define in the X-Ray console to determine which requests to record. The default rule traces the first request each second, and five percent of any additional requests across all services sending traces to X-Ray. Create additional rules in the X-Ray console to customize the amount of data recorded for each of your applications. The SDK applies custom rules in the order in which they are defined. If a request matches multiple custom rules, the SDK applies only the first rule. Note If the SDK can't reach X-Ray to get sampling rules, it reverts to a default local rule of the first request each second, and five percent of any additional requests per host. This can occur if the host doesn't have permission to call sampling APIs, or can't connect to the X- Ray daemon, which acts as a TCP proxy for API calls made by the SDK. You can also configure the SDK to load sampling rules from a JSON document. The SDK can use local rules as a backup for cases where X-Ray sampling is unavailable, or use local rules exclusively. Example sampling-rules.json { "version": 2, "rules": [ { Configuration 394 AWS X-Ray Developer Guide "description": "Player moves.", "host": "*", "http_method": "*", "url_path": "/api/move/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 } } This example defines one custom rule and a default rule. The custom rule applies a five-percent sampling rate with no minimum number of requests to trace for paths under /api/move/. The default rule traces the first request each |
xray-guide-114 | xray-guide.pdf | 114 | from a JSON document. The SDK can use local rules as a backup for cases where X-Ray sampling is unavailable, or use local rules exclusively. Example sampling-rules.json { "version": 2, "rules": [ { Configuration 394 AWS X-Ray Developer Guide "description": "Player moves.", "host": "*", "http_method": "*", "url_path": "/api/move/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 } } This example defines one custom rule and a default rule. The custom rule applies a five-percent sampling rate with no minimum number of requests to trace for paths under /api/move/. The default rule traces the first request each second and 10 percent of additional requests. The disadvantage of defining rules locally is that the fixed target is applied by each instance of the recorder independently, instead of being managed by the X-Ray service. As you deploy more hosts, the fixed rate is multiplied, making it harder to control the amount of data recorded. On AWS Lambda, you cannot modify the sampling rate. If your function is called by an instrumented service, calls that generated requests that were sampled by that service will be recorded by Lambda. If active tracing is enabled and no tracing header is present, Lambda makes the sampling decision. To configure backup rules, tell the X-Ray SDK for Node.js to load sampling rules from a file with setSamplingRules. Example app.js - sampling rules from a file var AWSXRay = require('aws-xray-sdk'); AWSXRay.middleware.setSamplingRules('sampling-rules.json'); You can also define your rules in code and pass them to setSamplingRules as an object. Example app.js - sampling rules from an object var AWSXRay = require('aws-xray-sdk'); var rules = { Configuration 395 AWS X-Ray Developer Guide "rules": [ { "description": "Player moves.", "service_name": "*", "http_method": "*", "url_path": "/api/move/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 }, "version": 1 } AWSXRay.middleware.setSamplingRules(rules); To use only local rules, call disableCentralizedSampling. AWSXRay.middleware.disableCentralizedSampling() Logging To log output from the SDK, call AWSXRay.setLogger(logger), where logger is an object that provides standard logging methods (warn, info, etc.). By default the SDK will log error messages to the console using the standard methods on the console object. The log level of the built-in logger can be set by using either the AWS_XRAY_DEBUG_MODE or AWS_XRAY_LOG_LEVEL environment variables. For a list of valid log level values, see Environment variables. If you wish to provide a different format or destination for the logs then you can provide the SDK with your own implementation of the logger interface as shown below. Any object that implements this interface can be used. This means that many logging libraries, e.g. Winston, could be used and passed to the SDK directly. Example app.js - logging var AWSXRay = require('aws-xray-sdk'); // Create your own logger, or instantiate one using a library. var logger = { error: (message, meta) => { /* logging code */ }, warn: (message, meta) => { /* logging code */ }, info: (message, meta) => { /* logging code */ }, debug: (message, meta) => { /* logging code */ } } AWSXRay.setLogger(logger); AWSXRay.config([AWSXRay.plugins.EC2Plugin]); Configuration 396 AWS X-Ray Developer Guide Call setLogger before you run other configuration methods to ensure that you capture output from those operations. X-Ray daemon address If the X-Ray daemon listens on a port or host other than 127.0.0.1:2000, you can configure the X-Ray SDK for Node.js to send trace data to a different address. AWSXRay.setDaemonAddress('host:port'); You can specify the host by name or by IPv4 address. Example app.js - daemon address var AWSXRay = require('aws-xray-sdk'); AWSXRay.setDaemonAddress('daemonhost:8082'); If you configured the daemon to listen on different ports for TCP and UDP, you can specify both in the daemon address setting. Example app.js - daemon address on separate ports var AWSXRay = require('aws-xray-sdk'); AWSXRay.setDaemonAddress('tcp:daemonhost:8082 udp:daemonhost:8083'); You can also set the daemon address by using the AWS_XRAY_DAEMON_ADDRESS environment variable. Environment variables You can use environment variables to configure the X-Ray SDK for Node.js. The SDK supports the following variables. • AWS_XRAY_CONTEXT_MISSING – Set to RUNTIME_ERROR to throw exceptions when your instrumented code attempts to record data when no segment is open. Valid Values • RUNTIME_ERROR – Throw a runtime exception. • LOG_ERROR – Log an error and continue (default). Configuration 397 AWS X-Ray Developer Guide • IGNORE_ERROR – Ignore error and continue. Errors related to missing segments or subsegments can occur when you attempt to use an instrumented client in startup code that runs when no request is open, or in code that spawns a new thread. • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener. By default, the SDK uses 127.0.0.1:2000 for both trace data (UDP) and sampling (TCP). Use this variable if you have configured the daemon to listen on a different port or if it is running on a different host. Format • Same port – address:port • Different ports – |
xray-guide-115 | xray-guide.pdf | 115 | Ignore error and continue. Errors related to missing segments or subsegments can occur when you attempt to use an instrumented client in startup code that runs when no request is open, or in code that spawns a new thread. • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener. By default, the SDK uses 127.0.0.1:2000 for both trace data (UDP) and sampling (TCP). Use this variable if you have configured the daemon to listen on a different port or if it is running on a different host. Format • Same port – address:port • Different ports – tcp:address:port udp:address:port • AWS_XRAY_DEBUG_MODE – Set to TRUE to configure the SDK to output logs to the console, at debug level. • AWS_XRAY_LOG_LEVEL – Set a log level for the default logger. Valid values are debug, info, warn, error, and silent. This value is ignored when AWS_XRAY_DEBUG_MODE is set to TRUE. • AWS_XRAY_TRACING_NAME – Set a service name that the SDK uses for segments. Overrides the segment name that you set on the Express middleware. Tracing incoming requests with the X-Ray SDK for Node.js You can use the X-Ray SDK for Node.js to trace incoming HTTP requests that your Express and Restify applications serve on an EC2 instance in Amazon EC2, AWS Elastic Beanstalk, or Amazon ECS. The X-Ray SDK for Node.js provides middleware for applications that use the Express and Restify frameworks. When you add the X-Ray middleware to your application, the X-Ray SDK for Node.js creates a segment for each sampled request. This segment includes timing, method, and disposition of the HTTP request. Additional instrumentation creates subsegments on this segment. Note For AWS Lambda functions, Lambda creates a segment for each sampled request. See AWS Lambda and AWS X-Ray for more information. Incoming requests 398 AWS X-Ray Developer Guide Each segment has a name that identifies your application in the service map. The segment can be named statically, or you can configure the SDK to name it dynamically based on the host header in the incoming request. Dynamic naming lets you group traces based on the domain name in the request, and apply a default name if the name doesn't match an expected pattern (for example, if the host header is forged). Forwarded Requests If a load balancer or other intermediary forwards a request to your application, X-Ray takes the client IP from the X-Forwarded-For header in the request instead of from the source IP in the IP packet. The client IP that is recorded for a forwarded request can be forged, so it should not be trusted. When a request is forwarded, the SDK sets an additional field in the segment to indicate this. If the segment contains the field x_forwarded_for set to true, the client IP was taken from the X- Forwarded-For header in the HTTP request. The message handler creates a segment for each incoming request with an http block that contains the following information: • HTTP method – GET, POST, PUT, DELETE, etc. • Client address – The IP address of the client that sent the request. • Response code – The HTTP response code for the completed request. • Timing – The start time (when the request was received) and end time (when the response was sent). • User agent — The user-agent from the request. • Content length — The content-length from the response. Sections • Tracing incoming requests with Express • Tracing incoming requests with restify • Configuring a segment naming strategy Incoming requests 399 AWS X-Ray Developer Guide Tracing incoming requests with Express To use the Express middleware, initialize the SDK client and use the middleware returned by the express.openSegment function before you define your routes. Example app.js - Express var app = express(); var AWSXRay = require('aws-xray-sdk'); app.use(AWSXRay.express.openSegment('MyApp')); app.get('/', function (req, res) { res.render('index'); }); app.use(AWSXRay.express.closeSegment()); After you define your routes, use the output of express.closeSegment as shown to handle any errors returned by the X-Ray SDK for Node.js. Tracing incoming requests with restify To use the Restify middleware, initialize the SDK client and run enable. Pass it your Restify server and segment name. Example app.js - restify var AWSXRay = require('aws-xray-sdk'); var AWSXRayRestify = require('aws-xray-sdk-restify'); var restify = require('restify'); var server = restify.createServer(); AWSXRayRestify.enable(server, 'MyApp')); server.get('/', function (req, res) { res.render('index'); }); Incoming requests 400 AWS X-Ray Developer Guide Configuring a segment naming strategy AWS X-Ray uses a service name to identify your application and distinguish it from the other applications, databases, external APIs, and AWS resources that your application uses. When the X- Ray SDK generates segments for incoming requests, it records your application's service name in the segment's name field. The X-Ray SDK can name segments after the hostname in the HTTP request header. However, this header can be forged, which could result in unexpected nodes |
xray-guide-116 | xray-guide.pdf | 116 | require('restify'); var server = restify.createServer(); AWSXRayRestify.enable(server, 'MyApp')); server.get('/', function (req, res) { res.render('index'); }); Incoming requests 400 AWS X-Ray Developer Guide Configuring a segment naming strategy AWS X-Ray uses a service name to identify your application and distinguish it from the other applications, databases, external APIs, and AWS resources that your application uses. When the X- Ray SDK generates segments for incoming requests, it records your application's service name in the segment's name field. The X-Ray SDK can name segments after the hostname in the HTTP request header. However, this header can be forged, which could result in unexpected nodes in your service map. To prevent the SDK from naming segments incorrectly due to requests with forged host headers, you must specify a default name for incoming requests. If your application serves requests for multiple domains, you can configure the SDK to use a dynamic naming strategy to reflect this in segment names. A dynamic naming strategy allows the SDK to use the hostname for requests that match an expected pattern, and apply the default name to requests that don't. For example, you might have a single application serving requests to three subdomains– www.example.com, api.example.com, and static.example.com. You can use a dynamic naming strategy with the pattern *.example.com to identify segments for each subdomain with a different name, resulting in three service nodes on the service map. If your application receives requests with a hostname that doesn't match the pattern, you will see a fourth node on the service map with a fallback name that you specify. To use the same name for all request segments, specify the name of your application when you initialize the middleware, as shown in the previous sections. Note You can override the default service name that you define in code with the AWS_XRAY_TRACING_NAME environment variable. A dynamic naming strategy defines a pattern that hostnames should match, and a default name to use if the hostname in the HTTP request does not match the pattern. To name segments dynamically, use AWSXRay.middleware.enableDynamicNaming. Incoming requests 401 AWS X-Ray Developer Guide Example app.js - dynamic segment names If the hostname in the request matches the pattern *.example.com, use the hostname. Otherwise, use MyApp. var app = express(); var AWSXRay = require('aws-xray-sdk'); app.use(AWSXRay.express.openSegment('MyApp')); AWSXRay.middleware.enableDynamicNaming('*.example.com'); app.get('/', function (req, res) { res.render('index'); }); app.use(AWSXRay.express.closeSegment()); Tracing AWS SDK calls with the X-Ray SDK for Node.js When your application makes calls to AWS services to store data, write to a queue, or send notifications, the X-Ray SDK for Node.js tracks the calls downstream in subsegments. Traced AWS services, and resources that you access within those services (for example, an Amazon S3 bucket or Amazon SQS queue), appear as downstream nodes on the trace map in the X-Ray console. Instrument AWS SDK clients that you create via the AWS SDK for JavaScript V2 or AWS SDK for JavaScript V3. Each AWS SDK version provides different methods for instrumenting AWS SDK clients. Note Currently, the AWS X-Ray SDK for Node.js returns less segment information when instrumenting AWS SDK for JavaScript V3 clients, as compared to instrumenting V2 clients. For instance, subsegments representing calls to DynamoDB will not return the table name. If you need this segment information in your traces, consider using the AWS SDK for JavaScript V2. AWS SDK clients 402 AWS X-Ray AWS SDK for JavaScript V2 Developer Guide You can instrument all AWS SDK V2 clients by wrapping your aws-sdk require statement in a call to AWSXRay.captureAWS. Example app.js - AWS SDK instrumentation const AWS = AWSXRay.captureAWS(require('aws-sdk')); To instrument individual clients, wrap your AWS SDK client in a call to AWSXRay.captureAWSClient. For example, to instrument an AmazonDynamoDB client: Example app.js - DynamoDB client instrumentation const AWSXRay = require('aws-xray-sdk'); ... const ddb = AWSXRay.captureAWSClient(new AWS.DynamoDB()); Warning Do not use both captureAWS and captureAWSClient together. This will lead to duplicate subsegments. If you want to use TypeScript with ECMAScript modules (ESM) to load your JavaScript code, use the following example to import libraries: Example app.js - AWS SDK instrumentation import * as AWS from 'aws-sdk'; import * as AWSXRay from 'aws-xray-sdk'; To instrument all AWS clients with ESM, use the following code: Example app.js - AWS SDK instrumentation import * as AWS from 'aws-sdk'; import * as AWSXRay from 'aws-xray-sdk'; AWS SDK clients 403 AWS X-Ray Developer Guide const XRAY_AWS = AWSXRay.captureAWS(AWS); const ddb = new XRAY_AWS.DynamoDB(); For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a separate node in the service |
xray-guide-117 | xray-guide.pdf | 117 | import * as AWSXRay from 'aws-xray-sdk'; AWS SDK clients 403 AWS X-Ray Developer Guide const XRAY_AWS = AWSXRay.captureAWS(AWS); const ddb = new XRAY_AWS.DynamoDB(); For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a separate node in the service map, with a generic DynamoDB node for calls that don't target a table. Example Subsegment for a call to DynamoDB to save an item { "id": "24756640c0d0978a", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "DynamoDB", "namespace": "aws", "http": { "response": { "content_length": 60, "status": 200 } }, "aws": { "table_name": "scorekeep-user", "operation": "UpdateItem", "request_id": "UBQNSO5AEM8T4FDA4RQDEB94OVTDRVV4K4HIRGVJF66Q9ASUAAJG", } } When you access named resources, calls to the following services create additional nodes in the service map. Calls that don't target specific resources create a generic node for the service. • Amazon DynamoDB – Table name • Amazon Simple Storage Service – Bucket and key name • Amazon Simple Queue Service – Queue name AWS SDK clients 404 AWS X-Ray AWS SDK for JavaScript V3 Developer Guide The AWS SDK for JavaScript V3 is modular, so your code only loads the modules it needs. Because of this, it isn't possible to instrument all AWS SDK clients as V3 does not support the captureAWS method. If you want to use TypeScript with ECMAScript Modules (ESM) to load your JavaScript code, you can use the following example to import libraries: import * as AWS from 'aws-sdk'; import * as AWSXRay from 'aws-xray-sdk'; Instrument each AWS SDK client using the AWSXRay.captureAWSv3Client method. For example, to instrument an AmazonDynamoDB client: Example app.js - DynamoDB client instrumentation using SDK for Javascript V3 const AWSXRay = require('aws-xray-sdk'); const { DynamoDBClient } = require("@aws-sdk/client-dynamodb"); ... const ddb = AWSXRay.captureAWSv3Client(new DynamoDBClient({ region: "region" })); When using AWS SDK for JavaScript V3, metadata such as table name, bucket and key name, or queue name, are not currently returned, and therefore the trace map will not contain discrete nodes for each named resource as it would when instrumenting AWS SDK clients using the AWS SDK for JavaScript V2. Example Subsegment for a call to DynamoDB to save an item, when using the AWS SDK for JavaScript V3 { "id": "24756640c0d0978a", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "DynamoDB", "namespace": "aws", "http": { "response": { "content_length": 60, AWS SDK clients 405 AWS X-Ray Developer Guide "status": 200 } }, "aws": { "operation": "UpdateItem", "request_id": "UBQNSO5AEM8T4FDA4RQDEB94OVTDRVV4K4HIRGVJF66Q9ASUAAJG", } } Tracing calls to downstream HTTP web services using the X-Ray SDK for Node.js When your application makes calls to microservices or public HTTP APIs, you can use the X-Ray SDK for Node.js client to instrument those calls and add the API to the service graph as a downstream service. Pass your http or https client to the X-Ray SDK for Node.js captureHTTPs method to trace outgoing calls. Note Calls using third-party HTTP request libraries, such as Axios or Superagent, are supported through the captureHTTPsGlobal() API and will still be traced when they use the native http module. Example app.js - HTTP client var AWSXRay = require('aws-xray-sdk'); var http = AWSXRay.captureHTTPs(require('http')); To enable tracing on all HTTP clients, call captureHTTPsGlobal before you load http. Example app.js - HTTP client (global) var AWSXRay = require('aws-xray-sdk'); AWSXRay.captureHTTPsGlobal(require('http')); var http = require('http'); Outgoing HTTP calls 406 AWS X-Ray Developer Guide When you instrument a call to a downstream web API, the X-Ray SDK for Node.js records a subsegment that contains information about the HTTP request and response. X-Ray uses the subsegment to generate an inferred segment for the remote API. Example Subsegment for a downstream HTTP call { "id": "004f72be19cddc2a", "start_time": 1484786387.131, "end_time": 1484786387.501, "name": "names.example.com", "namespace": "remote", "http": { "request": { "method": "GET", "url": "https://names.example.com/" }, "response": { "content_length": -1, "status": 200 } } } Example Inferred segment for a downstream HTTP call { "id": "168416dc2ea97781", "name": "names.example.com", "trace_id": "1-62be1272-1b71c4274f39f122afa64eab", "start_time": 1484786387.131, "end_time": 1484786387.501, "parent_id": "004f72be19cddc2a", "http": { "request": { "method": "GET", "url": "https://names.example.com/" }, "response": { "content_length": -1, "status": 200 } }, Outgoing HTTP calls 407 AWS X-Ray "inferred": true } Developer Guide Tracing SQL queries with the X-Ray SDK for Node.js Instrument SQL database queries by wrapping your SQL client in the corresponding X-Ray SDK for Node.js client method. • PostgreSQL – AWSXRay.capturePostgres() var AWSXRay = require('aws-xray-sdk'); var pg = AWSXRay.capturePostgres(require('pg')); var client = new pg.Client(); • MySQL – AWSXRay.captureMySQL() var AWSXRay = require('aws-xray-sdk'); var mysql = AWSXRay.captureMySQL(require('mysql')); ... var connection = mysql.createConnection(config); When you use an instrumented client to make SQL queries, the X-Ray SDK for Node.js records information about the |
xray-guide-118 | xray-guide.pdf | 118 | }, "response": { "content_length": -1, "status": 200 } }, Outgoing HTTP calls 407 AWS X-Ray "inferred": true } Developer Guide Tracing SQL queries with the X-Ray SDK for Node.js Instrument SQL database queries by wrapping your SQL client in the corresponding X-Ray SDK for Node.js client method. • PostgreSQL – AWSXRay.capturePostgres() var AWSXRay = require('aws-xray-sdk'); var pg = AWSXRay.capturePostgres(require('pg')); var client = new pg.Client(); • MySQL – AWSXRay.captureMySQL() var AWSXRay = require('aws-xray-sdk'); var mysql = AWSXRay.captureMySQL(require('mysql')); ... var connection = mysql.createConnection(config); When you use an instrumented client to make SQL queries, the X-Ray SDK for Node.js records information about the connection and query in a subsegment. Including additional data in SQL subsegments You can add additional information to subsegments generated for SQL queries, as long as it's mapped to an allow-listed SQL field. For example, to record the sanitized SQL query string in a subsegment, you can add it directly to the subsegment's SQL object. Example Assign SQL to subsegment const queryString = 'SELECT * FROM MyTable'; connection.query(queryString, ...); // Retrieve the most recently created subsegment const subs = AWSXRay.getSegment().subsegments; if (subs & & subs.length > 0) { var sqlSub = subs[subs.length - 1]; sqlSub.sql.sanitized_query = queryString; SQL queries 408 AWS X-Ray } Developer Guide For a full list of allow-listed SQL fields, see SQL Queries in the AWS X-Ray Developer Guide. Generating custom subsegments with the X-Ray SDK for Node.js Subsegments extend a trace's segment with details about work done in order to serve a request. Each time you make a call with an instrumented client, the X-Ray SDK records the information generated in a subsegment. You can create additional subsegments to group other subsegments, to measure the performance of a section of code, or to record annotations and metadata. Custom Express subsegments To create a custom subsegment for a function that makes calls to downstream services, use the captureAsyncFunc function. Example app.js - custom subsegments Express var AWSXRay = require('aws-xray-sdk'); app.use(AWSXRay.express.openSegment('MyApp')); app.get('/', function (req, res) { var host = 'api.example.com'; AWSXRay.captureAsyncFunc('send', function(subsegment) { sendRequest(host, function() { console.log('rendering!'); res.render('index'); subsegment.close(); }); }); }); app.use(AWSXRay.express.closeSegment()); function sendRequest(host, cb) { var options = { host: host, path: '/', }; Custom subsegments 409 AWS X-Ray Developer Guide var callback = function(response) { var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { cb(); }); } http.request(options, callback).end(); }; In this example, the application creates a custom subsegment named send for calls to the sendRequest function. captureAsyncFunc passes a subsegment that you must close within the callback function when the asynchronous calls that it makes are complete. For synchronous functions, you can use the captureFunc function, which closes the subsegment automatically as soon as the function block finishes executing. When you create a subsegment within a segment or another subsegment, the X-Ray SDK for Node.js generates an ID for it and records the start time and end time. Example Subsegment with metadata "subsegments": [{ "id": "6f1605cd8a07cb70", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "Custom subsegment for UserModel.saveUser function", "metadata": { "debug": { "test": "Metadata string from UserModel.saveUser" } }, Custom Lambda subsegments The SDK is configured to automatically create a placeholder facade segment when it detects it's running in Lambda. To create a basic subsegement, which will create a single Custom subsegments 410 AWS X-Ray Developer Guide AWS::Lambda::Function node on the X-Ray trace map, call and repurpose the facade segment. If you manually create a new segment with a new ID (while sharing the trace ID, parent ID and the sampling decision) you will be able to send a new segment. Example app.js - manual custom subsegments const segment = AWSXRay.getSegment(); //returns the facade segment const subsegment = segment.addNewSubsegment('subseg'); ... subsegment.close(); //the segment is closed by the SDK automatically Add annotations and metadata to segments with the X-Ray SDK for Node.js You can record additional information about requests, the environment, or your application with annotations and metadata. You can add annotations and metadata to the segments that the X-Ray SDK creates, or to custom subsegments that you create. Annotations are key-value pairs with string, number, or Boolean values. Annotations are indexed for use with filter expressions. Use annotations to record data that you want to use to group traces in the console, or when calling the GetTraceSummaries API. Metadata are key-value pairs that can have values of any type, including objects and lists, but are not indexed for use with filter expressions. Use metadata to record additional data that you want stored in the trace but don't need to use with search. In addition to annotations and metadata, you can also record user ID strings on segments. User IDs are recorded in a separate field on segments and are indexed for use with search. Sections • Recording annotations with the X-Ray SDK for Node.js • Recording metadata with the |
xray-guide-119 | xray-guide.pdf | 119 | in the console, or when calling the GetTraceSummaries API. Metadata are key-value pairs that can have values of any type, including objects and lists, but are not indexed for use with filter expressions. Use metadata to record additional data that you want stored in the trace but don't need to use with search. In addition to annotations and metadata, you can also record user ID strings on segments. User IDs are recorded in a separate field on segments and are indexed for use with search. Sections • Recording annotations with the X-Ray SDK for Node.js • Recording metadata with the X-Ray SDK for Node.js • Recording user IDs with the X-Ray SDK for Node.js Recording annotations with the X-Ray SDK for Node.js Use annotations to record information on segments or subsegments that you want indexed for search. Annotations and metadata 411 AWS X-Ray Annotation Requirements Developer Guide • Keys – The key for an X-Ray annotation can have up to 500 alphanumeric characters. You cannot use spaces or symbols other than a dot or period ( . ) • Values – The value for an X-Ray annotation can have up to 1,000 Unicode characters. • The number of Annotations – You can use up to 50 annotations per trace. To record annotations 1. Get a reference to the current segment or subsegment. var AWSXRay = require('aws-xray-sdk'); ... var document = AWSXRay.getSegment(); 2. Call addAnnotation with a String key, and a Boolean, Number, or String value. document.addAnnotation("mykey", "my value"); The following example shows how to call putAnnotation with a String key that includes a dot, and a Boolean, Number, or String value. document.putAnnotation("testkey.test", "my value"); The SDK records annotations as key-value pairs in an annotations object in the segment document. Calling addAnnotation twice with the same key overwrites previously recorded values on the same segment or subsegment. To find traces that have annotations with specific values, use the annotation[key] keyword in a filter expression. Example app.js - annotations var AWS = require('aws-sdk'); var AWSXRay = require('aws-xray-sdk'); var ddb = AWSXRay.captureAWSClient(new AWS.DynamoDB()); ... app.post('/signup', function(req, res) { Annotations and metadata 412 Developer Guide AWS X-Ray var item = { 'email': {'S': req.body.email}, 'name': {'S': req.body.name}, 'preview': {'S': req.body.previewAccess}, 'theme': {'S': req.body.theme} }; var seg = AWSXRay.getSegment(); seg.addAnnotation('theme', req.body.theme); ddb.putItem({ 'TableName': ddbTable, 'Item': item, 'Expected': { email: { Exists: false } } }, function(err, data) { ... Recording metadata with the X-Ray SDK for Node.js Use metadata to record information on segments or subsegments that you don't need indexed for search. Metadata values can be strings, numbers, Booleans, or any other object that can be serialized into a JSON object or array. To record metadata 1. Get a reference to the current segment or subsegment. var AWSXRay = require('aws-xray-sdk'); ... var document = AWSXRay.getSegment(); 2. Call addMetadata with a string key, a Boolean, number, string, or object value, and a string namespace. document.addMetadata("my key", "my value", "my namespace"); or Call addMetadata with just a key and value. document.addMetadata("my key", "my value"); Annotations and metadata 413 AWS X-Ray Developer Guide If you don't specify a namespace, the SDK uses default. Calling addMetadata twice with the same key overwrites previously recorded values on the same segment or subsegment. Recording user IDs with the X-Ray SDK for Node.js Record user IDs on request segments to identify the user who sent the request. This operation isn’t compatible with AWS Lambda functions because segments in Lambda environments are immutable. The setUser call can be applied only to segments, not subsegments. To record user IDs 1. Get a reference to the current segment or subsegment. var AWSXRay = require('aws-xray-sdk'); ... var document = AWSXRay.getSegment(); 2. Call setUser() with a string ID of the user who sent the request. var user = 'john123'; AWSXRay.getSegment().setUser(user); You can call setUser to record the user ID as soon as your express application starts processing a request. If you will use the segment only to set the user ID, you can chain the calls in a single line. Example app.js - user ID var AWS = require('aws-sdk'); var AWSXRay = require('aws-xray-sdk'); var uuidv4 = require('uuid/v4'); var ddb = AWSXRay.captureAWSClient(new AWS.DynamoDB()); ... app.post('/signup', function(req, res) { var userId = uuidv4(); var item = { 'userId': {'S': userId}, 'email': {'S': req.body.email}, 'name': {'S': req.body.name} }; Annotations and metadata 414 AWS X-Ray Developer Guide var seg = AWSXRay.getSegment().setUser(userId); ddb.putItem({ 'TableName': ddbTable, 'Item': item, 'Expected': { email: { Exists: false } } }, function(err, data) { ... To find traces for a user ID, use the user keyword in a filter expression. Annotations and metadata 415 AWS X-Ray Developer Guide Working with Python There are two ways to instrument your Python application to send traces to X-Ray: • AWS Distro for OpenTelemetry Python – An AWS distribution that provides a set of open source libraries for sending correlated |
xray-guide-120 | xray-guide.pdf | 120 | {'S': userId}, 'email': {'S': req.body.email}, 'name': {'S': req.body.name} }; Annotations and metadata 414 AWS X-Ray Developer Guide var seg = AWSXRay.getSegment().setUser(userId); ddb.putItem({ 'TableName': ddbTable, 'Item': item, 'Expected': { email: { Exists: false } } }, function(err, data) { ... To find traces for a user ID, use the user keyword in a filter expression. Annotations and metadata 415 AWS X-Ray Developer Guide Working with Python There are two ways to instrument your Python application to send traces to X-Ray: • AWS Distro for OpenTelemetry Python – An AWS distribution that provides a set of open source libraries for sending correlated metrics and traces to multiple AWS monitoring solutions, including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service, via the AWS Distro for OpenTelemetry Collector. • AWS X-Ray SDK for Python – A set of libraries for generating and sending traces to X-Ray via the X-Ray daemon. For more information, see Choosing between the AWS Distro for OpenTelemetry and X-Ray SDKs. AWS Distro for OpenTelemetry Python With the AWS Distro for OpenTelemetry (ADOT) Python, you can instrument your applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Using X-Ray with ADOT requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. ADOT Python includes auto-instrumentation support, enabling your application to send traces without code changes. To get started, see the AWS Distro for OpenTelemetry Python documentation. For more information about using the AWS Distro for OpenTelemetry with AWS X-Ray and other AWS services, see AWS Distro for OpenTelemetry or the AWS Distro for OpenTelemetry Documentation. For more information about language support and usage, see AWS Observability on GitHub. AWS X-Ray SDK for Python The X-Ray SDK for Python is a library for Python web applications that provides 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, HTTP clients, or an SQL database connector. You can also create segments manually and add debug information in annotations and metadata. AWS Distro for OpenTelemetry Python 416 AWS X-Ray Developer Guide You can download the SDK with pip. $ pip install aws-xray-sdk Note The X-Ray SDK for Python is an open source project. You can follow the project and submit issues and pull requests on GitHub: github.com/aws/aws-xray-sdk-python If you use Django or Flask, start by adding the SDK middleware to your application to trace incoming requests. The middleware creates a segment for each traced request, and completes the segment when the response is sent. While the segment is open, you can use the SDK client's methods to add information to the segment and create subsegments to trace downstream calls. The SDK also automatically records exceptions that your application throws while the segment is open. For other applications, you can create segments manually. For Lambda functions called by an instrumented application or service, Lambda reads the tracing header and traces sampled requests automatically. For other functions, you can configure Lambda to sample and trace incoming requests. In either case, Lambda creates the segment and provides it to the X-Ray SDK. Note On Lambda, the X-Ray SDK is optional. If you don't use it in your function, your service map will still include a node for the Lambda service, and one for each Lambda function. By adding the SDK, you can instrument your function code to add subsegments to the function segment recorded by Lambda. See AWS Lambda and AWS X-Ray for more information. See Worker for a example Python function instrumented in Lambda. Next, use the X-Ray SDK for Python to instrument downstream calls by patching your application's libraries. The SDK supports the following libraries. Supported Libraries • botocore, boto3 – Instrument AWS SDK for Python (Boto) clients. X-Ray SDK for Python 417 AWS X-Ray Developer Guide • pynamodb – Instrument PynamoDB's version of the Amazon DynamoDB client. • aiobotocore, aioboto3 – Instrument asyncio-integrated versions of SDK for Python clients. • requests, aiohttp – Instrument high-level HTTP clients. • httplib, http.client – Instrument low-level HTTP clients and the higher level libraries that use them. • sqlite3 – Instrument SQLite clients. • mysql-connector-python – Instrument MySQL clients. • pg8000 – Instrument Pure-Python PostgreSQL interface. • psycopg2 – Instrument PostgreSQL database adapter. • pymongo – Instrument MongoDB clients. • pymysql – Instrument PyMySQL based clients for MySQL and MariaDB. Whenever your application makes calls to AWS, an SQL database, or other HTTP services, the SDK records information about the call in a subsegment. AWS services and the resources that you access within the services appear as downstream nodes on the trace map to |
xray-guide-121 | xray-guide.pdf | 121 | – Instrument low-level HTTP clients and the higher level libraries that use them. • sqlite3 – Instrument SQLite clients. • mysql-connector-python – Instrument MySQL clients. • pg8000 – Instrument Pure-Python PostgreSQL interface. • psycopg2 – Instrument PostgreSQL database adapter. • pymongo – Instrument MongoDB clients. • pymysql – Instrument PyMySQL based clients for MySQL and MariaDB. Whenever your application makes calls to AWS, an SQL database, or other HTTP services, the SDK records information about the call in a subsegment. AWS services and the resources that you access within the services appear as downstream nodes on the trace map to help you identify errors and throttling issues on individual connections. After you start using the SDK, customize its behavior by configuring the recorder and middleware. You can add plugins to record data about the compute resources running your application, customize sampling behavior by defining sampling rules, and set the log level to see more or less information from the SDK in your application logs. Record additional information about requests and the work that your application does in annotations and metadata. Annotations are simple key-value pairs that are indexed for use with filter expressions, so that you can search for traces that contain specific data. Metadata entries are less restrictive and can record entire objects and arrays — anything that can be serialized into JSON. Annotations and Metadata Annotations and metadata are arbitrary text that you add to segments with the X-Ray SDK. Annotations are indexed for use with filter expressions. Metadata are not indexed, but can be viewed in the raw segment with the X-Ray console or API. Anyone that you grant read access to X-Ray can view this data. X-Ray SDK for Python 418 AWS X-Ray Developer Guide When you have a lot of instrumented clients in your code, a single request segment can contain a large number of subsegments, one for each call made with an instrumented client. You can organize and group subsegments by wrapping client calls in custom subsegments. You can create a custom subsegment for an entire function or any section of code. You can then you can record metadata and annotations on the subsegment instead of writing everything on the parent segment. For reference documentation for the SDK's classes and methods, see the AWS X-Ray SDK for Python API Reference. Requirements The X-Ray SDK for Python supports the following language and library versions. • Python – 2.7, 3.4, and newer • Django – 1.10 and newer • Flask – 0.10 and newer • aiohttp – 2.3.0 and newer • AWS SDK for Python (Boto) – 1.4.0 and newer • botocore – 1.5.0 and newer • enum – 0.4.7 and newer, for Python versions 3.4.0 and older • jsonpickle – 1.0.0 and newer • setuptools – 40.6.3 and newer • wrapt – 1.11.0 and newer Dependency management The X-Ray SDK for Python is available from pip. • Package – aws-xray-sdk Add the SDK as a dependency in your requirements.txt file. Example requirements.txt aws-xray-sdk==2.4.2 Requirements 419 AWS X-Ray boto3==1.4.4 botocore==1.5.55 Django==1.11.3 Developer Guide If you use Elastic Beanstalk to deploy your application, Elastic Beanstalk installs all of the packages in requirements.txt automatically. Configuring the X-Ray SDK for Python The X-Ray SDK for Python has a class named xray_recorder that provides the global recorder. You can configure the global recorder to customize the middleware that creates segments for incoming HTTP calls. Sections • Service plugins • Sampling rules • Logging • Recorder configuration in code • Recorder configuration with Django • Environment variables Service plugins Use plugins to record information about the service hosting your application. Plugins • Amazon EC2 – EC2Plugin adds the instance ID, Availability Zone, and the CloudWatch Logs Group. • Elastic Beanstalk – ElasticBeanstalkPlugin adds the environment name, version label, and deployment ID. • Amazon ECS – ECSPlugin adds the container ID. Configuration 420 AWS X-Ray Developer Guide To use a plugin, call configure on the xray_recorder. from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core import patch_all xray_recorder.configure(service='My app') plugins = ('ElasticBeanstalkPlugin', 'EC2Plugin') xray_recorder.configure(plugins=plugins) patch_all() Note Since plugins are passed in as a tuple, be sure to include a trailing , when specifying a single plugin. For example, plugins = ('EC2Plugin',) You can also use environment variables, which take precedence over values set in code, to configure the recorder. Configure plugins before patching libraries to record downstream calls. The SDK also uses plugin settings to set the origin field on the segment. This indicates the type of AWS resource that runs your application. When you use multiple plugins, the SDK uses the following resolution order to determine the origin: ElasticBeanstalk > EKS > ECS > EC2. Configuration 421 AWS X-Ray Sampling rules Developer Guide The SDK uses the sampling rules you define in the X-Ray console to determine which requests to record. The default rule |
xray-guide-122 | xray-guide.pdf | 122 | environment variables, which take precedence over values set in code, to configure the recorder. Configure plugins before patching libraries to record downstream calls. The SDK also uses plugin settings to set the origin field on the segment. This indicates the type of AWS resource that runs your application. When you use multiple plugins, the SDK uses the following resolution order to determine the origin: ElasticBeanstalk > EKS > ECS > EC2. Configuration 421 AWS X-Ray Sampling rules Developer Guide The SDK uses the sampling rules you define in the X-Ray console to determine which requests to record. The default rule traces the first request each second, and five percent of any additional requests across all services sending traces to X-Ray. Create additional rules in the X-Ray console to customize the amount of data recorded for each of your applications. The SDK applies custom rules in the order in which they are defined. If a request matches multiple custom rules, the SDK applies only the first rule. Note If the SDK can't reach X-Ray to get sampling rules, it reverts to a default local rule of the first request each second, and five percent of any additional requests per host. This can occur if the host doesn't have permission to call sampling APIs, or can't connect to the X- Ray daemon, which acts as a TCP proxy for API calls made by the SDK. You can also configure the SDK to load sampling rules from a JSON document. The SDK can use local rules as a backup for cases where X-Ray sampling is unavailable, or use local rules exclusively. Example sampling-rules.json { "version": 2, "rules": [ { "description": "Player moves.", "host": "*", "http_method": "*", "url_path": "/api/move/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 } } Configuration 422 AWS X-Ray Developer Guide This example defines one custom rule and a default rule. The custom rule applies a five-percent sampling rate with no minimum number of requests to trace for paths under /api/move/. The default rule traces the first request each second and 10 percent of additional requests. The disadvantage of defining rules locally is that the fixed target is applied by each instance of the recorder independently, instead of being managed by the X-Ray service. As you deploy more hosts, the fixed rate is multiplied, making it harder to control the amount of data recorded. On AWS Lambda, you cannot modify the sampling rate. If your function is called by an instrumented service, calls that generated requests that were sampled by that service will be recorded by Lambda. If active tracing is enabled and no tracing header is present, Lambda makes the sampling decision. To configure backup sampling rules, call xray_recorder.configure, as shown in the following example, where rules is either a dictionary of rules or the absolute path to a JSON file containing sampling rules. xray_recorder.configure(sampling_rules=rules) To use only local rules, configure the recorder with a LocalSampler. from aws_xray_sdk.core.sampling.local.sampler import LocalSampler xray_recorder.configure(sampler=LocalSampler()) You can also configure the global recorder to disable sampling and instrument all incoming requests. Example main.py – Disable sampling xray_recorder.configure(sampling=False) Logging The SDK uses Python’s built-in logging module with a default WARNING logging level. Get a reference to the logger for the aws_xray_sdk class and call setLevel on it to configure the different log level for the library and the rest of your application. Example app.py – Logging logging.basicConfig(level='WARNING') Configuration 423 AWS X-Ray Developer Guide logging.getLogger('aws_xray_sdk').setLevel(logging.ERROR) Use debug logs to identify issues, such as unclosed subsegments, when you generate subsegments manually. Recorder configuration in code Additional settings are available from the configure method on xray_recorder. • context_missing – Set to LOG_ERROR to avoid throwing exceptions when your instrumented code attempts to record data when no segment is open. • daemon_address – Set the host and port of the X-Ray daemon listener. • service – Set a service name that the SDK uses for segments. • plugins – Record information about your application's AWS resources. • sampling – Set to False to disable sampling. • sampling_rules – Set the path of the JSON file containing your sampling rules. Example main.py – Disable context missing exceptions from aws_xray_sdk.core import xray_recorder xray_recorder.configure(context_missing='LOG_ERROR') Recorder configuration with Django If you use the Django framework, you can use the Django settings.py file to configure options on the global recorder. • AUTO_INSTRUMENT (Django only) – Record subsegments for built-in database and template rendering operations. • AWS_XRAY_CONTEXT_MISSING – Set to LOG_ERROR to avoid throwing exceptions when your instrumented code attempts to record data when no segment is open. • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener. • AWS_XRAY_TRACING_NAME – Set a service name that the SDK uses for segments. • PLUGINS – Record information about your application's AWS resources. • SAMPLING – Set to False to |
xray-guide-123 | xray-guide.pdf | 123 | If you use the Django framework, you can use the Django settings.py file to configure options on the global recorder. • AUTO_INSTRUMENT (Django only) – Record subsegments for built-in database and template rendering operations. • AWS_XRAY_CONTEXT_MISSING – Set to LOG_ERROR to avoid throwing exceptions when your instrumented code attempts to record data when no segment is open. • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener. • AWS_XRAY_TRACING_NAME – Set a service name that the SDK uses for segments. • PLUGINS – Record information about your application's AWS resources. • SAMPLING – Set to False to disable sampling. Configuration 424 AWS X-Ray Developer Guide • SAMPLING_RULES – Set the path of the JSON file containing your sampling rules. To enable recorder configuration in settings.py, add the Django middleware to the list of installed apps. Example settings.py – Installed apps INSTALLED_APPS = [ ... 'django.contrib.sessions', 'aws_xray_sdk.ext.django', ] Configure the available settings in a dict named XRAY_RECORDER. Example settings.py – Installed apps XRAY_RECORDER = { 'AUTO_INSTRUMENT': True, 'AWS_XRAY_CONTEXT_MISSING': 'LOG_ERROR', 'AWS_XRAY_DAEMON_ADDRESS': '127.0.0.1:5000', 'AWS_XRAY_TRACING_NAME': 'My application', 'PLUGINS': ('ElasticBeanstalkPlugin', 'EC2Plugin', 'ECSPlugin'), 'SAMPLING': False, } Environment variables You can use environment variables to configure the X-Ray SDK for Python. The SDK supports the following variables: • AWS_XRAY_TRACING_NAME – Set a service name that the SDK uses for segments. Overrides the service name that you set programmatically. • AWS_XRAY_SDK_ENABLED – When set to false, disables the SDK. By default, the SDK is enabled unless the environment variable is set to false. • When disabled, the global recorder automatically generates dummy segments and subsegments that are not sent to the daemon, and automatic patching is disabled. Middlewares are written as a wrapper over the global recorder. All segment and subsegment generation through the middleware also become dummy segment and dummy subsegments. Configuration 425 AWS X-Ray Developer Guide • Set the value of AWS_XRAY_SDK_ENABLED through the environment variable or through direct interaction with the global_sdk_config object from the aws_xray_sdk library. Settings to the environment variable override these interactions. • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener. By default, the SDK uses 127.0.0.1:2000 for both trace data (UDP) and sampling (TCP). Use this variable if you have configured the daemon to listen on a different port or if it is running on a different host. Format • Same port – address:port • Different ports – tcp:address:port udp:address:port • AWS_XRAY_CONTEXT_MISSING – Set to RUNTIME_ERROR to throw exceptions when your instrumented code attempts to record data when no segment is open. Valid Values • RUNTIME_ERROR – Throw a runtime exception. • LOG_ERROR – Log an error and continue (default). • IGNORE_ERROR – Ignore error and continue. Errors related to missing segments or subsegments can occur when you attempt to use an instrumented client in startup code that runs when no request is open, or in code that spawns a new thread. Environment variables override values set in code. Tracing incoming requests with the X-Ray SDK for Python middleware When you add the middleware to your application and configure a segment name, the X-Ray SDK for Python creates a segment for each sampled request. This segment includes timing, method, and disposition of the HTTP request. Additional instrumentation creates subsegments on this segment. The X-Ray SDK for Python supports the following middleware to instrument incoming HTTP requests: • Django Incoming requests 426 AWS X-Ray • Flask • Bottle Note Developer Guide For AWS Lambda functions, Lambda creates a segment for each sampled request. See AWS Lambda and AWS X-Ray for more information. See Worker for a example Python function instrumented in Lambda. For scripts or Python applications on other frameworks, you can create segments manually. Each segment has a name that identifies your application in the service map. The segment can be named statically, or you can configure the SDK to name it dynamically based on the host header in the incoming request. Dynamic naming lets you group traces based on the domain name in the request, and apply a default name if the name doesn't match an expected pattern (for example, if the host header is forged). Forwarded Requests If a load balancer or other intermediary forwards a request to your application, X-Ray takes the client IP from the X-Forwarded-For header in the request instead of from the source IP in the IP packet. The client IP that is recorded for a forwarded request can be forged, so it should not be trusted. When a request is forwarded, the SDK sets an additional field in the segment to indicate this. If the segment contains the field x_forwarded_for set to true, the client IP was taken from the X- Forwarded-For header in the HTTP request. The middleware creates a segment for each incoming request with an http block that contains the following information: • HTTP |
xray-guide-124 | xray-guide.pdf | 124 | the client IP from the X-Forwarded-For header in the request instead of from the source IP in the IP packet. The client IP that is recorded for a forwarded request can be forged, so it should not be trusted. When a request is forwarded, the SDK sets an additional field in the segment to indicate this. If the segment contains the field x_forwarded_for set to true, the client IP was taken from the X- Forwarded-For header in the HTTP request. The middleware creates a segment for each incoming request with an http block that contains the following information: • HTTP method – GET, POST, PUT, DELETE, etc. • Client address – The IP address of the client that sent the request. • Response code – The HTTP response code for the completed request. Incoming requests 427 AWS X-Ray Developer Guide • Timing – The start time (when the request was received) and end time (when the response was sent). • User agent — The user-agent from the request. • Content length — The content-length from the response. Sections • Adding the middleware to your application (Django) • Adding the middleware to your application (flask) • Adding the middleware to your application (Bottle) • Instrumenting Python code manually • Configuring a segment naming strategy Adding the middleware to your application (Django) Add the middleware to the MIDDLEWARE list in your settings.py file. The X-Ray middleware should be the first line in your settings.py file to ensure that requests that fail in other middleware are recorded. Example settings.py - X-Ray SDK for Python middleware MIDDLEWARE = [ 'aws_xray_sdk.ext.django.middleware.XRayMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware' ] Add the X-Ray SDK Django app to the INSTALLED_APPS list in your settings.py file. This will allow the X-Ray recorder to be configured during your app's startup. Example settings.py - X-Ray SDK for Python Django app INSTALLED_APPS = [ 'aws_xray_sdk.ext.django', Incoming requests 428 AWS X-Ray Developer Guide 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Configure a segment name in your settings.py file. Example settings.py – Segment name XRAY_RECORDER = { 'AWS_XRAY_TRACING_NAME': 'My application', 'PLUGINS': ('EC2Plugin',), } This tells the X-Ray recorder to trace requests served by your Django application with the default sampling rate. You can configure the recorder your Django settings file to apply custom sampling rules or change other settings. Note Since plugins are passed in as a tuple, be sure to include a trailing , when specifying a single plugin. For example, plugins = ('EC2Plugin',) Adding the middleware to your application (flask) To instrument your Flask application, first configure a segment name on the xray_recorder. Then, use the XRayMiddleware function to patch your Flask application in code. Example app.py from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.ext.flask.middleware import XRayMiddleware app = Flask(__name__) xray_recorder.configure(service='My application') XRayMiddleware(app, xray_recorder) Incoming requests 429 AWS X-Ray Developer Guide This tells the X-Ray recorder to trace requests served by your Flask application with the default sampling rate. You can configure the recorder in code to apply custom sampling rules or change other settings. Adding the middleware to your application (Bottle) To instrument your Bottle application, first configure a segment name on the xray_recorder. Then, use the XRayMiddleware function to patch your Bottle application in code. Example app.py from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.ext.bottle.middleware import XRayMiddleware app = Bottle() xray_recorder.configure(service='fallback_name', dynamic_naming='My application') app.install(XRayMiddleware(xray_recorder)) This tells the X-Ray recorder to trace requests served by your Bottle application with the default sampling rate. You can configure the recorder in code to apply custom sampling rules or change other settings. Instrumenting Python code manually If you don't use Django or Flask, you can create segments manually. You can create a segment for each incoming request, or create segments around patched HTTP or AWS SDK clients to provide context for the recorder to add subsegments. Example main.py – Manual instrumentation from aws_xray_sdk.core import xray_recorder # Start a segment segment = xray_recorder.begin_segment('segment_name') # Start a subsegment subsegment = xray_recorder.begin_subsegment('subsegment_name') # Add metadata and annotations segment.put_metadata('key', dict, 'namespace') subsegment.put_annotation('key', 'value') Incoming requests 430 AWS X-Ray Developer Guide # Close the subsegment and segment xray_recorder.end_subsegment() xray_recorder.end_segment() Configuring a segment naming strategy AWS X-Ray uses a service name to identify your application and distinguish it from the other applications, databases, external APIs, and AWS resources that your application uses. When the X- Ray SDK generates segments for incoming requests, it records your application's service name in the segment's name field. The X-Ray SDK can name segments after the hostname in the HTTP request header. However, this header can be forged, which could result in unexpected nodes in your service map. To prevent the SDK from naming segments incorrectly due to requests with forged host headers, you must specify a default name for incoming requests. If your application serves requests for multiple domains, you can configure the SDK to use a |
xray-guide-125 | xray-guide.pdf | 125 | external APIs, and AWS resources that your application uses. When the X- Ray SDK generates segments for incoming requests, it records your application's service name in the segment's name field. The X-Ray SDK can name segments after the hostname in the HTTP request header. However, this header can be forged, which could result in unexpected nodes in your service map. To prevent the SDK from naming segments incorrectly due to requests with forged host headers, you must specify a default name for incoming requests. If your application serves requests for multiple domains, you can configure the SDK to use a dynamic naming strategy to reflect this in segment names. A dynamic naming strategy allows the SDK to use the hostname for requests that match an expected pattern, and apply the default name to requests that don't. For example, you might have a single application serving requests to three subdomains– www.example.com, api.example.com, and static.example.com. You can use a dynamic naming strategy with the pattern *.example.com to identify segments for each subdomain with a different name, resulting in three service nodes on the service map. If your application receives requests with a hostname that doesn't match the pattern, you will see a fourth node on the service map with a fallback name that you specify. To use the same name for all request segments, specify the name of your application when you configure the recorder, as shown in the previous sections. A dynamic naming strategy defines a pattern that hostnames should match, and a default name to use if the hostname in the HTTP request doesn't match the pattern. To name segments dynamically in Django, add the DYNAMIC_NAMING setting to your settings.py file. Example settings.py – Dynamic naming XRAY_RECORDER = { 'AUTO_INSTRUMENT': True, 'AWS_XRAY_TRACING_NAME': 'My application', Incoming requests 431 AWS X-Ray Developer Guide 'DYNAMIC_NAMING': '*.example.com', 'PLUGINS': ('ElasticBeanstalkPlugin', 'EC2Plugin') } You can use '*' in the pattern to match any string, or '?' to match any single character. For Flask, configure the recorder in code. Example main.py – Segment name from aws_xray_sdk.core import xray_recorder xray_recorder.configure(service='My application') xray_recorder.configure(dynamic_naming='*.example.com') Note You can override the default service name that you define in code with the AWS_XRAY_TRACING_NAME environment variable. Patching libraries to instrument downstream calls To instrument downstream calls, use the X-Ray SDK for Python to patch the libraries that your application uses. The X-Ray SDK for Python can patch the following libraries. Supported Libraries • botocore, boto3 – Instrument AWS SDK for Python (Boto) clients. • pynamodb – Instrument PynamoDB's version of the Amazon DynamoDB client. • aiobotocore, aioboto3 – Instrument asyncio-integrated versions of SDK for Python clients. • requests, aiohttp – Instrument high-level HTTP clients. • httplib, http.client – Instrument low-level HTTP clients and the higher level libraries that use them. • sqlite3 – Instrument SQLite clients. • mysql-connector-python – Instrument MySQL clients. • pg8000 – Instrument Pure-Python PostgreSQL interface. • psycopg2 – Instrument PostgreSQL database adapter. • pymongo – Instrument MongoDB clients. Patching libraries 432 AWS X-Ray Developer Guide • pymysql – Instrument PyMySQL based clients for MySQL and MariaDB. When you use a patched library, the X-Ray SDK for Python creates a subsegment for the call and records information from the request and response. A segment must be available for the SDK to create the subsegment, either from the SDK middleware or from AWS Lambda. Note If you use SQLAlchemy ORM, you can instrument your SQL queries by importing the SDK's version of SQLAlchemy's session and query classes. See Use SQLAlchemy ORM for instructions. To patch all available libraries, use the patch_all function in aws_xray_sdk.core. Some libraries, such as httplib and urllib, may need to enable double patching by calling patch_all(double_patch=True). Example main.py – Patch all supported libraries import boto3 import botocore import requests import sqlite3 from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core import patch_all patch_all() To patch a single library, call patch with a tuple of the library name. In order to achieve this, you will need to provide a single element list. Example main.py – Patch specific libraries import boto3 import botocore import requests import mysql-connector-python from aws_xray_sdk.core import xray_recorder Patching libraries 433 AWS X-Ray Developer Guide from aws_xray_sdk.core import patch libraries = (['botocore']) patch(libraries) Note In some cases, the key that you use to patch a library does not match the library name. Some keys serve as aliases for one or more libraries. Libraries Aliases • httplib – httplib and http.client • mysql – mysql-connector-python Tracing context for asynchronous work For asyncio integrated libraries, or to create subsegments for asynchronous functions, you must also configure the X-Ray SDK for Python with an async context. Import the AsyncContext class and pass an instance of it to the X-Ray recorder. Note Web framework support libraries, such as AIOHTTP, are not handled through the aws_xray_sdk.core.patcher module. They will not appear in the patcher catalog |
xray-guide-126 | xray-guide.pdf | 126 | you use to patch a library does not match the library name. Some keys serve as aliases for one or more libraries. Libraries Aliases • httplib – httplib and http.client • mysql – mysql-connector-python Tracing context for asynchronous work For asyncio integrated libraries, or to create subsegments for asynchronous functions, you must also configure the X-Ray SDK for Python with an async context. Import the AsyncContext class and pass an instance of it to the X-Ray recorder. Note Web framework support libraries, such as AIOHTTP, are not handled through the aws_xray_sdk.core.patcher module. They will not appear in the patcher catalog of supported libraries. Example main.py – Patch aioboto3 import asyncio import aioboto3 import requests from aws_xray_sdk.core.async_context import AsyncContext from aws_xray_sdk.core import xray_recorder xray_recorder.configure(service='my_service', context=AsyncContext()) from aws_xray_sdk.core import patch Patching libraries 434 AWS X-Ray libraries = (['aioboto3']) patch(libraries) Developer Guide Tracing AWS SDK calls with the X-Ray SDK for Python When your application makes calls to AWS services to store data, write to a queue, or send notifications, the X-Ray SDK for Python tracks the calls downstream in subsegments. Traced AWS services and resources that you access within those services (for example, an Amazon S3 bucket or Amazon SQS queue), appear as downstream nodes on the trace map in the X-Ray console. The X-Ray SDK for Python automatically instruments all AWS SDK clients when you patch the botocore library. You cannot instrument individual clients. For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a separate node in the service map, with a generic DynamoDB node for calls that don't target a table. Example Subsegment for a call to DynamoDB to save an item { "id": "24756640c0d0978a", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "DynamoDB", "namespace": "aws", "http": { "response": { "content_length": 60, "status": 200 } }, "aws": { "table_name": "scorekeep-user", "operation": "UpdateItem", "request_id": "UBQNSO5AEM8T4FDA4RQDEB94OVTDRVV4K4HIRGVJF66Q9ASUAAJG", } } AWS SDK clients 435 AWS X-Ray Developer Guide When you access named resources, calls to the following services create additional nodes in the service map. Calls that don't target specific resources create a generic node for the service. • Amazon DynamoDB – Table name • Amazon Simple Storage Service – Bucket and key name • Amazon Simple Queue Service – Queue name Tracing calls to downstream HTTP web services using the X-Ray SDK for Python When your application makes calls to microservices or public HTTP APIs, you can use the X-Ray SDK for Python to instrument those calls and add the API to the service graph as a downstream service. To instrument HTTP clients, patch the library that you use to make outgoing calls. If you use requests or Python's built in HTTP client, that's all you need to do. For aiohttp, also configure the recorder with an async context. If you use aiohttp 3's client API, you also need to configure the ClientSession's with an instance of the tracing configuration provided by the SDK. Example aiohttp 3 client API from aws_xray_sdk.ext.aiohttp.client import aws_xray_trace_config async def foo(): trace_config = aws_xray_trace_config() async with ClientSession(loop=loop, trace_configs=[trace_config]) as session: async with session.get(url) as resp await resp.read() When you instrument a call to a downstream web API, the X-Ray SDK for Python records a subsegment that contains information about the HTTP request and response. X-Ray uses the subsegment to generate an inferred segment for the remote API. Example Subsegment for a downstream HTTP call { "id": "004f72be19cddc2a", Outgoing HTTP calls 436 AWS X-Ray Developer Guide "start_time": 1484786387.131, "end_time": 1484786387.501, "name": "names.example.com", "namespace": "remote", "http": { "request": { "method": "GET", "url": "https://names.example.com/" }, "response": { "content_length": -1, "status": 200 } } } Example Inferred segment for a downstream HTTP call { "id": "168416dc2ea97781", "name": "names.example.com", "trace_id": "1-62be1272-1b71c4274f39f122afa64eab", "start_time": 1484786387.131, "end_time": 1484786387.501, "parent_id": "004f72be19cddc2a", "http": { "request": { "method": "GET", "url": "https://names.example.com/" }, "response": { "content_length": -1, "status": 200 } }, "inferred": true } Generating custom subsegments with the X-Ray SDK for Python Subsegments extend a trace's segment with details about work done in order to serve a request. Each time you make a call with an instrumented client, the X-Ray SDK records the information Custom subsegments 437 AWS X-Ray Developer Guide generated in a subsegment. You can create additional subsegments to group other subsegments, to measure the performance of a section of code, or to record annotations and metadata. To manage subsegments, use the begin_subsegment and end_subsegment methods. Example main.py – Custom subsegment from aws_xray_sdk.core import xray_recorder subsegment = xray_recorder.begin_subsegment('annotations') subsegment.put_annotation('id', 12345) xray_recorder.end_subsegment() To create a subsegment for a synchronous |
xray-guide-127 | xray-guide.pdf | 127 | for Python Subsegments extend a trace's segment with details about work done in order to serve a request. Each time you make a call with an instrumented client, the X-Ray SDK records the information Custom subsegments 437 AWS X-Ray Developer Guide generated in a subsegment. You can create additional subsegments to group other subsegments, to measure the performance of a section of code, or to record annotations and metadata. To manage subsegments, use the begin_subsegment and end_subsegment methods. Example main.py – Custom subsegment from aws_xray_sdk.core import xray_recorder subsegment = xray_recorder.begin_subsegment('annotations') subsegment.put_annotation('id', 12345) xray_recorder.end_subsegment() To create a subsegment for a synchronous function, use the @xray_recorder.capture decorator. You can pass a name for the subsegment to the capture function or leave it out to use the function name. Example main.py – Function subsegment from aws_xray_sdk.core import xray_recorder @xray_recorder.capture('## create_user') def create_user(): ... For an asynchronous function, use the @xray_recorder.capture_async decorator, and pass an async context to the recorder. Example main.py – Asynchronous function subsegment from aws_xray_sdk.core.async_context import AsyncContext from aws_xray_sdk.core import xray_recorder xray_recorder.configure(service='my_service', context=AsyncContext()) @xray_recorder.capture_async('## create_user') async def create_user(): ... async def main(): await myfunc() Custom subsegments 438 AWS X-Ray Developer Guide When you create a subsegment within a segment or another subsegment, the X-Ray SDK for Python generates an ID for it and records the start time and end time. Example Subsegment with metadata "subsegments": [{ "id": "6f1605cd8a07cb70", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "Custom subsegment for UserModel.saveUser function", "metadata": { "debug": { "test": "Metadata string from UserModel.saveUser" } }, Add annotations and metadata to segments with the X-Ray SDK for Python You can record additional information about requests, the environment, or your application with annotations and metadata. You can add annotations and metadata to the segments that the X-Ray SDK creates, or to custom subsegments that you create. Annotations are key-value pairs with string, number, or Boolean values. Annotations are indexed for use with filter expressions. Use annotations to record data that you want to use to group traces in the console, or when calling the GetTraceSummaries API. Metadata are key-value pairs that can have values of any type, including objects and lists, but are not indexed for use with filter expressions. Use metadata to record additional data that you want stored in the trace but don't need to use with search. In addition to annotations and metadata, you can also record user ID strings on segments. User IDs are recorded in a separate field on segments and are indexed for use with search. Sections • Recording annotations with the X-Ray SDK for Python • Recording metadata with the X-Ray SDK for Python • Recording user IDs with the X-Ray SDK for Python Annotations and metadata 439 AWS X-Ray Developer Guide Recording annotations with the X-Ray SDK for Python Use annotations to record information on segments or subsegments that you want indexed for search. Annotation Requirements • Keys – The key for an X-Ray annotation can have up to 500 alphanumeric characters. You cannot use spaces or symbols other than a dot or period ( . ) • Values – The value for an X-Ray annotation can have up to 1,000 Unicode characters. • The number of Annotations – You can use up to 50 annotations per trace. To record annotations 1. Get a reference to the current segment or subsegment from xray_recorder. from aws_xray_sdk.core import xray_recorder ... document = xray_recorder.current_segment() or from aws_xray_sdk.core import xray_recorder ... document = xray_recorder.current_subsegment() 2. Call put_annotation with a String key, and a Boolean, Number, or String value. document.put_annotation("mykey", "my value"); The following example shows how to call putAnnotation with a String key that includes a dot, and a Boolean, Number, or String value. document.putAnnotation("testkey.test", "my value"); Alternatively, you can use the put_annotation method on the xray_recorder. This method records annotations on the current subsegment or, if no subsegment is open, on the segment. Annotations and metadata 440 AWS X-Ray Developer Guide xray_recorder.put_annotation("mykey", "my value"); The SDK records annotations as key-value pairs in an annotations object in the segment document. Calling put_annotation twice with the same key overwrites previously recorded values on the same segment or subsegment. To find traces that have annotations with specific values, use the annotation[key] keyword in a filter expression. Recording metadata with the X-Ray SDK for Python Use metadata to record information on segments or subsegments that you don't need indexed for search. Metadata values can be strings, numbers, Booleans, or any object that can be serialized into a JSON object or array. To record metadata 1. Get a reference to the current segment or subsegment from xray_recorder. from aws_xray_sdk.core import xray_recorder ... document = xray_recorder.current_segment() or from aws_xray_sdk.core import xray_recorder ... document = xray_recorder.current_subsegment() 2. Call put_metadata with a String key; a Boolean, Number, String, or Object value; and a String namespace. document.put_metadata("my key", "my value", "my namespace"); or |
xray-guide-128 | xray-guide.pdf | 128 | metadata with the X-Ray SDK for Python Use metadata to record information on segments or subsegments that you don't need indexed for search. Metadata values can be strings, numbers, Booleans, or any object that can be serialized into a JSON object or array. To record metadata 1. Get a reference to the current segment or subsegment from xray_recorder. from aws_xray_sdk.core import xray_recorder ... document = xray_recorder.current_segment() or from aws_xray_sdk.core import xray_recorder ... document = xray_recorder.current_subsegment() 2. Call put_metadata with a String key; a Boolean, Number, String, or Object value; and a String namespace. document.put_metadata("my key", "my value", "my namespace"); or Call put_metadata with just a key and value. document.put_metadata("my key", "my value"); Annotations and metadata 441 AWS X-Ray Developer Guide Alternatively, you can use the put_metadata method on the xray_recorder. This method records metadata on the current subsegment or, if no subsegment is open, on the segment. xray_recorder.put_metadata("my key", "my value"); If you don't specify a namespace, the SDK uses default. Calling put_metadata twice with the same key overwrites previously recorded values on the same segment or subsegment. Recording user IDs with the X-Ray SDK for Python Record user IDs on request segments to identify the user who sent the request. To record user IDs 1. Get a reference to the current segment from xray_recorder. from aws_xray_sdk.core import xray_recorder ... document = xray_recorder.current_segment() 2. Call setUser with a String ID of the user who sent the request. document.set_user("U12345"); You can call set_user in your controllers to record the user ID as soon as your application starts processing a request. To find traces for a user ID, use the user keyword in a filter expression. Instrumenting web frameworks deployed to serverless environments The AWS X-Ray SDK for Python supports instrumenting web frameworks deployed in serverless applications. Serverless is the native architecture of the cloud that enables you to shift more of your operational responsibilities to AWS, increasing your agility and innovation. Serverless architecture is a software application model that enables you to build and run applications and services without thinking about servers. It eliminates infrastructure management tasks such as server or cluster provisioning, patching, operating system maintenance, and capacity provisioning. You can build serverless solutions for nearly any type of application or backend Instrument serverless applications 442 AWS X-Ray Developer Guide service, and everything required to run and scale your application with high availability is handled for you. This tutorial shows you how to automatically instrument AWS X-Ray on a web framework, such as Flask or Django, that is deployed to a serverless environment. X-Ray instrumentation of the application enables you to view all downstream calls that are made, starting from Amazon API Gateway through your AWS Lambda function, and the outgoing calls your application makes. The X-Ray SDK for Python supports the following Python application frameworks: • Flask version 0.8, or later • Django version 1.0, or later This tutorial develops an example serverless application that is deployed to Lambda and invoked by API Gateway. This tutorial uses Zappa to automatically deploy the application to Lambda and to configure the API Gateway endpoint. Prerequisites • Zappa • Python – Version 2.7 or 3.6. • AWS CLI – Verify that your AWS CLI is configured with the account and AWS Region in which you will deploy your application. • Pip • Virtualenv Step 1: Create an environment In this step, you create a virtual environment using virtualenv to host an application. 1. Using the AWS CLI, create a directory for the application. Then change to the new directory. mkdir serverless_application cd serverless_application 2. Next, create a virtual environment within your new directory. Use the following command to activate it. Instrument serverless applications 443 AWS X-Ray Developer Guide # Create our virtual environment virtualenv serverless_env # Activate it source serverless_env/bin/activate 3. Install X-Ray, Flask, Zappa, and the Requests library to your environment. # Install X-Ray, Flask, Zappa, and Requests into your environment pip install aws-xray-sdk flask zappa requests 4. Add application code to the serverless_application directory. For this example, we can build off of Flasks's Hello World example. In the serverless_application directory, create a file named my_app.py. Then use a text editor to add the following commands. This application instruments the Requests library, patches the Flask application's middleware, and opens the endpoint '/'. # Import the X-Ray modules from aws_xray_sdk.ext.flask.middleware import XRayMiddleware from aws_xray_sdk.core import patcher, xray_recorder from flask import Flask import requests # Patch the requests module to enable automatic instrumentation patcher.patch(('requests',)) app = Flask(__name__) # Configure the X-Ray recorder to generate segments with our service name xray_recorder.configure(service='My First Serverless App') # Instrument the Flask application XRayMiddleware(app, xray_recorder) @app.route('/') def hello_world(): resp = requests.get("https://aws.amazon.com") return 'Hello, World: %s' % resp.url Instrument serverless applications 444 AWS X-Ray Developer Guide Step 2: Create and deploy a zappa environment In this step you will |
xray-guide-129 | xray-guide.pdf | 129 | library, patches the Flask application's middleware, and opens the endpoint '/'. # Import the X-Ray modules from aws_xray_sdk.ext.flask.middleware import XRayMiddleware from aws_xray_sdk.core import patcher, xray_recorder from flask import Flask import requests # Patch the requests module to enable automatic instrumentation patcher.patch(('requests',)) app = Flask(__name__) # Configure the X-Ray recorder to generate segments with our service name xray_recorder.configure(service='My First Serverless App') # Instrument the Flask application XRayMiddleware(app, xray_recorder) @app.route('/') def hello_world(): resp = requests.get("https://aws.amazon.com") return 'Hello, World: %s' % resp.url Instrument serverless applications 444 AWS X-Ray Developer Guide Step 2: Create and deploy a zappa environment In this step you will use Zappa to automatically configure an API Gateway endpoint and then deploy to Lambda. 1. Initialize Zappa from within the serverless_application directory. For this example, we used the default settings, but if you have customization preferences, Zappa displays configuration instructions. zappa init What do you want to call this environment (default 'dev'): dev ... What do you want to call your bucket? (default 'zappa-*******'): zappa-******* ... ... It looks like this is a Flask application. What's the modular path to your app's function? This will likely be something like 'your_module.app'. We discovered: my_app.app Where is your app's function? (default 'my_app.app'): my_app.app ... Would you like to deploy this application globally? (default 'n') [y/n/ (p)rimary]: n 2. Enable X-Ray. Open the zappa_settings.json file and verify that it looks similar to the example. { "dev": { "app_function": "my_app.app", "aws_region": "us-west-2", "profile_name": "default", "project_name": "serverless-exam", "runtime": "python2.7", "s3_bucket": "zappa-*********" } } 3. Add "xray_tracing": true as an entry to the configuration file. Instrument serverless applications 445 AWS X-Ray Developer Guide { "dev": { "app_function": "my_app.app", "aws_region": "us-west-2", "profile_name": "default", "project_name": "serverless-exam", "runtime": "python2.7", "s3_bucket": "zappa-*********", "xray_tracing": true } } 4. Deploy the application. This automatically configures the API Gateway endpoint and uploads your code to Lambda. zappa deploy ... Deploying API Gateway.. Deployment complete!: https://**********.execute-api.us-west-2.amazonaws.com/dev Step 3: Enable X-Ray tracing for API Gateway In this step you will interact with the API Gateway console to enable X-Ray tracing. 1. Sign in to the AWS Management Console and open the API Gateway console at https:// console.aws.amazon.com/apigateway/. 2. Find your newly generated API. It should look something like serverless-exam-dev. 3. Choose Stages. 4. Choose the name of your deployment stage. The default is dev. 5. On the Logs/Tracing tab, select the Enable X-Ray Tracing box. 6. Choose Save Changes. 7. Access the endpoint in your browser. If you used the example Hello World application, it should display the following. "Hello, World: https://aws.amazon.com/" Instrument serverless applications 446 AWS X-Ray Developer Guide Step 4: View the created trace In this step you will interact with the X-Ray console to view the trace created by the example application. For a more detailed walkthrough on trace analysis, see Viewing the Service Map. 1. Sign in to the AWS Management Console and open the X-Ray console at https:// console.aws.amazon.com/xray/home. 2. View segments generated by API Gateway, the Lambda function, and the Lambda container. 3. Under the Lambda function segment, view a subsegment named My First Serverless App. It's followed by a second subsegment named https://aws.amazon.com. 4. During initialization, Lambda might also generate a third subsegment named initialization. Instrument serverless applications 447 AWS X-Ray Developer Guide Step 5: Clean up Always terminate resources you are no longer using to avoid the accumulation of unexpected costs. As this tutorial demonstrates, tools such as Zappa streamline serverless redeployment. To remove your application from Lambda, API Gateway, and Amazon S3, run the following command in your project directory by using the AWS CLI. zappa undeploy dev Next steps Add more features to your application by adding AWS clients and instrumenting them with X-Ray. Learn more about serverless computing options at Serverless on AWS. Instrument serverless applications 448 AWS X-Ray Developer Guide Working with .NET There are two ways to instrument your .NET application to send traces to X-Ray: • AWS Distro for OpenTelemetry .NET – An AWS distribution that provides a set of open source libraries for sending correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service, via the AWS Distro for OpenTelemetry Collector. • AWS X-Ray SDK for .NET – A set of libraries for generating and sending traces to X-Ray via the X- Ray daemon. For more information, see Choosing between the AWS Distro for OpenTelemetry and X-Ray SDKs. AWS Distro for OpenTelemetry .NET With the AWS Distro for OpenTelemetry .NET, you can instrument your applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Using X-Ray with AWS Distro for OpenTelemetry requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. To get started, see the AWS |
xray-guide-130 | xray-guide.pdf | 130 | for generating and sending traces to X-Ray via the X- Ray daemon. For more information, see Choosing between the AWS Distro for OpenTelemetry and X-Ray SDKs. AWS Distro for OpenTelemetry .NET With the AWS Distro for OpenTelemetry .NET, you can instrument your applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Using X-Ray with AWS Distro for OpenTelemetry requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. To get started, see the AWS Distro for OpenTelemetry .NET documentation. For more information about using the AWS Distro for OpenTelemetry with AWS X-Ray and other AWS services, see AWS Distro for OpenTelemetry or the AWS Distro for OpenTelemetry Documentation. For more information about language support and usage, see AWS Observability on GitHub. AWS X-Ray SDK for .NET The X-Ray SDK for .NET is a library for instrumenting C# .NET web applications, .NET Core web applications, and .NET Core functions on AWS Lambda. It provides classes and methods for generating and sending trace data to the X-Ray daemon. This includes information about incoming requests served by the application, and calls that the application makes to downstream AWS services, HTTP web APIs, and SQL databases. AWS Distro for OpenTelemetry .NET 449 AWS X-Ray Note Developer Guide The X-Ray SDK for .NET is an open source project. You can follow the project and submit issues and pull requests on GitHub: github.com/aws/aws-xray-sdk-dotnet For web applications, start by adding a message handler to your web configuration to trace incoming requests. The message handler creates a segment for each traced request, and completes the segment when the response is sent. While the segment is open you can use the SDK client's methods to add information to the segment and create subsegments to trace downstream calls. The SDK also automatically records exceptions that your application throws while the segment is open. For Lambda functions called by an instrumented application or service, Lambda reads the tracing header and traces sampled requests automatically. For other functions, you can configure Lambda to sample and trace incoming requests. In either case, Lambda creates the segment and provides it to the X-Ray SDK. Note On Lambda, the X-Ray SDK is optional. If you don't use it in your function, your service map will still include a node for the Lambda service, and one for each Lambda function. By adding the SDK, you can instrument your function code to add subsegments to the function segment recorded by Lambda. See AWS Lambda and AWS X-Ray for more information. Next, use the X-Ray SDK for .NET to instrument your AWS SDK for .NET clients. Whenever you make a call to a downstream AWS service or resource with an instrumented client, the SDK records information about the call in a subsegment. AWS services and the resources that you access within the services appear as downstream nodes on the trace map to help you identify errors and throttling issues on individual connections. The X-Ray SDK for .NET also provides instrumentation for downstream calls to HTTP web APIs and SQL databases. The GetResponseTraced extension method for System.Net.HttpWebRequest traces outgoing HTTP calls. You can use the X-Ray SDK for .NET's version of SqlCommand to instrument SQL queries. X-Ray SDK for .NET 450 AWS X-Ray Developer Guide After you start using the SDK, customize its behavior by configuring the recorder and message handler. You can add plugins to record data about the compute resources running your application, customize sampling behavior by defining sampling rules, and set the log level to see more or less information from the SDK in your application logs. Record additional information about requests and the work that your application does in annotations and metadata. Annotations are simple key-value pairs that are indexed for use with filter expressions, so that you can search for traces that contain specific data. Metadata entries are less restrictive and can record entire objects and arrays — anything that can be serialized into JSON. Annotations and Metadata Annotations and metadata are arbitrary text that you add to segments with the X-Ray SDK. Annotations are indexed for use with filter expressions. Metadata are not indexed, but can be viewed in the raw segment with the X-Ray console or API. Anyone that you grant read access to X-Ray can view this data. When you have many instrumented clients in your code, a single request segment can contain a large number of subsegments, one for each call made with an instrumented client. You can organize and group subsegments by wrapping client calls in custom subsegments. You can create a custom subsegment for an entire function or any section of code, and record metadata and annotations on the subsegment instead of |
xray-guide-131 | xray-guide.pdf | 131 | with filter expressions. Metadata are not indexed, but can be viewed in the raw segment with the X-Ray console or API. Anyone that you grant read access to X-Ray can view this data. When you have many instrumented clients in your code, a single request segment can contain a large number of subsegments, one for each call made with an instrumented client. You can organize and group subsegments by wrapping client calls in custom subsegments. You can create a custom subsegment for an entire function or any section of code, and record metadata and annotations on the subsegment instead of writing everything on the parent segment. For reference documentation about the SDK's classes and methods, see the following: • AWS X-Ray SDK for .NET API Reference • AWS X-Ray SDK for .NET Core API Reference The same package supports both .NET and .NET Core, but the classes that are used vary. Examples in this chapter link to the .NET API reference unless the class is specific to .NET Core. Requirements The X-Ray SDK for .NET requires the .NET Framework 4.5 or later and AWS SDK for .NET. For .NET Core applications and functions, the SDK requires .NET Core 2.0 or later. Requirements 451 AWS X-Ray Developer Guide Adding the X-Ray SDK for .NET to your application Use NuGet to add the X-Ray SDK for .NET to your application. To install the X-Ray SDK for .NET with NuGet package manager in Visual Studio 1. Choose Tools, NuGet Package Manager, Manage NuGet Packages for Solution. 2. Search for AWSXRayRecorder. 3. Choose the package, and then choose Install. Dependency management The X-Ray SDK for .NET is available from Nuget. Install the SDK using the package manager: Install-Package AWSXRayRecorder -Version 2.10.1 The AWSXRayRecorder v2.10.1 nuget package has the following dependencies: NET Framework 4.5 AWSXRayRecorder (2.10.1) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- AWSSDK.Core (>= 3.3.25.1) | |-- AWSXRayRecorder.Handlers.AspNet (>= 2.7.3) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- AWSXRayRecorder.Handlers.AwsSdk (>= 2.8.3) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- AWSXRayRecorder.Handlers.EntityFramework (>= 1.1.1) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- EntityFramework (>= 6.2.0) | |-- AWSXRayRecorder.Handlers.SqlServer (>= 2.7.3) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- AWSXRayRecorder.Handlers.System.Net (>= 2.7.3) Adding the X-Ray SDK for .NET to your application 452 AWS X-Ray Developer Guide |-- AWSXRayRecorder.Core (>= 2.10.1) NET Framework 2.0 AWSXRayRecorder (2.10.1) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- AWSSDK.Core (>= 3.3.25.1) | |-- Microsoft.AspNetCore.Http (>= 2.0.0) | |-- Microsoft.Extensions.Configuration (>= 2.0.0) | |-- System.Net.Http (>= 4.3.4) | |-- AWSXRayRecorder.Handlers.AspNetCore (>= 2.7.3) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- Microsoft.AspNetCore.Http.Extensions (>= 2.0.0) | |-- Microsoft.AspNetCore.Mvc.Abstractions (>= 2.0.0) | |-- AWSXRayRecorder.Handlers.AwsSdk (>= 2.8.3) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- AWSXRayRecorder.Handlers.EntityFramework (>= 1.1.1) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- Microsoft.EntityFrameworkCore.Relational (>= 3.1.0) | |-- AWSXRayRecorder.Handlers.SqlServer (>= 2.7.3) | |-- AWSXRayRecorder.Core (>= 2.10.1) | |-- System.Data.SqlClient (>= 4.4.0) | |-- AWSXRayRecorder.Handlers.System.Net (>= 2.7.3) |-- AWSXRayRecorder.Core (>= 2.10.1) For more details about dependency management, refer to Microsoft's documentation about Nuget dependency and Nuget dependency resolution. Configuring the X-Ray SDK for .NET You can configure the X-Ray SDK for .NET with plugins to include information about the service that your application runs on, modify the default sampling behavior, or add sampling rules that apply to requests to specific paths. Configuration 453 AWS X-Ray Developer Guide For .NET web applications, add keys to the appSettings section of your Web.config file. Example Web.config <configuration> <appSettings> <add key="AWSXRayPlugins" value="EC2Plugin"/> <add key="SamplingRuleManifest" value="sampling-rules.json"/> </appSettings> </configuration> For .NET Core, create a file named appsettings.json with a top-level key named XRay. Example .NET appsettings.json { "XRay": { "AWSXRayPlugins": "EC2Plugin", "SamplingRuleManifest": "sampling-rules.json" } } Then, in your application code, build a configuration object and use it to initialize the X-Ray recorder. Do this before you initialize the recorder. Example .NET Core Program.cs – Recorder configuration using Amazon.XRay.Recorder.Core; ... AWSXRayRecorder.InitializeInstance(configuration); If you are instrumenting a .NET Core web application, you can also pass the configuration object to the UseXRay method when you configure the message handler. For Lambda functions, use the InitializeInstance method as shown above. For more information on the .NET Core configuration API, see Configure an ASP.NET Core App on docs.microsoft.com. Sections • Plugins Configuration 454 AWS X-Ray • Sampling rules • Logging (.NET) • Logging (.NET Core) • Environment variables Plugins Developer Guide Use plugins to add data about the service that is hosting your application. Plugins • Amazon EC2 – EC2Plugin adds the instance ID, Availability Zone, and the CloudWatch Logs Group. • Elastic Beanstalk – ElasticBeanstalkPlugin adds the environment name, version label, and deployment ID. • Amazon ECS – ECSPlugin adds the container ID. To use a plugin, configure the X-Ray SDK for .NET client by adding the AWSXRayPlugins setting. If multiple plugins apply to your application, specify all of them in the same setting, separated by commas. Example Web.config - plugins <configuration> <appSettings> |
xray-guide-132 | xray-guide.pdf | 132 | Core) • Environment variables Plugins Developer Guide Use plugins to add data about the service that is hosting your application. Plugins • Amazon EC2 – EC2Plugin adds the instance ID, Availability Zone, and the CloudWatch Logs Group. • Elastic Beanstalk – ElasticBeanstalkPlugin adds the environment name, version label, and deployment ID. • Amazon ECS – ECSPlugin adds the container ID. To use a plugin, configure the X-Ray SDK for .NET client by adding the AWSXRayPlugins setting. If multiple plugins apply to your application, specify all of them in the same setting, separated by commas. Example Web.config - plugins <configuration> <appSettings> <add key="AWSXRayPlugins" value="EC2Plugin,ElasticBeanstalkPlugin"/> </appSettings> </configuration> Example .NET Core appsettings.json – Plugins { "XRay": { "AWSXRayPlugins": "EC2Plugin,ElasticBeanstalkPlugin" } } Configuration 455 AWS X-Ray Sampling rules Developer Guide The SDK uses the sampling rules you define in the X-Ray console to determine which requests to record. The default rule traces the first request each second, and five percent of any additional requests across all services sending traces to X-Ray. Create additional rules in the X-Ray console to customize the amount of data recorded for each of your applications. The SDK applies custom rules in the order in which they are defined. If a request matches multiple custom rules, the SDK applies only the first rule. Note If the SDK can't reach X-Ray to get sampling rules, it reverts to a default local rule of the first request each second, and five percent of any additional requests per host. This can occur if the host doesn't have permission to call sampling APIs, or can't connect to the X- Ray daemon, which acts as a TCP proxy for API calls made by the SDK. You can also configure the SDK to load sampling rules from a JSON document. The SDK can use local rules as a backup for cases where X-Ray sampling is unavailable, or use local rules exclusively. Example sampling-rules.json { "version": 2, "rules": [ { "description": "Player moves.", "host": "*", "http_method": "*", "url_path": "/api/move/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 } } Configuration 456 AWS X-Ray Developer Guide This example defines one custom rule and a default rule. The custom rule applies a five-percent sampling rate with no minimum number of requests to trace for paths under /api/move/. The default rule traces the first request each second and 10 percent of additional requests. The disadvantage of defining rules locally is that the fixed target is applied by each instance of the recorder independently, instead of being managed by the X-Ray service. As you deploy more hosts, the fixed rate is multiplied, making it harder to control the amount of data recorded. On AWS Lambda, you cannot modify the sampling rate. If your function is called by an instrumented service, calls that generated requests that were sampled by that service will be recorded by Lambda. If active tracing is enabled and no tracing header is present, Lambda makes the sampling decision. To configure backup rules, tell the X-Ray SDK for .NET to load sampling rules from a file with the SamplingRuleManifest setting. Example .NET Web.config - sampling rules <configuration> <appSettings> <add key="SamplingRuleManifest" value="sampling-rules.json"/> </appSettings> </configuration> Example .NET Core appsettings.json – Sampling rules { "XRay": { "SamplingRuleManifest": "sampling-rules.json" } } To use only local rules, build the recorder with a LocalizedSamplingStrategy. If you have backup rules configured, remove that configuration. Example .NET global.asax – Local sampling rules var recorder = new AWSXRayRecorderBuilder().WithSamplingStrategy(new LocalizedSamplingStrategy("samplingrules.json")).Build(); AWSXRayRecorder.InitializeInstance(recorder: recorder); Configuration 457 AWS X-Ray Developer Guide Example .NET Core Program.cs – Local sampling rules var recorder = new AWSXRayRecorderBuilder().WithSamplingStrategy(new LocalizedSamplingStrategy("sampling-rules.json")).Build(); AWSXRayRecorder.InitializeInstance(configuration,recorder); Logging (.NET) The X-Ray SDK for .NET uses the same logging mechanism as the AWS SDK for .NET. If you already configured your application to log AWS SDK for .NET output, the same configuration applies to output from the X-Ray SDK for .NET. To configure logging, add a configuration section named aws to your App.config file or Web.config file. Example Web.config - logging ... <configuration> <configSections> <section name="aws" type="Amazon.AWSSection, AWSSDK.Core"/> </configSections> <aws> <logging logTo="Log4Net"/> </aws> </configuration> For more information, see Configuring Your AWS SDK for .NET Application in the AWS SDK for .NET Developer Guide. Logging (.NET Core) The X-Ray SDK for .NET uses the same logging options as the AWS SDK for .NET. To configure logging for .NET Core applications, pass the logging option to the AWSXRayRecorder.RegisterLogger method. For example, to use log4net, create a configuration file that defines the logger, the output format, and the file location. Example .NET Core log4net.config <?xml version="1.0" encoding="utf-8" ?> Configuration 458 AWS X-Ray <log4net> Developer Guide <appender name="FileAppender" type="log4net.Appender.FileAppender,log4net"> <file value="c:\logs\sdk-log.txt" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %level %logger - %message%newline" /> </layout> </appender> <logger name="Amazon"> <level value="DEBUG" /> <appender-ref ref="FileAppender" /> </logger> </log4net> Then, create the logger and apply the configuration in your |
xray-guide-133 | xray-guide.pdf | 133 | .NET uses the same logging options as the AWS SDK for .NET. To configure logging for .NET Core applications, pass the logging option to the AWSXRayRecorder.RegisterLogger method. For example, to use log4net, create a configuration file that defines the logger, the output format, and the file location. Example .NET Core log4net.config <?xml version="1.0" encoding="utf-8" ?> Configuration 458 AWS X-Ray <log4net> Developer Guide <appender name="FileAppender" type="log4net.Appender.FileAppender,log4net"> <file value="c:\logs\sdk-log.txt" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %level %logger - %message%newline" /> </layout> </appender> <logger name="Amazon"> <level value="DEBUG" /> <appender-ref ref="FileAppender" /> </logger> </log4net> Then, create the logger and apply the configuration in your program code. Example .NET Core Program.cs – Logging using log4net; using Amazon.XRay.Recorder.Core; class Program { private static ILog log; static Program() { var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); log = LogManager.GetLogger(typeof(Program)); AWSXRayRecorder.RegisterLogger(LoggingOptions.Log4Net); } static void Main(string[] args) { ... } } For more information on configuring log4net, see Configuration on logging.apache.org. Environment variables You can use environment variables to configure the X-Ray SDK for .NET. The SDK supports the following variables. Configuration 459 AWS X-Ray Developer Guide • AWS_XRAY_TRACING_NAME – Set a service name that the SDK uses for segments. Overrides the service name that you set on the servlet filter's segment naming strategy. • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener. By default, the SDK uses 127.0.0.1:2000 for both trace data (UDP) and sampling (TCP). Use this variable if you have configured the daemon to listen on a different port or if it is running on a different host. Format • Same port – address:port • Different ports – tcp:address:port udp:address:port • AWS_XRAY_CONTEXT_MISSING – Set to RUNTIME_ERROR to throw exceptions when your instrumented code attempts to record data when no segment is open. Valid Values • RUNTIME_ERROR – Throw a runtime exception. • LOG_ERROR – Log an error and continue (default). • IGNORE_ERROR – Ignore error and continue. Errors related to missing segments or subsegments can occur when you attempt to use an instrumented client in startup code that runs when no request is open, or in code that spawns a new thread. Instrumenting incoming HTTP requests with the X-Ray SDK for .NET You can use the X-Ray SDK to trace incoming HTTP requests that your application serves on an EC2 instance in Amazon EC2, AWS Elastic Beanstalk, or Amazon ECS. Use a message handler to instrument incoming HTTP requests. When you add the X-Ray message handler to your application, the X-Ray SDK for .NET creates a segment for each sampled request. This segment includes timing, method, and disposition of the HTTP request. Additional instrumentation creates subsegments on this segment. Note For AWS Lambda functions, Lambda creates a segment for each sampled request. See AWS Lambda and AWS X-Ray for more information. Incoming requests 460 AWS X-Ray Developer Guide Each segment has a name that identifies your application in the service map. The segment can be named statically, or you can configure the SDK to name it dynamically based on the host header in the incoming request. Dynamic naming lets you group traces based on the domain name in the request, and apply a default name if the name doesn't match an expected pattern (for example, if the host header is forged). Forwarded Requests If a load balancer or other intermediary forwards a request to your application, X-Ray takes the client IP from the X-Forwarded-For header in the request instead of from the source IP in the IP packet. The client IP that is recorded for a forwarded request can be forged, so it should not be trusted. The message handler creates a segment for each incoming request with an http block that contains the following information: • HTTP method – GET, POST, PUT, DELETE, etc. • Client address – The IP address of the client that sent the request. • Response code – The HTTP response code for the completed request. • Timing – The start time (when the request was received) and end time (when the response was sent). • User agent — The user-agent from the request. • Content length — The content-length from the response. Sections • Instrumenting incoming requests (.NET) • Instrumenting incoming requests (.NET Core) • Configuring a segment naming strategy Instrumenting incoming requests (.NET) To instrument requests served by your application, call RegisterXRay in the Init method of your global.asax file. Incoming requests 461 AWS X-Ray Developer Guide Example global.asax - message handler using System.Web.Http; using Amazon.XRay.Recorder.Handlers.AspNet; namespace SampleEBWebApplication { public class MvcApplication : System.Web.HttpApplication { public override void Init() { base.Init(); AWSXRayASPNET.RegisterXRay(this, "MyApp"); } } } Instrumenting incoming requests (.NET Core) To instrument requests served by your application, call UseXRay method before any other middleware in the Configure method of your Startup class as ideally X-Ray middleware should be the first middleware to process the |
xray-guide-134 | xray-guide.pdf | 134 | a segment naming strategy Instrumenting incoming requests (.NET) To instrument requests served by your application, call RegisterXRay in the Init method of your global.asax file. Incoming requests 461 AWS X-Ray Developer Guide Example global.asax - message handler using System.Web.Http; using Amazon.XRay.Recorder.Handlers.AspNet; namespace SampleEBWebApplication { public class MvcApplication : System.Web.HttpApplication { public override void Init() { base.Init(); AWSXRayASPNET.RegisterXRay(this, "MyApp"); } } } Instrumenting incoming requests (.NET Core) To instrument requests served by your application, call UseXRay method before any other middleware in the Configure method of your Startup class as ideally X-Ray middleware should be the first middleware to process the request and last middleware to process the response in the pipeline. Note For .NET Core 2.0, if you have a UseExceptionHandler method in the application, make sure to call UseXRay after UseExceptionHandler method to ensure exceptions are recorded. Example Startup.cs <caption>.NET Core 2.1 and above</caption> using Microsoft.AspNetCore.Builder; public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseXRay("MyApp"); // additional middleware Incoming requests 462 AWS X-Ray ... } <caption>.NET Core 2.0</caption> using Microsoft.AspNetCore.Builder; Developer Guide public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseExceptionHandler("/Error"); app.UseXRay("MyApp"); // additional middleware ... } The UseXRay method can also take a configuration object as a second argument. app.UseXRay("MyApp", configuration); Configuring a segment naming strategy AWS X-Ray uses a service name to identify your application and distinguish it from the other applications, databases, external APIs, and AWS resources that your application uses. When the X- Ray SDK generates segments for incoming requests, it records your application's service name in the segment's name field. The X-Ray SDK can name segments after the hostname in the HTTP request header. However, this header can be forged, which could result in unexpected nodes in your service map. To prevent the SDK from naming segments incorrectly due to requests with forged host headers, you must specify a default name for incoming requests. If your application serves requests for multiple domains, you can configure the SDK to use a dynamic naming strategy to reflect this in segment names. A dynamic naming strategy allows the SDK to use the hostname for requests that match an expected pattern, and apply the default name to requests that don't. For example, you might have a single application serving requests to three subdomains– www.example.com, api.example.com, and static.example.com. You can use a dynamic naming strategy with the pattern *.example.com to identify segments for each subdomain with a different name, resulting in three service nodes on the service map. If your application receives Incoming requests 463 AWS X-Ray Developer Guide requests with a hostname that doesn't match the pattern, you will see a fourth node on the service map with a fallback name that you specify. To use the same name for all request segments, specify the name of your application when you initialize the message handler, as shown in the previous section. This has the same effect as creating a FixedSegmentNamingStrategy and passing it to the RegisterXRay method. AWSXRayASPNET.RegisterXRay(this, new FixedSegmentNamingStrategy("MyApp")); Note You can override the default service name that you define in code with the AWS_XRAY_TRACING_NAME environment variable. A dynamic naming strategy defines a pattern that hostnames should match, and a default name to use if the hostname in the HTTP request does not match the pattern. To name segments dynamically, create a DynamicSegmentNamingStrategy and pass it to the RegisterXRay method. AWSXRayASPNET.RegisterXRay(this, new DynamicSegmentNamingStrategy("MyApp", "*.example.com")); Tracing AWS SDK calls with the X-Ray SDK for .NET When your application makes calls to AWS services to store data, write to a queue, or send notifications, the X-Ray SDK for .NET tracks the calls downstream in subsegments. Traced AWS services and resources that you access within those services (for example, an Amazon S3 bucket or Amazon SQS queue), appear as downstream nodes on the trace map in the X-Ray console. You can instrument all of your AWS SDK for .NET clients by calling RegisterXRayForAllServices before you create them. Example SampleController.cs - DynamoDB client instrumentation using Amazon; using Amazon.Util; using Amazon.DynamoDBv2; AWS SDK clients 464 AWS X-Ray Developer Guide using Amazon.DynamoDBv2.DocumentModel; using Amazon.XRay.Recorder.Core; using Amazon.XRay.Recorder.Handlers.AwsSdk; namespace SampleEBWebApplication.Controllers { public class SampleController : ApiController { AWSSDKHandler.RegisterXRayForAllServices(); private static readonly Lazy<AmazonDynamoDBClient> LazyDdbClient = new Lazy<AmazonDynamoDBClient>(() => { var client = new AmazonDynamoDBClient(EC2InstanceMetadata.Region ?? RegionEndpoint.USEast1); return client; }); To instrument clients for some services and not others, call RegisterXRay instead of RegisterXRayForAllServices. Replace the highlighted text with the name of the service's client interface. AWSSDKHandler.RegisterXRay<IAmazonDynamoDB>() For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a |
xray-guide-135 | xray-guide.pdf | 135 | }); To instrument clients for some services and not others, call RegisterXRay instead of RegisterXRayForAllServices. Replace the highlighted text with the name of the service's client interface. AWSSDKHandler.RegisterXRay<IAmazonDynamoDB>() For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a separate node in the service map, with a generic DynamoDB node for calls that don't target a table. Example Subsegment for a call to DynamoDB to save an item { "id": "24756640c0d0978a", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "DynamoDB", "namespace": "aws", "http": { "response": { AWS SDK clients 465 AWS X-Ray "content_length": 60, "status": 200 } }, "aws": { "table_name": "scorekeep-user", "operation": "UpdateItem", Developer Guide "request_id": "UBQNSO5AEM8T4FDA4RQDEB94OVTDRVV4K4HIRGVJF66Q9ASUAAJG", } } When you access named resources, calls to the following services create additional nodes in the service map. Calls that don't target specific resources create a generic node for the service. • Amazon DynamoDB – Table name • Amazon Simple Storage Service – Bucket and key name • Amazon Simple Queue Service – Queue name Tracing calls to downstream HTTP web services with the X-Ray SDK for .NET When your application makes calls to microservices or public HTTP APIs, you can use the X-Ray SDK for .NET's GetResponseTraced extension method for System.Net.HttpWebRequest to instrument those calls and add the API to the service graph as a downstream service. Example HttpWebRequest using System.Net; using Amazon.XRay.Recorder.Core; using Amazon.XRay.Recorder.Handlers.System.Net; private void MakeHttpRequest() { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://names.example.com/ api"); request.GetResponseTraced(); } For asynchronous calls, use GetAsyncResponseTraced. Outgoing HTTP calls 466 AWS X-Ray Developer Guide request.GetAsyncResponseTraced(); If you use system.net.http.httpclient, use the HttpClientXRayTracingHandler delegating handler to record calls. Example HttpClient using System.Net.Http; using Amazon.XRay.Recorder.Core; using Amazon.XRay.Recorder.Handlers.System.Net; private void MakeHttpRequest() { var httpClient = new HttpClient(new HttpClientXRayTracingHandler(new HttpClientHandler())); httpClient.GetAsync(URL); } When you instrument a call to a downstream web API, the X-Ray SDK for .NET records a subsegment with information about the HTTP request and response. X-Ray uses the subsegment to generate an inferred segment for the API. Example Subsegment for a downstream HTTP call { "id": "004f72be19cddc2a", "start_time": 1484786387.131, "end_time": 1484786387.501, "name": "names.example.com", "namespace": "remote", "http": { "request": { "method": "GET", "url": "https://names.example.com/" }, "response": { "content_length": -1, "status": 200 } } } Outgoing HTTP calls 467 AWS X-Ray Developer Guide Example Inferred segment for a downstream HTTP call { "id": "168416dc2ea97781", "name": "names.example.com", "trace_id": "1-62be1272-1b71c4274f39f122afa64eab", "start_time": 1484786387.131, "end_time": 1484786387.501, "parent_id": "004f72be19cddc2a", "http": { "request": { "method": "GET", "url": "https://names.example.com/" }, "response": { "content_length": -1, "status": 200 } }, "inferred": true } Tracing SQL queries with the X-Ray SDK for .NET The X-Ray SDK for .NET provides a wrapper class for System.Data.SqlClient.SqlCommand, named TraceableSqlCommand, that you can use in place of SqlCommand. You can initialize an SQL command with the TraceableSqlCommand class. Tracing SQL queries with synchronous and asynchronous methods The following examples show how to use the TraceableSqlCommand to automatically trace SQL Server queries synchronously and asynchronously. Example Controller.cs - SQL client instrumentation (synchronous) using Amazon; using Amazon.Util; using Amazon.XRay.Recorder.Core; using Amazon.XRay.Recorder.Handlers.SqlServer; private void QuerySql(int id) { SQL queries 468 AWS X-Ray Developer Guide var connectionString = ConfigurationManager.AppSettings["RDS_CONNECTION_STRING"]; using (var sqlConnection = new SqlConnection(connectionString)) using (var sqlCommand = new TraceableSqlCommand("SELECT " + id, sqlConnection)) { sqlCommand.Connection.Open(); sqlCommand.ExecuteNonQuery(); } } You can execute the query asynchronously by using the ExecuteReaderAsync method. Example Controller.cs - SQL client instrumentation (asynchronous) using Amazon; using Amazon.Util; using Amazon.XRay.Recorder.Core; using Amazon.XRay.Recorder.Handlers.SqlServer; private void QuerySql(int id) { var connectionString = ConfigurationManager.AppSettings["RDS_CONNECTION_STRING"]; using (var sqlConnection = new SqlConnection(connectionString)) using (var sqlCommand = new TraceableSqlCommand("SELECT " + id, sqlConnection)) { await sqlCommand.ExecuteReaderAsync(); } } Collecting SQL queries made to SQL Server You can enable the capture of SqlCommand.CommandText as part of the subsegment created by your SQL query. SqlCommand.CommandText appears as the field sanitized_query in the subsegment JSON. By default, this feature is disabled for security. Note Do not enable the collection feature if you are including sensitive information as clear text in your SQL queries. You can enable the collection of SQL queries in two ways: • Set the CollectSqlQueries property to true in the global configuration for your application. SQL queries 469 AWS X-Ray Developer Guide • Set the collectSqlQueries parameter in the TraceableSqlCommand instance to true to collect calls within the instance. Enable the global CollectSqlQueries property The following examples show how to enable the CollectSqlQueries property for .NET and .NET Core. .NET To set the CollectSqlQueries property to true in the global configuration of your application in .NET, modify the appsettings of your App.config or Web.config file, as shown. Example App.config Or |
xray-guide-136 | xray-guide.pdf | 136 | You can enable the collection of SQL queries in two ways: • Set the CollectSqlQueries property to true in the global configuration for your application. SQL queries 469 AWS X-Ray Developer Guide • Set the collectSqlQueries parameter in the TraceableSqlCommand instance to true to collect calls within the instance. Enable the global CollectSqlQueries property The following examples show how to enable the CollectSqlQueries property for .NET and .NET Core. .NET To set the CollectSqlQueries property to true in the global configuration of your application in .NET, modify the appsettings of your App.config or Web.config file, as shown. Example App.config Or Web.config – Enable SQL Query collection globally <configuration> <appSettings> <add key="CollectSqlQueries" value="true"> </appSettings> </configuration> .NET Core To set the CollectSqlQueries property to true in the global configuration of your application in .NET Core, modify your appsettings.json file under the X-Ray key, as shown. Example appsettings.json – Enable SQL Query collection globally { "XRay": { "CollectSqlQueries":"true" } } Enable the collectSqlQueries parameter You can set the collectSqlQueries parameter in the TraceableSqlCommand instance to true to collect the SQL query text for SQL Server queries made using that instance. Setting the SQL queries 470 AWS X-Ray Developer Guide parameter to false disables the CollectSqlQuery feature for the TraceableSqlCommand instance. Note The value of collectSqlQueries in the TraceableSqlCommand instance overrides the value set in the global configuration of the CollectSqlQueries property. Example Example Controller.cs – Enable SQL Query collection for the instance using Amazon; using Amazon.Util; using Amazon.XRay.Recorder.Core; using Amazon.XRay.Recorder.Handlers.SqlServer; private void QuerySql(int id) { var connectionString = ConfigurationManager.AppSettings["RDS_CONNECTION_STRING"]; using (var sqlConnection = new SqlConnection(connectionString)) using (var command = new TraceableSqlCommand("SELECT " + id, sqlConnection, collectSqlQueries: true)) { command.ExecuteNonQuery(); } } Creating additional subsegments Subsegments extend a trace's segment with details about work done in order to serve a request. Each time you make a call with an instrumented client, the X-Ray SDK records the information generated in a subsegment. You can create additional subsegments to group other subsegments, to measure the performance of a section of code, or to record annotations and metadata. To manage subsegments, use the BeginSubsegment and EndSubsegment methods. Perform any work in the subsegment in a try block and use AddException to trace exceptions. Call EndSubsegment in a finally block to ensure that the subsegment is closed. Example Controller.cs – Custom subsegment AWSXRayRecorder.Instance.BeginSubsegment("custom method"); Custom subsegments 471 Developer Guide AWS X-Ray try { DoWork(); } catch (Exception e) { AWSXRayRecorder.Instance.AddException(e); } finally { AWSXRayRecorder.Instance.EndSubsegment(); } When you create a subsegment within a segment or another subsegment, the X-Ray SDK for .NET generates an ID for it and records the start time and end time. Example Subsegment with metadata "subsegments": [{ "id": "6f1605cd8a07cb70", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "Custom subsegment for UserModel.saveUser function", "metadata": { "debug": { "test": "Metadata string from UserModel.saveUser" } }, Add annotations and metadata to segments with the X-Ray SDK for .NET You can record additional information about requests, the environment, or your application with annotations and metadata. You can add annotations and metadata to the segments that the X-Ray SDK creates, or to custom subsegments that you create. Annotations are key-value pairs with string, number, or Boolean values. Annotations are indexed for use with filter expressions. Use annotations to record data that you want to use to group traces in the console, or when calling the GetTraceSummaries API. Annotations and metadata 472 AWS X-Ray Developer Guide Metadata are key-value pairs that can have values of any type, including objects and lists, but are not indexed for use with filter expressions. Use metadata to record additional data that you want stored in the trace but don't need to use with search. Sections • Recording annotations with the X-Ray SDK for .NET • Recording metadata with the X-Ray SDK for .NET Recording annotations with the X-Ray SDK for .NET Use annotations to record information on segments or subsegments that you want indexed for search. The following are required for all annotations in X-Ray: Annotation Requirements • Keys – The key for an X-Ray annotation can have up to 500 alphanumeric characters. You cannot use spaces or symbols other than a dot or period ( . ) • Values – The value for an X-Ray annotation can have up to 1,000 Unicode characters. • The number of Annotations – You can use up to 50 annotations per trace. To record annotations outside of a AWS Lambda function 1. Get an instance of AWSXRayRecorder. using Amazon.XRay.Recorder.Core; ... AWSXRayRecorder recorder = AWSXRayRecorder.Instance; 2. Call addAnnotation with a String key and a Boolean, Int32, Int64, Double, or String value. recorder.AddAnnotation("mykey", "my value"); The following example shows how to call putAnnotation with a String key that includes a dot, and a Boolean, Number, or String value. document.putAnnotation("testkey.test", "my value"); Annotations and metadata 473 AWS X-Ray Developer Guide To record annotations inside |
xray-guide-137 | xray-guide.pdf | 137 | have up to 1,000 Unicode characters. • The number of Annotations – You can use up to 50 annotations per trace. To record annotations outside of a AWS Lambda function 1. Get an instance of AWSXRayRecorder. using Amazon.XRay.Recorder.Core; ... AWSXRayRecorder recorder = AWSXRayRecorder.Instance; 2. Call addAnnotation with a String key and a Boolean, Int32, Int64, Double, or String value. recorder.AddAnnotation("mykey", "my value"); The following example shows how to call putAnnotation with a String key that includes a dot, and a Boolean, Number, or String value. document.putAnnotation("testkey.test", "my value"); Annotations and metadata 473 AWS X-Ray Developer Guide To record annotations inside of a AWS Lambda function Both segments and subsegments inside a Lambda function are managed by the Lambda runtime environment. If you want to add an annotation to a segment or subsegment inside a Lambda function, you must do the following: 1. Create the segment or subsegment inside the Lambda function. 2. Add the annotation to the segment or subsegment. 3. End the segment or subsegment. The following code example shows you how to add an annotation to a subsegment inside a Lambda function: #Create the subsegment AWSXRayRecorder.Instance.BeginSubsegment("custom method"); #Add an annotation AWSXRayRecorder.Instance.AddAnnotation("My", "Annotation"); try { YourProcess(); #Your function } catch (Exception e) { AWSXRayRecorder.Instance.AddException(e); } finally #End the subsegment { AWSXRayRecorder.Instance.EndSubsegment(); } The X-Ray SDK records annotations as key-value pairs in an annotations object in the segment document. Calling the addAnnotation operation twice with the same key overwrites a previously recorded value on the same segment or subsegment. To find traces that have annotations with specific values, use the annotation[key] keyword in a filter expression. Annotations and metadata 474 AWS X-Ray Developer Guide Recording metadata with the X-Ray SDK for .NET Use metadata to record information on segments or subsegments that you don't need to index for use inside a search. Metadata values can be strings, numbers, booleans, or any other object that can be serialized into a JSON object or array. To record metadata 1. Get an instance of AWSXRayRecorder, as shown in the following code example: using Amazon.XRay.Recorder.Core; ... AWSXRayRecorder recorder = AWSXRayRecorder.Instance; 2. Call AddMetadata with a string namespace, string key, and an object value, as shown in the following code example: recorder.AddMetadata("my namespace", "my key", "my value"); You can also call the AddMetadata operation using just a key and value pair, as shown in the following code example: recorder.AddMetadata("my key", "my value"); If you don't specify a value for the namespace, the X-Ray SDK uses default. Calling the AddMetadata operation twice with the same key overwrites a previously recorded value on the same segment or subsegment. Annotations and metadata 475 AWS X-Ray Developer Guide Working with Ruby There are two ways to instrument your Ruby application to send traces to X-Ray: • AWS Distro for OpenTelemetry Ruby – An AWS distribution that provides a set of open source libraries for sending correlated metrics and traces to multiple AWS monitoring solutions, including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service, via the AWS Distro for OpenTelemetry Collector. • AWS X-Ray SDK for Ruby – A set of libraries for generating and sending traces to X-Ray via the X- Ray daemon. For more information, see Choosing between the AWS Distro for OpenTelemetry and X-Ray SDKs. AWS Distro for OpenTelemetry Ruby With the AWS Distro for OpenTelemetry (ADOT) Ruby, you can instrument your applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, and Amazon OpenSearch Service. Using X-Ray with ADOT requires two components: an OpenTelemetry SDK enabled for use with X-Ray, and the AWS Distro for OpenTelemetry Collector enabled for use with X-Ray. To get started, see the AWS Distro for OpenTelemetry Ruby documentation. For more information about using the AWS Distro for OpenTelemetry with AWS X-Ray and other AWS services, see AWS Distro for OpenTelemetry or the AWS Distro for OpenTelemetry Documentation. For more information about language support and usage, see AWS Observability on GitHub. AWS X-Ray SDK for Ruby The X-Ray SDK is a library for Ruby web applications that provides 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, HTTP clients, or an active record client. You can also create segments manually and add debug information in annotations and metadata. You can download the SDK by adding it to your gemfile and running bundle install. AWS Distro for OpenTelemetry Ruby 476 AWS X-Ray Example Gemfile gem 'aws-sdk' Developer Guide If you use Rails, start by adding the X-Ray SDK middleware to trace incoming requests. A request filter creates a segment. While the segment is open, you can use the SDK client's methods to add information to the |
xray-guide-138 | xray-guide.pdf | 138 | calls that the application makes to downstream services using the AWS SDK, HTTP clients, or an active record client. You can also create segments manually and add debug information in annotations and metadata. You can download the SDK by adding it to your gemfile and running bundle install. AWS Distro for OpenTelemetry Ruby 476 AWS X-Ray Example Gemfile gem 'aws-sdk' Developer Guide If you use Rails, start by adding the X-Ray SDK middleware to trace incoming requests. A request filter creates a segment. While the segment is open, you can use the SDK client's methods to add information to the segment and create subsegments to trace downstream calls. The SDK also automatically records exceptions that your application throws while the segment is open. For non- Rails applications, you can create segments manually. Next, use the X-Ray SDK to instrument your AWS SDK for Ruby, HTTP, and SQL clients by configuring the recorder to patch the associated libraries. Whenever you make a call to a downstream AWS service or resource with an instrumented client, the SDK records information about the call in a subsegment. AWS services and the resources that you access within the services appear as downstream nodes on the trace map to help you identify errors and throttling issues on individual connections. Once you get going with the SDK, customize its behavior by configuring the recorder. You can add plugins to record data about the compute resources running your application, customize sampling behavior by defining sampling rules, and provide a logger to see more or less information from the SDK in your application logs. Record additional information about requests and the work that your application does in annotations and metadata. Annotations are simple key-value pairs that are indexed for use with filter expressions, so that you can search for traces that contain specific data. Metadata entries are less restrictive and can record entire objects and arrays — anything that can be serialized into JSON. Annotations and Metadata Annotations and metadata are arbitrary text that you add to segments with the X-Ray SDK. Annotations are indexed for use with filter expressions. Metadata are not indexed, but can be viewed in the raw segment with the X-Ray console or API. Anyone that you grant read access to X-Ray can view this data. When you have a lot of instrumented clients in your code, a single request segment can contain a large number of subsegments, one for each call made with an instrumented client. You can organize and group subsegments by wrapping client calls in custom subsegments. You can create X-Ray SDK for Ruby 477 AWS X-Ray Developer Guide a custom subsegment for an entire function or any section of code, and record metadata and annotations on the subsegment instead of writing everything on the parent segment. For reference documentation for the SDK's classes and methods, see the AWS X-Ray SDK for Ruby API Reference. Requirements The X-Ray SDK requires Ruby 2.3 or later and is compatible with the following libraries: • AWS SDK for Ruby version 3.0 or later • Rails version 5.1 or later Configuring the X-Ray SDK for Ruby The X-Ray SDK for Ruby has a class named XRay.recorder that provides the global recorder. You can configure the global recorder to customize the middleware that creates segments for incoming HTTP calls. Sections • Service plugins • Sampling rules • Logging • Recorder configuration in code • Recorder configuration with rails • Environment variables Service plugins Use plugins to record information about the service hosting your application. Plugins • Amazon EC2 – ec2 adds the instance ID and Availability Zone. • Elastic Beanstalk – elastic_beanstalk adds the environment name, version label, and deployment ID. • Amazon ECS – ecs adds the container ID. Requirements 478 AWS X-Ray Developer Guide To use plugins, specify it in the configuration object that you pass to the recorder. Example main.rb – Plugin configuration my_plugins = %I[ec2 elastic_beanstalk] config = { plugins: my_plugins, name: 'my app', } XRay.recorder.configure(config) You can also use environment variables, which take precedence over values set in code, to configure the recorder. The SDK also uses plugin settings to set the origin field on the segment. This indicates the type of AWS resource that runs your application. When you use multiple plugins, the SDK uses the following resolution order to determine the origin: ElasticBeanstalk > EKS > ECS > EC2. Sampling rules The SDK uses the sampling rules you define in the X-Ray console to determine which requests to record. The default rule traces the first request each second, and five percent of any additional Configuration 479 AWS X-Ray Developer Guide requests across all services sending traces to X-Ray. Create additional rules in the X-Ray console to customize the amount of data recorded for each of your applications. The SDK applies |
xray-guide-139 | xray-guide.pdf | 139 | AWS resource that runs your application. When you use multiple plugins, the SDK uses the following resolution order to determine the origin: ElasticBeanstalk > EKS > ECS > EC2. Sampling rules The SDK uses the sampling rules you define in the X-Ray console to determine which requests to record. The default rule traces the first request each second, and five percent of any additional Configuration 479 AWS X-Ray Developer Guide requests across all services sending traces to X-Ray. Create additional rules in the X-Ray console to customize the amount of data recorded for each of your applications. The SDK applies custom rules in the order in which they are defined. If a request matches multiple custom rules, the SDK applies only the first rule. Note If the SDK can't reach X-Ray to get sampling rules, it reverts to a default local rule of the first request each second, and five percent of any additional requests per host. This can occur if the host doesn't have permission to call sampling APIs, or can't connect to the X- Ray daemon, which acts as a TCP proxy for API calls made by the SDK. You can also configure the SDK to load sampling rules from a JSON document. The SDK can use local rules as a backup for cases where X-Ray sampling is unavailable, or use local rules exclusively. Example sampling-rules.json { "version": 2, "rules": [ { "description": "Player moves.", "host": "*", "http_method": "*", "url_path": "/api/move/*", "fixed_target": 0, "rate": 0.05 } ], "default": { "fixed_target": 1, "rate": 0.1 } } This example defines one custom rule and a default rule. The custom rule applies a five-percent sampling rate with no minimum number of requests to trace for paths under /api/move/. The default rule traces the first request each second and 10 percent of additional requests. Configuration 480 AWS X-Ray Developer Guide The disadvantage of defining rules locally is that the fixed target is applied by each instance of the recorder independently, instead of being managed by the X-Ray service. As you deploy more hosts, the fixed rate is multiplied, making it harder to control the amount of data recorded. To configure backup rules, define a hash for the document in the configuration object that you pass to the recorder. Example main.rb – Backup rule configuration require 'aws-xray-sdk' my_sampling_rules = { version: 1, default: { fixed_target: 1, rate: 0.1 } } config = { sampling_rules: my_sampling_rules, name: 'my app', } XRay.recorder.configure(config) To store the sampling rules independently, define the hash in a separate file and require the file to pull it into your application. Example config/sampling-rules.rb my_sampling_rules = { version: 1, default: { fixed_target: 1, rate: 0.1 } } Example main.rb – Sampling rule from a file require 'aws-xray-sdk' require 'config/sampling-rules.rb' config = { Configuration 481 AWS X-Ray Developer Guide sampling_rules: my_sampling_rules, name: 'my app', } XRay.recorder.configure(config) To use only local rules, require the sampling rules and configure the LocalSampler. Example main.rb – Local rule sampling require 'aws-xray-sdk' require 'aws-xray-sdk/sampling/local/sampler' config = { sampler: LocalSampler.new, name: 'my app', } XRay.recorder.configure(config) You can also configure the global recorder to disable sampling and instrument all incoming requests. Example main.rb – Disable sampling require 'aws-xray-sdk' config = { sampling: false, name: 'my app', } XRay.recorder.configure(config) Logging By default, the recorder outputs info-level events to $stdout. You can customize logging by defining a logger in the configuration object that you pass to the recorder. Example main.rb – Logging require 'aws-xray-sdk' config = { logger: my_logger, name: 'my app', } Configuration 482 AWS X-Ray Developer Guide XRay.recorder.configure(config) Use debug logs to identify issues, such as unclosed subsegments, when you generate subsegments manually. Recorder configuration in code Additional settings are available from the configure method on XRay.recorder. • context_missing – Set to LOG_ERROR to avoid throwing exceptions when your instrumented code attempts to record data when no segment is open. • daemon_address – Set the host and port of the X-Ray daemon listener. • name – Set a service name that the SDK uses for segments. • naming_pattern – Set a domain name pattern to use dynamic naming. • plugins – Record information about your application's AWS resources with plugins. • sampling – Set to false to disable sampling. • sampling_rules – Set the hash containing your sampling rules. Example main.rb – Disable context missing exceptions require 'aws-xray-sdk' config = { context_missing: 'LOG_ERROR' } XRay.recorder.configure(config) Recorder configuration with rails If you use the Rails framework, you can configure options on the global recorder in a Ruby file under app_root/initializers. The X-Ray SDK supports an additional configuration key for use with Rails. • active_record – Set to true to record subsegments for Active Record database transactions. Configure the available settings in a configuration object named Rails.application.config.xray. Configuration 483 AWS X-Ray Developer Guide Example config/initializers/aws_xray.rb Rails.application.config.xray = { name: 'my app', patch: |
xray-guide-140 | xray-guide.pdf | 140 | sampling_rules – Set the hash containing your sampling rules. Example main.rb – Disable context missing exceptions require 'aws-xray-sdk' config = { context_missing: 'LOG_ERROR' } XRay.recorder.configure(config) Recorder configuration with rails If you use the Rails framework, you can configure options on the global recorder in a Ruby file under app_root/initializers. The X-Ray SDK supports an additional configuration key for use with Rails. • active_record – Set to true to record subsegments for Active Record database transactions. Configure the available settings in a configuration object named Rails.application.config.xray. Configuration 483 AWS X-Ray Developer Guide Example config/initializers/aws_xray.rb Rails.application.config.xray = { name: 'my app', patch: %I[net_http aws_sdk], active_record: true } Environment variables You can use environment variables to configure the X-Ray SDK for Ruby. The SDK supports the following variables: • AWS_XRAY_TRACING_NAME – Set a service name that the SDK uses for segments. Overrides the service name that you set on the servlet filter's segment naming strategy. • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener. By default, the SDK sends trace data to 127.0.0.1:2000. Use this variable if you have configured the daemon to listen on a different port or if it is running on a different host. • AWS_XRAY_CONTEXT_MISSING – Set to RUNTIME_ERROR to throw exceptions when your instrumented code attempts to record data when no segment is open. Valid Values • RUNTIME_ERROR – Throw a runtime exception. • LOG_ERROR – Log an error and continue (default). • IGNORE_ERROR – Ignore error and continue. Errors related to missing segments or subsegments can occur when you attempt to use an instrumented client in startup code that runs when no request is open, or in code that spawns a new thread. Environment variables override values set in code. Tracing incoming requests with the X-Ray SDK for Ruby middleware You can use the X-Ray SDK to trace incoming HTTP requests that your application serves on an EC2 instance in Amazon EC2, AWS Elastic Beanstalk, or Amazon ECS. Incoming requests 484 AWS X-Ray Developer Guide If you use Rails, use the Rails middleware to instrument incoming HTTP requests. When you add the middleware to your application and configure a segment name, the X-Ray SDK for Ruby creates a segment for each sampled request. Any segments created by additional instrumentation become subsegments of the request-level segment that provides information about the HTTP request and response. This information includes timing, method, and disposition of the request. Each segment has a name that identifies your application in the service map. The segment can be named statically, or you can configure the SDK to name it dynamically based on the host header in the incoming request. Dynamic naming lets you group traces based on the domain name in the request, and apply a default name if the name doesn't match an expected pattern (for example, if the host header is forged). Forwarded Requests If a load balancer or other intermediary forwards a request to your application, X-Ray takes the client IP from the X-Forwarded-For header in the request instead of from the source IP in the IP packet. The client IP that is recorded for a forwarded request can be forged, so it should not be trusted. When a request is forwarded, the SDK sets an additional field in the segment to indicate this. If the segment contains the field x_forwarded_for set to true, the client IP was taken from the X- Forwarded-For header in the HTTP request. The middleware creates a segment for each incoming request with an http block that contains the following information: • HTTP method – GET, POST, PUT, DELETE, etc. • Client address – The IP address of the client that sent the request. • Response code – The HTTP response code for the completed request. • Timing – The start time (when the request was received) and end time (when the response was sent). • User agent — The user-agent from the request. • Content length — The content-length from the response. Incoming requests 485 AWS X-Ray Developer Guide Using the rails middleware To use the middleware, update your gemfile to include the required railtie. Example Gemfile - rails gem 'aws-xray-sdk', require: ['aws-xray-sdk/facets/rails/railtie'] To use the middleware, you must also configure the recorder with a name that represents the application in the trace map. Example config/initializers/aws_xray.rb Rails.application.config.xray = { name: 'my app' } Instrumenting code manually If you don't use Rails, create segments manually. You can create a segment for each incoming request, or create segments around patched HTTP or AWS SDK clients to provide context for the recorder to add subsegments. # Start a segment segment = XRay.recorder.begin_segment 'my_service' # Start a subsegment subsegment = XRay.recorder.begin_subsegment 'outbound_call', namespace: 'remote' # Add metadata or annotation here if necessary my_annotations = { k1: 'v1', k2: 1024 } segment.annotations.update my_annotations # Add metadata |
xray-guide-141 | xray-guide.pdf | 141 | the recorder with a name that represents the application in the trace map. Example config/initializers/aws_xray.rb Rails.application.config.xray = { name: 'my app' } Instrumenting code manually If you don't use Rails, create segments manually. You can create a segment for each incoming request, or create segments around patched HTTP or AWS SDK clients to provide context for the recorder to add subsegments. # Start a segment segment = XRay.recorder.begin_segment 'my_service' # Start a subsegment subsegment = XRay.recorder.begin_subsegment 'outbound_call', namespace: 'remote' # Add metadata or annotation here if necessary my_annotations = { k1: 'v1', k2: 1024 } segment.annotations.update my_annotations # Add metadata to default namespace subsegment.metadata[:k1] = 'v1' # Set user for the segment (subsegment is not supported) segment.user = 'my_name' Incoming requests 486 AWS X-Ray Developer Guide # End segment/subsegment XRay.recorder.end_subsegment XRay.recorder.end_segment Configuring a segment naming strategy AWS X-Ray uses a service name to identify your application and distinguish it from the other applications, databases, external APIs, and AWS resources that your application uses. When the X- Ray SDK generates segments for incoming requests, it records your application's service name in the segment's name field. The X-Ray SDK can name segments after the hostname in the HTTP request header. However, this header can be forged, which could result in unexpected nodes in your service map. To prevent the SDK from naming segments incorrectly due to requests with forged host headers, you must specify a default name for incoming requests. If your application serves requests for multiple domains, you can configure the SDK to use a dynamic naming strategy to reflect this in segment names. A dynamic naming strategy allows the SDK to use the hostname for requests that match an expected pattern, and apply the default name to requests that don't. For example, you might have a single application serving requests to three subdomains– www.example.com, api.example.com, and static.example.com. You can use a dynamic naming strategy with the pattern *.example.com to identify segments for each subdomain with a different name, resulting in three service nodes on the service map. If your application receives requests with a hostname that doesn't match the pattern, you will see a fourth node on the service map with a fallback name that you specify. To use the same name for all request segments, specify the name of your application when you configure the recorder, as shown in the previous sections. A dynamic naming strategy defines a pattern that hostnames should match, and a default name to use if the hostname in the HTTP request doesn't match the pattern. To name segments dynamically, specify a naming pattern in the config hash. Example main.rb – Dynamic naming config = { Incoming requests 487 AWS X-Ray Developer Guide naming_pattern: '*mydomain*', name: 'my app', } XRay.recorder.configure(config) You can use '*' in the pattern to match any string, or '?' to match any single character. Note You can override the default service name that you define in code with the AWS_XRAY_TRACING_NAME environment variable. Patching libraries to instrument downstream calls To instrument downstream calls, use the X-Ray SDK for Ruby to patch the libraries that your application uses. The X-Ray SDK for Ruby can patch the following libraries. Supported Libraries • net/http – Instrument HTTP clients. • aws-sdk – Instrument AWS SDK for Ruby clients. When you use a patched library, the X-Ray SDK for Ruby creates a subsegment for the call and records information from the request and response. A segment must be available for the SDK to create the subsegment, either from the SDK middleware or a call to XRay.recorder.begin_segment. To patch libraries, specify them in the configuration object that you pass to the X-Ray recorder. Example main.rb – Patch libraries require 'aws-xray-sdk' config = { name: 'my app', patch: %I[net_http aws_sdk] } Patching libraries 488 AWS X-Ray Developer Guide XRay.recorder.configure(config) Tracing AWS SDK calls with the X-Ray SDK for Ruby When your application makes calls to AWS services to store data, write to a queue, or send notifications, the X-Ray SDK for Ruby tracks the calls downstream in subsegments. Traced AWS services and resources that you access within those services (for example, an Amazon S3 bucket or Amazon SQS queue), appear as downstream nodes on the trace map in the X-Ray console. The X-Ray SDK for Ruby automatically instruments all AWS SDK clients when you patch the aws- sdk library. You cannot instrument individual clients. For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a separate node in |
xray-guide-142 | xray-guide.pdf | 142 | X-Ray console. The X-Ray SDK for Ruby automatically instruments all AWS SDK clients when you patch the aws- sdk library. You cannot instrument individual clients. For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a separate node in the service map, with a generic DynamoDB node for calls that don't target a table. Example Subsegment for a call to DynamoDB to save an item { "id": "24756640c0d0978a", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "DynamoDB", "namespace": "aws", "http": { "response": { "content_length": 60, "status": 200 } }, "aws": { "table_name": "scorekeep-user", "operation": "UpdateItem", "request_id": "UBQNSO5AEM8T4FDA4RQDEB94OVTDRVV4K4HIRGVJF66Q9ASUAAJG", } } AWS SDK clients 489 AWS X-Ray Developer Guide When you access named resources, calls to the following services create additional nodes in the service map. Calls that don't target specific resources create a generic node for the service. • Amazon DynamoDB – Table name • Amazon Simple Storage Service – Bucket and key name • Amazon Simple Queue Service – Queue name Generating custom subsegments with the X-Ray SDK Subsegments extend a trace's segment with details about work done in order to serve a request. Each time you make a call with an instrumented client, the X-Ray SDK records the information generated in a subsegment. You can create additional subsegments to group other subsegments, to measure the performance of a section of code, or to record annotations and metadata. To manage subsegments, use the begin_subsegment and end_subsegment methods. subsegment = XRay.recorder.begin_subsegment name: 'annotations', namespace: 'remote' my_annotations = { id: 12345 } subsegment.annotations.update my_annotations XRay.recorder.end_subsegment To create a subsegment for a function, wrap it in a call to XRay.recorder.capture. XRay.recorder.capture('name_for_subsegment') do |subsegment| resp = myfunc() # myfunc is your function subsegment.annotations.update k1: 'v1' resp end When you create a subsegment within a segment or another subsegment, the X-Ray SDK generates an ID for it and records the start time and end time. Example Subsegment with metadata "subsegments": [{ "id": "6f1605cd8a07cb70", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "Custom subsegment for UserModel.saveUser function", "metadata": { Custom subsegments 490 AWS X-Ray "debug": { "test": "Metadata string from UserModel.saveUser" } }, Developer Guide Add annotations and metadata to segments with the X-Ray SDK for Ruby You can record additional information about requests, the environment, or your application with annotations and metadata. You can add annotations and metadata to the segments that the X-Ray SDK creates, or to custom subsegments that you create. Annotations are key-value pairs with string, number, or Boolean values. Annotations are indexed for use with filter expressions. Use annotations to record data that you want to use to group traces in the console, or when calling the GetTraceSummaries API. Metadata are key-value pairs that can have values of any type, including objects and lists, but are not indexed for use with filter expressions. Use metadata to record additional data that you want stored in the trace but don't need to use with search. In addition to annotations and metadata, you can also record user ID strings on segments. User IDs are recorded in a separate field on segments and are indexed for use with search. Sections • Recording annotations with the X-Ray SDK for Ruby • Recording metadata with the X-Ray SDK for Ruby • Recording user IDs with the X-Ray SDK for Ruby Recording annotations with the X-Ray SDK for Ruby Use annotations to record information on segments or subsegments that you want indexed for search. Annotation Requirements • Keys – The key for an X-Ray annotation can have up to 500 alphanumeric characters. You cannot use spaces or symbols other than a dot or period ( . ) • Values – The value for an X-Ray annotation can have up to 1,000 Unicode characters. Annotations and metadata 491 AWS X-Ray Developer Guide • The number of Annotations – You can use up to 50 annotations per trace. To record annotations 1. Get a reference to the current segment or subsegment from xray_recorder. require 'aws-xray-sdk' ... document = XRay.recorder.current_segment or require 'aws-xray-sdk' ... document = XRay.recorder.current_subsegment 2. Call update with a hash value. my_annotations = { id: 12345 } document.annotations.update my_annotations The following is an example that shows how to call update with an annotation key that contains a dot. my_annotations = { testkey.test: 12345 } document.annotations.update my_annotations The SDK records annotations as key-value pairs in an annotations object in the segment document. Calling add_annotations twice with the same key overwrites previously recorded values on the same segment or subsegment. To find traces that have |
xray-guide-143 | xray-guide.pdf | 143 | to the current segment or subsegment from xray_recorder. require 'aws-xray-sdk' ... document = XRay.recorder.current_segment or require 'aws-xray-sdk' ... document = XRay.recorder.current_subsegment 2. Call update with a hash value. my_annotations = { id: 12345 } document.annotations.update my_annotations The following is an example that shows how to call update with an annotation key that contains a dot. my_annotations = { testkey.test: 12345 } document.annotations.update my_annotations The SDK records annotations as key-value pairs in an annotations object in the segment document. Calling add_annotations twice with the same key overwrites previously recorded values on the same segment or subsegment. To find traces that have annotations with specific values, use the annotation[key] keyword in a filter expression. Recording metadata with the X-Ray SDK for Ruby Use metadata to record information on segments or subsegments that you don't need indexed for search. Metadata values can be strings, numbers, Booleans, or any object that can be serialized into a JSON object or array. Annotations and metadata 492 AWS X-Ray To record metadata Developer Guide 1. Get a reference to the current segment or subsegment from xray_recorder. require 'aws-xray-sdk' ... document = XRay.recorder.current_segment or require 'aws-xray-sdk' ... document = XRay.recorder.current_subsegment 2. Call metadata with a String key; a Boolean, Number, String, or Object value; and a String namespace. my_metadata = { my_namespace: { key: 'value' } } subsegment.metadata my_metadata Calling metadata twice with the same key overwrites previously recorded values on the same segment or subsegment. Recording user IDs with the X-Ray SDK for Ruby Record user IDs on request segments to identify the user who sent the request. To record user IDs 1. Get a reference to the current segment from xray_recorder. require 'aws-xray-sdk' ... document = XRay.recorder.current_segment 2. Set the user field on the segment to a String ID of the user who sent the request. Annotations and metadata 493 AWS X-Ray Developer Guide segment.user = 'U12345' You can set the user in your controllers to record the user ID as soon as your application starts processing a request. To find traces for a user ID, use the user keyword in a filter expression. Annotations and metadata 494 AWS X-Ray Developer Guide Creating X-Ray resources with AWS CloudFormation AWS X-Ray is integrated with AWS CloudFormation, a service that helps you to model and set up your AWS resources so that you can spend less time creating and managing your resources and infrastructure. You create a template that describes all the AWS resources that you want, and AWS CloudFormation provisions and configures those resources for you. When you use AWS CloudFormation, you can reuse your template to set up your X-Ray resources consistently and repeatedly. Describe your resources once, and then provision the same resources over and over in multiple AWS accounts and Regions. X-Ray and AWS CloudFormation templates To provision and configure resources for X-Ray and related services, you must understand AWS CloudFormation templates. Templates are formatted text files in JSON or YAML. These templates describe the resources that you want to provision in your AWS CloudFormation stacks. If you're unfamiliar with JSON or YAML, you can use AWS CloudFormation Designer to help you get started with AWS CloudFormation templates. For more information, see What is AWS CloudFormation Designer? in the AWS CloudFormation User Guide. X-Ray supports creating AWS::XRay::Group, AWS::XRay::SamplingRule, and AWS::XRay::ResourcePolicy resources in AWS CloudFormation. For more information, including examples of JSON and YAML templates, see the X-Ray resource type reference in the AWS CloudFormation User Guide. Learn more about AWS CloudFormation To learn more about AWS CloudFormation, see the following resources: • AWS CloudFormation • AWS CloudFormation User Guide • AWS CloudFormation API Reference • AWS CloudFormation Command Line Interface User Guide X-Ray and AWS CloudFormation templates 495 AWS X-Ray Developer Guide Tagging X-Ray sampling rules and groups Tags are words or phrases that you can use to identify and organize your AWS resources. You can add multiple tags to each resource. Each tag includes a key and an optional value that you define. For example, a tag key might be domain, and the tag value might be example.com. You can search and filter your resources based on tags that you add. For more information about ways to use tags, see Tagging AWS resources in the AWS General Reference. You can use tags to enforce tag-based permissions on CloudFront distributions. For more information, see Controlling Access to AWS Resources Using Resource Tags. Note Tag Editor and AWS Resource Groups do not currently support X-Ray resources. You add and manage tags by using the AWS X-Ray console or API. You can apply tags to resources by using the X-Ray console, API, AWS CLI, SDKs, and AWS Tools for Windows PowerShell. For more information, see the following documentation: • X-Ray API – See the following operations in the AWS X-Ray API Reference: • ListTagsForResource • CreateSamplingRule |
xray-guide-144 | xray-guide.pdf | 144 | in the AWS General Reference. You can use tags to enforce tag-based permissions on CloudFront distributions. For more information, see Controlling Access to AWS Resources Using Resource Tags. Note Tag Editor and AWS Resource Groups do not currently support X-Ray resources. You add and manage tags by using the AWS X-Ray console or API. You can apply tags to resources by using the X-Ray console, API, AWS CLI, SDKs, and AWS Tools for Windows PowerShell. For more information, see the following documentation: • X-Ray API – See the following operations in the AWS X-Ray API Reference: • ListTagsForResource • CreateSamplingRule • CreateGroup • TagResource • UntagResource • AWS CLI – See xray in the AWS CLI Command Reference • SDKs – See the applicable SDK documentation on the AWS Documentation page Note If you cannot add or change tags on an X-Ray resource, or you cannot add a resource that has specific tags, you might not have permissions to perform this operation. To request access, contact an AWS user in your enterprise who has Administrator permissions in X-Ray. 496 Developer Guide AWS X-Ray Topics • Tag restrictions • Managing tags in the console • Managing tags in the AWS CLI • Control access to X-Ray resources based on tags Tag restrictions The following restrictions apply to tags. • Maximum number of tags per resource – 50 • Maximum key length – 128 Unicode characters • Maximum value length – 256 Unicode characters • Valid values for key and value – a-z, A-Z, 0-9, space, and the following characters: _ . : / = + - and @ • Tag keys and values are case sensitive. • Don't use aws: as a prefix for keys; it's reserved for AWS use. Note You cannot edit or delete system tags. Managing tags in the console You can add optional tags as you create an X-Ray group or sampling rule. Tags can also be changed or deleted in the console later. The following procedures explain how to add, edit, and delete tags for your groups and sampling rules in the X-Ray console. Topics • Add tags to a new group (console) • Add tags to a new sampling rule (console) • Edit or delete tags for a group (console) Tag restrictions 497 AWS X-Ray Developer Guide • Edit or delete tags for a sampling rule (console) Add tags to a new group (console) As you create a new X-Ray group, you can add optional tags on the Create group page. 1. Sign in to the AWS Management Console and open the X-Ray console at https:// console.aws.amazon.com/xray/home. 2. In the navigation pane, expand Configuration, and choose Groups. 3. Choose Create group. 4. On the Create group page, specify a name and filter expression for the group. For more information about these properties, see Configuring groups. 5. In Tags, enter a tag key, and optionally, a tag value. For example, you can enter a tag key of Stage, and a tag value of Production, to indicate that this group is for production use. As you add a tag, a new line appears for you to add another tag, if needed. See Tag restrictions in this topic for limitations on tags. 6. When you are finished adding tags, choose Create group. Add tags to a new sampling rule (console) As you create a new X-Ray sampling rule, you can add tags on the Create sampling rule page. 1. Sign in to the AWS Management Console and open the X-Ray console at https:// console.aws.amazon.com/xray/home. 2. In the navigation pane, expand Configuration, and choose Sampling. 3. Choose Create sampling rule. 4. On the Create sampling rule page, specify a name, priority, limits, matching criteria, and matching attributes. For more information about these properties, see Configuring sampling rules. 5. In Tags, enter a tag key, and optionally, a tag value. For example, you can enter a tag key of Stage, and a tag value of Production, to indicate that this sampling rule is for production use. As you add a tag, a new line appears for you to add another tag, if needed. See Tag restrictions in this topic for limitations on tags. 6. When you are finished adding tags, choose Create sampling rule. Add tags to a new group (console) 498 AWS X-Ray Developer Guide Edit or delete tags for a group (console) You can change or delete tags on an X-Ray group on the Edit group page. 1. Sign in to the AWS Management Console and open the X-Ray console at https:// console.aws.amazon.com/xray/home. 2. 3. In the navigation pane, expand Configuration, and choose Groups. In the Groups table, choose the name of a group. 4. On the Edit group page, in Tags, edit tag keys and values. You cannot have duplicate tag keys. Tag values are optional; you |
xray-guide-145 | xray-guide.pdf | 145 | choose Create sampling rule. Add tags to a new group (console) 498 AWS X-Ray Developer Guide Edit or delete tags for a group (console) You can change or delete tags on an X-Ray group on the Edit group page. 1. Sign in to the AWS Management Console and open the X-Ray console at https:// console.aws.amazon.com/xray/home. 2. 3. In the navigation pane, expand Configuration, and choose Groups. In the Groups table, choose the name of a group. 4. On the Edit group page, in Tags, edit tag keys and values. You cannot have duplicate tag keys. Tag values are optional; you can delete values if desired. For more information about other properties on the Edit group page, see Configuring groups. See Tag restrictions in this topic for limitations on tags. 5. To delete a tag, choose X at the right of the tag. 6. When you are finished editing or deleting tags, choose Update group. Edit or delete tags for a sampling rule (console) You can change or delete tags on an X-Ray sampling rule on the Edit sampling rule page. 1. Sign in to the AWS Management Console and open the X-Ray console at https:// 2. 3. 4. console.aws.amazon.com/xray/home. In the navigation pane, expand Configuration, and choose Sampling. In the Sampling rules table, choose the name of a sampling rule. In Tags, edit tag keys and values. You cannot have duplicate tag keys. Tag values are optional; you can delete values if desired. For more information about other properties on the Edit sampling rule page, see Configuring sampling rules. See Tag restrictions in this topic for limitations on tags. 5. To delete a tag, choose X at the right of the tag. 6. When you are finished editing or deleting tags, choose Update sampling rule. Managing tags in the AWS CLI You can add tags when you create an X-Ray group or sampling rule. You can also use the AWS CLI to create and manage tags. To update tags on an existing group or sampling rule, use the AWS X- Ray console, or the TagResource or UntagResource APIs. Edit or delete tags for a group (console) 499 AWS X-Ray Topics • Add tags to a new X-Ray group or sampling rule (CLI) • Add tags to an existing resource (CLI) • List tags on a resource (CLI) • Delete tags on a resource (CLI) Developer Guide Add tags to a new X-Ray group or sampling rule (CLI) To add optional tags as you're creating a new X-Ray group or sampling rule, use one of the following commands. • To add tags to a new group, run the following command, replacing group_name with the name of your group, mydomain.com with the endpoint of your service, key_name with a tag key, and optionally, value with a tag value. For more information about how to create a group, see Groups. aws xray create-group \ --group-name "group_name" \ --filter-expression "service(\"mydomain.com\") {fault OR error}" \ --tags [{"Key": "key_name","Value": "value"},{"Key": "key_name","Value": "value"}] The following is an example. aws xray create-group \ --group-name "AdminGroup" \ --filter-expression "service(\"mydomain.com\") {fault OR error}" \ --tags [{"Key": "Stage","Value": "Prod"},{"Key": "Department","Value": "QA"}] • To add tags to a new sampling rule, run the following command, replacing key_name with a tag key, and optionally, value with a tag value. This command specifies the values in the --sampling-rule parameter as a JSON file. For more information about how to create a sampling rule, see Sampling rules. aws xray create-sampling-rule \ --cli-input-json file://file_name.json Add tags to a new X-Ray group or sampling rule (CLI) 500 AWS X-Ray Developer Guide The following are the contents of the JSON file file_name.json that is specified by the -- cli-input-json parameter. { "SamplingRule": { "RuleName": "rule_name", "RuleARN": "string", "ResourceARN": "string", "Priority": integer, "FixedRate": double, "ReservoirSize": integer, "ServiceName": "string", "ServiceType": "string", "Host": "string", "HTTPMethod": "string", "URLPath": "string", "Version": integer, "Attributes": {"attribute_name": "value","attribute_name": "value"...} } "Tags": [ { "Key":"key_name", "Value":"value" }, { "Key":"key_name", "Value":"value" } ] } The following command is an example. aws xray create-sampling-rule \ --cli-input-json file://9000-base-scorekeep.json The following are the contents of the example 9000-base-scorekeep.json file specified by the --cli-input-json parameter. { "SamplingRule": { Add tags to a new X-Ray group or sampling rule (CLI) 501 AWS X-Ray Developer Guide "RuleName": "base-scorekeep", "ResourceARN": "*", "Priority": 9000, "FixedRate": 0.1, "ReservoirSize": 5, "ServiceName": "Scorekeep", "ServiceType": "*", "Host": "*", "HTTPMethod": "*", "URLPath": "*", "Version": 1 } "Tags": [ { "Key":"Stage", "Value":"Prod" }, { "Key":"Department", "Value":"QA" } ] } Add tags to an existing resource (CLI) You can run the tag-resource command to add tags to an existing X-Ray group or sampling rule This method might be simpler than adding tags by running update-group or update- sampling-rule. To add tags to a group or a sampling rule, run the following command, replacing the ARN with the ARN of the resource, and specifying |
xray-guide-146 | xray-guide.pdf | 146 | Developer Guide "RuleName": "base-scorekeep", "ResourceARN": "*", "Priority": 9000, "FixedRate": 0.1, "ReservoirSize": 5, "ServiceName": "Scorekeep", "ServiceType": "*", "Host": "*", "HTTPMethod": "*", "URLPath": "*", "Version": 1 } "Tags": [ { "Key":"Stage", "Value":"Prod" }, { "Key":"Department", "Value":"QA" } ] } Add tags to an existing resource (CLI) You can run the tag-resource command to add tags to an existing X-Ray group or sampling rule This method might be simpler than adding tags by running update-group or update- sampling-rule. To add tags to a group or a sampling rule, run the following command, replacing the ARN with the ARN of the resource, and specifying the keys and optional values of tags that you want to add. aws xray tag-resource \ --resource-arn "ARN" \ --tag-keys [{"Key":"key_name","Value":"value"}, {"Key":"key_name","Value":"value"}] The following is an example. aws xray tag-resource \ --resource-arn "arn:aws:xray:us-east-2:01234567890:group/AdminGroup" \ Add tags to an existing resource (CLI) 502 AWS X-Ray Developer Guide --tag-keys [{"Key": "Stage","Value": "Prod"},{"Key": "Department","Value": "QA"}] List tags on a resource (CLI) You can run the list-tags-for-resource command to list tags of an X-Ray group or sampling rule. To list the tags that are associated with a group or a sampling rule, run the following command, replacing the ARN with the ARN of the resource. aws xray list-tags-for-resource \ --resource-arn "ARN" The following is an example. aws xray list-tags-for-resource \ --resource-arn "arn:aws:xray:us-east-2:01234567890:group/AdminGroup" Delete tags on a resource (CLI) You can run the untag-resource command to remove tags from an X-Ray group or sampling rule. To remove tags from a group or a sampling rule, run the following command, replacing the ARN with the ARN of the resource, and specifying the keys of tags that you want to remove. You can remove only entire tags with the untag-resource command. To remove tag values, use the X-Ray console, or delete tags and add new tags with the same keys, but different or empty values. aws xray untag-resource \ --resource-arn "ARN" \ --tag-keys ["key_name","key_name"] The following is an example. aws xray untag-resource \ --resource-arn "arn:aws:xray:us-east-2:01234567890:group/group_name" \ --tag-keys ["Stage","Department"] List tags on a resource (CLI) 503 AWS X-Ray Developer Guide Control access to X-Ray resources based on tags You can attach tags to X-Ray groups or sampling rules, or pass tags in a request to X-Ray. To control access based on tags, you provide tag information in the condition element of a policy using the xray:ResourceTag/key-name, aws:RequestTag/key-name, or aws:TagKeys condition keys. To learn more about these condition keys, see Controlling access to AWS resources using resource tags. To view an example identity-based policy for limiting access to a resource based on the tags on that resource, see Managing access to X-Ray groups and sampling rules based on tags. Control access to X-Ray resources based on tags 504 AWS X-Ray Developer Guide Troubleshooting AWS X-Ray This topic lists common errors and issues that you might encounter when using the X-Ray API, console, or SDKs. If you find an issue that is not listed here, you can use the Feedback button on this page to report it. Sections • X-Ray trace map and trace details pages • X-Ray SDK for Java • X-Ray SDK for Node.js • The X-Ray daemon X-Ray trace map and trace details pages The following sections can help if you're having issues using the X-Ray trace map and Trace details page: I don't see all of my CloudWatch logs How to configure logs so that they appear in the X-Ray trace map and trace details pages depends on the service. • API Gateway logs appear if logging is turned on in API Gateway. Not all service map nodes support viewing the associated logs. View logs for the following node types: • Lambda context • Lambda function • API Gateway stage • Amazon ECS cluster • Amazon ECS instance • Amazon ECS service • Amazon ECS task X-Ray trace map and trace details pages 505 AWS X-Ray • Amazon EKS cluster • Amazon EKS namespace • Amazon EKS node • Amazon EKS pod • Amazon EKS service Developer Guide I don't see all of my alarms on the X-Ray trace map The X-Ray trace map shows only the alert icon for a node if any alarms that are associated with that node are in the ALARM state. The trace map associates alarms with nodes using the following logic: • If the node represents an AWS service, then all alarms with the namespace associated with that service are associated with the node. For example, a node of type AWS::Kinesis is linked with all alarms that are based on metrics in the CloudWatch namespace AWS/Kinesis. • If the node represents an AWS resource, then the alarms on that specific resource are linked. For example, a node of type AWS::DynamoDB::Table with the name “MyTable” is linked to all alarms that are based on a metric with the namespace AWS/DynamoDB and |
xray-guide-147 | xray-guide.pdf | 147 | The trace map associates alarms with nodes using the following logic: • If the node represents an AWS service, then all alarms with the namespace associated with that service are associated with the node. For example, a node of type AWS::Kinesis is linked with all alarms that are based on metrics in the CloudWatch namespace AWS/Kinesis. • If the node represents an AWS resource, then the alarms on that specific resource are linked. For example, a node of type AWS::DynamoDB::Table with the name “MyTable” is linked to all alarms that are based on a metric with the namespace AWS/DynamoDB and have the TableName dimension set to MyTable. • If the node is of unknown type, which is identified by a dashed border around the name, then no alarms are associated with that node. I don't see some AWS resources on the trace map Not every AWS resource is represented by a dedicated node. Some AWS services are represented by a single node for all requests to the service. The following resource types are displayed with a node per resource: • AWS::DynamoDB::Table • AWS::Lambda::Function Lambda functions are represented by two nodes—one for the Lambda container, and one for the function. This helps to identify cold start problems with Lambda functions. Lambda container nodes are associated with alarms and dashboards in the same way as Lambda function nodes. • AWS::ApiGateway::Stage I don't see all of my alarms on the X-Ray trace map 506 AWS X-Ray • AWS::SQS::Queue • AWS::SNS::Topic Developer Guide There are too many nodes on the trace map Use X-Ray groups to break your map into multiple maps. For more information, see Using Filter Expressions with Groups. X-Ray SDK for Java Error: Exception in thread "Thread-1" com.amazonaws.xray.exceptions.SegmentNotFoundException: Failed to begin subsegment named 'AmazonSNS': segment cannot be found. This error indicates that the X-Ray SDK attempted to record an outgoing call to AWS, but couldn't find an open segment. This can occur in the following situations: • A servlet filter is not configured – The X-Ray SDK creates segments for incoming requests with a filter named AWSXRayServletFilter. Configure a servlet filter to instrument incoming requests. • You're using instrumented clients outside of servlet code – If you use an instrumented client to make calls in startup code or other code that doesn't run in response to an incoming request, you must create a segment manually. See Instrumenting startup code for examples. • You're using instrumented clients in worker threads – When you create a new thread, the X- Ray recorder loses its reference to the open segment. You can use the getTraceEntity and setTraceEntity methods to get a reference to the current segment or subsegment (Entity), and pass it back to the recorder inside of the thread. See Using instrumented clients in worker threads for an example. X-Ray SDK for Node.js Issue: CLS does not work with Sequelize Pass the X-Ray SDK for Node.js namespace to Sequelize with the cls method. var AWSXRay = require('aws-xray-sdk'); const Sequelize = require('sequelize'); Sequelize.cls = AWSXRay.getNamespace(); There are too many nodes on the trace map 507 AWS X-Ray Developer Guide const sequelize = new Sequelize(...); Issue: CLS does not work with Bluebird Use cls-bluebird to get Bluebird working with CLS. var AWSXRay = require('aws-xray-sdk'); var Promise = require('bluebird'); var clsBluebird = require('cls-bluebird'); clsBluebird(AWSXRay.getNamespace()); The X-Ray daemon Issue: The daemon is using the wrong credentials The daemon uses the AWS SDK to load credentials. If you use multiple methods of providing credentials, the method with the highest precedence is used. See Running the daemon for more information. The X-Ray daemon 508 AWS X-Ray Developer Guide Document History for AWS X-Ray The following table describes the important changes to the documentation for AWS X-Ray. For notification about updates to this documentation, you can subscribe to an RSS feed. Latest documentation update: March 07, 2024 Change Description Date Added functionality Added functionality November 21, 2024 November 21, 2024 AWS X-Ray now supports Transaction Search. For more information, see Transaction Search. AWS X-Ray now supports OpenTelemetry Protocol (OTLP) Endpoint. For more information, see OpenTelem etry. Added functionality X-Ray now logs data events, March 7, 2024 including PutTraceS egments , GetTraceS ummaries , and BatchGetT races to AWS CloudTrai l. X-Ray also now logs the GetSamplingStatist icSummaries managemen t event to CloudTrail. For more information, see Logging X-Ray API calls with AWS CloudTrail. X-Ray now supports trace IDs created via OpenTelem etry or any other framework which conforms to the W3C October 25, 2023 509 Added functionality AWS X-Ray Developer Guide Added functionality Updated X-Ray SDK for Node.js topic Trace Context specification. For more information, see Sending trace data to X-Ray. You can now configure Amazon SNS active tracing, enabling you to trace and analyze requests as they travel through your Amazon SNS topics. For more information, see Amazon SNS |
xray-guide-148 | xray-guide.pdf | 148 | X-Ray also now logs the GetSamplingStatist icSummaries managemen t event to CloudTrail. For more information, see Logging X-Ray API calls with AWS CloudTrail. X-Ray now supports trace IDs created via OpenTelem etry or any other framework which conforms to the W3C October 25, 2023 509 Added functionality AWS X-Ray Developer Guide Added functionality Updated X-Ray SDK for Node.js topic Trace Context specification. For more information, see Sending trace data to X-Ray. You can now configure Amazon SNS active tracing, enabling you to trace and analyze requests as they travel through your Amazon SNS topics. For more information, see Amazon SNS and AWS X-Ray. Added details for instrumen ting clients using the AWS SDK for JavaScript V3. For details, see Tracing AWS SDK calls with the X-Ray SDK for Node.js. February 8, 2023 February 7, 2023 Updated IAM managed policy details Added IAM permission for cross-account observability to February 7, 2023 the AWSXRayReadOnlyAcc ess , AWSXRayFullAccess and AWSXrayCrossAccoun tSharingConfigurat ion managed policies. For details, see IAM managed policies for X-Ray. 510 AWS X-Ray Added functionality Added functionality Developer Guide November 27, 2022 November 20, 2022 AWS X-Ray now supports cross-account observability, enabling you to monitor and troubleshoot applications that span across multiple accounts within an AWS Region. For details, see Cross- account tracing. You can now view linked traces between message producers, an Amazon SQS queue, and consumers, providing a connected view of traces sent from event-dri ven applications. For more information, see tracing event-driven applications. Updated IAM managed policy details Added IAM permission for listing resource policies to November 15, 2022 Updated IAM console permissions and managed policy details the AWSXRayReadOnlyAcc ess managed policy. For details, see IAM managed policies for X-Ray. The set of IAM permissions the X-Ray console uses has been updated, along with the description of the AWSXRayRe adOnlyAccess policy. For details, see Using managed the X-Ray console. November 11, 2022 511 Developer Guide February 7, 2022 January 24, 2022 December 3, 2021 AWS X-Ray Added AWS Distro for OpenTelemetry Ruby Added functionality Integrated CloudWatch RUM AWS Distro for OpenTelem etry (ADOT) provides a single set of open source APIs, libraries, and agents to collect distributed traces and metrics. ADOT Ruby enables you to instrument your Ruby application for X-Ray and other tracing back-ends. For more information, see AWS Distro for OpenTelemetry Ruby. You can now view traces and configure X-Ray from the CloudWatch console. For more information, see X-Ray console. With AWS X-Ray and CloudWatch RUM, you can analyze and debug the request path starting from end users of your applicati on through downstream AWS managed services. For more information, see CloudWatch RUM and AWS X-Ray. 512 AWS X-Ray Developer Guide Integrated AWS Distro for OpenTelemetry The AWS Distro for OpenTelemetry (ADOT) September 23, 2021 provides a single set of open source APIs, libraries, and agents to collect distribut ed traces and metrics. ADOT enables you to instrument your application for X-Ray and other tracing back-ends . For more information, see Instrumenting your app. AWS X-Ray now integrates with Amazon Virtual Private Cloud, enabling resources in your Amazon VPC to communicate with the X-Ray service without going through the public internet. For more information, see Using AWS X-Ray with VPC endpoints. AWS X-Ray now integrates with AWS CloudFormation, enabling you to provision and configure X-Ray resources . For more information, see Creating X-Ray resources with CloudFormation. May 20, 2021 May 6, 2021 Added functionality Added functionality 513 AWS X-Ray Added functionality Added daemon to ECR Added functionality Developer Guide March 2, 2021 March 1, 2021 October 15, 2020 AWS X-Ray now integrate s with Amazon EventBrid ge to trace events that are passed through EventBrid ge. This provides users with a more complete view of their system. For more information, see Amazon EventBridge and AWS X-Ray. The daemon can now be downloaded from Amazon ECR. For more informati on, see Downloading the daemon. AWS X-Ray now supports insights related notificat ions to Amazon EventBrid ge. This allows you to take automatic actions on insights using EventBridge. For more information, see Insights Notifications. Added Downloadable Daemons AWS X-Ray introduce s support daemon for October 1, 2020 Linux ARM64. For more information, see AWS X-Ray daemonbrazil ws 514 AWS X-Ray Added functionality Added functionality Developer Guide September 24, 2020 September 14, 2020 AWS X-Ray now supports active integration with Amazon CloudWatch Synthetics. This allows you to see details about a Synthetic s canary client node such as response time and status. You can also do analysis in the Analytics console based on information from a Synthetics canary client node. For more information, see Debugging CloudWatch synthetics canaries using X- Ray . AWS X-Ray now supports tracing end-to-end workflows for AWS Step Functions . You can visualize the components of your state machine, identify performan ce bottlenecks, and troublesh |
xray-guide-149 | xray-guide.pdf | 149 | AWS X-Ray Added functionality Added functionality Developer Guide September 24, 2020 September 14, 2020 AWS X-Ray now supports active integration with Amazon CloudWatch Synthetics. This allows you to see details about a Synthetic s canary client node such as response time and status. You can also do analysis in the Analytics console based on information from a Synthetics canary client node. For more information, see Debugging CloudWatch synthetics canaries using X- Ray . AWS X-Ray now supports tracing end-to-end workflows for AWS Step Functions . You can visualize the components of your state machine, identify performan ce bottlenecks, and troublesh oot requests that resulted in an error. For more informati on, see AWS Step Functions and AWS X-Ray. 515 AWS X-Ray Added functionality Added functionality Added functionality Developer Guide September 3, 2020 September 3, 2020 August 24, 2020 AWS X-Ray introduces insights to continuously analyze trace data in your account to identify emergent issues in your applications. Insights records incidents and track incident impact until resolution. For more informati on, see Using insights in the AWS X-Ray console AWS X-Ray introduces the Java auto-instrumentation agent, enabling customers to collect trace data without having to modify existing Java-based application. You can now trace Java web and servlet based applicati ons with minimal configura tion change and no code change. For more informati on, see AWS X-Ray auto-inst rumentation agent for Java. AWS X-Ray has added a new Groups page to the X-Ray console to help ease the creation and management of groups of traces. For more information, see Configuring groups in the X-Ray console. 516 AWS X-Ray Added functionality Developer Guide August 24, 2020 AWS X-Ray now lets you add tags to groups and sampling rules. You can also control access to groups and sampling rules based on tags. For more information, see Tagging X-Ray sampling rules and groups and Managing access to X-Ray groups and sampling rules based on tags. 517 |
zonal-shift-api-001 | zonal-shift-api.pdf | 1 | API Reference Guide for Zonal Shift and Zonal Autoshift Amazon Route 53 Application Recovery Controller API Version 2022-10-30 Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon Route 53 Application Recovery Controller API Reference Guide for Zonal Shift and Zonal Autoshift Amazon Route 53 Application Recovery Controller: API Reference Guide for Zonal Shift and Zonal Autoshift Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon. Amazon Route 53 Application Recovery Controller API Reference Guide for Zonal Shift and Zonal Autoshift Table of Contents Welcome ........................................................................................................................................... 1 Actions .............................................................................................................................................. 3 CancelZonalShift ........................................................................................................................................... 4 Request Syntax ........................................................................................................................................ 4 URI Request Parameters ........................................................................................................................ 4 Request Body ........................................................................................................................................... 4 Response Syntax ...................................................................................................................................... 4 Response Elements ................................................................................................................................. 5 Errors .......................................................................................................................................................... 7 See Also ..................................................................................................................................................... 7 CreatePracticeRunConfiguration ................................................................................................................ 9 Request Syntax ........................................................................................................................................ 9 URI Request Parameters ........................................................................................................................ 9 Request Body ......................................................................................................................................... 10 Response Syntax ................................................................................................................................... 12 Response Elements ............................................................................................................................... 12 Errors ....................................................................................................................................................... 13 See Also .................................................................................................................................................. 14 DeletePracticeRunConfiguration ............................................................................................................. 16 Request Syntax ...................................................................................................................................... 16 URI Request Parameters ...................................................................................................................... 16 Request Body ......................................................................................................................................... 16 Response Syntax ................................................................................................................................... 16 Response Elements ............................................................................................................................... 17 Errors ....................................................................................................................................................... 17 See Also .................................................................................................................................................. 18 GetAutoshiftObserverNotificationStatus ............................................................................................... 20 Request Syntax ...................................................................................................................................... 20 URI Request Parameters ...................................................................................................................... 20 Request Body ......................................................................................................................................... 20 Response Syntax ................................................................................................................................... 20 Response Elements ............................................................................................................................... 20 Errors ....................................................................................................................................................... 21 See Also .................................................................................................................................................. 21 API Version 2022-10-30 iii Amazon Route 53 Application Recovery Controller API Reference Guide for Zonal Shift and Zonal Autoshift GetManagedResource ................................................................................................................................ 23 Request Syntax ...................................................................................................................................... 23 URI Request Parameters ...................................................................................................................... 23 Request Body ......................................................................................................................................... 23 Response Syntax ................................................................................................................................... 23 Response Elements ............................................................................................................................... 25 Errors ....................................................................................................................................................... 26 See Also .................................................................................................................................................. 27 ListAutoshifts .............................................................................................................................................. 28 Request Syntax ...................................................................................................................................... 28 URI Request Parameters ...................................................................................................................... 28 Request Body ......................................................................................................................................... 28 Response Syntax ................................................................................................................................... 28 Response Elements ............................................................................................................................... 29 Errors ....................................................................................................................................................... 29 See Also .................................................................................................................................................. 30 ListManagedResources .............................................................................................................................. 31 Request Syntax ...................................................................................................................................... 31 URI Request Parameters ...................................................................................................................... 31 Request Body ......................................................................................................................................... 31 Response Syntax ................................................................................................................................... 31 Response Elements ............................................................................................................................... 32 Errors ....................................................................................................................................................... 33 See Also .................................................................................................................................................. 33 ListZonalShifts ............................................................................................................................................ 35 Request Syntax ...................................................................................................................................... 35 URI Request Parameters ...................................................................................................................... 35 Request Body ......................................................................................................................................... 36 Response Syntax ................................................................................................................................... 36 Response Elements ............................................................................................................................... 36 Errors ....................................................................................................................................................... 37 See Also .................................................................................................................................................. 37 StartZonalShift ........................................................................................................................................... 39 Request Syntax ...................................................................................................................................... 39 URI Request Parameters ...................................................................................................................... 39 Request Body ......................................................................................................................................... 40 API Version 2022-10-30 iv Amazon Route 53 Application Recovery Controller API Reference Guide for Zonal Shift and Zonal Autoshift Response Syntax ................................................................................................................................... 41 Response Elements ............................................................................................................................... 42 Errors ....................................................................................................................................................... 44 See Also .................................................................................................................................................. 44 UpdateAutoshiftObserverNotificationStatus ........................................................................................ 46 Request Syntax ...................................................................................................................................... 46 URI Request Parameters ...................................................................................................................... 46 Request Body ......................................................................................................................................... 46 Response Syntax ................................................................................................................................... 47 Response Elements ............................................................................................................................... 47 Errors ....................................................................................................................................................... 47 See Also .................................................................................................................................................. 48 UpdatePracticeRunConfiguration ............................................................................................................ 49 Request Syntax ...................................................................................................................................... 49 URI Request Parameters ...................................................................................................................... 49 Request Body ......................................................................................................................................... 50 Response Syntax ................................................................................................................................... 51 Response Elements ............................................................................................................................... 52 Errors ....................................................................................................................................................... 53 See Also .................................................................................................................................................. 54 UpdateZonalAutoshiftConfiguration ...................................................................................................... 55 Request Syntax ...................................................................................................................................... 55 URI Request Parameters ...................................................................................................................... 55 Request Body ......................................................................................................................................... 55 Response Syntax ................................................................................................................................... 56 Response Elements ............................................................................................................................... 56 Errors ....................................................................................................................................................... 57 See Also .................................................................................................................................................. 57 UpdateZonalShift ....................................................................................................................................... 59 Request Syntax ...................................................................................................................................... 59 URI Request Parameters ...................................................................................................................... 59 Request Body ......................................................................................................................................... 59 Response Syntax ................................................................................................................................... 60 Response Elements ............................................................................................................................... 61 Errors ....................................................................................................................................................... 63 See Also .................................................................................................................................................. 63 API Version 2022-10-30 v Amazon Route 53 Application Recovery Controller API Reference Guide for Zonal Shift and Zonal Autoshift Data Types ..................................................................................................................................... 65 AutoshiftInResource ................................................................................................................................... 66 Contents .................................................................................................................................................. 66 See Also .................................................................................................................................................. 67 AutoshiftSummary ..................................................................................................................................... 68 Contents .................................................................................................................................................. 68 See Also .................................................................................................................................................. 69 ControlCondition ........................................................................................................................................ 70 Contents .................................................................................................................................................. 70 See Also .................................................................................................................................................. 70 ManagedResourceSummary ..................................................................................................................... 72 Contents .................................................................................................................................................. 72 See Also .................................................................................................................................................. 74 PracticeRunConfiguration ......................................................................................................................... 75 Contents .................................................................................................................................................. 75 See Also .................................................................................................................................................. 76 ZonalShiftInResource ................................................................................................................................. 77 Contents .................................................................................................................................................. 77 See Also .................................................................................................................................................. 80 ZonalShiftSummary ................................................................................................................................... 81 Contents .................................................................................................................................................. 81 See Also .................................................................................................................................................. 84 Common Parameters ..................................................................................................................... 85 Common Errors .............................................................................................................................. 88 API Version 2022-10-30 vi Amazon Route 53 Application Recovery Controller API Reference Guide for Zonal Shift and Zonal Autoshift Welcome Welcome to the API Reference Guide for zonal shift and zonal autoshift in Amazon Route 53 Application Recovery Controller (ARC). You can start a zonal shift to move traffic for a load balancer resource away from an Availability Zone to help your application recover quickly from an impairment in an Availability Zone. For example, you can recover your application from a developer's bad code deployment or from an AWS infrastructure failure in |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.