index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune | Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune/auth/package-info.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/**
* Authorization related code for Amazon Neptune, e.g.
* providing simple wrappers that ease implementation of
* IAM and SigV4 signing for various client libraries.
*/
package com.amazonaws.neptune.auth;
| 3,700 |
0 | Create_ds/amazon-chime-sdk-android/amazon-chime-sdk/src/test/java/com/amazonaws/services/chime/sdk/meetings | Create_ds/amazon-chime-sdk-android/amazon-chime-sdk/src/test/java/com/amazonaws/services/chime/sdk/meetings/session/MeetingSessionConfigurationJavaTest.java | package com.amazonaws.services.chime.sdk.meetings.session;
import org.junit.Test;
import kotlin.jvm.functions.Function1;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
public class MeetingSessionConfigurationJavaTest {
// Meeting
private String externalMeetingId = "I am the meeting";
private String mediaRegion = "us-east-1";
private String meetingId = "meetingId";
// Attendee
private String attendeeId = "attendeeId";
private String externalUserId = "Alice";
private String joinToken = "joinToken";
// MediaPlacement
private String audioFallbackURL = "audioFallbackURL";
private String audioHostURL = "audioHostURL";
private String turnControlURL = "turnControlURL";
private String signalingURL = "signalingURL";
private CreateMeetingResponse createMeeting = new CreateMeetingResponse(
new Meeting(
externalMeetingId,
new MediaPlacement(audioFallbackURL, audioHostURL, signalingURL, turnControlURL),
mediaRegion,
meetingId
)
);
private CreateAttendeeResponse createAttendee = new CreateAttendeeResponse(new Attendee(attendeeId, externalUserId, joinToken));
@Test
public void constructorShouldUseDefaultUrlRewriterWhenNotProvided() {
MeetingSessionConfiguration meetingSessionConfiguration1 = new MeetingSessionConfiguration(
createMeeting, createAttendee);
assertEquals(audioHostURL, meetingSessionConfiguration1.getUrls().getAudioHostURL());
assertEquals(audioFallbackURL, meetingSessionConfiguration1.getUrls().getAudioFallbackURL());
assertEquals(signalingURL, meetingSessionConfiguration1.getUrls().getSignalingURL());
assertEquals(turnControlURL, meetingSessionConfiguration1.getUrls().getTurnControlURL());
}
@Test
public void constructorShouldSetExternalMeetingIdToNullWhenNotProvidedThroughMeeting() {
MediaPlacement mediaPlacement = new MediaPlacement(audioFallbackURL, audioHostURL, signalingURL, turnControlURL);
Function1<String, String> urlRewrite = new Function1<String, String>() {
@Override
public String invoke(String s) {
return s;
}
};
MeetingSessionCredentials creds = new MeetingSessionCredentials(
attendeeId,
externalUserId,
joinToken
);
MeetingSessionURLs urls = new MeetingSessionURLs(
mediaPlacement.getAudioFallbackUrl(),
mediaPlacement.getAudioHostUrl(),
mediaPlacement.getTurnControlUrl(),
mediaPlacement.getSignalingUrl(),
urlRewrite
);
MeetingSessionConfiguration meetingSessionConfiguration = new MeetingSessionConfiguration(
meetingId, creds, urls);
assertNull(meetingSessionConfiguration.getExternalMeetingId());
}
@Test
public void constructorShouldSetExternalMeetingIdToNullWhenNotProvidedThroughConstructor() {
CreateMeetingResponse createMeetingNullExternal = new CreateMeetingResponse(
new Meeting(
null,
new MediaPlacement(audioFallbackURL, audioHostURL, signalingURL, turnControlURL),
mediaRegion,
meetingId
)
);
MeetingSessionConfiguration meetingSessionConfiguration = new MeetingSessionConfiguration(
createMeetingNullExternal, createAttendee);
assertNull(meetingSessionConfiguration.getExternalMeetingId());
}
private String urlRewriter(String url) {
return url + "a";
}
@Test
public void constructorShouldUseUrlRewriterWhenProvided() {
Function1<String, String> urlRewrite = new Function1<String, String>() {
@Override
public String invoke(String s) {
return urlRewriter(s);
}
};
MeetingSessionConfiguration meetingSessionConfiguration = new MeetingSessionConfiguration(
createMeeting,
createAttendee,
urlRewrite
);
assertEquals(urlRewriter(audioHostURL), meetingSessionConfiguration.getUrls().getAudioHostURL());
assertEquals(urlRewriter(audioFallbackURL), meetingSessionConfiguration.getUrls().getAudioFallbackURL());
assertEquals(urlRewriter(signalingURL), meetingSessionConfiguration.getUrls().getSignalingURL());
assertEquals(urlRewriter(turnControlURL), meetingSessionConfiguration.getUrls().getTurnControlURL());
}
}
| 3,701 |
0 | Create_ds/dgs-examples-java16/.mvn | Create_ds/dgs-examples-java16/.mvn/wrapper/MavenWrapperDownloader.java | /*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| 3,702 |
0 | Create_ds/dgs-examples-java16/src/test/java/com/example | Create_ds/dgs-examples-java16/src/test/java/com/example/dgsjava16maven/DemoApplicationTests.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dgsjava16maven;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
}
| 3,703 |
0 | Create_ds/dgs-examples-java16/src/main/java/com/example | Create_ds/dgs-examples-java16/src/main/java/com/example/dgsjava16maven/ShowsDataFetcher.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dgsjava16maven;
import com.example.dgsjava16maven.records.Show;
import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsData;
import com.netflix.graphql.dgs.InputArgument;
import java.util.List;
@DgsComponent
public class ShowsDataFetcher {
private final List<Show> showData = List.of(
new Show(1, "Stringer Things", 2016),
new Show(2, "Ozark", 2017)
);
@DgsData(parentType = "Query", field = "shows")
public List<Show> shows(@InputArgument String titleFilter) {
if(titleFilter != null) {
return showData.stream().filter(s -> s.title().startsWith(titleFilter)).toList();
} else {
return showData;
}
}
}
| 3,704 |
0 | Create_ds/dgs-examples-java16/src/main/java/com/example | Create_ds/dgs-examples-java16/src/main/java/com/example/dgsjava16maven/DemoApplication.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dgsjava16maven;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
| 3,705 |
0 | Create_ds/dgs-examples-java16/src/main/java/com/example/dgsjava16maven | Create_ds/dgs-examples-java16/src/main/java/com/example/dgsjava16maven/records/Show.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dgsjava16maven.records;
public record Show(Integer id, String title, Integer releaseYear) {
}
| 3,706 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-v2/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-v2/src/test/java/com/amazonaws/xray/interceptors/TracingInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.interceptors;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Cause;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.async.EmptyPublisher;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;
import software.amazon.awssdk.services.lambda.LambdaAsyncClient;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.InvokeRequest;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;
@FixMethodOrder(MethodSorters.JVM)
@RunWith(MockitoJUnitRunner.class)
public class TracingInterceptorTest {
@Before
public void setup() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
AWSXRay.setGlobalRecorder(
AWSXRayRecorderBuilder.standard()
.withEmitter(blankEmitter)
.build()
);
AWSXRay.clearTraceEntity();
AWSXRay.beginSegment("test");
}
@After
public void teardown() {
AWSXRay.endSegment();
}
@Test
public void testResponseDescriptors() throws Exception {
String responseBody = "{\"LastEvaluatedTableName\":\"baz\",\"TableNames\":[\"foo\",\"bar\",\"baz\"]}";
SdkHttpResponse mockResponse = SdkHttpResponse.builder()
.statusCode(200)
.putHeader("x-amzn-requestid", "1111-2222-3333-4444")
.putHeader("Content-Length", "84")
.putHeader("Content-Type", "application/x-amz-json-1.0")
.build();
SdkHttpClient mockClient = mockSdkHttpClient(mockResponse, responseBody);
DynamoDbClient client = dynamoDbClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
client.listTables(ListTablesRequest.builder()
.limit(3)
.build()
);
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
@SuppressWarnings("unchecked")
Map<String, Object> httpResponseStats = (Map<String, Object>) subsegment.getHttp().get("response");
Assert.assertEquals("ListTables", awsStats.get("operation"));
Assert.assertEquals(3, awsStats.get("limit"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals(3, awsStats.get("table_count"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(84L, httpResponseStats.get("content_length"));
Assert.assertEquals(200, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
}
@Test
public void testSqsSendMessageSubsegmentContainsQueueUrl() throws Exception {
SdkHttpClient mockClient = mockClientWithSuccessResponse(
"<SendMessageResponse>" +
"<SendMessageResult>" +
"<MD5OfMessageBody>b10a8db164e0754105b7a99be72e3fe5</MD5OfMessageBody>" +
"<MessageId>abc-def-ghi</MessageId>" +
"</SendMessageResult>" +
"<ResponseMetadata><RequestId>123-456-789</RequestId></ResponseMetadata>" +
"</SendMessageResponse>"
);
SqsClient client = sqsClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
client.sendMessage(SendMessageRequest.builder()
.queueUrl("http://queueurl.com")
.messageBody("Hello World")
.build()
);
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Assert.assertEquals("SendMessage", awsStats.get("operation"));
Assert.assertEquals("http://queueurl.com", awsStats.get("queue_url"));
Assert.assertEquals("abc-def-ghi", awsStats.get("message_id"));
Assert.assertEquals("123-456-789", awsStats.get("request_id"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(false, subsegment.isInProgress());
}
@Test
public void testSnsPublishSubsegmentContainsTopicArn() throws Exception {
SdkHttpClient mockClient = mockClientWithSuccessResponse(
"<PublishResponse>" +
"<PublishResult><MessageId>abc-def-ghi</MessageId></PublishResult>" +
"<ResponseMetadata><RequestId>123-456-789</RequestId></ResponseMetadata>" +
"</PublishResponse>"
);
SnsClient client = snsClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
client.publish(PublishRequest.builder()
.topicArn("arn:aws:sns:us-west-42:123456789012:MyTopic")
.message("Hello World")
.build()
);
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
Assert.assertEquals("Publish", awsStats.get("operation"));
Assert.assertEquals("arn:aws:sns:us-west-42:123456789012:MyTopic", awsStats.get("topic_arn"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals("123-456-789", awsStats.get("request_id"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(false, subsegment.isInProgress());
}
@Test
public void testLambdaInvokeSubsegmentContainsFunctionName() throws Exception {
SdkHttpClient mockClient = mockSdkHttpClient(generateLambdaInvokeResponse(200));
LambdaClient client = lambdaClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
);
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
@SuppressWarnings("unchecked")
Map<String, Object> httpResponseStats = (Map<String, Object>) subsegment.getHttp().get("response");
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("Failure", awsStats.get("function_error"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(200, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
}
@Test
public void testAsyncLambdaInvokeSubsegmentContainsFunctionName() {
SdkAsyncHttpClient mockClient = mockSdkAsyncHttpClient(generateLambdaInvokeResponse(200));
LambdaAsyncClient client = lambdaAsyncClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
).join();
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
@SuppressWarnings("unchecked")
Map<String, Object> httpResponseStats = (Map<String, Object>) subsegment.getHttp().get("response");
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("Failure", awsStats.get("function_error"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(200, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
}
@Test
public void test400Exception() throws Exception {
SdkHttpClient mockClient = mockSdkHttpClient(generateLambdaInvokeResponse(400));
LambdaClient client = lambdaClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
);
} catch (Exception e) {
// ignore SDK errors
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
@SuppressWarnings("unchecked")
Map<String, Object> httpResponseStats = (Map<String, Object>) subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(400, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
Assert.assertEquals(true, subsegment.isError());
Assert.assertEquals(false, subsegment.isThrottle());
Assert.assertEquals(false, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testAsync400Exception() {
SdkAsyncHttpClient mockClient = mockSdkAsyncHttpClient(generateLambdaInvokeResponse(400));
LambdaAsyncClient client = lambdaAsyncClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
).get();
} catch (Exception e) {
// ignore exceptions
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
@SuppressWarnings("unchecked")
Map<String, Object> httpResponseStats = (Map<String, Object>) subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(0, awsStats.get("retries"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(400, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isInProgress());
Assert.assertEquals(true, subsegment.isError());
Assert.assertEquals(false, subsegment.isThrottle());
Assert.assertEquals(false, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testThrottledException() throws Exception {
SdkHttpClient mockClient = mockSdkHttpClient(generateLambdaInvokeResponse(429));
LambdaClient client = lambdaClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
);
} catch (Exception e) {
// ignore SDK errors
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
@SuppressWarnings("unchecked")
Map<String, Object> httpResponseStats = (Map<String, Object>) subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(429, httpResponseStats.get("status"));
Assert.assertEquals(true, subsegment.isError());
Assert.assertEquals(true, subsegment.isThrottle());
Assert.assertEquals(false, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testAsyncThrottledException() {
SdkAsyncHttpClient mockClient = mockSdkAsyncHttpClient(generateLambdaInvokeResponse(429));
LambdaAsyncClient client = lambdaAsyncClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
).get();
} catch (Exception e) {
// ignore exceptions
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
@SuppressWarnings("unchecked")
Map<String, Object> httpResponseStats = (Map<String, Object>) subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(429, httpResponseStats.get("status"));
Assert.assertEquals(true, subsegment.isError());
Assert.assertEquals(true, subsegment.isThrottle());
Assert.assertEquals(false, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void test500Exception() throws Exception {
SdkHttpClient mockClient = mockSdkHttpClient(generateLambdaInvokeResponse(500));
LambdaClient client = lambdaClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
);
} catch (Exception e) {
// ignore SDK errors
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
@SuppressWarnings("unchecked")
Map<String, Object> httpResponseStats = (Map<String, Object>) subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(500, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isError());
Assert.assertEquals(false, subsegment.isThrottle());
Assert.assertEquals(true, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testAsync500Exception() {
SdkAsyncHttpClient mockClient = mockSdkAsyncHttpClient(generateLambdaInvokeResponse(500));
LambdaAsyncClient client = lambdaAsyncClient(mockClient);
Segment segment = AWSXRay.getCurrentSegment();
try {
client.invoke(InvokeRequest.builder()
.functionName("testFunctionName")
.build()
).get();
} catch (Exception e) {
// ignore exceptions
} finally {
Assert.assertEquals(1, segment.getSubsegments().size());
Subsegment subsegment = segment.getSubsegments().get(0);
Map<String, Object> awsStats = subsegment.getAws();
@SuppressWarnings("unchecked")
Map<String, Object> httpResponseStats = (Map<String, Object>) subsegment.getHttp().get("response");
Cause cause = subsegment.getCause();
Assert.assertEquals("Invoke", awsStats.get("operation"));
Assert.assertEquals("testFunctionName", awsStats.get("function_name"));
Assert.assertEquals("1111-2222-3333-4444", awsStats.get("request_id"));
Assert.assertEquals("extended", awsStats.get("id_2"));
Assert.assertEquals("us-west-42", awsStats.get("region"));
Assert.assertEquals(2L, httpResponseStats.get("content_length"));
Assert.assertEquals(500, httpResponseStats.get("status"));
Assert.assertEquals(false, subsegment.isError());
Assert.assertEquals(false, subsegment.isThrottle());
Assert.assertEquals(true, subsegment.isFault());
Assert.assertEquals(1, cause.getExceptions().size());
Assert.assertEquals(true, cause.getExceptions().get(0).isRemote());
}
}
@Test
public void testNoHeaderAddedWhenPropagationOff() {
Subsegment subsegment = Subsegment.noOp(AWSXRay.getGlobalRecorder(), false);
TracingInterceptor interceptor = new TracingInterceptor();
Context.ModifyHttpRequest context = Mockito.mock(Context.ModifyHttpRequest.class);
SdkHttpRequest mockRequest = Mockito.mock(SdkHttpRequest.class);
SdkHttpRequest.Builder mockRequestBuilder = Mockito.mock(SdkHttpRequest.Builder.class);
when(context.httpRequest()).thenReturn(mockRequest);
Mockito.lenient().when(context.httpRequest().toBuilder()).thenReturn(mockRequestBuilder);
ExecutionAttributes attributes = new ExecutionAttributes();
attributes.putAttribute(TracingInterceptor.entityKey, subsegment);
interceptor.modifyHttpRequest(context, attributes);
verify(mockRequest.toBuilder(), never()).appendHeader(anyString(), anyString());
}
private SdkHttpClient mockSdkHttpClient(SdkHttpResponse response) throws Exception {
return mockSdkHttpClient(response, "OK");
}
private SdkHttpClient mockSdkHttpClient(SdkHttpResponse response, String body) throws Exception {
ExecutableHttpRequest abortableCallable = Mockito.mock(ExecutableHttpRequest.class);
SdkHttpClient mockClient = Mockito.mock(SdkHttpClient.class);
when(mockClient.prepareRequest(Mockito.any())).thenReturn(abortableCallable);
when(abortableCallable.call()).thenReturn(HttpExecuteResponse.builder()
.response(response)
.responseBody(AbortableInputStream.create(
new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8))
))
.build()
);
return mockClient;
}
private SdkAsyncHttpClient mockSdkAsyncHttpClient(SdkHttpResponse response) {
SdkAsyncHttpClient mockClient = Mockito.mock(SdkAsyncHttpClient.class);
when(mockClient.execute(Mockito.any(AsyncExecuteRequest.class)))
.thenAnswer((Answer<CompletableFuture<Void>>) invocationOnMock -> {
AsyncExecuteRequest request = invocationOnMock.getArgument(0);
SdkAsyncHttpResponseHandler handler = request.responseHandler();
handler.onHeaders(response);
handler.onStream(new EmptyPublisher<>());
return CompletableFuture.completedFuture(null);
});
return mockClient;
}
private SdkHttpResponse generateLambdaInvokeResponse(int statusCode) {
return SdkHttpResponse.builder()
.statusCode(statusCode)
.putHeader("x-amz-request-id", "1111-2222-3333-4444")
.putHeader("x-amz-id-2", "extended")
.putHeader("Content-Length", "2")
.putHeader("X-Amz-Function-Error", "Failure")
.build();
}
private SdkHttpClient mockClientWithSuccessResponse(String responseBody) throws Exception {
SdkHttpResponse mockResponse = SdkHttpResponse.builder()
.statusCode(200)
.build();
return mockSdkHttpClient(mockResponse, responseBody);
}
private static LambdaClient lambdaClient(SdkHttpClient mockClient) {
return LambdaClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.overrideConfiguration(ClientOverrideConfiguration.builder()
.addExecutionInterceptor(new TracingInterceptor())
.build()
)
.build();
}
private static LambdaAsyncClient lambdaAsyncClient(SdkAsyncHttpClient mockClient) {
return LambdaAsyncClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.overrideConfiguration(ClientOverrideConfiguration.builder()
.addExecutionInterceptor(new TracingInterceptor())
.build()
)
.build();
}
private static DynamoDbClient dynamoDbClient(SdkHttpClient mockClient) {
return DynamoDbClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.overrideConfiguration(ClientOverrideConfiguration.builder()
.addExecutionInterceptor(new TracingInterceptor())
.build()
)
.build();
}
private static SqsClient sqsClient(SdkHttpClient mockClient) {
return SqsClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.overrideConfiguration(ClientOverrideConfiguration.builder()
.addExecutionInterceptor(new TracingInterceptor())
.build()
)
.build();
}
private static SnsClient snsClient(SdkHttpClient mockClient) {
return SnsClient.builder()
.httpClient(mockClient)
.endpointOverride(URI.create("http://example.com"))
.region(Region.of("us-west-42"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsSessionCredentials.create("key", "secret", "session")
))
.overrideConfiguration(ClientOverrideConfiguration.builder()
.addExecutionInterceptor(new TracingInterceptor())
.build()
)
.build();
}
}
| 3,707 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-v2/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk-v2/src/main/java/com/amazonaws/xray/interceptors/TracingInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.interceptors;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.EntityDataKeys;
import com.amazonaws.xray.entities.EntityHeaderKeys;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.handlers.config.AWSOperationHandler;
import com.amazonaws.xray.handlers.config.AWSOperationHandlerManifest;
import com.amazonaws.xray.handlers.config.AWSServiceHandlerManifest;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.awscore.AwsResponse;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.regions.Region;
public class TracingInterceptor implements ExecutionInterceptor {
/**
* @deprecated For internal use only.
*/
@Deprecated
@SuppressWarnings("checkstyle:ConstantName")
// TODO(anuraaga): Make private in next major version and rename.
public static final ExecutionAttribute<Subsegment> entityKey = new ExecutionAttribute("AWS X-Ray Entity");
private static final Log logger = LogFactory.getLog(TracingInterceptor.class);
private static final ObjectMapper MAPPER = new ObjectMapper()
.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
private static final PropertyNamingStrategies.NamingBase
SNAKE_CASE_NAMING_STRATEGY = (PropertyNamingStrategies.NamingBase) PropertyNamingStrategies.SNAKE_CASE;
private static final URL DEFAULT_OPERATION_PARAMETER_WHITELIST =
TracingInterceptor.class.getResource("/com/amazonaws/xray/interceptors/DefaultOperationParameterWhitelist.json");
private static final String UNKNOWN_REQUEST_ID = "UNKNOWN";
private static final List<String> REQUEST_ID_KEYS = Arrays.asList("x-amz-request-id", "x-amzn-requestid");
private AWSServiceHandlerManifest awsServiceHandlerManifest;
private AWSXRayRecorder recorder;
private final String accountId;
public TracingInterceptor() {
this(null, null, null);
}
public TracingInterceptor(AWSXRayRecorder recorder, String accountId, URL parameterWhitelist) {
this.recorder = recorder;
this.accountId = accountId;
initInterceptorManifest(parameterWhitelist);
}
private void initInterceptorManifest(URL parameterWhitelist) {
if (parameterWhitelist != null) {
try {
awsServiceHandlerManifest = MAPPER.readValue(parameterWhitelist, AWSServiceHandlerManifest.class);
return;
} catch (IOException e) {
logger.error(
"Unable to parse operation parameter whitelist at " + parameterWhitelist.getPath()
+ ". Falling back to default operation parameter whitelist at "
+ TracingInterceptor.DEFAULT_OPERATION_PARAMETER_WHITELIST.getPath() + ".",
e
);
}
}
try {
awsServiceHandlerManifest = MAPPER.readValue(
TracingInterceptor.DEFAULT_OPERATION_PARAMETER_WHITELIST, AWSServiceHandlerManifest.class);
} catch (IOException e) {
logger.error(
"Unable to parse default operation parameter whitelist at "
+ TracingInterceptor.DEFAULT_OPERATION_PARAMETER_WHITELIST.getPath()
+ ". This will affect this handler's ability to capture AWS operation parameter information.",
e
);
}
}
private AWSOperationHandler getOperationHandler(ExecutionAttributes executionAttributes) {
String serviceName = executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME);
String operationName = executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME);
if (awsServiceHandlerManifest == null) {
return null;
}
AWSOperationHandlerManifest operationManifest = awsServiceHandlerManifest.getOperationHandlerManifest(serviceName);
if (operationManifest == null) {
return null;
}
return operationManifest.getOperationHandler(operationName);
}
private HashMap<String, Object> extractRequestParameters(
Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
HashMap<String, Object> parameters = new HashMap<>();
AWSOperationHandler operationHandler = getOperationHandler(executionAttributes);
if (operationHandler == null) {
return parameters;
}
if (operationHandler.getRequestParameters() != null) {
operationHandler.getRequestParameters().forEach((parameterName) -> {
SdkRequest request = context.request();
Optional<Object> parameterValue = request.getValueForField(parameterName, Object.class);
if (parameterValue.isPresent()) {
parameters.put(SNAKE_CASE_NAMING_STRATEGY.translate(parameterName), parameterValue.get());
}
});
}
if (operationHandler.getRequestDescriptors() != null) {
operationHandler.getRequestDescriptors().forEach((key, descriptor) -> {
if (descriptor.isMap() && descriptor.shouldGetKeys()) {
SdkRequest request = context.request();
Optional<Map> parameterValue = request.getValueForField(key, Map.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(SNAKE_CASE_NAMING_STRATEGY.translate(renameTo), parameterValue.get().keySet());
}
} else if (descriptor.isList() && descriptor.shouldGetCount()) {
SdkRequest request = context.request();
Optional<List> parameterValue = request.getValueForField(key, List.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(SNAKE_CASE_NAMING_STRATEGY.translate(renameTo), parameterValue.get().size());
}
}
});
}
return parameters;
}
private HashMap<String, Object> extractResponseParameters(
Context.AfterExecution context, ExecutionAttributes executionAttributes) {
HashMap<String, Object> parameters = new HashMap<>();
AWSOperationHandler operationHandler = getOperationHandler(executionAttributes);
if (operationHandler == null) {
return parameters;
}
if (operationHandler.getResponseParameters() != null) {
operationHandler.getResponseParameters().forEach((parameterName) -> {
SdkResponse response = context.response();
Optional<Object> parameterValue = response.getValueForField(parameterName, Object.class);
if (parameterValue.isPresent()) {
parameters.put(SNAKE_CASE_NAMING_STRATEGY.translate(parameterName), parameterValue.get());
}
});
}
if (operationHandler.getResponseDescriptors() != null) {
operationHandler.getResponseDescriptors().forEach((key, descriptor) -> {
if (descriptor.isMap() && descriptor.shouldGetKeys()) {
SdkResponse response = context.response();
Optional<Map> parameterValue = response.getValueForField(key, Map.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(SNAKE_CASE_NAMING_STRATEGY.translate(renameTo), parameterValue.get().keySet());
}
} else if (descriptor.isList() && descriptor.shouldGetCount()) {
SdkResponse response = context.response();
Optional<List> parameterValue = response.getValueForField(key, List.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(SNAKE_CASE_NAMING_STRATEGY.translate(renameTo), parameterValue.get().size());
}
}
});
}
return parameters;
}
@Override
public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
AWSXRayRecorder recorder = getRecorder();
Entity origin = recorder.getTraceEntity();
Subsegment subsegment = recorder.beginSubsegment(executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME));
subsegment.setNamespace(Namespace.AWS.toString());
subsegment.putAws(EntityDataKeys.AWS.OPERATION_KEY,
executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME));
Region region = executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION);
if (region != null) {
subsegment.putAws(EntityDataKeys.AWS.REGION_KEY, region.id());
}
subsegment.putAllAws(extractRequestParameters(context, executionAttributes));
if (accountId != null) {
subsegment.putAws(EntityDataKeys.AWS.ACCOUNT_ID_SUBSEGMENT_KEY, accountId);
}
recorder.setTraceEntity(origin);
// store the subsegment in the AWS SDK's executionAttributes so it can be accessed across threads
executionAttributes.putAttribute(entityKey, subsegment);
}
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
SdkHttpRequest httpRequest = context.httpRequest();
Subsegment subsegment = executionAttributes.getAttribute(entityKey);
if (!subsegment.shouldPropagate()) {
return httpRequest;
}
return httpRequest.toBuilder().appendHeader(
TraceHeader.HEADER_KEY,
TraceHeader.fromEntity(subsegment).toString()).build();
}
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
Subsegment subsegment = executionAttributes.getAttribute(entityKey);
if (subsegment == null) {
return;
}
Map<String, Object> awsProperties = subsegment.getAws();
// beforeTransmission is run before every API call attempt
// default value is set to -1 and will always be -1 on the first API call attempt
// this value will be incremented by 1, so initial run will have a stored retryCount of 0
int retryCount = (int) awsProperties.getOrDefault(EntityDataKeys.AWS.RETRIES_KEY, -1);
awsProperties.put(EntityDataKeys.AWS.RETRIES_KEY, retryCount + 1);
}
@Override
public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) {
Subsegment subsegment = executionAttributes.getAttribute(entityKey);
if (subsegment == null) {
return;
}
populateRequestId(subsegment, context);
populateSubsegmentWithResponse(subsegment, context.httpResponse());
subsegment.putAllAws(extractResponseParameters(context, executionAttributes));
getRecorder().endSubsegment(subsegment);
}
@Override
public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) {
Subsegment subsegment = executionAttributes.getAttribute(entityKey);
if (subsegment == null) {
return;
}
populateSubsegmentException(subsegment, context);
populateRequestId(subsegment, context);
if (context.httpResponse().isPresent()) {
populateSubsegmentWithResponse(subsegment, context.httpResponse().get());
}
getRecorder().endSubsegment(subsegment);
}
private HashMap<String, Object> extractHttpResponseParameters(SdkHttpResponse httpResponse) {
HashMap<String, Object> parameters = new HashMap<>();
HashMap<String, Object> responseData = new HashMap<>();
responseData.put(EntityDataKeys.HTTP.STATUS_CODE_KEY, httpResponse.statusCode());
try {
if (httpResponse.headers().containsKey(EntityHeaderKeys.HTTP.CONTENT_LENGTH_HEADER)) {
responseData.put(EntityDataKeys.HTTP.CONTENT_LENGTH_KEY, Long.parseLong(
httpResponse.headers().get(EntityHeaderKeys.HTTP.CONTENT_LENGTH_HEADER).get(0))
);
}
} catch (NumberFormatException e) {
logger.warn("Unable to parse Content-Length header.", e);
}
parameters.put(EntityDataKeys.HTTP.RESPONSE_KEY, responseData);
return parameters;
}
private void setRemoteForException(Subsegment subsegment, Throwable exception) {
subsegment.getCause().getExceptions().forEach((e) -> {
if (e.getThrowable() == exception) {
e.setRemote(true);
}
});
}
private void populateSubsegmentException(Subsegment subsegment, Context.FailedExecution context) {
Throwable exception = context.exception();
subsegment.addException(exception);
int statusCode = -1;
if (exception instanceof SdkServiceException) {
statusCode = ((SdkServiceException) exception).statusCode();
subsegment.getCause().setMessage(exception.getMessage());
if (((SdkServiceException) exception).isThrottlingException()) {
subsegment.setThrottle(true);
// throttling errors are considered client-side errors
subsegment.setError(true);
}
setRemoteForException(subsegment, exception);
} else if (context.httpResponse().isPresent()) {
statusCode = context.httpResponse().get().statusCode();
}
if (statusCode == -1) {
return;
}
if (statusCode >= 400 && statusCode < 500) {
subsegment.setFault(false);
subsegment.setError(true);
if (statusCode == 429) {
subsegment.setThrottle(true);
}
} else if (statusCode >= 500) {
subsegment.setFault(true);
}
}
private void populateRequestId(
Subsegment subsegment,
Optional<SdkResponse> response,
Optional<SdkHttpResponse> httpResponse,
Throwable exception
) {
String requestId = null;
if (exception != null) {
requestId = extractRequestIdFromThrowable(exception);
}
if (requestId == null || requestId.equals(UNKNOWN_REQUEST_ID)) {
requestId = extractRequestIdFromResponse(response);
}
if (requestId == null || requestId.equals(UNKNOWN_REQUEST_ID)) {
requestId = extractRequestIdFromHttp(httpResponse);
}
if (requestId != null && !requestId.equals(UNKNOWN_REQUEST_ID)) {
subsegment.putAws(EntityDataKeys.AWS.REQUEST_ID_KEY, requestId);
}
}
private void populateRequestId(Subsegment subsegment, Context.FailedExecution context) {
populateRequestId(subsegment, context.response(), context.httpResponse(), context.exception());
}
private void populateRequestId(Subsegment subsegment, Context.AfterExecution context) {
populateRequestId(subsegment, Optional.of(context.response()), Optional.of(context.httpResponse()), null);
}
private String extractRequestIdFromHttp(Optional<SdkHttpResponse> httpResponse) {
if (!httpResponse.isPresent()) {
return null;
}
return extractRequestIdFromHttp(httpResponse.get());
}
private String extractRequestIdFromHttp(SdkHttpResponse httpResponse) {
Map<String, List<String>> headers = httpResponse.headers();
Set<String> headerKeys = headers.keySet();
String requestIdKey = headerKeys
.stream()
.filter(key -> REQUEST_ID_KEYS.contains(key.toLowerCase()))
.findFirst()
.orElse(null);
return requestIdKey != null ? headers.get(requestIdKey).get(0) : null;
}
private String extractExtendedRequestIdFromHttp(SdkHttpResponse httpResponse) {
Map<String, List<String>> headers = httpResponse.headers();
return headers.containsKey(EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER) ?
headers.get(EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER).get(0) : null;
}
private String extractRequestIdFromThrowable(Throwable exception) {
if (exception instanceof SdkServiceException) {
return ((SdkServiceException) exception).requestId();
}
return null;
}
private String extractRequestIdFromResponse(Optional<SdkResponse> response) {
if (response.isPresent()) {
return extractRequestIdFromResponse(response.get());
}
return null;
}
private String extractRequestIdFromResponse(SdkResponse response) {
if (response instanceof AwsResponse) {
return ((AwsResponse) response).responseMetadata().requestId();
}
return null;
}
private void populateSubsegmentWithResponse(Subsegment subsegment, SdkHttpResponse httpResponse) {
if (subsegment == null || httpResponse == null) {
return;
}
String extendedRequestId = extractExtendedRequestIdFromHttp(httpResponse);
if (extendedRequestId != null) {
subsegment.putAws(EntityDataKeys.AWS.EXTENDED_REQUEST_ID_KEY, extendedRequestId);
}
subsegment.putAllHttp(extractHttpResponseParameters(httpResponse));
}
private AWSXRayRecorder getRecorder() {
if (recorder == null) {
recorder = AWSXRay.getGlobalRecorder();
}
return recorder;
}
}
| 3,708 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk/src/test/java/com/amazonaws/xray/handlers/TracingHandlerLambdaTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import com.amazonaws.DefaultRequest;
import com.amazonaws.Response;
import com.amazonaws.http.HttpResponse;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.InvokeResult;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.contexts.LambdaSegmentContext;
import com.amazonaws.xray.contexts.LambdaSegmentContextResolver;
import com.amazonaws.xray.emitters.DefaultEmitter;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.strategy.sampling.NoSamplingStrategy;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@FixMethodOrder(MethodSorters.JVM)
@PrepareForTest({LambdaSegmentContext.class, LambdaSegmentContextResolver.class})
@PowerMockIgnore("javax.net.ssl.*")
public class TracingHandlerLambdaTest {
private static final String TRACE_HEADER =
"Root=1-57ff426a-80c11c39b0c928905eb0828d;Parent=1234abcd1234abcd;Sampled=1";
@Test
public void testSamplingOverrideFalseInLambda() throws Exception {
TraceHeader header = TraceHeader.fromString(TRACE_HEADER);
PowerMockito.stub(PowerMockito.method(
LambdaSegmentContext.class, "getTraceHeaderFromEnvironment")).toReturn(header);
PowerMockito.stub(PowerMockito.method(
LambdaSegmentContextResolver.class, "getLambdaTaskRoot")).toReturn("/var/task");
Emitter mockedEmitted = Mockito.mock(DefaultEmitter.class);
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withEmitter(mockedEmitted)
.build();
lambdaTestHelper(recorder, "testFalse", false);
Mockito.verify(mockedEmitted, Mockito.times(0)).sendSubsegment(any());
}
@Test
public void testSamplingOverrideTrueInLambda() {
Emitter mockedEmitted = Mockito.mock(DefaultEmitter.class);
TraceHeader header = TraceHeader.fromString(TRACE_HEADER);
PowerMockito.stub(PowerMockito.method(
LambdaSegmentContext.class, "getTraceHeaderFromEnvironment")).toReturn(header);
PowerMockito.stub(PowerMockito.method(
LambdaSegmentContextResolver.class, "getLambdaTaskRoot")).toReturn("/var/task");
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withEmitter(mockedEmitted)
.build();
Mockito.doAnswer(invocation -> { return true; }).when(mockedEmitted).sendSubsegment(any());
lambdaTestHelper(recorder, "testTrue", true);
Mockito.verify(mockedEmitted, Mockito.times(1)).sendSubsegment(any());
}
@Test
public void testSamplingOverrideMixedInLambda() {
Emitter mockedEmitted = Mockito.mock(DefaultEmitter.class);
TraceHeader header = TraceHeader.fromString(TRACE_HEADER);
PowerMockito.stub(PowerMockito.method(
LambdaSegmentContext.class, "getTraceHeaderFromEnvironment")).toReturn(header);
PowerMockito.stub(PowerMockito.method(
LambdaSegmentContextResolver.class, "getLambdaTaskRoot")).toReturn("/var/task");
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withEmitter(mockedEmitted)
.build();
Mockito.doAnswer(invocation -> { return true; }).when(mockedEmitted).sendSubsegment(any());
lambdaTestHelper(recorder, "test1", true);
Mockito.verify(mockedEmitted, Mockito.times(1)).sendSubsegment(any());
lambdaTestHelper(recorder, "test2", false);
Mockito.verify(mockedEmitted, Mockito.times(1)).sendSubsegment(any());
lambdaTestHelper(recorder, "test3", true);
Mockito.verify(mockedEmitted, Mockito.times(2)).sendSubsegment(any());
lambdaTestHelper(recorder, "test4", false);
Mockito.verify(mockedEmitted, Mockito.times(2)).sendSubsegment(any());
}
public static void lambdaTestHelper(AWSXRayRecorder recorder, String name, boolean sampled) {
if (sampled) {
recorder.beginSubsegment(name);
} else {
recorder.beginSubsegmentWithoutSampling(name);
}
Subsegment subsegment = ((Subsegment) recorder.getTraceEntity());
assertThat(subsegment.shouldPropagate()).isTrue();
DefaultRequest<Void> request = new DefaultRequest<>(new InvokeRequest(), "Test");
TracingHandler tracingHandler = new TracingHandler(recorder);
tracingHandler.beforeRequest(request);
TraceHeader traceHeader = TraceHeader.fromString(request.getHeaders().get(TraceHeader.HEADER_KEY));
String serviceEntityId = recorder.getCurrentSubsegment().getId();
assertThat(traceHeader.getSampled()).isEqualTo(
subsegment.isSampled() ?
TraceHeader.SampleDecision.SAMPLED :
TraceHeader.SampleDecision.NOT_SAMPLED);
assertThat(traceHeader.getRootTraceId()).isEqualTo(subsegment.getTraceId());
assertThat(traceHeader.getParentId()).isEqualTo(subsegment.isSampled() ? serviceEntityId : null);
tracingHandler.afterResponse(request, new Response(new InvokeResult(), new HttpResponse(request, null)));
recorder.endSubsegment();
}
}
| 3,709 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk/src/test/java/com/amazonaws/xray/handlers/TracingHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.http.AmazonHttpClient;
import com.amazonaws.http.apache.client.impl.ConnectionManagerAwareHttpClient;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.AWSLambdaClientBuilder;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.xray.AWSXRayClientBuilder;
import com.amazonaws.services.xray.model.GetSamplingRulesRequest;
import com.amazonaws.services.xray.model.GetSamplingTargetsRequest;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.strategy.LogErrorContextMissingStrategy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.io.EmptyInputStream;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.apache.http.protocol.HttpContext;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.powermock.reflect.Whitebox;
class TracingHandlerTest {
@BeforeEach
void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard().withEmitter(blankEmitter).build());
AWSXRay.clearTraceEntity();
}
private void mockHttpClient(Object client, String responseContent) {
AmazonHttpClient amazonHttpClient = new AmazonHttpClient(new ClientConfiguration());
ConnectionManagerAwareHttpClient apacheHttpClient = Mockito.mock(ConnectionManagerAwareHttpClient.class);
HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
BasicHttpEntity responseBody = new BasicHttpEntity();
InputStream in = EmptyInputStream.INSTANCE;
if (null != responseContent && !responseContent.isEmpty()) {
in = new ByteArrayInputStream(responseContent.getBytes(StandardCharsets.UTF_8));
}
responseBody.setContent(in);
httpResponse.setEntity(responseBody);
try {
Mockito.doReturn(httpResponse).when(apacheHttpClient).execute(Mockito.any(HttpUriRequest.class),
Mockito.any(HttpContext.class));
} catch (IOException e) {
// Ignore
}
Whitebox.setInternalState(amazonHttpClient, "httpClient", apacheHttpClient);
Whitebox.setInternalState(client, "client", amazonHttpClient);
}
@Test
void testLambdaInvokeSubsegmentContainsFunctionName() {
// Setup test
AWSLambda lambda = AWSLambdaClientBuilder
.standard()
.withRequestHandlers(new TracingHandler())
.withRegion(Regions.US_EAST_1)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
.build();
mockHttpClient(lambda, "null"); // Lambda returns "null" on successful fn. with no return value
// Test logic
Segment segment = AWSXRay.beginSegment("test");
InvokeRequest request = new InvokeRequest();
request.setFunctionName("testFunctionName");
lambda.invoke(request);
Assertions.assertEquals(1, segment.getSubsegments().size());
Assertions.assertEquals("Invoke", segment.getSubsegments().get(0).getAws().get("operation"));
Assertions.assertEquals("testFunctionName", segment.getSubsegments().get(0).getAws().get("function_name"));
}
@Test
void testS3PutObjectSubsegmentContainsBucketName() {
// Setup test
AmazonS3 s3 = AmazonS3ClientBuilder
.standard()
.withRequestHandlers(new TracingHandler())
.withRegion(Regions.US_EAST_1)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
.build();
mockHttpClient(s3, null);
String bucket = "test-bucket";
String key = "test-key";
// Test logic
Segment segment = AWSXRay.beginSegment("test");
s3.putObject(bucket, key, "This is a test from java");
Assertions.assertEquals(1, segment.getSubsegments().size());
Assertions.assertEquals("PutObject", segment.getSubsegments().get(0).getAws().get("operation"));
Assertions.assertEquals(bucket, segment.getSubsegments().get(0).getAws().get("bucket_name"));
Assertions.assertEquals(key, segment.getSubsegments().get(0).getAws().get("key"));
}
@Test
void testS3CopyObjectSubsegmentContainsBucketName() {
// Setup test
final String copyResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<CopyObjectResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
"<LastModified>2018-01-21T10:09:54.000Z</LastModified><ETag>" +
""31748afd7b576119d3c2471f39fc7a55"</ETag>" +
"</CopyObjectResult>";
AmazonS3 s3 = AmazonS3ClientBuilder
.standard()
.withRequestHandlers(new TracingHandler())
.withRegion(Regions.US_EAST_1)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
.build();
mockHttpClient(s3, copyResponse);
String bucket = "source-bucket";
String key = "source-key";
String dstBucket = "dest-bucket";
String dstKey = "dest-key";
// Test logic
Segment segment = AWSXRay.beginSegment("test");
s3.copyObject(bucket, key, dstBucket, dstKey);
Assertions.assertEquals(1, segment.getSubsegments().size());
Assertions.assertEquals("CopyObject", segment.getSubsegments().get(0).getAws().get("operation"));
Assertions.assertEquals(bucket, segment.getSubsegments().get(0).getAws().get("source_bucket_name"));
Assertions.assertEquals(key, segment.getSubsegments().get(0).getAws().get("source_key"));
Assertions.assertEquals(dstBucket, segment.getSubsegments().get(0).getAws().get("destination_bucket_name"));
Assertions.assertEquals(dstKey, segment.getSubsegments().get(0).getAws().get("destination_key"));
}
@Test
void testSNSPublish() {
// Setup test
// reference : https://docs.aws.amazon.com/sns/latest/api/API_Publish.html
final String publishResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<PublishResponse xmlns=\"http://sns.amazonaws.com/doc/2010-03-31/\">" +
"<PublishResult><MessageId>94f20ce6-13c5-43a0-9a9e-ca52d816e90b</MessageId>" +
"</PublishResult>" +
"</PublishResponse>";
final String topicArn = "testTopicArn";
AmazonSNS sns = AmazonSNSClientBuilder
.standard()
.withRequestHandlers(new TracingHandler())
.withRegion(Regions.US_EAST_1)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
.build();
mockHttpClient(sns, publishResponse);
// Test logic
Segment segment = AWSXRay.beginSegment("test");
sns.publish(new PublishRequest(topicArn, "testMessage"));
Assertions.assertEquals(1, segment.getSubsegments().size());
Assertions.assertEquals("Publish", segment.getSubsegments().get(0).getAws().get("operation"));
Assertions.assertEquals(topicArn, segment.getSubsegments().get(0).getAws().get("topic_arn"));
}
@Test
void testShouldNotTraceXRaySamplingOperations() {
com.amazonaws.services.xray.AWSXRay xray = AWSXRayClientBuilder
.standard()
.withRequestHandlers(new TracingHandler()).withRegion(Regions.US_EAST_1)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
.build();
mockHttpClient(xray, null);
Segment segment = AWSXRay.beginSegment("test");
xray.getSamplingRules(new GetSamplingRulesRequest());
Assertions.assertEquals(0, segment.getSubsegments().size());
xray.getSamplingTargets(new GetSamplingTargetsRequest());
Assertions.assertEquals(0, segment.getSubsegments().size());
}
@Test
void testShouldNotThrowContextMissingOnXRaySampling() {
com.amazonaws.services.xray.AWSXRay xray = AWSXRayClientBuilder
.standard()
.withRequestHandlers(new TracingHandler()).withRegion(Regions.US_EAST_1)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
.build();
mockHttpClient(xray, null);
xray.getSamplingRules(new GetSamplingRulesRequest());
xray.getSamplingTargets(new GetSamplingTargetsRequest());
}
@Test
void testRaceConditionOnRecorderInitialization() {
AWSXRay.setGlobalRecorder(null);
// TracingHandler will not have the initialized recorder
AWSLambda lambda = AWSLambdaClientBuilder
.standard()
.withRequestHandlers(new TracingHandler())
.withRegion(Regions.US_EAST_1)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
.build();
mockHttpClient(lambda, "null");
// Now init the global recorder
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.defaultRecorder();
recorder.setContextMissingStrategy(new LogErrorContextMissingStrategy());
AWSXRay.setGlobalRecorder(recorder);
// Test logic
InvokeRequest request = new InvokeRequest();
request.setFunctionName("testFunctionName");
lambda.invoke(request);
}
}
| 3,710 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-aws-sdk/src/main/java/com/amazonaws/xray/handlers/TracingHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.handlers;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.AmazonWebServiceResult;
import com.amazonaws.Request;
import com.amazonaws.Response;
import com.amazonaws.ResponseMetadata;
import com.amazonaws.handlers.HandlerContextKey;
import com.amazonaws.handlers.RequestHandler2;
import com.amazonaws.http.HttpResponse;
import com.amazonaws.retry.RetryUtils;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.EntityDataKeys;
import com.amazonaws.xray.entities.EntityHeaderKeys;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.handlers.config.AWSOperationHandler;
import com.amazonaws.xray.handlers.config.AWSOperationHandlerManifest;
import com.amazonaws.xray.handlers.config.AWSServiceHandlerManifest;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Extension of {@code RequestHandler2} that intercepts requests made by {@code AmazonWebServiceClient}s and generates
* corresponding subsegments. Operation-level customization of this request handler is by default performed based on the
* information contained in the file at {@code "/com/amazonaws/xray/handlers/DefaultOperationParameterWhitelist.json")}.
*/
public class TracingHandler extends RequestHandler2 {
private static final Log logger = LogFactory.getLog(TracingHandler.class);
private static final ObjectMapper MAPPER = new ObjectMapper()
.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
private static final URL DEFAULT_OPERATION_PARAMETER_WHITELIST =
TracingHandler.class.getResource("/com/amazonaws/xray/handlers/DefaultOperationParameterWhitelist.json");
private static final String GETTER_METHOD_NAME_PREFIX = "get";
private static final String S3_SERVICE_NAME = "Amazon S3";
private static final String S3_PRESIGN_REQUEST = "GeneratePresignedUrl";
private static final String S3_REQUEST_ID_HEADER_KEY = "x-amz-request-id";
private static final String XRAY_SERVICE_NAME = "AWSXRay";
private static final String XRAY_SAMPLING_RULE_REQUEST = "GetSamplingRules";
private static final String XRAY_SAMPLING_TARGET_REQUEST = "GetSamplingTargets";
private static final String REQUEST_ID_SUBSEGMENT_KEY = "request_id";
private static final HandlerContextKey<Entity> ENTITY_KEY = new HandlerContextKey<>("AWS X-Ray Entity");
private static final HandlerContextKey<Long> EXECUTING_THREAD_KEY = new HandlerContextKey<>("AWS X-Ray Executing Thread ID");
private static final PropertyNamingStrategies.NamingBase
SNAKE_CASE_NAMING_STRATEGY = (PropertyNamingStrategies.NamingBase) PropertyNamingStrategies.SNAKE_CASE;
private final String accountId;
private AWSServiceHandlerManifest awsServiceHandlerManifest;
private AWSXRayRecorder recorder;
public TracingHandler() {
this(AWSXRay.getGlobalRecorder(), null, null);
}
public TracingHandler(AWSXRayRecorder recorder) {
this(recorder, null, null);
}
public TracingHandler(String accountId) {
this(AWSXRay.getGlobalRecorder(), accountId, null);
}
public TracingHandler(AWSXRayRecorder recorder, String accountId) {
this(recorder, accountId, null);
}
public TracingHandler(URL operationParameterWhitelist) {
this(AWSXRay.getGlobalRecorder(), null, operationParameterWhitelist);
}
public TracingHandler(AWSXRayRecorder recorder, URL operationParameterWhitelist) {
this(recorder, null, operationParameterWhitelist);
}
public TracingHandler(String accountId, URL operationParameterWhitelist) {
this(AWSXRay.getGlobalRecorder(), accountId, operationParameterWhitelist);
}
public TracingHandler(AWSXRayRecorder recorder, String accountId, URL operationParameterWhitelist) {
this.recorder = recorder;
this.accountId = accountId;
initRequestManifest(operationParameterWhitelist);
}
private void initRequestManifest(URL operationParameterWhitelist) {
if (null != operationParameterWhitelist) {
try {
awsServiceHandlerManifest = MAPPER.readValue(operationParameterWhitelist, AWSServiceHandlerManifest.class);
return;
} catch (IOException e) {
logger.error("Unable to parse operation parameter whitelist at " + operationParameterWhitelist.getPath()
+ ". Falling back to default operation parameter whitelist at "
+ TracingHandler.DEFAULT_OPERATION_PARAMETER_WHITELIST.getPath()
+ ".", e);
}
}
try {
awsServiceHandlerManifest = MAPPER.readValue(
TracingHandler.DEFAULT_OPERATION_PARAMETER_WHITELIST, AWSServiceHandlerManifest.class);
} catch (IOException e) {
logger.error("Unable to parse default operation parameter whitelist at "
+ TracingHandler.DEFAULT_OPERATION_PARAMETER_WHITELIST.getPath()
+ ". This will affect this handler's ability to capture AWS operation parameter information.", e);
}
}
private boolean isSubsegmentDuplicate(Optional<Subsegment> subsegment, Request<?> request) {
return subsegment.isPresent() &&
Namespace.AWS.toString().equals(subsegment.get().getNamespace()) &&
(null != extractServiceName(request) && extractServiceName(request).equals(subsegment.get().getName()));
}
@Override
public AmazonWebServiceRequest beforeExecution(AmazonWebServiceRequest request) {
lazyLoadRecorder();
request.addHandlerContext(ENTITY_KEY, recorder.getTraceEntity());
request.addHandlerContext(EXECUTING_THREAD_KEY, Thread.currentThread().getId());
return request;
}
@Override
public void beforeRequest(Request<?> request) {
String serviceName = extractServiceName(request);
String operationName = extractOperationName(request);
if (S3_SERVICE_NAME.equals(serviceName) && S3_PRESIGN_REQUEST.equals(operationName)) {
return;
}
if (XRAY_SERVICE_NAME.equals(serviceName) && (XRAY_SAMPLING_RULE_REQUEST.equals(operationName)
|| XRAY_SAMPLING_TARGET_REQUEST.equals(operationName))) {
return;
}
if (isSubsegmentDuplicate(recorder.getCurrentSubsegmentOptional(), request)) {
return;
}
Entity entityContext = request.getHandlerContext(ENTITY_KEY);
if (null != entityContext) {
recorder.setTraceEntity(entityContext);
}
Subsegment currentSubsegment = recorder.beginSubsegment(serviceName);
currentSubsegment.putAllAws(extractRequestParameters(request));
currentSubsegment.putAws(EntityDataKeys.AWS.OPERATION_KEY, operationName);
if (null != accountId) {
currentSubsegment.putAws(EntityDataKeys.AWS.ACCOUNT_ID_SUBSEGMENT_KEY, accountId);
}
currentSubsegment.setNamespace(Namespace.AWS.toString());
if (recorder.getCurrentSegment() != null && recorder.getCurrentSubsegment().shouldPropagate()) {
request.addHeader(TraceHeader.HEADER_KEY, TraceHeader.fromEntity(currentSubsegment).toString());
}
}
private String extractServiceName(Request<?> request) {
return request.getServiceName();
}
private String extractOperationName(Request<?> request) {
String ret = request.getOriginalRequest().getClass().getSimpleName();
ret = ret.substring(0, ret.length() - 7); // remove 'Request'
return ret;
}
private HashMap<String, Object> extractRequestParameters(Request<?> request) {
HashMap<String, Object> ret = new HashMap<>();
if (null == awsServiceHandlerManifest) {
return ret;
}
AWSOperationHandlerManifest serviceHandler =
awsServiceHandlerManifest.getOperationHandlerManifest(extractServiceName(request));
if (null == serviceHandler) {
return ret;
}
AWSOperationHandler operationHandler = serviceHandler.getOperationHandler(extractOperationName(request));
if (null == operationHandler) {
return ret;
}
Object originalRequest = request.getOriginalRequest();
if (null != operationHandler.getRequestParameters()) {
operationHandler.getRequestParameters().forEach(parameterName -> {
try {
Object parameterValue = originalRequest
.getClass().getMethod(GETTER_METHOD_NAME_PREFIX + parameterName).invoke(originalRequest);
if (null != parameterValue) {
ret.put(SNAKE_CASE_NAMING_STRATEGY.translate(parameterName), parameterValue);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
logger.error("Error getting request parameter: " + parameterName, e);
}
});
}
if (null != operationHandler.getRequestDescriptors()) {
operationHandler.getRequestDescriptors().forEach((requestKeyName, requestDescriptor) -> {
try {
if (requestDescriptor.isMap() && requestDescriptor.shouldGetKeys()) {
@SuppressWarnings("unchecked")
Map<String, Object> parameterValue =
(Map<String, Object>) originalRequest
.getClass()
.getMethod(GETTER_METHOD_NAME_PREFIX + requestKeyName).invoke(originalRequest);
if (null != parameterValue) {
String renameTo =
null != requestDescriptor.getRenameTo() ? requestDescriptor.getRenameTo() : requestKeyName;
ret.put(SNAKE_CASE_NAMING_STRATEGY.translate(renameTo), parameterValue.keySet());
}
} else if (requestDescriptor.isList() && requestDescriptor.shouldGetCount()) {
@SuppressWarnings("unchecked")
List<Object> parameterValue =
(List<Object>) originalRequest
.getClass().getMethod(GETTER_METHOD_NAME_PREFIX + requestKeyName).invoke(originalRequest);
if (null != parameterValue) {
String renameTo =
null != requestDescriptor.getRenameTo() ? requestDescriptor.getRenameTo() : requestKeyName;
ret.put(SNAKE_CASE_NAMING_STRATEGY.translate(renameTo), parameterValue.size());
}
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassCastException e) {
logger.error("Error getting request parameter: " + requestKeyName, e);
}
});
}
return ret;
}
private HashMap<String, Object> extractResponseParameters(Request<?> request, Object response) {
HashMap<String, Object> ret = new HashMap<>();
if (null == awsServiceHandlerManifest) {
return ret;
}
AWSOperationHandlerManifest serviceHandler =
awsServiceHandlerManifest.getOperationHandlerManifest(extractServiceName(request));
if (null == serviceHandler) {
return ret;
}
AWSOperationHandler operationHandler = serviceHandler.getOperationHandler(extractOperationName(request));
if (null == operationHandler) {
return ret;
}
if (null != operationHandler.getResponseParameters()) {
operationHandler.getResponseParameters().forEach(parameterName -> {
try {
Object parameterValue = response
.getClass().getMethod(GETTER_METHOD_NAME_PREFIX + parameterName).invoke(response);
if (null != parameterValue) {
ret.put(SNAKE_CASE_NAMING_STRATEGY.translate(parameterName), parameterValue);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
logger.error("Error getting response parameter: " + parameterName, e);
}
});
}
if (null != operationHandler.getResponseDescriptors()) {
operationHandler.getResponseDescriptors().forEach((responseKeyName, responseDescriptor) -> {
try {
if (responseDescriptor.isMap() && responseDescriptor.shouldGetKeys()) {
@SuppressWarnings("unchecked")
Map<String, Object> parameterValue =
(Map<String, Object>) response
.getClass().getMethod(GETTER_METHOD_NAME_PREFIX + responseKeyName).invoke(response);
if (null != parameterValue) {
String renameTo =
null != responseDescriptor.getRenameTo() ? responseDescriptor.getRenameTo() : responseKeyName;
ret.put(SNAKE_CASE_NAMING_STRATEGY.translate(renameTo), parameterValue.keySet());
}
} else if (responseDescriptor.isList() && responseDescriptor.shouldGetCount()) {
@SuppressWarnings("unchecked")
List<Object> parameterValue =
(List<Object>) response
.getClass().getMethod(GETTER_METHOD_NAME_PREFIX + responseKeyName).invoke(response);
if (null != parameterValue) {
String renameTo =
null != responseDescriptor.getRenameTo() ? responseDescriptor.getRenameTo() : responseKeyName;
ret.put(SNAKE_CASE_NAMING_STRATEGY.translate(renameTo), parameterValue.size());
}
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassCastException e) {
logger.error("Error getting request parameter: " + responseKeyName, e);
}
});
}
return ret;
}
private HashMap<String, Object> extractHttpResponseInformation(AmazonServiceException ase) {
HashMap<String, Object> ret = new HashMap<>();
HashMap<String, Object> response = new HashMap<>();
response.put(EntityDataKeys.HTTP.STATUS_CODE_KEY, ase.getStatusCode());
try {
if (null != ase.getHttpHeaders() && null != ase.getHttpHeaders().get(EntityHeaderKeys.HTTP.CONTENT_LENGTH_HEADER)) {
response.put(EntityDataKeys.HTTP.CONTENT_LENGTH_KEY,
Long.parseLong(ase.getHttpHeaders().get(EntityHeaderKeys.HTTP.CONTENT_LENGTH_HEADER)));
}
} catch (NumberFormatException nfe) {
logger.warn("Unable to parse Content-Length header.", nfe);
}
ret.put(EntityDataKeys.HTTP.RESPONSE_KEY, response);
return ret;
}
private HashMap<String, Object> extractHttpResponseInformation(HttpResponse httpResponse) {
HashMap<String, Object> ret = new HashMap<>();
HashMap<String, Object> response = new HashMap<>();
response.put(EntityDataKeys.HTTP.STATUS_CODE_KEY, httpResponse.getStatusCode());
try {
if (null != httpResponse.getHeaders().get(EntityHeaderKeys.HTTP.CONTENT_LENGTH_HEADER)) {
response.put(EntityDataKeys.HTTP.CONTENT_LENGTH_KEY,
Long.parseLong(httpResponse.getHeaders().get(EntityHeaderKeys.HTTP.CONTENT_LENGTH_HEADER)));
}
} catch (NumberFormatException nfe) {
logger.warn("Unable to parse Content-Length header.", nfe);
}
ret.put(EntityDataKeys.HTTP.RESPONSE_KEY, response);
return ret;
}
@Override
public void afterResponse(Request<?> request, Response<?> response) {
if (isSubsegmentDuplicate(recorder.getCurrentSubsegmentOptional(), request)) {
Optional<Subsegment> currentSubsegmentOptional = recorder.getCurrentSubsegmentOptional();
if (!currentSubsegmentOptional.isPresent()) {
return;
}
Subsegment currentSubsegment = currentSubsegmentOptional.get();
populateAndEndSubsegment(currentSubsegment, request, response, null);
}
}
@Override
public void afterError(Request<?> request, Response<?> response, Exception e) {
if (isSubsegmentDuplicate(recorder.getCurrentSubsegmentOptional(), request)) {
Optional<Subsegment> currentSubsegmentOptional = recorder.getCurrentSubsegmentOptional();
if (!currentSubsegmentOptional.isPresent()) {
return;
}
Subsegment currentSubsegment = currentSubsegmentOptional.get();
int statusCode = -1;
if (null != response) {
statusCode = response.getHttpResponse().getStatusCode();
} else {
if (e instanceof AmazonServiceException) {
AmazonServiceException ase = (AmazonServiceException) e;
statusCode = ase.getStatusCode();
// The S3 client will throw and re-swallow AmazonServiceExceptions if they have these status codes. Customers
// will never see the exceptions in their application code but they still travel through our
// TracingHandler#afterError method. We special case these status codes in order to prevent addition of the
// full exception object to the current subsegment. Instead, we'll just add any exception error message to the
// current subsegment's cause's message.
if ((304 == statusCode || 412 == statusCode) && S3_SERVICE_NAME.equals(ase.getServiceName())) {
populateAndEndSubsegment(currentSubsegment, request, response, ase);
return;
}
if (RetryUtils.isThrottlingException(ase)) {
currentSubsegment.setError(true);
currentSubsegment.setThrottle(true);
}
}
}
if (-1 != statusCode) {
int statusCodePrefix = statusCode / 100;
if (4 == statusCodePrefix) {
currentSubsegment.setError(true);
if (429 == statusCode) {
currentSubsegment.setThrottle(true);
}
}
}
currentSubsegment.addException(e);
if (e instanceof AmazonServiceException) {
populateAndEndSubsegment(currentSubsegment, request, response, (AmazonServiceException) e);
} else {
populateAndEndSubsegment(currentSubsegment, request, response);
}
}
}
private void populateAndEndSubsegment(Subsegment currentSubsegment, Request<?> request, Response<?> response) {
if (null != response) {
String requestId = null;
if (response.getAwsResponse() instanceof AmazonWebServiceResult<?>) {
// Not all services return responses extending AmazonWebServiceResult (e.g. S3)
ResponseMetadata metadata = ((AmazonWebServiceResult<?>) response.getAwsResponse()).getSdkResponseMetadata();
if (null != metadata) {
requestId = metadata.getRequestId();
if (null != requestId) {
currentSubsegment.putAws(REQUEST_ID_SUBSEGMENT_KEY, requestId);
}
}
} else if (null != response.getHttpResponse()) { // S3 does not follow request id header convention
if (null != response.getHttpResponse().getHeader(S3_REQUEST_ID_HEADER_KEY)) {
currentSubsegment.putAws(REQUEST_ID_SUBSEGMENT_KEY,
response.getHttpResponse().getHeader(S3_REQUEST_ID_HEADER_KEY));
}
if (null != response.getHttpResponse().getHeader(EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER)) {
currentSubsegment.putAws(EntityDataKeys.AWS.EXTENDED_REQUEST_ID_KEY,
response.getHttpResponse().getHeader(
EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER));
}
}
currentSubsegment.putAllAws(extractResponseParameters(request, response.getAwsResponse()));
currentSubsegment.putAllHttp(extractHttpResponseInformation(response.getHttpResponse()));
}
finalizeSubsegment(request);
}
private void populateAndEndSubsegment(
Subsegment currentSubsegment, Request<?> request, Response<?> response, AmazonServiceException ase) {
if (null != response) {
populateAndEndSubsegment(currentSubsegment, request, response);
return;
} else if (null != ase) {
if (null != ase.getRequestId()) {
currentSubsegment.putAws(REQUEST_ID_SUBSEGMENT_KEY, ase.getRequestId());
}
if (null != ase.getHttpHeaders() &&
null != ase.getHttpHeaders().get(EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER)) {
currentSubsegment.putAws(EntityDataKeys.AWS.EXTENDED_REQUEST_ID_KEY,
ase.getHttpHeaders().get(EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER));
}
if (null != ase.getErrorMessage()) {
currentSubsegment.getCause().setMessage(ase.getErrorMessage());
}
currentSubsegment.putAllHttp(extractHttpResponseInformation(ase));
}
finalizeSubsegment(request);
}
private void finalizeSubsegment(Request<?> request) {
recorder.endSubsegment();
Long executingThreadContext = request.getHandlerContext(EXECUTING_THREAD_KEY);
if (executingThreadContext != null && Thread.currentThread().getId() != executingThreadContext) {
recorder.clearTraceEntity();
}
}
private void lazyLoadRecorder() {
if (recorder != null) {
return;
}
recorder = AWSXRay.getGlobalRecorder();
}
}
| 3,711 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/test/java/com/amazonaws/xray/spring | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/test/java/com/amazonaws/xray/spring/aop/BaseAbstractXRayInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.spring.aop;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.entities.Segment;
import java.util.Optional;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class BaseAbstractXRayInterceptorTest {
@Rule
public MockitoRule mocks = MockitoJUnit.rule();
static class ImplementedXRayInterceptor extends BaseAbstractXRayInterceptor {
@Override
protected void xrayEnabledClasses() {
}
}
private BaseAbstractXRayInterceptor xRayInterceptor = new ImplementedXRayInterceptor();
@Mock
private AWSXRayRecorder mockRecorder;
@Mock
private ProceedingJoinPoint mockPjp;
@Mock
private Signature mockSignature;
@Before
public void setup() {
AWSXRay.setGlobalRecorder(mockRecorder);
when(mockPjp.getArgs()).thenReturn(new Object[] {});
when(mockPjp.getSignature()).thenReturn(mockSignature);
when(mockSignature.getName()).thenReturn("testSpringName");
}
@Test
public void testNullSegmentOnProcessFailure() throws Throwable {
// Test to ensure that getCurrentSegment()/getCurrentSegmentOptional() don't throw NPEs when customers are using
// the Log context missing strategy during the processXRayTrace call.
Exception expectedException = new RuntimeException("An intended exception");
// Cause an intended exception to be thrown so that getCurrentSegmentOptional() is called.
when(mockRecorder.beginSubsegment(any())).thenThrow(expectedException);
when(mockRecorder.getCurrentSegmentOptional()).thenReturn(Optional.empty());
when(mockRecorder.getCurrentSegment()).thenReturn(null);
try {
xRayInterceptor.processXRayTrace(mockPjp);
} catch (Exception e) {
// A null pointer exception here could potentially indicate that a call to getCurrentSegment() is returning null.
// i.e. there is another exception other than our intended exception that is thrown that's not supposed to be thrown.
assertNotEquals(NullPointerException.class, e.getClass());
assertEquals(expectedException.getMessage(), e.getMessage());
}
}
@Test
public void testSegmentOnProcessFailure() throws Throwable {
// Test to ensure that the exception is populated to the segment when an error occurs during the
// processXRayTrace call.
Exception expectedException = new RuntimeException("An intended exception");
// Cause an intended exception to be thrown so that getCurrentSegmentOptional() is called.
when(mockRecorder.beginSubsegment(any())).thenThrow(expectedException);
Segment mockSegment = mock(Segment.class);
when(mockRecorder.getCurrentSegmentOptional()).thenReturn(Optional.of(mockSegment));
when(mockRecorder.getCurrentSegment()).thenReturn(mockSegment);
try {
xRayInterceptor.processXRayTrace(mockPjp);
} catch (Exception e) {
verify(mockSegment).addException(expectedException);
}
}
}
| 3,712 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring/aop/XRayEnabled.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.spring.aop;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface XRayEnabled {
}
| 3,713 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring/aop/XRayTraced.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.spring.aop;
public interface XRayTraced {
}
| 3,714 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring/aop/XRaySpringDataInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.spring.aop;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Subsegment;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Configurable;
@Aspect
@Configurable
public class XRaySpringDataInterceptor {
private static final Log logger = LogFactory.getLog(XRaySpringDataInterceptor.class);
@Around("queryExecution()")
public Object traceSQL(ProceedingJoinPoint pjp) throws Throwable {
try {
Subsegment subsegment = AWSXRay.beginSubsegment(pjp.getSignature().getName());
XRayInterceptorUtils.generateMetadata(pjp, subsegment);
return XRayInterceptorUtils.conditionalProceed(pjp);
} catch (Exception e) {
logger.error(e.getMessage());
AWSXRay.getCurrentSegment().addException(e);
throw e;
} finally {
logger.trace("Ending Subsegment");
AWSXRay.endSubsegment();
}
}
// TODO(anuraaga): Pretty sure a no-op Pointcut is safe to remove but not sure, magic can be tricky to reason about.
@SuppressWarnings("UnusedMethod")
@Pointcut("execution(public !void java.sql.Statement.execute*(java.lang.String))")
private void queryExecution() {
}
}
| 3,715 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring/aop/BaseAbstractXRayInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.spring.aop;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Subsegment;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
/**
* Allows for use of this library without Spring Data JPA being in the classpath.
* For projects using Spring Data JPA, consider using {@link AbstractXRayInterceptor} instead.
*/
public abstract class BaseAbstractXRayInterceptor {
private static final Log logger = LogFactory.getLog(BaseAbstractXRayInterceptor.class);
/**
* @param pjp the proceeding join point
* @return the result of the method being wrapped
* @throws Throwable
*/
@Around("xrayTracedClasses() || xrayEnabledClasses()")
public Object traceAroundMethods(ProceedingJoinPoint pjp) throws Throwable {
return this.processXRayTrace(pjp);
}
protected Object processXRayTrace(ProceedingJoinPoint pjp) throws Throwable {
try {
Subsegment subsegment = AWSXRay.beginSubsegment(pjp.getSignature().getName());
if (subsegment != null) {
subsegment.setMetadata(generateMetadata(pjp, subsegment));
}
return XRayInterceptorUtils.conditionalProceed(pjp);
} catch (Exception e) {
AWSXRay.getCurrentSegmentOptional().ifPresent(x -> x.addException(e));
throw e;
} finally {
logger.trace("Ending Subsegment");
AWSXRay.endSubsegment();
}
}
protected abstract void xrayEnabledClasses();
@Pointcut("execution(* XRayTraced+.*(..))")
protected void xrayTracedClasses() {
}
protected Map<String, Map<String, Object>> generateMetadata(ProceedingJoinPoint pjp, Subsegment subsegment) {
return XRayInterceptorUtils.generateMetadata(pjp, subsegment);
}
}
| 3,716 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring/aop/XRayInterceptorUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.spring.aop;
import com.amazonaws.xray.entities.Subsegment;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.ProceedingJoinPoint;
/**
* @deprecated For internal use only.
*/
@SuppressWarnings("checkstyle:HideUtilityClassConstructor")
@Deprecated
public class XRayInterceptorUtils {
public static Object conditionalProceed(ProceedingJoinPoint pjp) throws Throwable {
if (pjp.getArgs().length == 0) {
return pjp.proceed();
} else {
return pjp.proceed(pjp.getArgs());
}
}
public static Map<String, Map<String, Object>> generateMetadata(ProceedingJoinPoint pjp, Subsegment subsegment) {
final Map<String, Map<String, Object>> metadata = new HashMap<>();
final Map<String, Object> classInfo = new HashMap<>();
classInfo.put("Class", pjp.getTarget().getClass().getSimpleName());
metadata.put("ClassInfo", classInfo);
return metadata;
}
}
| 3,717 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-spring/src/main/java/com/amazonaws/xray/spring/aop/AbstractXRayInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.spring.aop;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
public abstract class AbstractXRayInterceptor extends BaseAbstractXRayInterceptor {
private static final Log logger = LogFactory.getLog(AbstractXRayInterceptor.class);
@Pointcut("execution(public !void org.springframework.data.repository.Repository+.*(..))")
protected void springRepositories() {
}
/**
* @param pjp the proceeding join point
* @return the result of the method being wrapped
* @throws Throwable
*/
@Around("springRepositories()")
public Object traceAroundRepositoryMethods(ProceedingJoinPoint pjp) throws Throwable {
logger.trace("Advising repository");
boolean hasClassAnnotation = false;
for (Class<?> i : pjp.getTarget().getClass().getInterfaces()) {
if (i.getAnnotation(XRayEnabled.class) != null) {
hasClassAnnotation = true;
break;
}
}
if (hasClassAnnotation) {
return this.processXRayTrace(pjp);
} else {
return XRayInterceptorUtils.conditionalProceed(pjp);
}
}
}
| 3,718 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/test/java/com/amazonaws/xray/metrics/EMFMetricFormatterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.metrics;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.TraceID;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class EMFMetricFormatterTest {
private static final String TEST_SERVICE = "testService";
private static final String TEST_ORIGIN = "Test::Origin";
private static final double START_TIME = 550378800.0d;
private static final double END_TIME = 550382400.0d;
private static final String EXPECTED_JSON =
"{\"Timestamp\":550382400000,\"log_group_name\":\"ServiceMetricsSDK\",\"CloudWatchMetrics\":"
+ "[{\"Metrics\":[{\"Name\":\"ErrorRate\",\"Unit\":\"None\"},{\"Name\":\"FaultRate\","
+ "\"Unit\":\"None\"},{\"Name\":\"ThrottleRate\",\"Unit\":\"None\"},{\"Name\":\"OkRate\","
+ "\"Unit\":\"None\"},{\"Name\":\"Latency\",\"Unit\":\"Milliseconds\"}],\"Namespace\":"
+ "\"ServiceMetrics/SDK\",\"Dimensions\":[[\"ServiceType\",\"ServiceName\"]]}],\"Latency"
+ "\":3600000.000,\"ErrorRate\":1,\"FaultRate\":1,\"ThrottleRate\":1,\"OkRate\":0,"
+ "\"TraceId\":\"1-5759e988-bd862e3fe1be46a994272793\",\"ServiceType\":\"Test::Origin\","
+ "\"ServiceName\":\"testService\",\"Version\":\"0\"}";
private Segment testSegment;
private EMFMetricFormatter formatter;
@BeforeEach
void setup() {
TraceID traceId = TraceID.fromString("1-5759e988-bd862e3fe1be46a994272793");
testSegment = mock(Segment.class);
when(testSegment.getTraceId()).thenReturn(traceId);
when(testSegment.getStartTime()).thenReturn(START_TIME);
when(testSegment.getEndTime()).thenReturn(END_TIME);
when(testSegment.isError()).thenReturn(true);
when(testSegment.isFault()).thenReturn(true);
when(testSegment.isThrottle()).thenReturn(true);
when(testSegment.getName()).thenReturn(TEST_SERVICE);
when(testSegment.getOrigin()).thenReturn(TEST_ORIGIN);
formatter = new EMFMetricFormatter();
}
@Test
void testJsonFormat() {
String json = formatter.formatSegment(testSegment);
Assertions.assertEquals(EXPECTED_JSON, json);
}
@Test
void jsonContainsNoNewlines() {
String json = formatter.formatSegment(testSegment);
Assertions.assertFalse(json.contains("\n"));
}
}
| 3,719 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/test/java/com/amazonaws/xray/config/MetricsDaemonConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.config;
import static org.junit.Assert.assertEquals;
import java.net.InetSocketAddress;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
public class MetricsDaemonConfigurationTest {
@Rule
public EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Rule
public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
@Before
public void setup() {
environmentVariables.set(MetricsDaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, null);
System.setProperty(MetricsDaemonConfiguration.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "");
}
@Test
public void testDefaultConfiguration() {
MetricsDaemonConfiguration config = new MetricsDaemonConfiguration();
InetSocketAddress address = config.getAddressForEmitter();
assertEquals("localhost:25888", config.getUDPAddress());
assertEquals(25888, address.getPort());
assertEquals("localhost", address.getHostString());
}
@Test
public void testEnvironmentConfiguration() {
environmentVariables.set(MetricsDaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, "127.0.0.1:15888");
MetricsDaemonConfiguration config = new MetricsDaemonConfiguration();
InetSocketAddress address = config.getAddressForEmitter();
assertEquals("127.0.0.1:15888", config.getUDPAddress());
assertEquals(15888, address.getPort());
assertEquals("127.0.0.1", address.getHostString());
}
@Test
public void testPropertyConfiguration() {
System.setProperty(MetricsDaemonConfiguration.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "127.0.0.1:16888");
MetricsDaemonConfiguration config = new MetricsDaemonConfiguration();
InetSocketAddress address = config.getAddressForEmitter();
assertEquals("127.0.0.1:16888", config.getUDPAddress());
assertEquals(16888, address.getPort());
assertEquals("127.0.0.1", address.getHostString());
}
@Test
public void testEnvironmentOverridesPropertyConfiguration() {
System.setProperty(MetricsDaemonConfiguration.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "127.0.0.1:16888");
environmentVariables.set(MetricsDaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, "127.0.0.1:15888");
MetricsDaemonConfiguration config = new MetricsDaemonConfiguration();
InetSocketAddress address = config.getAddressForEmitter();
assertEquals("127.0.0.1:15888", config.getUDPAddress());
assertEquals(15888, address.getPort());
assertEquals("127.0.0.1", address.getHostString());
}
@Test
public void invalidFormat() {
environmentVariables.set(MetricsDaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, "127.0.0.1:15888");
MetricsDaemonConfiguration config = new MetricsDaemonConfiguration();
config.setUDPAddress("INVALID_STRING");
config.setUDPAddress("REALLY:INVALID:STRING");
InetSocketAddress address = config.getAddressForEmitter();
assertEquals("127.0.0.1:15888", config.getUDPAddress());
assertEquals(15888, address.getPort());
assertEquals("127.0.0.1", address.getHostString());
}
@Test
public void setDaemonAddressFailsWhenEnvironment() {
environmentVariables.set(MetricsDaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, "127.0.0.1:15888");
MetricsDaemonConfiguration config = new MetricsDaemonConfiguration();
config.setDaemonAddress("127.0.0.1:16888");
InetSocketAddress address = config.getAddressForEmitter();
assertEquals("127.0.0.1:15888", config.getUDPAddress());
assertEquals(15888, address.getPort());
assertEquals("127.0.0.1", address.getHostString());
}
@Test
public void setDaemonAddressWithNoEnv() {
MetricsDaemonConfiguration config = new MetricsDaemonConfiguration();
config.setDaemonAddress("127.0.0.1:16888");
InetSocketAddress address = config.getAddressForEmitter();
assertEquals("127.0.0.1:16888", config.getUDPAddress());
assertEquals(16888, address.getPort());
assertEquals("127.0.0.1", address.getHostString());
}
}
| 3,720 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray/metrics/EMFMetricFormatter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.metrics;
import com.amazonaws.xray.entities.Segment;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Creates metrics based on a Segment.
*
* <p>These metrics are published to CloudWatch via a structured log through CloudWatch Logs. These logs are created in the
* <u>ServiceMetricsSDK</u> log group.</p>
*
* <p>In addition to the metrics describe below these logs contain properties to enable correlation with Traces.
* <ul>
* <li><u>Timestamp:</u> The end time of the segment, used for the timestamp of the generated metric.</li>
* <li><u>TraceId:</u> The Trace ID</li>
* </ul>
*
* <p>Metrics are published to the <u>ServiceMetrics/SDK</u> namespace with dimensions:</p>
* <ul>
* <li><u>ServiceType:</u> The Segment Origin
* <li><u>ServiceName:</u> The Segment Name</li>
* </ul>
*
* <p>The following metrics will be reported:</p>
* <ul>
* <li><u>Latency:</u> The difference between Start and End time in milliseconds</li>
* <li><u>ErrorRate:</u> 1 if the segment is marked as an error, zero otherwise. </li>
* <li><u>FaultRate:</u> 1 if the segment is marked as an fault, zero otherwise. </li>
* <li><u>ThrottleRate:</u> 1 if the segment is marked as throttled, zero otherwise.</li>
* <li><u>OkRate:</u> 1 if no other statuses are set, zero otherwise.</li>
* </ul>
*
* <p>Rate metrics above may be used with the CloudWatch AVG statistic to get a percentage of requests in a category or may be
* used as a SUM. COUNT of Latency represents the total count of invocations of this segment.</p>
*/
public class EMFMetricFormatter implements MetricFormatter {
private static final Log logger = LogFactory.getLog(EMFMetricFormatter.class);
private static final String EMF_FORMAT = "{\"Timestamp\":%d,\"log_group_name\":\"ServiceMetricsSDK\",\"CloudWatchMetrics\":"
+ "[{\"Metrics\":[{\"Name\":\"ErrorRate\",\"Unit\":\"None\"},{\"Name\":\"FaultRate\","
+ "\"Unit\":\"None\"},{\"Name\":\"ThrottleRate\",\"Unit\":\"None\"},"
+ "{\"Name\":\"OkRate\",\"Unit\":\"None\"},{\"Name\":\"Latency\","
+ "\"Unit\":\"Milliseconds\"}],\"Namespace\":\"ServiceMetrics/SDK\","
+ "\"Dimensions\":[[\"ServiceType\",\"ServiceName\"]]}],\"Latency\":%.3f,"
+ "\"ErrorRate\":%d,\"FaultRate\":%d,\"ThrottleRate\":%d,\"OkRate\":%d,"
+ "\"TraceId\":\"%s\",\"ServiceType\":\"%s\",\"ServiceName\":\"%s\","
+ "\"Version\":\"0\"}";
@Override
public String formatSegment(final Segment segment) {
int errorRate = segment.isError() ? 1 : 0;
int faultRate = segment.isFault() ? 1 : 0;
int throttleRate = segment.isThrottle() ? 1 : 0;
int okRate = (errorRate + faultRate + throttleRate) > 0 ? 0 : 1;
double duration = (segment.getEndTime() - segment.getStartTime()) * 1000;
long endTimeMillis = (long) (segment.getEndTime() * 1000);
String json = String.format(EMF_FORMAT,
endTimeMillis,
duration,
errorRate,
faultRate,
throttleRate,
okRate,
segment.getTraceId().toString(),
segment.getOrigin(),
segment.getName());
if (logger.isDebugEnabled()) {
logger.debug("Formatted segment " + segment.getName() + " as EMF: " + json);
}
return json;
}
}
| 3,721 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray/metrics/NoOpMetricEmitter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.metrics;
import com.amazonaws.xray.entities.Segment;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class NoOpMetricEmitter implements MetricEmitter {
private static final Log logger = LogFactory.getLog(NoOpMetricEmitter.class);
@Override
public void emitMetric(final Segment segment) {
if (logger.isDebugEnabled()) {
logger.debug("Not emitting metrics for Segment:" + segment.getTraceId() + segment.getId());
}
}
}
| 3,722 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray/metrics/MetricsSegmentListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.metrics;
import com.amazonaws.xray.entities.FacadeSegment;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.listeners.SegmentListener;
import java.net.SocketException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Listener that extracts metrics from Segments and emits them to CloudWatch using a structured log mechanism.
* Structured logs are sent via UDP to the CloudWatch agent.
*
* Configuration of UDP metric emissions is described in {@link com.amazonaws.xray.config.MetricsDaemonConfiguration}.
*
* For a list of supported metrics see {@link EMFMetricFormatter}.
*/
public class MetricsSegmentListener implements SegmentListener {
private static final Log logger = LogFactory.getLog(MetricsSegmentListener.class);
private static final String AWS_EXECUTION_ENV_NAME = "AWS_EXECUTION_ENV";
private static final String AWS_LAMBDA_PREFIX = "AWS_Lambda_";
private MetricEmitter emitter = new NoOpMetricEmitter();
public MetricsSegmentListener() {
String awsEnv = System.getenv(AWS_EXECUTION_ENV_NAME);
try {
if (awsEnv != null && awsEnv.contains(AWS_LAMBDA_PREFIX)) {
// Metrics are not supported on Lambda as the root Segment is managed by Lambda and not this SDK.
logger.info("Metric emissions is not supported on Lambda.");
} else {
logger.info("Emitting metrics to the CloudWatch Agent.");
emitter = new UDPMetricEmitter();
}
} catch (SocketException e) {
logger.error("Unable to construct metrics emitter. No metrics will be published.", e);
}
}
@Override
public void afterEndSegment(final Segment segment) {
if (segment != null && !(segment instanceof FacadeSegment)) {
emitter.emitMetric(segment);
}
}
}
| 3,723 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray/metrics/UDPMetricEmitter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.metrics;
import com.amazonaws.xray.config.MetricsDaemonConfiguration;
import com.amazonaws.xray.entities.Segment;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Generates EMF formatted metrics and send them to the CloudWatch Agent for publication.
*/
public class UDPMetricEmitter implements MetricEmitter {
private static final Log logger = LogFactory.getLog(UDPMetricEmitter.class);
private static final int BUFFER_SIZE = 64 * 1024;
private MetricFormatter formatter;
private DatagramSocket socket;
private InetSocketAddress address;
private byte[] sendBuffer = new byte[BUFFER_SIZE];
public UDPMetricEmitter() throws SocketException {
MetricsDaemonConfiguration configuration = new MetricsDaemonConfiguration();
formatter = new EMFMetricFormatter();
try {
socket = new DatagramSocket();
address = configuration.getAddressForEmitter();
} catch (SocketException e) {
logger.error("Exception while instantiating daemon socket.", e);
throw e;
}
}
/**
* {@inheritDoc}
*/
@Override
public void emitMetric(final Segment segment) {
String formattedMetric = formatter.formatSegment(segment);
DatagramPacket packet = new DatagramPacket(sendBuffer, BUFFER_SIZE, address);
packet.setData(formattedMetric.getBytes(StandardCharsets.UTF_8));
try {
socket.send(packet);
} catch (IOException e) {
logger.error("Unable to send metric to agent.", e);
}
}
}
| 3,724 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray/metrics/MetricFormatter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.metrics;
import com.amazonaws.xray.entities.Segment;
/**
* Convert a segment into a formatted log string.
*/
public interface MetricFormatter {
/**
* Converts a segment into a metric string.
* @param segment Segment to format into metrics
* @return a string representation of the {@link Segment}
*/
String formatSegment(Segment segment);
}
| 3,725 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray/metrics/MetricEmitter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.metrics;
import com.amazonaws.xray.entities.Segment;
/**
* Extract metrics from a segment and emit them to a a given destination.
*/
public interface MetricEmitter {
/**
* Format the given metric and emit it.
*
* @param segment Segment to emit metrics from
*/
void emitMetric(Segment segment);
}
| 3,726 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray/metrics/StdoutMetricEmitter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.metrics;
import com.amazonaws.xray.entities.Segment;
/**
* Writes EMF formatted structured logs to stdout for testing.
*/
public class StdoutMetricEmitter implements MetricEmitter {
private MetricFormatter formatter;
public StdoutMetricEmitter() {
formatter = new EMFMetricFormatter();
}
@SuppressWarnings("checkstyle:Regexp")
@Override
public void emitMetric(final Segment segment) {
String output = formatter.formatSegment(segment);
System.out.println(output);
}
}
| 3,727 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-metrics/src/main/java/com/amazonaws/xray/config/MetricsDaemonConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.config;
import com.amazonaws.xray.entities.StringValidator;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Configuration specifying where to publish EMF metrics over UDP
*/
public class MetricsDaemonConfiguration {
/**
* Environment variable key used to override the address to which UDP packets will be emitted. Valid values are of the form
* `ip_address:port`. Takes precedence over the system property when used.
*/
public static final String DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY = "AWS_XRAY_METRICS_DAEMON_ADDRESS";
/**
* System property key used to override the address to which UDP packets will be emitted. Valid values are of the form
* `ip_address:port`.
* used.
*/
public static final String DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY = "com.amazonaws.xray.metrics.daemonAddress";
private static final Log logger = LogFactory.getLog(MetricsDaemonConfiguration.class);
private static final int DEFAULT_PORT = 25888;
private InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), DEFAULT_PORT);
public MetricsDaemonConfiguration() {
String environmentAddress = System.getenv(DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY);
String systemAddress = System.getProperty(DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY);
if (setUDPAddress(environmentAddress)) {
logger.info(String.format("Environment variable %s is set. Emitting to daemon on address %s.",
DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, getUDPAddress()));
} else if (setUDPAddress(systemAddress)) {
logger.info(String.format("System property %s is set. Emitting to daemon on address %s.",
DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, getUDPAddress()));
}
}
/**
* Sets the metrics daemon address. If either the {@code AWS_XRAY_METRICS_DAEMON_ADDRESS} environment variable or
* {@code com.amazonaws.xray.metrics.daemonAddress} system property are set to a non-empty value, calling this method does
* nothing. Logs an error if the address format is invalid to allow tracing if metrics are inoperative.
*
* @param socketAddress
* Formatted as '127.0.0.1:25888'
*/
public void setDaemonAddress(String socketAddress) {
String environmentAddress = System.getenv(DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY);
String systemAddress = System.getProperty(DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY);
if (StringValidator.isNullOrBlank(environmentAddress) && StringValidator.isNullOrBlank(systemAddress)) {
setUDPAddress(socketAddress);
} else {
logger.info(String.format("Ignoring call to setDaemonAddress as one of %s or %s is set.",
DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY));
}
}
/**
* Set metrics daemon address, ignoring the value of of environment variable or system property.
* Logs an error if the address format is invalid to allow tracing if metrics are inoperative.
*
* @param addr
* Formatted as '127.0.0.1:25888'
*
* @return true if the address updates without error
*/
public boolean setUDPAddress(String addr) {
if (addr == null) {
return false;
}
int lastColonIndex = addr.lastIndexOf(':');
if (-1 == lastColonIndex) {
logger.error("Invalid value for agent address: " + addr + ". Value must be of form \"ip_address:port\".");
return false;
}
String[] parts = addr.split(":");
if (parts.length != 2) {
logger.error("Invalid value for agent address: " + addr + ". Value must be of form \"ip_address:port\".");
return false;
}
address = new InetSocketAddress(addr.substring(0, lastColonIndex), Integer.parseInt(addr.substring(lastColonIndex + 1)));
logger.debug("UDPAddress is set to " + addr + ".");
return true;
}
/**
* Get the UDP address to publish metrics to.
* @return the address in string form
*/
public String getUDPAddress() {
return address.getHostString() + ":" + String.valueOf(address.getPort());
}
/**
* Get the socket address to publish metrics to.
* @return the address as InetSocketAddress
*/
public InetSocketAddress getAddressForEmitter() {
return address;
}
}
| 3,728 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray/sql/TracingDataSourceTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class TracingDataSourceTest {
private DataSource dataSource;
public interface OtherWrapper extends DataSource, ExtraInterface {
}
public interface ExtraInterface {
}
@Mock
private OtherWrapper delegate;
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() throws SQLException {
dataSource = TracingDataSource.decorate(delegate);
doReturn(false).when(delegate).isWrapperFor(any());
doReturn(true).when(delegate).isWrapperFor(OtherWrapper.class);
doReturn(true).when(delegate).isWrapperFor(ExtraInterface.class);
doThrow(SQLException.class).when(delegate).unwrap(any());
doReturn(delegate).when(delegate).unwrap(OtherWrapper.class);
doReturn(delegate).when(delegate).unwrap(ExtraInterface.class);
}
@Test
void testDecoration() throws SQLException {
Assertions.assertTrue(dataSource instanceof TracingDataSource);
Assertions.assertTrue(dataSource.isWrapperFor(DataSource.class));
Assertions.assertTrue(dataSource.isWrapperFor(TracingDataSource.class));
Assertions.assertTrue(dataSource.isWrapperFor(OtherWrapper.class));
Assertions.assertTrue(dataSource.isWrapperFor(ExtraInterface.class));
Assertions.assertFalse(dataSource.isWrapperFor(Long.class));
verify(delegate, never()).isWrapperFor(DataSource.class);
verify(delegate, never()).isWrapperFor(TracingDataSource.class);
verify(delegate).isWrapperFor(OtherWrapper.class);
verify(delegate).isWrapperFor(ExtraInterface.class);
verify(delegate).isWrapperFor(Long.class);
}
@Test
void testUnwrap() throws SQLException {
Assertions.assertSame(dataSource, dataSource.unwrap(DataSource.class));
Assertions.assertSame(dataSource, dataSource.unwrap(TracingDataSource.class));
Assertions.assertSame(delegate, dataSource.unwrap(OtherWrapper.class));
Assertions.assertSame(delegate, dataSource.unwrap(ExtraInterface.class));
boolean exceptionThrown = false;
try {
dataSource.unwrap(Long.class);
} catch (final SQLException e) {
exceptionThrown = true;
}
Assertions.assertTrue(exceptionThrown);
verify(delegate, never()).unwrap(DataSource.class);
verify(delegate, never()).unwrap(TracingDataSource.class);
verify(delegate).unwrap(OtherWrapper.class);
verify(delegate).unwrap(ExtraInterface.class);
verify(delegate).unwrap(Long.class);
}
;
@Test
void testGetConnection() throws Exception {
Assertions.assertTrue(dataSource.getConnection() instanceof TracingConnection);
verify(delegate).getConnection();
Assertions.assertTrue(dataSource.getConnection("foo", "bar") instanceof TracingConnection);
verify(delegate).getConnection("foo", "bar");
}
}
| 3,729 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray/sql/TracingStatementTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.strategy.ContextMissingStrategy;
import com.amazonaws.xray.strategy.IgnoreErrorContextMissingStrategy;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class TracingStatementTest {
private static final String URL = "http://www.foo.com";
private static final String HOST = "www.foo.com";
private static final String USER = "user";
private static final String DRIVER_VERSION = "driver_version";
private static final String DB_TYPE = "db_version";
private static final String DB_VERSION = "db_version";
private static final String SQL = "sql";
private static final String CATALOG = "catalog";
private Statement statement;
private PreparedStatement preparedStatement;
private CallableStatement callableStatement;
private Map<String, Object> expectedSqlParams;
@Mock
private Statement delegate;
@Mock
private PreparedStatement preparedDelegate;
@Mock
private CallableStatement callableDelegate;
@Mock
private Connection connection;
@Mock
private DatabaseMetaData metaData;
@Before
public void setup() throws Exception {
statement = TracingStatement.decorateStatement(delegate);
preparedStatement = TracingStatement.decoratePreparedStatement(preparedDelegate, SQL);
callableStatement = TracingStatement.decorateCallableStatement(callableDelegate, SQL);
when(delegate.getConnection()).thenReturn(connection);
when(preparedDelegate.getConnection()).thenReturn(connection);
when(callableDelegate.getConnection()).thenReturn(connection);
when(connection.getMetaData()).thenReturn(metaData);
when(connection.getCatalog()).thenReturn(CATALOG);
when(metaData.getURL()).thenReturn(URL);
when(metaData.getUserName()).thenReturn(USER);
when(metaData.getDriverVersion()).thenReturn(DRIVER_VERSION);
when(metaData.getDatabaseProductName()).thenReturn(DB_TYPE);
when(metaData.getDatabaseProductVersion()).thenReturn(DB_VERSION);
expectedSqlParams = new HashMap<>();
expectedSqlParams.put("url", URL);
expectedSqlParams.put("user", USER);
expectedSqlParams.put("driver_version", DRIVER_VERSION);
expectedSqlParams.put("database_type", DB_TYPE);
expectedSqlParams.put("database_version", DB_VERSION);
AWSXRay.beginSegment("foo");
}
@After
public void cleanUp() {
AWSXRay.clearTraceEntity();
}
@Test
public void testExecute() throws Exception {
when(delegate.execute(SQL)).thenReturn(true);
assertEquals(true, statement.execute(SQL));
assertSubsegment();
}
@Test
public void testExecuteWithAutoGeneratedKeys() throws Exception {
when(delegate.execute(SQL, 2)).thenReturn(true);
assertEquals(true, statement.execute(SQL, 2));
assertSubsegment();
}
@Test
public void testExecuteBatch() throws Exception {
int[] result = {2, 3};
when(delegate.executeBatch()).thenReturn(result);
assertEquals(result, statement.executeBatch());
assertSubsegment();
}
@Test
public void testExecuteQuery() throws Exception {
ResultSet resultSet = Mockito.mock(ResultSet.class);
when(delegate.executeQuery(SQL)).thenReturn(resultSet);
assertEquals(resultSet, statement.executeQuery(SQL));
assertSubsegment();
}
@Test
public void testExecuteUpdate() throws Exception {
when(delegate.executeUpdate(SQL)).thenReturn(2);
assertEquals(2, statement.executeUpdate(SQL));
assertSubsegment();
}
@Test
public void testExecuteUpdateWithAutoGeneratedKeys() throws Exception {
when(delegate.executeUpdate(SQL, 3)).thenReturn(2);
assertEquals(2, statement.executeUpdate(SQL, 3));
assertSubsegment();
}
@Test
public void testPreparedStatementExecuteQuery() throws Exception {
ResultSet resultSet = Mockito.mock(ResultSet.class);
when(preparedDelegate.executeQuery()).thenReturn(resultSet);
assertEquals(resultSet, preparedStatement.executeQuery());
assertSubsegment();
}
@Test
public void testPreparedStatementExecuteUpdate() throws Exception {
when(preparedDelegate.executeUpdate()).thenReturn(2);
assertEquals(2, preparedStatement.executeUpdate());
assertSubsegment();
}
@Test
public void testCalledStatementExecute() throws Exception {
when(callableDelegate.execute()).thenReturn(true);
assertEquals(true, callableStatement.execute());
assertSubsegment();
}
@Test
public void testCalledStatementExecuteQuery() throws Exception {
ResultSet resultSet = Mockito.mock(ResultSet.class);
when(callableDelegate.executeQuery()).thenReturn(resultSet);
assertEquals(resultSet, callableStatement.executeQuery());
assertSubsegment();
}
@Test
public void testCalledStatementExecuteUpdate() throws Exception {
when(callableDelegate.executeUpdate()).thenReturn(2);
assertEquals(2, callableStatement.executeUpdate());
assertSubsegment();
}
@Test
public void testCaptureRuntimeException() throws Exception {
RuntimeException exception = new RuntimeException("foo");
when(delegate.execute(SQL)).thenThrow(exception);
try {
statement.execute(SQL);
fail("Expected exception is not thrown");
} catch (RuntimeException th) {
assertEquals(exception, th);
} finally {
assertEquals(exception, AWSXRay.getCurrentSegment().getSubsegments().get(0).getCause().getExceptions().get(0)
.getThrowable());
assertSubsegment();
}
}
@Test
public void testCaptureSqlException() throws Exception {
SQLException exception = new SQLException("foo");
when(delegate.execute(SQL)).thenThrow(exception);
try {
statement.execute(SQL);
fail("Expected exception is not thrown");
} catch (SQLException th) {
assertEquals(exception, th);
} finally {
assertEquals(exception, AWSXRay.getCurrentSegment().getSubsegments().get(0).getCause().getExceptions().get(0)
.getThrowable());
assertSubsegment();
}
}
@Test
public void testCaptureRuntimeExceptionWithoutSegment() throws Exception {
ContextMissingStrategy oldStrategy = AWSXRay.getGlobalRecorder().getContextMissingStrategy();
AWSXRay.getGlobalRecorder().setContextMissingStrategy(new IgnoreErrorContextMissingStrategy());
try {
RuntimeException exception = new RuntimeException("foo");
when(delegate.execute(SQL)).thenThrow(exception);
try {
statement.execute(SQL);
fail("Expected exception is not thrown");
} catch (RuntimeException th) {
assertEquals(exception, th);
}
} finally {
AWSXRay.getGlobalRecorder().setContextMissingStrategy(oldStrategy);
}
}
@Test
public void testCaptureSqlExceptionWithoutSegment() throws Exception {
ContextMissingStrategy oldStrategy = AWSXRay.getGlobalRecorder().getContextMissingStrategy();
AWSXRay.getGlobalRecorder().setContextMissingStrategy(new IgnoreErrorContextMissingStrategy());
try {
SQLException exception = new SQLException("foo");
when(delegate.execute(SQL)).thenThrow(exception);
try {
statement.execute(SQL);
fail("Expected exception is not thrown");
} catch (SQLException th) {
assertEquals(exception, th);
}
} finally {
AWSXRay.getGlobalRecorder().setContextMissingStrategy(oldStrategy);
}
}
@Test
public void testNonTracedMethod() throws Exception {
statement.close();
verify(delegate).close();
assertEquals(0, AWSXRay.getCurrentSegment().getSubsegments().size());
}
private void assertSubsegment() {
Subsegment subsegment = AWSXRay.getCurrentSegment().getSubsegments().get(0);
assertEquals(CATALOG + "@" + HOST, subsegment.getName());
assertEquals(Namespace.REMOTE.toString(), subsegment.getNamespace());
assertEquals(expectedSqlParams, subsegment.getSql());
}
}
| 3,730 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray/sql/TracingConnectionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class TracingConnectionTest {
private Connection connection;
public interface OtherWrapper extends Connection, ExtraInterface {
}
public interface ExtraInterface {
}
@Mock
private OtherWrapper delegate;
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() throws SQLException {
connection = TracingConnection.decorate(delegate);
doReturn(false).when(delegate).isWrapperFor(any());
doReturn(true).when(delegate).isWrapperFor(OtherWrapper.class);
doReturn(true).when(delegate).isWrapperFor(ExtraInterface.class);
doThrow(SQLException.class).when(delegate).unwrap(any());
doReturn(delegate).when(delegate).unwrap(OtherWrapper.class);
doReturn(delegate).when(delegate).unwrap(ExtraInterface.class);
}
@Test
void testDecoration() throws SQLException {
Assertions.assertTrue(connection instanceof TracingConnection);
Assertions.assertTrue(connection.isWrapperFor(Connection.class));
Assertions.assertTrue(connection.isWrapperFor(TracingConnection.class));
Assertions.assertTrue(connection.isWrapperFor(OtherWrapper.class));
Assertions.assertTrue(connection.isWrapperFor(ExtraInterface.class));
Assertions.assertFalse(connection.isWrapperFor(Long.class));
verify(delegate, never()).isWrapperFor(Connection.class);
verify(delegate, never()).isWrapperFor(TracingConnection.class);
verify(delegate).isWrapperFor(OtherWrapper.class);
verify(delegate).isWrapperFor(ExtraInterface.class);
verify(delegate).isWrapperFor(Long.class);
}
@Test
void testUnwrap() throws SQLException {
Assertions.assertSame(connection, connection.unwrap(Connection.class));
Assertions.assertSame(connection, connection.unwrap(TracingConnection.class));
Assertions.assertSame(delegate, connection.unwrap(OtherWrapper.class));
Assertions.assertSame(delegate, connection.unwrap(ExtraInterface.class));
boolean exceptionThrown = false;
try {
connection.unwrap(Long.class);
} catch (final SQLException e) {
exceptionThrown = true;
}
Assertions.assertTrue(exceptionThrown);
verify(delegate, never()).unwrap(Connection.class);
verify(delegate, never()).unwrap(TracingConnection.class);
verify(delegate).unwrap(OtherWrapper.class);
verify(delegate).unwrap(ExtraInterface.class);
verify(delegate).unwrap(Long.class);
}
@Test
void testCreateStatement() throws Exception {
Assertions.assertTrue(connection.createStatement() != null);
verify(delegate).createStatement();
Assertions.assertTrue(connection.createStatement(2, 3) != null);
verify(delegate).createStatement(2, 3);
Assertions.assertTrue(connection.createStatement(2, 3, 4) != null);
verify(delegate).createStatement(2, 3, 4);
}
@Test
void testPrepareStatement() throws Exception {
Assertions.assertTrue(connection.prepareStatement("foo") != null);
verify(delegate).prepareStatement("foo");
Assertions.assertTrue(connection.prepareStatement("foo", 2) != null);
verify(delegate).prepareStatement("foo", 2);
Assertions.assertTrue(connection.prepareStatement("foo", new int[] {2, 3}) != null);
verify(delegate).prepareStatement("foo", new int[]{2, 3});
Assertions.assertTrue(connection.prepareStatement("foo", new String[] {"bar", "baz"}) != null);
verify(delegate).prepareStatement("foo", new String[]{"bar", "baz"});
Assertions.assertTrue(connection.prepareStatement("foo", 2, 3) != null);
verify(delegate).prepareStatement("foo", 2, 3);
Assertions.assertTrue(connection.prepareStatement("foo", 2, 3, 4) != null);
verify(delegate).prepareStatement("foo", 2, 3, 4);
}
@Test
void testPrepareCall() throws Exception {
Assertions.assertTrue(connection.prepareCall("foo") != null);
verify(delegate).prepareCall("foo");
Assertions.assertTrue(connection.prepareCall("foo", 2, 3) != null);
verify(delegate).prepareCall("foo", 2, 3);
Assertions.assertTrue(connection.prepareCall("foo", 2, 3, 4) != null);
verify(delegate).prepareCall("foo", 2, 3, 4);
}
}
| 3,731 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray/sql/OracleConnectionUrlParserTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.xray.sql;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* Test class for parsing a bunch of acceptable Oracle URLs. The test cases are taken from the
* OpenTelemetry JdbcConnectionUrlParser test class.
*
* Original source: https://bit.ly/3mhFCud
*/
class OracleConnectionUrlParserTest {
// https://docs.oracle.com/cd/B28359_01/java.111/b31224/urls.htm
// https://docs.oracle.com/cd/B28359_01/java.111/b31224/jdbcthin.htm
// https://docs.oracle.com/cd/B28359_01/java.111/b31224/instclnt.htm
private static final String[] ORACLE_URLS = {
"jdbc:oracle:thin:orcluser/PW@localhost:55:orclsn",
"jdbc:oracle:thin:orcluser/PW@//orcl.host:55/orclsn",
"jdbc:oracle:thin:orcluser/PW@127.0.0.1:orclsn",
"jdbc:oracle:thin:orcluser/PW@//orcl.host/orclsn",
"jdbc:oracle:thin:@//orcl.host:55/orclsn",
"jdbc:oracle:thin:@ldap://orcl.host:55/some,cn=OracleContext,dc=com",
"jdbc:oracle:thin:127.0.0.1:orclsn",
"jdbc:oracle:thin:orcl.host:orclsn",
"jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= 127.0.0.1 )(POR T= 666))" +
"(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orclsn)))",
"jdbc:oracle:drivertype:orcluser/PW@orcl.host:55/orclsn",
"jdbc:oracle:oci8:@",
"jdbc:oracle:oci8:@orclsn",
"jdbc:oracle:oci:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)( HOST = orcl.host )" +
"( PORT = 55 ))(CONNECT_DATA=(SERVICE_NAME =orclsn )))"
};
private static final ConnectionInfo[] EXPECTED_INFO = {
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:thin:orcluser@localhost:55:orclsn").user("orcluser")
.host("localhost").dbName("orclsn").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:thin:orcluser@//orcl.host:55/orclsn").user("orcluser")
.host("orcl.host").dbName("orclsn").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:thin:orcluser@127.0.0.1:orclsn").user("orcluser")
.host("127.0.0.1").dbName("orclsn").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:thin:orcluser@//orcl.host/orclsn").user("orcluser")
.host("orcl.host").dbName("orclsn").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:thin:@//orcl.host:55/orclsn")
.host("orcl.host").dbName("orclsn").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:thin:@ldap://orcl.host:55/some,cn=oraclecontext,dc=com")
.host("orcl.host").dbName("some,cn=oraclecontext,dc=com").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:thin:127.0.0.1:orclsn")
.host("127.0.0.1").dbName("orclsn").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:thin:orcl.host:orclsn")
.host("orcl.host").dbName("orclsn").build(),
new ConnectionInfo.Builder()
.sanitizedUrl("jdbc:oracle:thin:@(description=(address=(protocol=tcp)(host= 127.0.0.1 )(por t= 666))" +
"(connect_data=(server=dedicated)(service_name=orclsn)))").host("127.0.0.1").dbName("orclsn").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:drivertype:orcluser@orcl.host:55/orclsn").user("orcluser")
.host("orcl.host").dbName("orclsn").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:oci8:@").build(),
new ConnectionInfo.Builder().sanitizedUrl("jdbc:oracle:oci8:@orclsn").dbName("orclsn").build(),
new ConnectionInfo.Builder()
.sanitizedUrl("jdbc:oracle:oci:@(description=(address=(protocol=tcp)( host = orcl.host )( port = 55 ))" +
"(connect_data=(service_name =orclsn )))").host("orcl.host").dbName("orclsn").build()
};
@Test
void testUrlParsing() {
assertThat(ORACLE_URLS.length).isEqualTo(EXPECTED_INFO.length);
for (int i = 0; i < ORACLE_URLS.length; i++) {
ConnectionInfo.Builder builder = new ConnectionInfo.Builder();
ConnectionInfo parsed = OracleConnectionUrlParser.parseUrl(ORACLE_URLS[i], builder);
assertThat(parsed).isEqualTo(EXPECTED_INFO[i]);
}
}
}
| 3,732 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/test/java/com/amazonaws/xray/sql/SqlSubsegmentsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import com.blogspot.mydailyjava.weaklockfree.WeakConcurrentMap;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
class SqlSubsegmentsTest {
private static final String URL = "http://www.foo.com";
private static final String HOST = "www.foo.com";
private static final String USER = "user";
private static final String DRIVER_VERSION = "driver_version";
private static final String DB_TYPE = "db_version";
private static final String DB_VERSION = "db_version";
private static final String SQL = "sql";
private static final String CATALOG = "catalog";
private Map<String, Object> expectedSqlParams;
@Mock
Connection connection;
@Mock
DatabaseMetaData metaData;
@Spy
WeakConcurrentMap<Connection, ConnectionInfo> mapSpy = new WeakConcurrentMap.WithInlinedExpunction<>();
@BeforeEach
void setup() throws SQLException {
MockitoAnnotations.initMocks(this);
when(connection.getMetaData()).thenReturn(metaData);
when(connection.getCatalog()).thenReturn(CATALOG);
when(metaData.getURL()).thenReturn(URL);
when(metaData.getUserName()).thenReturn(USER);
when(metaData.getDriverVersion()).thenReturn(DRIVER_VERSION);
when(metaData.getDatabaseProductName()).thenReturn(DB_TYPE);
when(metaData.getDatabaseProductVersion()).thenReturn(DB_VERSION);
AWSXRay.beginSegment("test");
SqlSubsegments.setConnMap(new WeakConcurrentMap.WithInlinedExpunction<>());
}
@AfterEach
void cleanup() {
AWSXRay.clearTraceEntity();
}
@Test
void testCreateSubsegmentWithoutSql() {
expectedSqlParams = new HashMap<>();
expectedSqlParams.put("url", URL);
expectedSqlParams.put("user", USER);
expectedSqlParams.put("driver_version", DRIVER_VERSION);
expectedSqlParams.put("database_type", DB_TYPE);
expectedSqlParams.put("database_version", DB_VERSION);
Subsegment sub = SqlSubsegments.forQuery(connection, null);
assertThat(sub.getName()).isEqualTo(CATALOG + "@" + HOST);
assertThat(sub.getNamespace()).isEqualTo(Namespace.REMOTE.toString());
assertThat(sub.getSql()).containsAllEntriesOf(expectedSqlParams);
}
@Test
void testCreateSubsegmentWithSql() {
expectedSqlParams = new HashMap<>();
expectedSqlParams.put("url", URL);
expectedSqlParams.put("user", USER);
expectedSqlParams.put("driver_version", DRIVER_VERSION);
expectedSqlParams.put("database_type", DB_TYPE);
expectedSqlParams.put("database_version", DB_VERSION);
expectedSqlParams.put("sanitized_query", SQL);
Subsegment sub = SqlSubsegments.forQuery(connection, SQL);
assertThat(sub.getName()).isEqualTo(CATALOG + "@" + HOST);
assertThat(sub.getNamespace()).isEqualTo(Namespace.REMOTE.toString());
assertThat(sub.getSql()).containsAllEntriesOf(expectedSqlParams);
}
@Test
void testCreateSubsegmentWhenConnectionThrowsException() throws SQLException {
when(connection.getMetaData()).thenThrow(new SQLException());
Subsegment sub = SqlSubsegments.forQuery(connection, SQL);
assertThat(AWSXRay.getCurrentSubsegment()).isEqualTo(sub);
assertThat(sub.getName()).isEqualTo(SqlSubsegments.DEFAULT_DATABASE_NAME);
assertThat(sub.isInProgress()).isTrue();
assertThat(sub.getParentSegment().getSubsegments()).contains(sub);
}
@Test
void testDbNameIsNotNull() throws SQLException {
when(connection.getCatalog()).thenReturn(null);
Subsegment sub = SqlSubsegments.forQuery(connection, SQL);
assertThat(sub.getName()).isEqualTo(SqlSubsegments.DEFAULT_DATABASE_NAME + "@" + HOST);
}
@Test
void testHostIsNotNull() throws SQLException {
when(metaData.getURL()).thenReturn("some invalid URL");
Subsegment sub = SqlSubsegments.forQuery(connection, SQL);
assertThat(sub.getName()).isEqualTo(CATALOG);
}
@Test
void testPrefersSubsegmentNameFromUrl() {
WeakConcurrentMap<Connection, ConnectionInfo> map = new WeakConcurrentMap.WithInlinedExpunction<>();
map.put(connection, new ConnectionInfo.Builder().dbName("newDb").host("another").build());
SqlSubsegments.setConnMap(map);
}
@Test
void testPrefersMetaDataFromUrl() {
WeakConcurrentMap<Connection, ConnectionInfo> map = new WeakConcurrentMap.WithInlinedExpunction<>();
map.put(connection, new ConnectionInfo.Builder()
.sanitizedUrl("jdbc:oracle:rds.us-west-2.com").user("another").dbName("newDb").host("rds.us-west-2.com").build());
SqlSubsegments.setConnMap(map);
Subsegment sub = SqlSubsegments.forQuery(connection, SQL);
assertThat(sub.getName()).isEqualTo("newDb@rds.us-west-2.com");
assertThat(sub.getSql()).containsEntry("url", "jdbc:oracle:rds.us-west-2.com");
assertThat(sub.getSql()).containsEntry("user", "another");
}
@Test
void testCacheInsertionOnNewConnection() throws SQLException {
when(metaData.getURL()).thenReturn("jdbc:oracle:thin@rds.us-west-2.com");
SqlSubsegments.setConnMap(mapSpy);
SqlSubsegments.forQuery(connection, "query 1");
SqlSubsegments.forQuery(connection, "query 2");
assertThat(mapSpy).hasSize(1);
assertThat(mapSpy.containsKey(connection)).isTrue();
verify(mapSpy, times(1)).put(eq(connection), any());
verify(mapSpy, times(2)).get(connection);
}
}
| 3,733 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray/sql/TracingStatement.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Subsegment;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @deprecated For internal use only.
*/
@SuppressWarnings("checkstyle:HideUtilityClassConstructor")
@Deprecated
public class TracingStatement {
private static final Log logger = LogFactory.getLog(TracingStatement.class);
private static final boolean COLLECT_SQL_ENV =
Boolean.parseBoolean(System.getenv("AWS_XRAY_COLLECT_SQL_QUERIES"));
private static final boolean COLLECT_SQL_PROP =
Boolean.parseBoolean(System.getProperty("com.amazonaws.xray.collectSqlQueries"));
/**
* Call {@code statement = TracingStatement.decorateStatement(statement)} to decorate your {@link Statement}
* in order to have the queries recorded with an X-Ray Subsegment. Do not use the method on {@link PreparedStatement}
* and {@link CallableStatement}. Use another two specific decorating method instead.
*
* @param statement the statement to decorate
* @return a {@link Statement} that traces all SQL queries in X-Ray
*/
public static Statement decorateStatement(Statement statement) {
return (Statement) Proxy.newProxyInstance(TracingStatement.class.getClassLoader(),
new Class[] { Statement.class },
new TracingStatementHandler(statement, null));
}
/**
* Call {@code preparedStatement = TracingStatement.decoratePreparedStatement(preparedStatement, sql)}
* to decorate your {@link PreparedStatement} in order to have the queries recorded with an X-Ray Subsegment.
*
* @param statement the {@link PreparedStatement} to decorate
* @param sql the sql query to execute
* @return a {@link PreparedStatement} that traces all SQL queries in X-Ray
*/
public static PreparedStatement decoratePreparedStatement(PreparedStatement statement, String sql) {
return (PreparedStatement) Proxy.newProxyInstance(TracingStatement.class.getClassLoader(),
new Class[] { PreparedStatement.class },
new TracingStatementHandler(statement, sql));
}
/**
* Call {@code callableStatement = TracingStatement.decorateCallableStatement(callableStatement, sql)}
* to decorate your {@link CallableStatement}in order to have the queries recorded with an X-Ray Subsegment.
*
* @param statement the {@link CallableStatement} to decorate
* @param sql the sql query to execute
* @return a {@link CallableStatement} that traces all SQL queries in X-Ray
*/
public static CallableStatement decorateCallableStatement(CallableStatement statement, String sql) {
return (CallableStatement) Proxy.newProxyInstance(TracingStatement.class.getClassLoader(),
new Class[] { CallableStatement.class },
new TracingStatementHandler(statement, sql));
}
private static class TracingStatementHandler implements InvocationHandler {
private static final String EXECUTE = "execute";
private static final String EXECUTE_QUERY = "executeQuery";
private static final String EXECUTE_UPDATE = "executeUpdate";
private static final String EXECUTE_BATCH = "executeBatch";
private final Statement delegate;
private final String sql;
TracingStatementHandler(Statement statement, String sql) {
this.delegate = statement;
this.sql = sql;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Subsegment subsegment = null;
if (isExecution(method)) {
// only trace on execution methods
subsegment = createSubsegment();
}
logger.debug(
String.format("Invoking statement execution with X-Ray tracing. Tracing active: %s", subsegment != null));
try {
// execute the query "wrapped" in a XRay Subsegment
return method.invoke(delegate, args);
} catch (Throwable t) {
Throwable rootThrowable = t;
if (t instanceof InvocationTargetException) {
// the reflection may wrap the actual error with an InvocationTargetException.
// we want to use the root cause to make the instrumentation seamless
InvocationTargetException ite = (InvocationTargetException) t;
if (ite.getTargetException() != null) {
rootThrowable = ite.getTargetException();
} else if (ite.getCause() != null) {
rootThrowable = ite.getCause();
}
}
if (subsegment != null) {
subsegment.addException(rootThrowable);
}
throw rootThrowable;
} finally {
if (subsegment != null && isExecution(method)) {
AWSXRay.endSubsegment();
}
}
}
private boolean isExecution(Method method) {
return EXECUTE.equals(method.getName())
|| EXECUTE_QUERY.equals(method.getName())
|| EXECUTE_UPDATE.equals(method.getName())
|| EXECUTE_BATCH.equals(method.getName());
}
private Subsegment createSubsegment() {
try {
return SqlSubsegments.forQuery(delegate.getConnection(), collectSqlQueries() ? sql : null);
} catch (SQLException exception) {
logger.warn("Failed to create X-Ray subsegment for the statement execution.", exception);
return null;
}
}
private boolean collectSqlQueries() {
return COLLECT_SQL_ENV || COLLECT_SQL_PROP;
}
}
}
| 3,734 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray/sql/ConnectionInfo.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql;
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.Nullable;
final class ConnectionInfo {
@Nullable
private final String sanitizedUrl;
@Nullable
private final String user;
@Nullable
private final String host;
@Nullable
private final String dbName;
private ConnectionInfo(@Nullable String sanitizedUrl,
@Nullable String user,
@Nullable String host,
@Nullable String dbName) {
this.sanitizedUrl = sanitizedUrl;
this.user = user;
this.host = host;
this.dbName = dbName;
}
String getSanitizedUrl() {
return sanitizedUrl;
}
String getUser() {
return user;
}
String getHost() {
return host;
}
String getDbName() {
return dbName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConnectionInfo that = (ConnectionInfo) o;
return Objects.equals(sanitizedUrl, that.sanitizedUrl) &&
Objects.equals(user, that.user) &&
Objects.equals(host, that.host) &&
Objects.equals(dbName, that.dbName);
}
@Override
public int hashCode() {
int result = sanitizedUrl != null ? sanitizedUrl.hashCode() : 0;
result = 31 * result + (user != null ? user.hashCode() : 0);
result = 31 * result + (host != null ? host.hashCode() : 0);
result = 31 * result + (dbName != null ? dbName.hashCode() : 0);
return result;
}
static class Builder {
private String sanitizedUrl;
private String user;
private String host;
private String dbName;
Builder sanitizedUrl(String sanitizedUrl) {
this.sanitizedUrl = sanitizedUrl;
return this;
}
Builder user(String user) {
this.user = user;
return this;
}
Builder host(String host) {
this.host = host;
return this;
}
Builder dbName(String dbName) {
this.dbName = dbName;
return this;
}
ConnectionInfo build() {
return new ConnectionInfo(sanitizedUrl, user, host, dbName);
}
}
}
| 3,735 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray/sql/TracingDataSource.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
import javax.sql.DataSource;
public class TracingDataSource implements DataSource {
protected DataSource delegate;
public TracingDataSource(DataSource dataSource) {
this.delegate = dataSource;
}
/**
* Call {@code dataSource = TracingDataSource.decorate(dataSource)} to decorate your {@link DataSource} before any calls
* to #getConnection in order to have all your SQL queries recorded with an X-Ray Subsegment.
*
* @param dataSource the datasource to decorate
* @return a DataSource that traces all SQL queries in X-Ray
*/
public static DataSource decorate(DataSource dataSource) {
return new TracingDataSource(dataSource);
}
/**
* Traced methods
*/
@Override
public Connection getConnection() throws SQLException {
return new TracingConnection(delegate.getConnection());
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return new TracingConnection(delegate.getConnection(username, password));
}
@Override
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isInstance(this)) {
return (T) this;
}
return delegate.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return (iface.isInstance(this) || delegate.isWrapperFor(iface));
}
/**
* Plain methods
*/
@Override
public PrintWriter getLogWriter() throws SQLException {
return delegate.getLogWriter();
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
delegate.setLogWriter(out);
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
delegate.setLoginTimeout(seconds);
}
@Override
public int getLoginTimeout() throws SQLException {
return delegate.getLoginTimeout();
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return delegate.getParentLogger();
}
}
| 3,736 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray/sql/SqlSubsegments.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import com.blogspot.mydailyjava.weaklockfree.WeakConcurrentMap;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Class containing utility method to create fully-populated SQL subsegments.
* See https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-sql
*/
public final class SqlSubsegments {
private static final Log logger = LogFactory.getLog(SqlSubsegments.class);
private static WeakConcurrentMap<Connection, ConnectionInfo> connMap = new WeakConcurrentMap.WithInlinedExpunction<>();
/**
* The URL of the database this query is made on
*/
public static final String URL = "url";
/**
* The database username
*/
public static final String USER = "user";
/**
* The version of the database driver library used for this database
*/
public static final String DRIVER_VERSION = "driver_version";
/**
* The type of SQL Database this query is done on, like MySQL or HikariCP
*/
public static final String DATABASE_TYPE = "database_type";
/**
* The version of the database product itself, like MySQL 8.0
*/
public static final String DATABASE_VERSION = "database_version";
/**
* The SQL query string used in this query. This is not recorded in subsegments by default due to security issues.
* SDK users may use this key or {@link #forQuery} to manually record their queries if they wish.
* See https://github.com/aws/aws-xray-sdk-java/issues/28
*/
public static final String SANITIZED_QUERY = "sanitized_query";
/**
* The fallback name for subsegments representing SQL queries that failed to be named dynamically
*/
public static final String DEFAULT_DATABASE_NAME = "database";
/**
* Begins a {@link Subsegment} populated with data provided by the {@link Connection#getMetaData} method. Includes
* the SQL query string if it is non-null, omits it otherwise. Takes care to swallow any potential
* {@link SQLException}s and always start a subsegment for consistency.
*
* @param connection the JDBC connection object used for the query this {@link Subsegment} represents.
* @param query the SQL query string used in this query, or {@code null} if it is not desirable to include in the
* subsegment, e.g. for security concerns.
* @return the created {@link Subsegment}.
*/
public static Subsegment forQuery(Connection connection, @Nullable String query) {
DatabaseMetaData metadata;
ConnectionInfo connectionInfo = connMap.get(connection);
String subsegmentName = DEFAULT_DATABASE_NAME;
try {
metadata = connection.getMetaData();
String connUrl = metadata.getURL();
// Parse URL if Oracle
if (connectionInfo == null && connUrl != null && connUrl.contains("jdbc:oracle")) {
connectionInfo = OracleConnectionUrlParser.parseUrl(connUrl, new ConnectionInfo.Builder());
connMap.put(connection, connectionInfo);
} else if (connectionInfo == null) {
connectionInfo = new ConnectionInfo.Builder().build();
}
// Get database name if available; otherwise fallback to default
String database;
if (connectionInfo.getDbName() != null) {
database = connectionInfo.getDbName();
} else if (connection.getCatalog() != null) {
database = connection.getCatalog();
} else {
database = DEFAULT_DATABASE_NAME;
}
// Get database host if available; otherwise omit host
String host = null;
if (connectionInfo.getHost() != null) {
host = connectionInfo.getHost();
} else if (connUrl != null) {
try {
host = new URI(new URI(connUrl).getSchemeSpecificPart()).getHost();
} catch (URISyntaxException e) {
logger.debug("Unable to parse database URI. Falling back to default '" + DEFAULT_DATABASE_NAME
+ "' for subsegment name.", e);
}
}
// Fully formed subsegment name is of form "dbName@host"
subsegmentName = database + (host != null ? "@" + host : "");
} catch (SQLException e) {
logger.debug("Encountered exception while retrieving metadata for SQL subsegment "
+ ", starting blank subsegment instead");
return AWSXRay.beginSubsegment(subsegmentName);
}
Subsegment subsegment = AWSXRay.beginSubsegment(subsegmentName);
subsegment.setNamespace(Namespace.REMOTE.toString());
try {
putSqlIfNotNull(subsegment, URL, connectionInfo.getSanitizedUrl() != null ?
connectionInfo.getSanitizedUrl() : metadata.getURL());
putSqlIfNotNull(subsegment, USER, connectionInfo.getUser() != null ?
connectionInfo.getUser() : metadata.getUserName());
putSqlIfNotNull(subsegment, DRIVER_VERSION, metadata.getDriverVersion());
putSqlIfNotNull(subsegment, DATABASE_TYPE, metadata.getDatabaseProductName());
putSqlIfNotNull(subsegment, DATABASE_VERSION, metadata.getDatabaseProductVersion());
} catch (SQLException e) {
logger.debug("Encountered exception while populating SQL subsegment metadata", e);
}
putSqlIfNotNull(subsegment, SANITIZED_QUERY, query);
return subsegment;
}
// Prevents NPEs if DatabaseMetaData returns null values
private static void putSqlIfNotNull(Subsegment subsegment, String key, String value) {
if (key != null && value != null) {
subsegment.putSql(key, value);
}
}
// Visible for testing
static void setConnMap(WeakConcurrentMap<Connection, ConnectionInfo> connMap) {
SqlSubsegments.connMap = connMap;
}
private SqlSubsegments() {
}
}
| 3,737 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray/sql/OracleConnectionUrlParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.xray.sql;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Class for parsing Oracle database connection URLs and extracting useful metadata.
* Adapted from the OpenTelemetry JdbcConnectionUrlParser class under the Apache 2.0 license.
*
* Original source: https://bit.ly/2OZB5jR
* Oracle URL documentation: https://docs.oracle.com/cd/B28359_01/java.111/b31224/urls.htm
*/
final class OracleConnectionUrlParser {
private static final Log log = LogFactory.getLog(OracleConnectionUrlParser.class);
private static final Pattern HOST_PATTERN = Pattern.compile("\\(\\s*host\\s*=\\s*([^ )]+)\\s*\\)");
private static final Pattern INSTANCE_PATTERN = Pattern.compile("\\(\\s*service_name\\s*=\\s*([^ )]+)\\s*\\)");
static ConnectionInfo parseUrl(String jdbcUrl, ConnectionInfo.Builder builder) {
jdbcUrl = jdbcUrl.toLowerCase();
recordSanitizedUrl(jdbcUrl, builder);
int subtypeEndIndex = jdbcUrl.indexOf(":", "jdbc:oracle:".length());
if (subtypeEndIndex < 0) {
return builder.build();
}
// Strip the constant prefix for simplicity
jdbcUrl = jdbcUrl.substring(subtypeEndIndex + 1);
if (jdbcUrl.contains("@")) {
return parseUrlWithAt(jdbcUrl, builder).build();
} else {
return parseOracleConnectInfo(jdbcUrl, builder).build();
}
}
private static ConnectionInfo.Builder recordSanitizedUrl(String jdbcUrl, ConnectionInfo.Builder builder) {
int atLoc = jdbcUrl.indexOf("@");
int userEndLoc = jdbcUrl.indexOf("/");
if (userEndLoc != -1 && userEndLoc < atLoc) {
builder.sanitizedUrl(jdbcUrl.substring(0, userEndLoc) + jdbcUrl.substring(atLoc));
} else {
builder.sanitizedUrl(jdbcUrl);
}
return builder;
}
private static ConnectionInfo.Builder parseOracleConnectInfo(String jdbcUrl, ConnectionInfo.Builder builder) {
String host;
String instance;
int hostEnd = jdbcUrl.indexOf(":");
int instanceLoc = jdbcUrl.indexOf("/");
if (hostEnd > 0) {
host = jdbcUrl.substring(0, hostEnd);
int afterHostEnd = jdbcUrl.indexOf(":", hostEnd + 1);
if (afterHostEnd > 0) {
instance = jdbcUrl.substring(afterHostEnd + 1);
} else {
if (instanceLoc > 0) {
instance = jdbcUrl.substring(instanceLoc + 1);
} else {
String portOrInstance = jdbcUrl.substring(hostEnd + 1);
Integer parsedPort = null;
try {
parsedPort = Integer.parseInt(portOrInstance);
} catch (NumberFormatException e) {
log.debug(e.getMessage(), e);
}
if (parsedPort == null) {
instance = portOrInstance;
} else {
instance = null;
}
}
}
} else {
if (instanceLoc > 0) {
host = jdbcUrl.substring(0, instanceLoc);
instance = jdbcUrl.substring(instanceLoc + 1);
} else {
if (jdbcUrl.isEmpty()) {
return builder;
} else {
host = null;
instance = jdbcUrl;
}
}
}
if (host != null) {
builder.host(host);
}
return builder.dbName(instance);
}
private static ConnectionInfo.Builder parseUrlWithAt(String jdbcUrl, ConnectionInfo.Builder builder) {
if (jdbcUrl.contains("@(description")) {
return parseDescription(jdbcUrl, builder);
}
String user;
String[] atSplit = jdbcUrl.split("@", 2);
int userInfoLoc = atSplit[0].indexOf("/");
if (userInfoLoc > 0) {
user = atSplit[0].substring(0, userInfoLoc);
} else {
user = null;
}
String connectInfo = atSplit[1];
int hostStart;
if (connectInfo.startsWith("//")) {
hostStart = "//".length();
} else if (connectInfo.startsWith("ldap://")) {
hostStart = "ldap://".length();
} else {
hostStart = 0;
}
if (user != null) {
builder.user(user);
}
return parseOracleConnectInfo(connectInfo.substring(hostStart), builder);
}
private static ConnectionInfo.Builder parseDescription(String jdbcUrl, ConnectionInfo.Builder builder) {
String[] atSplit = jdbcUrl.split("@", 2);
int userInfoLoc = atSplit[0].indexOf("/");
if (userInfoLoc > 0) {
builder.user(atSplit[0].substring(0, userInfoLoc));
}
Matcher hostMatcher = HOST_PATTERN.matcher(atSplit[1]);
if (hostMatcher.find()) {
builder.host(hostMatcher.group(1));
}
Matcher instanceMatcher = INSTANCE_PATTERN.matcher(atSplit[1]);
if (instanceMatcher.find()) {
builder.dbName(instanceMatcher.group(1));
}
return builder;
}
private OracleConnectionUrlParser() {
}
}
| 3,738 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql/src/main/java/com/amazonaws/xray/sql/TracingConnection.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
public class TracingConnection implements Connection {
protected Connection delegate;
public TracingConnection(Connection connection) {
this.delegate = connection;
}
/**
* Call {@code connection = TracingConnection.decorate(connection)} to decorate your {@link Connection} before any calls
* to #createStatement, #prepareStatement or #prepareCall in order to have all your SQL queries recorded with an X-Ray
* Subsegment.
*
* @param connection the connection to decorate
* @return a {@link Connection} that traces all SQL queries in X-Ray
*/
public static Connection decorate(Connection connection) {
return new TracingConnection(connection);
}
/**
* Traced methods
*/
@Override
public Statement createStatement() throws SQLException {
return TracingStatement.decorateStatement(delegate.createStatement());
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return TracingStatement.decorateStatement(delegate.createStatement(resultSetType, resultSetConcurrency));
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return TracingStatement.decorateStatement(
delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability));
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return TracingStatement.decoratePreparedStatement(delegate.prepareStatement(sql), sql);
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return TracingStatement.decoratePreparedStatement(delegate.prepareStatement(sql, autoGeneratedKeys), sql);
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return TracingStatement.decoratePreparedStatement(delegate.prepareStatement(sql, columnIndexes), sql);
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return TracingStatement.decoratePreparedStatement(delegate.prepareStatement(sql, columnNames), sql);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return TracingStatement.decoratePreparedStatement(
delegate.prepareStatement(sql, resultSetType, resultSetConcurrency), sql);
}
@Override
public PreparedStatement prepareStatement(
String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return TracingStatement.decoratePreparedStatement(
delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability), sql);
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return TracingStatement.decorateCallableStatement(delegate.prepareCall(sql), sql);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return TracingStatement.decorateCallableStatement(delegate.prepareCall(sql, resultSetType, resultSetConcurrency), sql);
}
@Override
public CallableStatement prepareCall(
String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return TracingStatement.decorateCallableStatement(
delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability), sql);
}
/**
* Plain methods
*/
@Override
public String nativeSQL(String sql) throws SQLException {
return delegate.nativeSQL(sql);
}
@Override
public boolean getAutoCommit() throws SQLException {
return delegate.getAutoCommit();
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
delegate.setAutoCommit(autoCommit);
}
@Override
public void commit() throws SQLException {
delegate.commit();
}
@Override
public void rollback() throws SQLException {
delegate.rollback();
}
@Override
public void close() throws SQLException {
delegate.close();
}
@Override
public boolean isClosed() throws SQLException {
return delegate.isClosed();
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return delegate.getMetaData();
}
@Override
public boolean isReadOnly() throws SQLException {
return delegate.isReadOnly();
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
delegate.setReadOnly(readOnly);
}
@Override
public String getCatalog() throws SQLException {
return delegate.getCatalog();
}
@Override
public void setCatalog(String catalog) throws SQLException {
delegate.setCatalog(catalog);
}
@Override
public int getTransactionIsolation() throws SQLException {
return delegate.getTransactionIsolation();
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
delegate.setTransactionIsolation(level);
}
@Override
public SQLWarning getWarnings() throws SQLException {
return delegate.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
delegate.clearWarnings();
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return delegate.getTypeMap();
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
delegate.setTypeMap(map);
}
@Override
public int getHoldability() throws SQLException {
return delegate.getHoldability();
}
@Override
public void setHoldability(int holdability) throws SQLException {
delegate.setHoldability(holdability);
}
@Override
public Savepoint setSavepoint() throws SQLException {
return delegate.setSavepoint();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return delegate.setSavepoint(name);
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
delegate.rollback(savepoint);
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
delegate.releaseSavepoint(savepoint);
}
@Override
public Clob createClob() throws SQLException {
return delegate.createClob();
}
@Override
public Blob createBlob() throws SQLException {
return delegate.createBlob();
}
@Override
public NClob createNClob() throws SQLException {
return delegate.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException {
return delegate.createSQLXML();
}
@Override
public boolean isValid(int timeout) throws SQLException {
return delegate.isValid(timeout);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
delegate.setClientInfo(name, value);
}
@Override
public String getClientInfo(String name) throws SQLException {
return delegate.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException {
return delegate.getClientInfo();
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
delegate.setClientInfo(properties);
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return delegate.createArrayOf(typeName, elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return delegate.createStruct(typeName, attributes);
}
@Override
public String getSchema() throws SQLException {
return delegate.getSchema();
}
@Override
public void setSchema(String schema) throws SQLException {
delegate.setSchema(schema);
}
@Override
public void abort(Executor executor) throws SQLException {
delegate.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
delegate.setNetworkTimeout(executor, milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException {
return delegate.getNetworkTimeout();
}
@Override
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isInstance(this)) {
return (T) this;
}
return delegate.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return (iface.isInstance(this) || delegate.isWrapperFor(iface));
}
}
| 3,739 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql-postgres/src/test/java/com/amazonaws/xray/sql | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql-postgres/src/test/java/com/amazonaws/xray/sql/postgres/SanitizeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql.postgres;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.JVM)
public class SanitizeTest {
public String[] queries = {
"a",
"test 'asdf'",
"test $$asdf$$",
"test $$zxcv'jdfa'dzxc$$",
"test $a$bbbbb$a$", //5
"test $a$bbb$zzz$b$aaaaaaaaa$b$bbb$a$",
"test $a$wwww$a$ test $b$www$b$",
"test 'aaaaaaaa''aaaaaa'",
"test 'aasdfasd' $$b$$ $a$a$a$",
"test 'zz' $$b$$ $a$a$a$ 'zz'", //10
"test ''",
"test 'zz''''zz' ooo'aaa''aa'",
"test 544 3456 43 '43' 345f",
"test \"32f\" '32' 32",
"test $aaa$wwww$aaa$ test",
"test $aaa$wwww$aaa$ $1 this is a test",
"now 'aabbccdd'''",
"now 'aabbccdd\\'\\''",
"now 'aabbccdd\\'\\''''",
"now 'aabbccdd''\\''''"
};
public String[] sanitized = {
"a",
"test ?",
"test ?",
"test ?",
"test ?", //5
"test ?",
"test ? test ?",
"test ?",
"test ? ? ?",
"test ? ? ? ?", //10
"test ?",
"test ? ooo?",
"test ? ? ? ? 345f",
"test \"32f\" ? ?",
"test ? test",
"test ? $? this is a test",
"now ?",
"now ?",
"now ?",
"now ?"
};
/*@Test
public void testSanitizeQuery() {
for (int i = 0; i < queries.length; i++) {
Assert.assertEquals("Sanitizing: " + queries[i], sanitized[i], TracingInterceptor.sanitizeSql(queries[i]));
}
}*/
/*@Test
public void testVeryLongString() {
String delimiter = "$a$";
StringBuilder mega = new StringBuilder();
for (int i = 0; i < 1000000; i++) { // ten million copies
mega.append("Fkwekfjb2k3hf4@#$'fbb4kbf'$4'fbf''4$'");
}
String veryLong = "test " + delimiter + mega.toString() + delimiter;
Assert.assertEquals("test ?", TracingInterceptor.sanitizeSql(veryLong));
}*/
}
| 3,740 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql-postgres/src/main/java/com/amazonaws/xray/sql | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-sql-postgres/src/main/java/com/amazonaws/xray/sql/postgres/TracingInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.sql.postgres;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.ConnectionPool;
import org.apache.tomcat.jdbc.pool.JdbcInterceptor;
import org.apache.tomcat.jdbc.pool.PooledConnection;
/*
* Inspired by: http://grepcode.com/file/repo1.maven.org/maven2/org.apache.tomcat/tomcat-jdbc/8.0.24/org/apache/tomcat/jdbc/pool/interceptor/AbstractQueryReport.java#AbstractQueryReport
*/
public class TracingInterceptor extends JdbcInterceptor {
protected static final String CREATE_STATEMENT = "createStatement";
protected static final int CREATE_STATEMENT_INDEX = 0;
protected static final String PREPARE_STATEMENT = "prepareStatement";
protected static final int PREPARE_STATEMENT_INDEX = 1;
protected static final String PREPARE_CALL = "prepareCall";
protected static final int PREPARE_CALL_INDEX = 2;
protected static final String[] STATEMENT_TYPES = {CREATE_STATEMENT, PREPARE_STATEMENT, PREPARE_CALL};
protected static final int STATEMENT_TYPE_COUNT = STATEMENT_TYPES.length;
protected static final String EXECUTE = "execute";
protected static final String EXECUTE_QUERY = "executeQuery";
protected static final String EXECUTE_UPDATE = "executeUpdate";
protected static final String EXECUTE_BATCH = "executeBatch";
protected static final String[] EXECUTE_TYPES = {EXECUTE, EXECUTE_QUERY, EXECUTE_UPDATE, EXECUTE_BATCH};
/**
* @deprecated For internal use only.
*/
@SuppressWarnings("checkstyle:ConstantName")
@Deprecated
protected static final Constructor<?>[] constructors =
new Constructor[STATEMENT_TYPE_COUNT];
private static final Log logger =
LogFactory.getLog(TracingInterceptor.class);
private static final String DEFAULT_DATABASE_NAME = "database";
/**
* Creates a constructor for a proxy class, if one doesn't already exist
*
* @param index the index of the constructor
* @param clazz the interface that the proxy will implement
* @return returns a constructor used to create new instances
* @throws NoSuchMethodException
*/
protected Constructor<?> getConstructor(int index, Class<?> clazz) throws NoSuchMethodException {
if (constructors[index] == null) {
Class<?> proxyClass = Proxy.getProxyClass(TracingInterceptor.class.getClassLoader(), new Class[] {clazz});
constructors[index] = proxyClass.getConstructor(new Class[] {InvocationHandler.class});
}
return constructors[index];
}
public Object createStatement(Object proxy, Method method, Object[] args, Object statementObject) {
try {
String name = method.getName();
String sql = null;
Constructor<?> constructor = null;
Map<String, Object> additionalParams = new HashMap<>();
if (compare(CREATE_STATEMENT, name)) {
//createStatement
constructor = getConstructor(CREATE_STATEMENT_INDEX, Statement.class);
} else if (compare(PREPARE_STATEMENT, name)) {
additionalParams.put("preparation", "statement");
sql = (String) args[0];
constructor = getConstructor(PREPARE_STATEMENT_INDEX, PreparedStatement.class);
} else if (compare(PREPARE_CALL, name)) {
additionalParams.put("preparation", "call");
sql = (String) args[0];
constructor = getConstructor(PREPARE_CALL_INDEX, CallableStatement.class);
} else {
//do nothing, might be a future unsupported method
//so we better bail out and let the system continue
return statementObject;
}
Statement statement = ((Statement) statementObject);
Connection connection = statement.getConnection();
DatabaseMetaData metadata = connection.getMetaData();
// parse cname for subsegment name
additionalParams.put("url", metadata.getURL());
additionalParams.put("user", metadata.getUserName());
additionalParams.put("driver_version", metadata.getDriverVersion());
additionalParams.put("database_type", metadata.getDatabaseProductName());
additionalParams.put("database_version", metadata.getDatabaseProductVersion());
String hostname = DEFAULT_DATABASE_NAME;
try {
URI normalizedUri = new URI(new URI(metadata.getURL()).getSchemeSpecificPart());
hostname = connection.getCatalog() + "@" + normalizedUri.getHost();
} catch (URISyntaxException e) {
logger.warn("Unable to parse database URI. Falling back to default '" + DEFAULT_DATABASE_NAME
+ "' for subsegment name.", e);
}
logger.debug("Instantiating new statement proxy.");
return constructor.newInstance(new TracingStatementProxy(statementObject, sql, hostname, additionalParams));
} catch (SQLException | InstantiationException | IllegalAccessException | InvocationTargetException
| NoSuchMethodException e) {
logger.warn("Unable to create statement proxy for tracing.", e);
}
return statementObject;
}
protected class TracingStatementProxy implements InvocationHandler {
protected boolean closed = false;
protected Object delegate;
protected final String query;
protected final String hostname;
protected Map<String, Object> additionalParams;
public TracingStatementProxy(Object parent, String query, String hostname, Map<String, Object> additionalParams) {
this.delegate = parent;
this.query = query;
this.hostname = hostname;
this.additionalParams = additionalParams;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//get the name of the method for comparison
final String name = method.getName();
//was close invoked?
boolean close = compare(JdbcInterceptor.CLOSE_VAL, name);
//allow close to be called multiple times
if (close && closed) {
return null;
}
//are we calling isClosed?
if (compare(JdbcInterceptor.ISCLOSED_VAL, name)) {
return Boolean.valueOf(closed);
}
//if we are calling anything else, bail out
if (closed) {
throw new SQLException("Statement closed.");
}
//check to see if we are about to execute a query
final boolean process = isExecute(method);
Object result = null;
Subsegment subsegment = null;
if (process) {
subsegment = AWSXRay.beginSubsegment(hostname);
}
try {
if (process && null != subsegment) {
subsegment.putAllSql(additionalParams);
subsegment.setNamespace(Namespace.REMOTE.toString());
}
result = method.invoke(delegate, args); //execute the query
} catch (Throwable t) {
if (null != subsegment) {
subsegment.addException(t);
}
if (t instanceof InvocationTargetException && t.getCause() != null) {
throw t.getCause();
} else {
throw t;
}
} finally {
if (process && null != subsegment) {
AWSXRay.endSubsegment();
}
}
//perform close cleanup
if (close) {
closed = true;
delegate = null;
}
return result;
}
}
/**
* {@inheritDoc}
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (compare(CLOSE_VAL, method)) {
return super.invoke(proxy, method, args);
} else {
boolean process = isStatement(method);
if (process) {
Object statement = super.invoke(proxy, method, args);
return createStatement(proxy, method, args, statement);
} else {
return super.invoke(proxy, method, args);
}
}
}
private boolean isStatement(Method method) {
return isMemberOf(STATEMENT_TYPES, method);
}
private boolean isExecute(Method method) {
return isMemberOf(EXECUTE_TYPES, method);
}
protected boolean isMemberOf(String[] names, Method method) {
boolean member = false;
final String name = method.getName();
for (int i = 0; !member && i < names.length; i++) {
member = compare(names[i], name);
}
return member;
}
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
//do nothing
}
}
| 3,741 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/AWSXRayRecorderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.contexts.LambdaSegmentContext;
import com.amazonaws.xray.contexts.LambdaSegmentContextResolver;
import com.amazonaws.xray.contexts.SegmentContextResolverChain;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.AWSLogReference;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceID;
import com.amazonaws.xray.exceptions.AlreadyEmittedException;
import com.amazonaws.xray.exceptions.SegmentNotFoundException;
import com.amazonaws.xray.plugins.EC2Plugin;
import com.amazonaws.xray.plugins.ECSPlugin;
import com.amazonaws.xray.plugins.EKSPlugin;
import com.amazonaws.xray.plugins.ElasticBeanstalkPlugin;
import com.amazonaws.xray.plugins.Plugin;
import com.amazonaws.xray.strategy.ContextMissingStrategy;
import com.amazonaws.xray.strategy.IgnoreErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.LogErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.RuntimeErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.NoSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.SamplingResponse;
import com.amazonaws.xray.strategy.sampling.SamplingStrategy;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.json.JSONException;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
@FixMethodOrder(MethodSorters.JVM)
@PrepareForTest({LambdaSegmentContext.class, LambdaSegmentContextResolver.class})
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.net.ssl.*")
public class AWSXRayRecorderTest {
private static final String TRACE_HEADER = "Root=1-57ff426a-80c11c39b0c928905eb0828d;Parent=1234abcd1234abcd;Sampled=1";
private static ExecutorService threadExecutor;
@Mock
private SamplingStrategy mockSamplingStrategy;
@Rule
public EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Rule
public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
@BeforeClass
public static void startExecutor() {
threadExecutor = Executors.newSingleThreadExecutor();
}
@AfterClass
public static void stopExecutor() {
threadExecutor.shutdown();
}
@Before
public void setupAWSXRay() {
MockitoAnnotations.initMocks(this);
Emitter blankEmitter = Mockito.mock(Emitter.class);
LocalizedSamplingStrategy defaultSamplingStrategy = new LocalizedSamplingStrategy();
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder
.standard()
.withEmitter(blankEmitter)
.withSamplingStrategy(defaultSamplingStrategy)
.build());
AWSXRay.clearTraceEntity();
}
@Test
public void testGetThreadLocalReturnsCurrentSegment() {
Segment segment = AWSXRay.beginSegment("test");
Assert.assertEquals(segment, AWSXRay.getTraceEntity());
AWSXRay.endSegment();
}
@Test
public void testGetTraceEntityReturnsCurrentSegment() {
Segment segment = AWSXRay.beginSegment("test");
Assert.assertEquals(segment, AWSXRay.getTraceEntity());
AWSXRay.endSegment();
}
@Test
public void testGetThreadLocalReturnsCurrentSubsegment() {
AWSXRay.beginSegment("test");
Subsegment subsegment = AWSXRay.beginSubsegment("test");
Assert.assertEquals(subsegment, AWSXRay.getTraceEntity());
AWSXRay.endSubsegment();
AWSXRay.endSegment();
}
@Test
public void testGetTraceEntityReturnsCurrentSubsegment() {
AWSXRay.beginSegment("test");
Subsegment subsegment = AWSXRay.beginSubsegment("test");
Assert.assertEquals(subsegment, AWSXRay.getTraceEntity());
AWSXRay.endSubsegment();
AWSXRay.endSegment();
}
@Test
public void testGetThreadLocalOnEmptyThreadDoesNotThrowException() {
AWSXRay.beginSegment("test");
AWSXRay.endSegment();
AWSXRay.getTraceEntity();
}
@Test
public void testGetTraceEntityOnEmptyThreadDoesNotThrowException() {
AWSXRay.beginSegment("test");
AWSXRay.endSegment();
AWSXRay.getTraceEntity();
}
@Test
public void testBeginSubsegmentOnEmptyThreadDoesNotThrowExceptionWithLogErrorContextMissingStrategy() {
AWSXRay.getGlobalRecorder().setContextMissingStrategy(new LogErrorContextMissingStrategy());
AWSXRay.beginSubsegment("test");
}
@Test
public void testBeginSubsegmentOnEmptyThreadDoesNotThrowExceptionWithIgnoreErrorContextMissingStrategy() {
AWSXRay.getGlobalRecorder().setContextMissingStrategy(new IgnoreErrorContextMissingStrategy());
AWSXRay.beginSubsegment("test");
}
@Test
public void testInjectThreadLocalInjectsCurrentSegment() throws Exception {
Segment segment = AWSXRay.beginSegment("test");
threadExecutor.submit(() -> {
AWSXRay.injectThreadLocal(segment);
Assert.assertEquals(segment, AWSXRay.getThreadLocal());
}).get();
AWSXRay.endSegment();
}
@Test
public void testSetTraceEntityInjectsCurrentSegment() throws Exception {
Segment segment = AWSXRay.beginSegment("test");
threadExecutor.submit(() -> {
AWSXRay.setTraceEntity(segment);
Assert.assertEquals(segment, AWSXRay.getTraceEntity());
}).get();
AWSXRay.endSegment();
}
@Test
public void testInjectThreadLocalInjectsCurrentSubsegment() throws Exception {
AWSXRay.beginSegment("test");
Subsegment subsegment = AWSXRay.beginSubsegment("test");
threadExecutor.submit(() -> {
AWSXRay.injectThreadLocal(subsegment);
Assert.assertEquals(subsegment, AWSXRay.getThreadLocal());
}).get();
AWSXRay.endSubsegment();
AWSXRay.endSegment();
}
@Test
public void testSetTraceEntityInjectsCurrentSubsegment() throws Exception {
AWSXRay.beginSegment("test");
Subsegment subsegment = AWSXRay.beginSubsegment("test");
threadExecutor.submit(() -> {
AWSXRay.setTraceEntity(subsegment);
Assert.assertEquals(subsegment, AWSXRay.getThreadLocal());
}).get();
AWSXRay.endSubsegment();
AWSXRay.endSegment();
}
@Test
public void testIsCurrentSegmentPresent() {
Assert.assertFalse(AWSXRay.getCurrentSegmentOptional().isPresent());
AWSXRay.beginSegment("test");
Assert.assertTrue(AWSXRay.getCurrentSegmentOptional().isPresent());
AWSXRay.endSegment();
Assert.assertFalse(AWSXRay.getCurrentSegmentOptional().isPresent());
}
@Test
public void testIsCurrentSubsegmentPresent() {
Assert.assertFalse(AWSXRay.getCurrentSubsegmentOptional().isPresent());
AWSXRay.beginSegment("test");
Assert.assertFalse(AWSXRay.getCurrentSubsegmentOptional().isPresent());
AWSXRay.beginSubsegment("test");
Assert.assertTrue(AWSXRay.getCurrentSubsegmentOptional().isPresent());
AWSXRay.endSubsegment();
Assert.assertFalse(AWSXRay.getCurrentSubsegmentOptional().isPresent());
AWSXRay.endSegment();
Assert.assertFalse(AWSXRay.getCurrentSubsegmentOptional().isPresent());
}
@Test(expected = SegmentNotFoundException.class)
public void testRuntimeContextStrategyEmitsExceptionOnMissingContext() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withContextMissingStrategy(new RuntimeErrorContextMissingStrategy())
.build();
recorder.beginSubsegment("test");
}
@Test
public void testNotSendingUnsampledSegment() {
Emitter mockEmitter = Mockito.mock(Emitter.class);
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withEmitter(mockEmitter).build();
Segment segment = recorder.beginSegment("test");
segment.setSampled(false);
recorder.endSegment();
Mockito.verify(mockEmitter, Mockito.times(0)).sendSegment(any());
}
@Test
public void testSegmentEmitted() {
Emitter mockEmitter = Mockito.mock(Emitter.class);
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withEmitter(mockEmitter).build();
recorder.beginSegment("test");
recorder.beginSubsegment("test");
recorder.endSubsegment();
recorder.endSegment();
Mockito.verify(mockEmitter, Mockito.times(1)).sendSegment(any());
}
@Test
public void testExplicitSubsegmentEmitted() {
Emitter mockEmitter = Mockito.mock(Emitter.class);
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withEmitter(mockEmitter).build();
recorder.beginSegment("test");
Subsegment subsegment = recorder.beginSubsegment("test");
recorder.endSubsegment(subsegment);
recorder.endSegment();
Mockito.verify(mockEmitter, Mockito.times(1)).sendSegment(any());
}
@Test
public void testDummySegmentNotEmitted() {
Emitter mockEmitter = Mockito.mock(Emitter.class);
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withEmitter(mockEmitter).build();
recorder.beginDummySegment();
recorder.beginSubsegment("test");
recorder.endSubsegment();
recorder.endSegment();
Mockito.verify(mockEmitter, Mockito.times(0)).sendSegment(any());
}
@Test
public void testSubsegmentEmittedInLambdaContext() throws JSONException {
TraceHeader header = TraceHeader.fromString(TRACE_HEADER);
PowerMockito.stub(PowerMockito.method(LambdaSegmentContext.class, "getTraceHeaderFromEnvironment")).toReturn(header);
PowerMockito.stub(PowerMockito.method(LambdaSegmentContextResolver.class, "getLambdaTaskRoot")).toReturn("/var/task");
Emitter mockEmitter = Mockito.mock(Emitter.class);
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withEmitter(mockEmitter).build();
recorder.createSubsegment("test", () -> {
});
ArgumentCaptor<Subsegment> emittedSubsegment = ArgumentCaptor.forClass(Subsegment.class);
Mockito.verify(mockEmitter, Mockito.times(1)).sendSubsegment(emittedSubsegment.capture());
Subsegment captured = emittedSubsegment.getValue();
JSONAssert.assertEquals(expectedLambdaSubsegment(
header.getRootTraceId(), header.getParentId(), captured.getId(), captured.getStartTime(),
captured.getEndTime()).toString(), captured.streamSerialize(), JSONCompareMode.NON_EXTENSIBLE);
}
@Test
public void testBeginSegment_awsRuntimeContextNotMutableBySegment() {
Segment segment = AWSXRay.beginSegment("test");
segment.putAws("foo", "bar");
assertThat(segment.getAws().get("foo")).isEqualTo("bar");
AWSXRay.endSegment();
segment = AWSXRay.beginSegment("test");
assertThat(segment.getAws().get("foo")).isNull();
AWSXRay.endSegment();
}
@Test
public void testBeginSegment_canSetRuleName() {
Segment segment = AWSXRay.beginSegment("test");
segment.setRuleName("rule");
assertThat(segment.getAws().get("xray")).isInstanceOfSatisfying(
Map.class, xray -> assertThat(xray.get("rule_name")).isEqualTo("rule"));
}
private ObjectNode expectedLambdaSubsegment(
TraceID traceId, String segmentId, String subsegmentId, double startTime, double endTime) {
ObjectNode expected = JsonNodeFactory.instance.objectNode();
expected.put("name", "test");
expected.put("type", "subsegment");
expected.put("start_time", startTime);
expected.put("end_time", endTime);
expected.put("trace_id", traceId.toString());
expected.put("parent_id", segmentId);
expected.put("id", subsegmentId);
return expected;
}
@Test
public void testSubsegmentNotEmittedWithoutExceptionInLambdaInitContext() {
PowerMockito.stub(PowerMockito.method(LambdaSegmentContext.class, "getTraceHeaderFromEnvironment"))
.toReturn(TraceHeader.fromString(null));
PowerMockito.stub(PowerMockito.method(LambdaSegmentContextResolver.class, "getLambdaTaskRoot")).toReturn("/var/task");
Emitter mockEmitter = Mockito.mock(Emitter.class);
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withEmitter(mockEmitter).build();
recorder.createSubsegment("test", () -> {
});
Mockito.verify(mockEmitter, Mockito.times(0)).sendSubsegment(any());
}
@Test
public void testSubsegmentWithChildEmittedTogetherInLambdaContext() {
TraceHeader header = TraceHeader.fromString(TRACE_HEADER);
PowerMockito.stub(PowerMockito.method(LambdaSegmentContext.class, "getTraceHeaderFromEnvironment")).toReturn(header);
PowerMockito.stub(PowerMockito.method(LambdaSegmentContextResolver.class, "getLambdaTaskRoot")).toReturn("/var/task");
Emitter mockEmitter = Mockito.mock(Emitter.class);
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withEmitter(mockEmitter).build();
recorder.createSubsegment("testTogether", () -> {
recorder.createSubsegment("testTogether2", () -> {
});
});
ArgumentCaptor<Subsegment> emittedSubsegment = ArgumentCaptor.forClass(Subsegment.class);
Mockito.verify(mockEmitter, Mockito.times(1)).sendSubsegment(emittedSubsegment.capture());
Subsegment captured = emittedSubsegment.getValue();
Assert.assertEquals(1, captured.getSubsegments().size());
}
@Test
public void testSubsequentSubsegmentBranchesEmittedInLambdaContext() {
TraceHeader header = TraceHeader.fromString(TRACE_HEADER);
PowerMockito.stub(PowerMockito.method(LambdaSegmentContext.class, "getTraceHeaderFromEnvironment")).toReturn(header);
PowerMockito.stub(PowerMockito.method(LambdaSegmentContextResolver.class, "getLambdaTaskRoot")).toReturn("/var/task");
Emitter mockEmitter = Mockito.mock(Emitter.class);
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withEmitter(mockEmitter).build();
recorder.createSubsegment("testTogether", () -> {
recorder.createSubsegment("testTogether2", () -> {
});
});
recorder.createSubsegment("testTogether3", () -> {
recorder.createSubsegment("testTogether4", () -> {
});
});
ArgumentCaptor<Subsegment> emittedSubsegments = ArgumentCaptor.forClass(Subsegment.class);
Mockito.verify(mockEmitter, Mockito.times(2)).sendSubsegment(emittedSubsegments.capture());
List<Subsegment> captured = emittedSubsegments.getAllValues();
captured.forEach((capturedSubsegment) -> {
Assert.assertEquals(1, capturedSubsegment.getSubsegments().size());
});
}
@Test
public void testContextMissingStrategyOverrideEnvironmentVariable() {
environmentVariables.set(ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_ENVIRONMENT_VARIABLE_OVERRIDE_KEY, "log_error");
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withContextMissingStrategy(
new RuntimeErrorContextMissingStrategy()).build();
Assert.assertTrue(recorder.getContextMissingStrategy() instanceof LogErrorContextMissingStrategy);
environmentVariables.set(ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_ENVIRONMENT_VARIABLE_OVERRIDE_KEY, null);
}
@Test
public void testContextMissingStrategyOverrideSystemProperty() {
System.setProperty(ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_SYSTEM_PROPERTY_OVERRIDE_KEY, "log_error");
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withContextMissingStrategy(
new RuntimeErrorContextMissingStrategy()).build();
Assert.assertTrue(recorder.getContextMissingStrategy() instanceof LogErrorContextMissingStrategy);
}
@Test
public void testContextMissingStrategyOverrideEnvironmentVariableOverridesSystemProperty() {
environmentVariables.set(ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_ENVIRONMENT_VARIABLE_OVERRIDE_KEY, "log_error");
System.setProperty(ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_SYSTEM_PROPERTY_OVERRIDE_KEY, "runtime_error");
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withContextMissingStrategy(
new RuntimeErrorContextMissingStrategy()).build();
Assert.assertTrue(recorder.getContextMissingStrategy() instanceof LogErrorContextMissingStrategy);
environmentVariables.set(ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_ENVIRONMENT_VARIABLE_OVERRIDE_KEY, null);
}
@Test(expected = AlreadyEmittedException.class)
public void testEmittingSegmentTwiceThrowsSegmentAlreadyEmittedException() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withContextMissingStrategy(new RuntimeErrorContextMissingStrategy())
.build();
Segment s = recorder.beginSegment("test");
recorder.endSegment();
recorder.injectThreadLocal(s);
recorder.endSegment();
}
@Test
public void testBeginSegmentWhenMissingContext() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSegmentContextResolverChain(new SegmentContextResolverChain())
.withContextMissingStrategy(new IgnoreErrorContextMissingStrategy())
.build();
Segment segment = recorder.beginSegment("hello");
assertThat(segment).isNotNull();
assertThat(segment.getNamespace()).isEmpty();
// No-op
segment.setNamespace("foo");
assertThat(segment.getNamespace()).isEmpty();
}
@Test
public void testBeginSubsegmentWhenMissingContext() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withContextMissingStrategy(new IgnoreErrorContextMissingStrategy())
.build();
Subsegment subsegment = recorder.beginSubsegment("hello");
assertThat(subsegment).isNotNull();
assertThat(subsegment.getNamespace()).isEmpty();
assertThat(subsegment.shouldPropagate()).isFalse();
}
@Test
public void testSubsegmentFunctionExceptionWhenMissingContext() {
IllegalStateException expectedException = new IllegalStateException("To be thrown by function");
Function<Subsegment, Void> function = (subsegment) -> {
throw expectedException;
};
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withContextMissingStrategy(new IgnoreErrorContextMissingStrategy())
.build();
assertThatThrownBy(() -> recorder.createSubsegment("test", function)).isEqualTo(expectedException);
}
@Test
public void testSubsegmentConsumerExceptionWhenMissingContext() {
IllegalStateException expectedException = new IllegalStateException("To be thrown by consumer");
Consumer<Subsegment> consumer = (subsegment) -> {
throw expectedException;
};
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withContextMissingStrategy(new IgnoreErrorContextMissingStrategy())
.build();
assertThatThrownBy(() -> recorder.createSubsegment("test", consumer)).isEqualTo(expectedException);
}
@Test
public void testSubsegmentSupplierExceptionWhenMissingContext() {
RuntimeException expectedException = new RuntimeException("To be thrown by supplier");
Supplier<Void> supplier = () -> {
throw expectedException;
};
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withContextMissingStrategy(new IgnoreErrorContextMissingStrategy())
.build();
assertThatThrownBy(() -> recorder.createSubsegment("test", supplier)).isEqualTo(expectedException);
}
@Test
public void testSubsegmentRunnableExceptionWhenMissingContext() {
RuntimeException expectedException = new RuntimeException("To be thrown by runnable");
Runnable runnable = () -> {
throw expectedException;
};
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withContextMissingStrategy(new IgnoreErrorContextMissingStrategy())
.build();
assertThatThrownBy(() -> recorder.createSubsegment("test", runnable)).isEqualTo(expectedException);
}
@Test
public void testOriginResolutionWithAllPlugins() {
//given
EC2Plugin ec2Plugin = Mockito.mock(EC2Plugin.class);
ECSPlugin ecsPlugin = Mockito.mock(ECSPlugin.class);
ElasticBeanstalkPlugin ebPlugin = Mockito.mock(ElasticBeanstalkPlugin.class);
EKSPlugin eksPlugin = Mockito.mock(EKSPlugin.class);
List<Plugin> plugins = new ArrayList<>();
plugins.add(ec2Plugin);
plugins.add(ecsPlugin);
plugins.add(ebPlugin);
plugins.add(eksPlugin);
List<String> origins = new ArrayList<>();
origins.add(EC2Plugin.ORIGIN);
origins.add(ECSPlugin.ORIGIN);
origins.add(ElasticBeanstalkPlugin.ORIGIN);
origins.add(EKSPlugin.ORIGIN);
Map<String, Object> runtimeContext = new HashMap<>();
runtimeContext.put("key", "value");
for (int i = 0; i < 4; i++) {
Mockito.doReturn(true).when(plugins.get(i)).isEnabled();
Mockito.doReturn(runtimeContext).when(plugins.get(i)).getRuntimeContext();
Mockito.doReturn("serviceName").when(plugins.get(i)).getServiceName();
Mockito.doReturn(origins.get(i)).when(plugins.get(i)).getOrigin();
}
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withPlugin(ec2Plugin)
.withPlugin(ecsPlugin)
.withPlugin(ebPlugin)
.withPlugin(eksPlugin)
.build();
// when
Assert.assertEquals(ElasticBeanstalkPlugin.ORIGIN, recorder.getOrigin());
}
@Test
public void testEKSOriginResolvesOverECSOrigin() {
//given
ECSPlugin ecsPlugin = Mockito.mock(ECSPlugin.class);
EKSPlugin eksPlugin = Mockito.mock(EKSPlugin.class);
Map<String, Object> runtimeContext = new HashMap<>();
runtimeContext.put("key", "value");
Mockito.doReturn(true).when(ecsPlugin).isEnabled();
Mockito.doReturn(runtimeContext).when(ecsPlugin).getRuntimeContext();
Mockito.doReturn("ecs").when(ecsPlugin).getServiceName();
Mockito.doReturn(ECSPlugin.ORIGIN).when(ecsPlugin).getOrigin();
Mockito.doReturn(true).when(eksPlugin).isEnabled();
Mockito.doReturn(runtimeContext).when(eksPlugin).getRuntimeContext();
Mockito.doReturn("eks").when(eksPlugin).getServiceName();
Mockito.doReturn(EKSPlugin.ORIGIN).when(eksPlugin).getOrigin();
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withPlugin(eksPlugin)
.withPlugin(ecsPlugin)
.build();
// when
Assert.assertEquals(EKSPlugin.ORIGIN, recorder.getOrigin());
}
@Test
public void testPluginEquality() {
Collection<Plugin> plugins = new HashSet<>();
plugins.add(new EC2Plugin());
plugins.add(new EC2Plugin()); // should be deduped
plugins.add(new ECSPlugin());
plugins.add(new EKSPlugin());
plugins.add(new ElasticBeanstalkPlugin());
Assert.assertEquals(4, plugins.size());
}
@Test
public void testCurrentFormattedId() {
TraceID traceId = TraceID.fromString("1-5759e988-bd862e3fe1be46a994272793");
String entityId = "123456789";
Segment seg = AWSXRay.beginSegment("test", traceId, "FakeParentId");
seg.setId(entityId);
Assert.assertEquals(traceId.toString() + "@" + entityId, AWSXRay.currentFormattedId());
}
@Test
public void testNoOpSegment() throws Exception {
Segment segment = AWSXRay.getGlobalRecorder().beginNoOpSegment();
Map<String, Object> map = new HashMap<>();
map.put("dog", "bark");
// Semantically relevant
assertThat(segment.end()).isFalse();
assertThat(segment.isRecording()).isFalse();
segment.setSampled(true);
assertThat(segment.isSampled()).isFalse();
// Semantically less relevant, we're mostly concerned with being no-op and avoiding exceptions.
segment.setResourceArn("foo");
assertThat(segment.getResourceArn()).isEmpty();
segment.setUser("foo");
assertThat(segment.getUser()).isEmpty();
segment.setOrigin("foo");
assertThat(segment.getOrigin()).isEmpty();
segment.setService(new HashMap<>());
segment.getService().put("foo", "bar");
segment.putService("cat", "meow");
segment.putAllService(map);
assertThat(segment.getService()).isEmpty();
assertThat(segment.getName()).isEmpty();
segment.setId("foo");
assertThat(segment.getId()).isEmpty();
segment.setStartTime(100);
assertThat(segment.getStartTime()).isZero();
segment.setEndTime(100);
assertThat(segment.getEndTime()).isZero();
segment.setFault(true);
assertThat(segment.isFault()).isFalse();
segment.setError(true);
assertThat(segment.isError()).isFalse();
segment.setNamespace("foo");
assertThat(segment.getNamespace()).isEmpty();
segment.setSubsegmentsLock(new ReentrantLock());
Thread thread = new Thread(() -> segment.getSubsegmentsLock().lock());
thread.start();
thread.join();
// No-op lock so we can lock again!
segment.getSubsegmentsLock().lock();
assertThat(segment.getCause()).isNotNull();
segment.setHttp(new HashMap<>());
segment.getHttp().put("foo", "bar");
segment.putHttp("cat", "meow");
segment.putAllHttp(map);
assertThat(segment.getHttp()).isEmpty();
segment.setAws(new HashMap<>());
segment.getAws().put("foo", "bar");
segment.putAws("cat", "meow");
segment.putAllAws(map);
assertThat(segment.getAws()).isEmpty();
segment.setSql(new HashMap<>());
segment.getSql().put("foo", "bar");
segment.putSql("cat", "meow");
segment.putAllSql(map);
assertThat(segment.getSql()).isEmpty();
segment.setMetadata(new HashMap<>());
segment.getMetadata().put("foo", new HashMap<>());
segment.putMetadata("cat", new HashMap<>());
segment.putMetadata("animal", "dog", new HashMap<>());
assertThat(segment.getMetadata()).isEmpty();
segment.setAnnotations(new HashMap<>());
segment.getAnnotations().put("foo", "bar");
segment.putAnnotation("cat", "meow");
segment.putAnnotation("lives", 9);
segment.putAnnotation("alive", true);
assertThat(segment.getAnnotations()).isEmpty();
assertThat(segment.getParent()).isSameAs(segment);
segment.setThrottle(true);
assertThat(segment.isThrottle()).isFalse(); // Not Full
segment.setInProgress(true);
assertThat(segment.isInProgress()).isFalse();
segment.setTraceId(TraceID.create());
assertThat(segment.getTraceId()).isEqualTo(TraceID.invalid());
segment.setParentId("foo");
assertThat(segment.getParentId()).isNull();
segment.setCreator(AWSXRayRecorderBuilder.standard().build());
assertThat(segment.getCreator()).isEqualTo(AWSXRay.getGlobalRecorder());
segment.setRuleName("foo");
assertThat(segment.getParentSegment()).isSameAs(segment);
segment.getSubsegments().add(Subsegment.noOp(AWSXRay.getGlobalRecorder(), true));
segment.addSubsegment(Subsegment.noOp(AWSXRay.getGlobalRecorder(), true));
assertThat(segment.getSubsegments()).isEmpty();
segment.addException(new IllegalStateException());
assertThat(segment.getReferenceCount()).isZero();
assertThat(segment.getTotalSize()).hasValue(0);
assertThat(segment.getTotalSize()).hasValue(0);
segment.incrementReferenceCount();
assertThat(segment.getReferenceCount()).isZero();
segment.decrementReferenceCount();
assertThat(segment.getReferenceCount()).isZero();
segment.removeSubsegment(Subsegment.noOp(AWSXRay.getGlobalRecorder(), true));
segment.setEmitted(true);
assertThat(segment.isEmitted()).isFalse();
assertThat(segment.serialize()).isEmpty();
assertThat(segment.prettySerialize()).isEmpty();
segment.close();
}
@Test
public void testNoOpSegmentWithTraceId() {
TraceID traceID = TraceID.create();
Segment segment = AWSXRay.getGlobalRecorder().beginNoOpSegment(traceID);
assertThat(segment.getTraceId()).isEqualTo(traceID);
}
@Test
public void testNoOpSegmentWithForcedTraceId() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withForcedTraceIdGeneration()
.build();
Segment segment = recorder.beginNoOpSegment();
assertThat(segment.getTraceId()).isNotEqualTo(TraceID.invalid());
AWSXRayRecorder recorder2 = AWSXRayRecorderBuilder.standard()
.build();
Segment segment2 = recorder2.beginNoOpSegment();
assertThat(segment2.getTraceId()).isEqualTo(TraceID.invalid());
}
@Test
public void testAlwaysCreateTraceId() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withForcedTraceIdGeneration()
.withSamplingStrategy(new NoSamplingStrategy())
.build();
Segment segment = recorder.beginSegmentWithSampling("test");
assertThat(segment.getTraceId()).isNotEqualTo(TraceID.invalid());
}
@Test
public void testNoOpSubsegment() throws Exception {
Subsegment subsegment = Subsegment.noOp(AWSXRay.getGlobalRecorder(), true);
Map<String, Object> map = new HashMap<>();
map.put("dog", "bark");
// Semantically relevant
assertThat(subsegment.end()).isFalse();
assertThat(subsegment.getName()).isEmpty();
subsegment.setStartTime(100);
assertThat(subsegment.getStartTime()).isZero();
subsegment.setEndTime(100);
assertThat(subsegment.getEndTime()).isZero();
subsegment.setFault(true);
assertThat(subsegment.isFault()).isFalse();
subsegment.setError(true);
assertThat(subsegment.isError()).isFalse();
assertThat(subsegment.getNamespace()).isEmpty();
subsegment.setSubsegmentsLock(new ReentrantLock());
Thread thread = new Thread(() -> subsegment.getSubsegmentsLock().lock());
thread.start();
thread.join();
// No-op lock so we can lock again!
subsegment.getSubsegmentsLock().lock();
assertThat(subsegment.getCause()).isNotNull();
subsegment.setHttp(new HashMap<>());
subsegment.getHttp().put("foo", "bar");
subsegment.putHttp("cat", "meow");
subsegment.putAllHttp(map);
assertThat(subsegment.getHttp()).isEmpty();
subsegment.setAws(new HashMap<>());
subsegment.getAws().put("foo", "bar");
subsegment.putAws("cat", "meow");
subsegment.putAllAws(map);
assertThat(subsegment.getAws()).isEmpty();
subsegment.setSql(new HashMap<>());
subsegment.getSql().put("foo", "bar");
subsegment.putSql("cat", "meow");
subsegment.putAllSql(map);
assertThat(subsegment.getSql()).isEmpty();
subsegment.setMetadata(new HashMap<>());
subsegment.getMetadata().put("foo", new HashMap<>());
subsegment.putMetadata("cat", new HashMap<>());
subsegment.putMetadata("animal", "dog", new HashMap<>());
assertThat(subsegment.getMetadata()).isEmpty();
subsegment.setAnnotations(new HashMap<>());
subsegment.getAnnotations().put("foo", "bar");
subsegment.putAnnotation("cat", "meow");
subsegment.putAnnotation("lives", 9);
subsegment.putAnnotation("alive", true);
assertThat(subsegment.getAnnotations()).isEmpty();
assertThat(subsegment.getParent()).isInstanceOfSatisfying(Segment.class, segment ->
assertThat(segment.getTraceId()).isEqualTo(TraceID.invalid()));
subsegment.setThrottle(true);
assertThat(subsegment.isThrottle()).isFalse(); // Not Full
subsegment.setInProgress(true);
assertThat(subsegment.isInProgress()).isFalse();
subsegment.setTraceId(TraceID.create());
assertThat(subsegment.getTraceId()).isEqualTo(TraceID.invalid());
subsegment.setParentId("foo");
assertThat(subsegment.getParentId()).isNull();
subsegment.setCreator(AWSXRayRecorderBuilder.standard().build());
assertThat(subsegment.getCreator()).isEqualTo(AWSXRay.getGlobalRecorder());
assertThat(subsegment.getParentSegment().getTraceId()).isEqualTo(TraceID.invalid());
subsegment.getSubsegments().add(Subsegment.noOp(AWSXRay.getGlobalRecorder(), true));
subsegment.addSubsegment(Subsegment.noOp(AWSXRay.getGlobalRecorder(), true));
assertThat(subsegment.getSubsegments()).isEmpty();
subsegment.addException(new IllegalStateException());
assertThat(subsegment.getReferenceCount()).isZero();
assertThat(subsegment.getTotalSize()).hasValue(0);
assertThat(subsegment.getTotalSize()).hasValue(0);
subsegment.incrementReferenceCount();
assertThat(subsegment.getReferenceCount()).isZero();
subsegment.decrementReferenceCount();
assertThat(subsegment.getReferenceCount()).isZero();
subsegment.removeSubsegment(Subsegment.noOp(AWSXRay.getGlobalRecorder(), true));
subsegment.setEmitted(true);
assertThat(subsegment.isEmitted()).isFalse();
assertThat(subsegment.serialize()).isEmpty();
assertThat(subsegment.prettySerialize()).isEmpty();
assertThat(subsegment.streamSerialize()).isEmpty();
assertThat(subsegment.prettyStreamSerialize()).isEmpty();
subsegment.close();
}
@Test
public void noOpSubsegmentWithParent() {
TraceID traceID = TraceID.create();
Segment parent = Segment.noOp(traceID, AWSXRay.getGlobalRecorder());
Subsegment subsegment = Subsegment.noOp(parent, AWSXRay.getGlobalRecorder());
assertThat(subsegment.getParentSegment().getTraceId()).isEqualTo(traceID);
}
@Test
public void testBeginSegmentWithSamplingDoesSample() {
SamplingResponse response = new SamplingResponse(true, "rule");
when(mockSamplingStrategy.shouldTrace(any())).thenReturn(response);
AWSXRay.getGlobalRecorder().setSamplingStrategy(mockSamplingStrategy);
Segment segment = AWSXRay.beginSegmentWithSampling("test");
assertThat(segment.isSampled()).isTrue();
assertThat(segment.getAws().get("xray")).isInstanceOfSatisfying(
Map.class, xray -> assertThat(xray.get("rule_name")).isEqualTo("rule"));
}
@Test
public void testBeginSegmentWithSamplingDoesNotSample() {
SamplingResponse response = new SamplingResponse(false, "rule");
when(mockSamplingStrategy.shouldTrace(any())).thenReturn(response);
AWSXRay.getGlobalRecorder().setSamplingStrategy(mockSamplingStrategy);
Segment segment = AWSXRay.beginSegmentWithSampling("test");
assertThat(segment.isSampled()).isFalse();
segment.setUser("user");
assertThat(segment.getUser()).isEmpty(); // Loose way to test that segment is a no-op
}
@Test
public void testBeginSegmentWithForcedSampling() {
SamplingResponse response = new SamplingResponse(false, "rule");
when(mockSamplingStrategy.isForcedSamplingSupported()).thenReturn(true);
when(mockSamplingStrategy.shouldTrace(any())).thenReturn(response);
AWSXRay.getGlobalRecorder().setSamplingStrategy(mockSamplingStrategy);
Segment segment = AWSXRay.beginSegmentWithSampling("test");
assertThat(segment.isSampled()).isFalse();
segment.setUser("user");
assertThat(segment.getUser()).isEqualTo("user"); // Loose way to test that segment is real
}
@Test
public void testLogGroupFromEnvironment() {
environmentVariables.set("AWS_LOG_GROUP", "my-group");
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().build();
Segment segment = recorder.beginSegment("test");
AWSLogReference expected = new AWSLogReference();
expected.setLogGroup("my-group");
assertThat(segment.getAws()).containsKey("cloudwatch_logs");
Set<AWSLogReference> logReferences = (Set<AWSLogReference>) segment.getAws().get("cloudwatch_logs");
assertThat(logReferences).containsOnly(expected);
}
@Test
public void testUnsampledSubsegmentPropagation() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.build();
Segment segment = recorder.beginSegmentWithSampling("test");
Subsegment subsegment = recorder.beginSubsegment("test");
assertThat(segment.isSampled()).isFalse();
assertThat(subsegment.shouldPropagate()).isTrue();
}
@Test
public void testDefaultContextMissingBehaviorBegin() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.build();
recorder.beginSubsegment("test");
}
@Test
public void testDefaultContextMissingBehaviorEnd() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.build();
recorder.endSubsegment();
}
@Test
public void testMalformedTraceId() {
TraceHeader malformedHeader = TraceHeader.fromString("malformedTraceID");
PowerMockito.stub(PowerMockito.method(
LambdaSegmentContext.class, "getTraceHeaderFromEnvironment"))
.toReturn(malformedHeader);
PowerMockito.stub(PowerMockito.method(
LambdaSegmentContextResolver.class, "getLambdaTaskRoot"))
.toReturn("/var/task");
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.build();
recorder.beginSubsegment("Test");
// Sanity checks that this is a NoOpSubsegment. (We cannot compare the instance of the private class directly)
assertThat(recorder.getTraceEntity().getName()).isEqualTo("");
assertThat(recorder.getTraceEntity().getNamespace()).isEmpty();
assertThat(recorder.getTraceEntity().getStartTime()).isEqualTo(0);
assertThat(recorder.getTraceEntity().getEndTime()).isEqualTo(0);
recorder.endSubsegment();
}
}
| 3,742 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/TraceHeaderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceHeader.SampleDecision;
import com.amazonaws.xray.entities.TraceID;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class TraceHeaderTest {
private static final String TRACE_ID = "1-57ff426a-80c11c39b0c928905eb0828d";
@Test
void testSampledEqualsOneFromString() {
TraceHeader header = TraceHeader.fromString("Sampled=1");
Assertions.assertEquals(SampleDecision.SAMPLED, header.getSampled());
Assertions.assertNull(header.getRootTraceId());
Assertions.assertNull(header.getParentId());
Assertions.assertTrue(header.getAdditionalParams().isEmpty());
}
@Test
void testLongHeaderFromString() {
TraceHeader header = TraceHeader.fromString("Sampled=?;Root=" + TRACE_ID + ";Parent=foo;Self=2;Foo=bar");
Assertions.assertEquals(SampleDecision.REQUESTED, header.getSampled());
Assertions.assertEquals(TraceID.fromString(TRACE_ID), header.getRootTraceId());
Assertions.assertEquals("foo", header.getParentId());
Assertions.assertEquals(1, header.getAdditionalParams().size());
Assertions.assertEquals("bar", header.getAdditionalParams().get("Foo"));
}
@Test
void testLongHeaderFromStringWithSpaces() {
TraceHeader header = TraceHeader.fromString("Sampled=?; Root=" + TRACE_ID + "; Parent=foo; Self=2; Foo=bar");
Assertions.assertEquals(SampleDecision.REQUESTED, header.getSampled());
Assertions.assertEquals(TraceID.fromString(TRACE_ID), header.getRootTraceId());
Assertions.assertEquals("foo", header.getParentId());
Assertions.assertEquals(1, header.getAdditionalParams().size());
Assertions.assertEquals("bar", header.getAdditionalParams().get("Foo"));
}
@Test
void testSampledUnknownToString() {
TraceHeader header = new TraceHeader();
header.setSampled(SampleDecision.UNKNOWN);
Assertions.assertEquals("", header.toString());
}
@Test
void testSampledEqualsOneWithSamplingRequestedToString() {
TraceHeader header = new TraceHeader();
header.setSampled(SampleDecision.REQUESTED);
header.setSampled(SampleDecision.SAMPLED);
Assertions.assertEquals("Sampled=1", header.toString());
}
@Test
void testSampledEqualsOneAndParentToString() {
TraceHeader header = new TraceHeader();
header.setSampled(SampleDecision.SAMPLED);
header.setParentId("foo");
Assertions.assertEquals("Parent=foo;Sampled=1", header.toString());
}
@Test
void testLongHeaderToString() {
TraceHeader header = new TraceHeader();
header.setSampled(SampleDecision.SAMPLED);
header.setRootTraceId(TraceID.fromString(TRACE_ID));
header.setParentId("foo");
header.getAdditionalParams().put("Foo", "bar");
Assertions.assertEquals("Root=" + TRACE_ID + ";Parent=foo;Sampled=1;Foo=bar", header.toString());
}
}
| 3,743 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/EntityTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.SegmentImpl;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.SubsegmentImpl;
import com.amazonaws.xray.entities.TraceID;
import com.amazonaws.xray.exceptions.AlreadyEmittedException;
import com.amazonaws.xray.strategy.RuntimeErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.NoSamplingStrategy;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.json.JSONException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
@FixMethodOrder(MethodSorters.JVM)
public class EntityTest {
private static final String[] PREFIXES = {"set", "increment", "decrement", "put", "add"};
private static final List<String> MUTATING_METHOD_PREFIXES = Arrays.asList(PREFIXES);
@Before
public void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
LocalizedSamplingStrategy defaultSamplingStrategy = new LocalizedSamplingStrategy();
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard()
.withEmitter(blankEmitter)
.withSamplingStrategy(defaultSamplingStrategy)
.build());
AWSXRay.clearTraceEntity();
}
@Test
public void testInProgressSegment() throws JSONException {
String segmentId = Entity.generateId();
TraceID traceId = new TraceID();
Segment segment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceId);
segment.setId(segmentId);
segment.setStartTime(1.0);
String expected = expectedInProgressSegment(traceId, segmentId, segment.getStartTime()).toString();
JSONAssert.assertEquals(expected, segment.serialize(), JSONCompareMode.NON_EXTENSIBLE);
}
public ObjectNode expectedInProgressSegment(TraceID traceId, String segmentId, double startTime) {
ObjectNode expected = JsonNodeFactory.instance.objectNode();
expected.put("name", "test");
expected.put("start_time", startTime);
expected.put("trace_id", traceId.toString());
expected.put("in_progress", true);
expected.put("id", segmentId);
return expected;
}
@Test
public void testInProgressSubsegment() throws JSONException {
Segment parent = AWSXRay.beginSegment("test");
Subsegment subsegment = AWSXRay.beginSubsegment("test");
subsegment.setStartTime(1.0);
String expected = expectedInProgressSubsegment(parent.getTraceId(), parent.getId(), subsegment.getId(),
subsegment.getStartTime()).toString();
JSONAssert.assertEquals(expected, subsegment.streamSerialize(), JSONCompareMode.NON_EXTENSIBLE);
}
public ObjectNode expectedInProgressSubsegment(TraceID traceId, String parentId, String subsegmentId, double startTime) {
ObjectNode expected = JsonNodeFactory.instance.objectNode();
expected.put("name", "test");
expected.put("start_time", startTime);
expected.put("trace_id", traceId.toString());
expected.put("in_progress", true);
expected.put("id", subsegmentId);
expected.put("type", "subsegment");
expected.put("parent_id", parentId);
return expected;
}
@Test
public void testSegmentWithSubsegment() throws JSONException {
TraceID traceId = new TraceID();
Segment segment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceId);
Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", segment);
segment.addSubsegment(subsegment);
segment.setStartTime(1.0);
subsegment.setStartTime(1.0);
subsegment.end();
segment.end();
String expected = expectedCompletedSegmentWithSubsegment(traceId, segment.getId(), subsegment.getId(), 1.0,
subsegment.getEndTime(), segment.getEndTime()).toString();
JSONAssert.assertEquals(expected, segment.serialize(), JSONCompareMode.NON_EXTENSIBLE);
}
@Test
public void testManuallySetEntityEndTime() {
Segment segment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", new TraceID());
Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", segment);
segment.addSubsegment(subsegment);
double endTime = 20.0d;
segment.setStartTime(1.0);
subsegment.setStartTime(1.0);
segment.setEndTime(endTime);
subsegment.setEndTime(endTime);
subsegment.end();
segment.end();
Assert.assertEquals(endTime, segment.getEndTime(), 0);
Assert.assertEquals(endTime, subsegment.getEndTime(), 0);
}
public ObjectNode expectedCompletedSegmentWithSubsegment(TraceID traceId, String segmentId, String subsegmentId,
double startTime, double subsegmentEndTime, double segmentEndTime) {
ObjectNode expected = expectedCompletedSegment(traceId, segmentId, startTime, segmentEndTime);
expected.putArray("subsegments").add(expectedCompletedSubsegment(traceId, subsegmentId, startTime, subsegmentEndTime));
return expected;
}
public ObjectNode expectedCompletedSegment(TraceID traceId, String segmentId, double startTime, double endTime) {
ObjectNode expected = JsonNodeFactory.instance.objectNode();
expected.put("name", "test");
expected.put("start_time", startTime);
expected.put("end_time", endTime);
expected.put("trace_id", traceId.toString());
expected.put("id", segmentId);
return expected;
}
public ObjectNode expectedCompletedSubsegment(TraceID traceId, String subsegmentId, double startTime, double endTime) {
ObjectNode expected = JsonNodeFactory.instance.objectNode();
expected.put("name", "test");
expected.put("start_time", startTime);
expected.put("end_time", endTime);
expected.put("id", subsegmentId);
return expected;
}
@SuppressWarnings("resource")
@Test(expected = AlreadyEmittedException.class)
public void testModifyingSegmentAfterEndingThrowsAlreadyEmittedException() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withContextMissingStrategy(new RuntimeErrorContextMissingStrategy())
.build();
TraceID traceId = new TraceID();
Segment segment = new SegmentImpl(recorder, "test", traceId);
segment.end();
segment.setStartTime(1.0);
}
private static class MutatingMethodCount {
private int mutatingMethods;
private int mutatingMethodsThrowingExceptions;
MutatingMethodCount(int mutatingMethods, int mutatingMethodsThrowingExceptions) {
this.mutatingMethods = mutatingMethods;
this.mutatingMethodsThrowingExceptions = mutatingMethodsThrowingExceptions;
}
public int getMutatingMethods() {
return mutatingMethods;
}
public int getMutatingMethodsThrowingExceptions() {
return mutatingMethodsThrowingExceptions;
}
}
private MutatingMethodCount numberOfMutatingMethodsThatThrewException(Entity entity, Class klass) {
int numberOfMutatingMethods = 0;
int numberOfMutatingMethodsThatThrewException = 0;
for (Method m : klass.getMethods()) {
if (MUTATING_METHOD_PREFIXES.stream().anyMatch((prefix) -> {
return m.getName().startsWith(prefix);
})) {
if (m.getName().equals("setCreator") || m.getName().equals("setSampledFalse")) {
// Skip this call since it will interfere with other tests.
continue;
}
numberOfMutatingMethods++;
try {
List<Parameter> parameters = Arrays.asList(m.getParameters());
List<?> arguments = parameters.stream().map(parameter -> {
try {
Class<?> argumentClass = parameter.getType();
if (boolean.class.equals(argumentClass)) {
return false;
} else if (double.class.equals(argumentClass)) {
return 0.0d;
} else {
return argumentClass.getConstructor().newInstance();
}
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException |
IllegalAccessException e) {
// Ignore
}
return null;
}).collect(Collectors.toList());
m.invoke(entity, arguments.toArray());
} catch (InvocationTargetException ite) {
if (ite.getCause() instanceof AlreadyEmittedException) {
numberOfMutatingMethodsThatThrewException++;
}
} catch (IllegalAccessException e) {
// Ignore
}
}
}
return new MutatingMethodCount(numberOfMutatingMethods, numberOfMutatingMethodsThatThrewException);
}
@Test
public void testAllSegmentImplMutationMethodsThrowAlreadyEmittedExceptions() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withContextMissingStrategy(new RuntimeErrorContextMissingStrategy())
.build();
SegmentImpl segment = new SegmentImpl(recorder, "test");
MutatingMethodCount mutationResults = numberOfMutatingMethodsThatThrewException(segment, SegmentImpl.class);
Assert.assertEquals(0, mutationResults.getMutatingMethodsThrowingExceptions());
segment.end();
mutationResults = numberOfMutatingMethodsThatThrewException(segment, SegmentImpl.class);
Assert.assertEquals(mutationResults.getMutatingMethods(), mutationResults.getMutatingMethodsThrowingExceptions());
}
@Test
public void testAllSubsegmentImplMutationMethodsThrowAlreadyEmittedExceptions() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withContextMissingStrategy(new RuntimeErrorContextMissingStrategy())
.build();
SegmentImpl segment = new SegmentImpl(recorder, "test");
segment.getName();
SubsegmentImpl subsegment = new SubsegmentImpl(recorder, "test", segment);
MutatingMethodCount mutationResults = numberOfMutatingMethodsThatThrewException(subsegment, SubsegmentImpl.class);
Assert.assertEquals(0, mutationResults.getMutatingMethodsThrowingExceptions());
subsegment.setParentSegment(segment); // the mutating methods set this to null...
segment.end();
subsegment.end();
mutationResults = numberOfMutatingMethodsThatThrewException(subsegment, SubsegmentImpl.class);
Assert.assertEquals(mutationResults.getMutatingMethods(), mutationResults.getMutatingMethodsThrowingExceptions());
}
@Test(expected = AlreadyEmittedException.class)
public void testEndingSegmentImplTwiceThrowsAlreadyEmittedException() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withContextMissingStrategy(new RuntimeErrorContextMissingStrategy())
.build();
SegmentImpl segment = new SegmentImpl(recorder, "test");
segment.getName();
segment.end();
segment.end();
}
@Test(expected = AlreadyEmittedException.class)
public void testEndingSubsegmentImplTwiceThrowsAlreadyEmittedException() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withContextMissingStrategy(new RuntimeErrorContextMissingStrategy())
.build();
SegmentImpl segment = new SegmentImpl(recorder, "test");
segment.getName();
SubsegmentImpl subsegment = new SubsegmentImpl(recorder, "test", segment);
segment.end();
subsegment.end();
subsegment.end();
}
@Test(expected = AlreadyEmittedException.class)
public void testEndingSubsegmentImplAfterStreamingThrowsAlreadyEmittedException() {
AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard()
.withSamplingStrategy(new NoSamplingStrategy())
.withContextMissingStrategy(new RuntimeErrorContextMissingStrategy())
.build();
SegmentImpl segment = new SegmentImpl(recorder, "test");
SubsegmentImpl firstSubsegment = new SubsegmentImpl(recorder, "test", segment);
firstSubsegment.end();
for (int i = 0; i < 100; i++) { // add enough subsegments to trigger the DefaultStreamingStrategy and stream subsegments
SubsegmentImpl current = new SubsegmentImpl(recorder, "test", segment);
current.end();
}
segment.end();
firstSubsegment.end();
}
}
| 3,744 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/ConcurrencyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.SegmentImpl;
import com.amazonaws.xray.entities.SubsegmentImpl;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ConcurrencyTest {
@BeforeEach
void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
LocalizedSamplingStrategy defaultSamplingStrategy = new LocalizedSamplingStrategy();
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard().withEmitter(blankEmitter)
.withSamplingStrategy(defaultSamplingStrategy).build());
AWSXRay.clearTraceEntity();
}
@Test
void testManyThreads() throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(100);
for (int i = 0; i < 100; i++) {
pool.execute(() -> {
try {
AWSXRay.createSegment("Segment", (segment) -> {
AWSXRay.createSubsegment("Subsegment", (subsegment) -> {
AWSXRay.createSubsegment("NestedSubsegment", (nSubsegment) -> {
});
});
});
latch.countDown();
} catch (Exception e) {
Thread.currentThread().interrupt();
}
});
}
try {
latch.await(5, TimeUnit.SECONDS);
} finally {
pool.shutdownNow();
}
}
@Test
public void testPrecursorIdConcurrency() throws Exception {
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test");
SubsegmentImpl subseg = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", seg);
final long startTime = System.currentTimeMillis();
Thread thread1 = new Thread(() -> {
while (true) {
subseg.addPrecursorId("ID" + new Random().nextInt());
}
});
thread1.start();
Callable<Void> callable = (Callable) () -> {
while (System.currentTimeMillis() - startTime < TimeUnit.SECONDS.toMillis(1)) {
Iterator it = subseg.getPrecursorIds().iterator();
while (it.hasNext()) {
it.next();
}
}
return null;
};
callable.call();
thread1.join();
}
}
| 3,745 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/contexts/CustomSegmentContextTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.SubsegmentImpl;
import com.amazonaws.xray.exceptions.SubsegmentNotFoundException;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class CustomSegmentContextTest {
static class GlobalMapSegmentContext implements SegmentContext {
private Map<Long, Entity> map = new HashMap<>();
@Override
public Subsegment beginSubsegmentWithoutSampling(
AWSXRayRecorder recorder,
String name) {
Subsegment subsegment = beginSubsegment(recorder, name);
subsegment.setSampledFalse();
return subsegment;
}
@Override
public Subsegment beginSubsegment(AWSXRayRecorder recorder, String name) {
Entity current = map.get(Thread.currentThread().getId());
Segment parentSegment = current.getParentSegment();
Subsegment subsegment = new SubsegmentImpl(recorder, name, parentSegment);
subsegment.setParent(current);
current.addSubsegment(subsegment);
map.put(Thread.currentThread().getId(), subsegment);
return subsegment;
}
@Override
public void endSubsegment(AWSXRayRecorder recorder) {
Entity current = map.get(Thread.currentThread().getId());
if (current instanceof Subsegment) {
Subsegment currentSubsegment = (Subsegment) current;
if (currentSubsegment.end() &&
currentSubsegment.isSampled()) {
recorder.sendSegment(currentSubsegment.getParentSegment());
} else {
if (recorder.getStreamingStrategy().requiresStreaming(currentSubsegment.getParentSegment())) {
recorder.getStreamingStrategy().streamSome(currentSubsegment.getParentSegment(), recorder.getEmitter());
}
map.put(Thread.currentThread().getId(), current.getParent());
}
} else {
recorder.getContextMissingStrategy().contextMissing("Failed to end subsegment: subsegment cannot be found.",
SubsegmentNotFoundException.class);
}
}
@Override
public Entity getTraceEntity() {
return map.get(Thread.currentThread().getId());
}
@Override
public void setTraceEntity(Entity entity) {
map.put(Thread.currentThread().getId(), entity);
}
@Override
public void clearTraceEntity() {
map.put(Thread.currentThread().getId(), null);
}
}
static class GlobalMapSegmentContextResolver implements SegmentContextResolver {
private GlobalMapSegmentContext gmsc = new GlobalMapSegmentContext();
@Override
public SegmentContext resolve() {
return gmsc;
}
}
@BeforeEach
void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
LocalizedSamplingStrategy defaultSamplingStrategy = new LocalizedSamplingStrategy();
SegmentContextResolverChain chain = new SegmentContextResolverChain();
chain.addResolver(new GlobalMapSegmentContextResolver());
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard()
.withEmitter(blankEmitter)
.withSegmentContextResolverChain(chain)
.withSamplingStrategy(defaultSamplingStrategy)
.build());
AWSXRay.clearTraceEntity();
}
@Test
void testGlobalMapSegmentContext() {
Segment test = AWSXRay.beginSegment("test");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add(i);
}
list.forEach(e -> {
AWSXRay.setTraceEntity(test);
AWSXRay.createSubsegment("print", (subsegment) -> {
});
});
Assertions.assertEquals(100, test.getTotalSize().intValue());
AWSXRay.endSegment();
}
}
| 3,746 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/contexts/SegmentContextExecutorsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.ThreadLocalStorage;
import com.amazonaws.xray.entities.Segment;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class SegmentContextExecutorsTest {
private static ExecutorService backgroundExecutor;
@Rule
public MockitoRule mocks = MockitoJUnit.rule();
@Mock
private volatile AWSXRayRecorder recorder;
@Spy
private volatile Segment current;
@Spy
private volatile Segment manual;
@Spy
private volatile Segment previous;
@BeforeClass
public static void startBackgroundExecutor() {
backgroundExecutor = Executors.newSingleThreadExecutor();
}
@AfterClass
public static void stopBackgroundExecutor() {
backgroundExecutor.shutdown();
}
@Before
public void setUp() {
when(recorder.getTraceEntity()).thenAnswer(invocation -> ThreadLocalStorage.get());
when(recorder.getCurrentSegmentOptional()).thenAnswer(invocation -> Optional.of(ThreadLocalStorage.get()));
doAnswer(invocation -> {
ThreadLocalStorage.set(invocation.getArgument(0));
return null;
}).when(recorder).setTraceEntity(any());
recorder.setTraceEntity(current);
AWSXRay.setGlobalRecorder(recorder);
}
@After
public void tearDown() {
recorder.setTraceEntity(null);
}
@Test
public void currentSegmentExecutor() {
runSegmentExecutorTest(SegmentContextExecutors.newSegmentContextExecutor(), current);
}
@Test
public void segmentExecutor() {
runSegmentExecutorTest(SegmentContextExecutors.newSegmentContextExecutor(manual), manual);
}
@Test
public void segmentAndRecorderExecutor() {
runSegmentExecutorTest(SegmentContextExecutors.newSegmentContextExecutor(recorder, manual), manual);
}
private void runSegmentExecutorTest(Executor segmentExecutor, Segment mounted) {
assertThat(recorder.getTraceEntity()).isEqualTo(current);
CountDownLatch ready = new CountDownLatch(1);
AtomicReference<Thread> backgroundThread = new AtomicReference<>();
CompletableFuture<?> future = CompletableFuture
.supplyAsync(() -> {
backgroundThread.set(Thread.currentThread());
recorder.setTraceEntity(previous);
try {
// We need to make sure callbacks are registered before we complete this future or else the callbacks will
// be called inline on the main thread (the one that registers them).
ready.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new IllegalStateException();
}
return null;
}, backgroundExecutor)
.thenAcceptAsync(unused -> {
// Sanity check our test is actually on a different thread.
assertThat(Thread.currentThread()).isEqualTo(backgroundThread.get());
assertThat(recorder.getTraceEntity()).isEqualTo(mounted);
}, segmentExecutor)
.thenAcceptAsync(unused -> {
assertThat(Thread.currentThread()).isEqualTo(backgroundThread.get());
assertThat(recorder.getTraceEntity()).isEqualTo(previous);
}, backgroundExecutor);
ready.countDown();
future.join();
assertThat(recorder.getTraceEntity()).isEqualTo(current);
}
}
| 3,747 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/contexts/LambdaSegmentContextTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.FacadeSegment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.exceptions.SubsegmentNotFoundException;
import com.amazonaws.xray.strategy.LogErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.RuntimeErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junitpioneer.jupiter.SetEnvironmentVariable;
import org.junitpioneer.jupiter.SetSystemProperty;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class LambdaSegmentContextTest {
private static final String TRACE_HEADER = "Root=1-57ff426a-80c11c39b0c928905eb0828d;Parent=1234abcd1234abcd;Sampled=1";
private static final String TRACE_HEADER_2 = "Root=1-57ff426a-90c11c39b0c928905eb0828d;Parent=9234abcd1234abcd;Sampled=0";
private static final String MALFORMED_TRACE_HEADER =
";;Root=1-57ff426a-80c11c39b0c928905eb0828d;;Parent=1234abcd1234abcd;;;Sampled=1;;;";
@BeforeEach
public void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard()
.withEmitter(blankEmitter)
.withSamplingStrategy(new LocalizedSamplingStrategy())
.build());
AWSXRay.clearTraceEntity();
}
@Test
void testBeginSubsegmentWithNullTraceHeaderEnvironmentVariableResultsInAFacadeSegmentParent() {
testContextResultsInFacadeSegmentParent();
}
@Test
@SetEnvironmentVariable(key = "_X_AMZN_TRACE_ID", value = "a")
void testBeginSubsegmentWithIncompleteTraceHeaderEnvironmentVariableResultsInAFacadeSegmentParent() {
testContextResultsInFacadeSegmentParent();
}
@Test
@SetEnvironmentVariable(key = "_X_AMZN_TRACE_ID", value = TRACE_HEADER)
void testBeginSubsegmentWithCompleteTraceHeaderEnvironmentVariableResultsInAFacadeSegmentParent() {
testContextResultsInFacadeSegmentParent();
}
@Test
@SetEnvironmentVariable(key = "_X_AMZN_TRACE_ID", value = MALFORMED_TRACE_HEADER)
void testBeginSubsegmentWithCompleteButMalformedTraceHeaderEnvironmentVariableResultsInAFacadeSegmentParent() {
testContextResultsInFacadeSegmentParent();
}
@Test
@SetEnvironmentVariable(key = "_X_AMZN_TRACE_ID", value = TRACE_HEADER_2)
void testNotSampledSetsParentToSubsegment() {
LambdaSegmentContext lsc = new LambdaSegmentContext();
lsc.beginSubsegment(AWSXRay.getGlobalRecorder(), "test");
lsc.beginSubsegment(AWSXRay.getGlobalRecorder(), "test2");
lsc.endSubsegment(AWSXRay.getGlobalRecorder());
lsc.endSubsegment(AWSXRay.getGlobalRecorder());
}
@Test
@SetEnvironmentVariable(key = "_X_AMZN_TRACE_ID", value = TRACE_HEADER)
void testEndSubsegmentUsesContextMissing() {
AWSXRay.getGlobalRecorder().setContextMissingStrategy(new LogErrorContextMissingStrategy());
AWSXRay.endSubsegment(); // No exception
AWSXRay.getGlobalRecorder().setContextMissingStrategy(new RuntimeErrorContextMissingStrategy());
assertThatThrownBy(AWSXRay::endSubsegment).isInstanceOf(SubsegmentNotFoundException.class);
}
// We create segments twice with different environment variables for the same context, similar to how Lambda would invoke
// a function.
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
static class LeakedSubsegments {
LambdaSegmentContext lsc;
@BeforeAll
void setupContext() {
lsc = new LambdaSegmentContext();
}
@Test
@SetEnvironmentVariable(key = "_X_AMZN_TRACE_ID", value = TRACE_HEADER)
void oneInvocationGeneratesSegment() {
Subsegment firstInvocation = lsc.beginSubsegment(AWSXRay.getGlobalRecorder(), "test");
assertThat(firstInvocation).isNotNull();
assertThat(firstInvocation.getParent()).isInstanceOf(FacadeSegment.class);
}
@Test
@SetEnvironmentVariable(key = "_X_AMZN_TRACE_ID", value = TRACE_HEADER_2)
void anotherInvocationGeneratesSegment() {
Subsegment secondInvocation = lsc.beginSubsegment(AWSXRay.getGlobalRecorder(), "test");
assertThat(secondInvocation).isNotNull();
assertThat(secondInvocation.getParent()).isInstanceOf(FacadeSegment.class);
}
@Test
@SetSystemProperty(key = "com.amazonaws.xray.traceHeader", value = TRACE_HEADER)
void oneInvocationGeneratesSegmentUsingSystemProperty() {
Subsegment firstInvocation = lsc.beginSubsegment(AWSXRay.getGlobalRecorder(), "test");
assertThat(firstInvocation).isNotNull();
assertThat(firstInvocation.getParent()).isInstanceOf(FacadeSegment.class);
}
}
private static void testContextResultsInFacadeSegmentParent() {
LambdaSegmentContext mockContext = new LambdaSegmentContext();
assertThat(mockContext.beginSubsegment(AWSXRay.getGlobalRecorder(), "test").getParent())
.isInstanceOf(FacadeSegment.class);
mockContext.endSubsegment(AWSXRay.getGlobalRecorder());
assertThat(AWSXRay.getTraceEntity()).isNull();
}
}
| 3,748 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/contexts/LambdaSegmentContextResolverTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@FixMethodOrder(MethodSorters.JVM)
@PrepareForTest(LambdaSegmentContextResolver.class)
@RunWith(PowerMockRunner.class)
public class LambdaSegmentContextResolverTest {
@Test
public void testLambdaTaskRootSetResolvesLambdaContext() {
Assert.assertNotNull(mockResolver("/var/test").resolve());
}
@Test
public void testBlankLambdaTaskRootDoesNotResolveLambdaContext() {
Assert.assertNull(mockResolver(" ").resolve());
}
@Test
public void testLambdaTaskRootNotSetDoesNotResolveLambdaContext() {
Assert.assertNull(mockResolver(null).resolve());
}
private LambdaSegmentContextResolver mockResolver(String taskRoot) {
PowerMockito.stub(PowerMockito.method(LambdaSegmentContextResolver.class, "getLambdaTaskRoot")).toReturn(taskRoot);
return new LambdaSegmentContextResolver();
}
}
| 3,749 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/config/DaemonConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.config;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.JVM)
public class DaemonConfigurationTest {
@Rule
public EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Rule
public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
@Before
public void setUp() {
environmentVariables.set(DaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, null);
System.setProperty(DaemonConfiguration.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "");
}
@Test
public void testDefaultDaemonConfiguration() {
DaemonConfiguration config = new DaemonConfiguration();
Assert.assertEquals("localhost", config.getAddressForEmitter().getHostString());
Assert.assertEquals(2000, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://127.0.0.1:2000", config.getEndpointForTCPConnection());
}
@Test
public void testDaemonAddressEnvironmentVariableOverride() {
environmentVariables.set(DaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, "1.2.3.4:5");
DaemonConfiguration config = new DaemonConfiguration();
Assert.assertEquals("1.2.3.4", config.getAddressForEmitter().getHostString());
Assert.assertEquals(5, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://1.2.3.4:5", config.getEndpointForTCPConnection());
}
@Test
public void testDaemonAddressSystemPropertyOverride() {
System.setProperty(DaemonConfiguration.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "1.2.3.4:5");
DaemonConfiguration config = new DaemonConfiguration();
Assert.assertEquals("1.2.3.4", config.getAddressForEmitter().getHostString());
Assert.assertEquals(5, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://1.2.3.4:5", config.getEndpointForTCPConnection());
}
@Test
public void testDaemonAddressEnvironmentVariableOverridesSystemProperty() {
environmentVariables.set(DaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, "1.2.3.4:5");
System.setProperty(DaemonConfiguration.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "6.7.8.9:10");
DaemonConfiguration config = new DaemonConfiguration();
Assert.assertEquals("1.2.3.4", config.getAddressForEmitter().getHostString());
Assert.assertEquals(5, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://1.2.3.4:5", config.getEndpointForTCPConnection());
}
@Test
public void testDaemonAddressSystemPropertyOverridesRuntimeConfig() {
System.setProperty(DaemonConfiguration.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "1.2.3.4:5");
DaemonConfiguration config = new DaemonConfiguration();
config.setDaemonAddress("6.7.8.9:10");
}
@Test
public void testDaemonAddressConfigAtRuntime() {
DaemonConfiguration config = new DaemonConfiguration();
config.setDaemonAddress("1.2.3.4:5");
Assert.assertEquals("1.2.3.4", config.getAddressForEmitter().getHostString());
Assert.assertEquals(5, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://1.2.3.4:5", config.getEndpointForTCPConnection());
}
@Test
public void testSetUDPAddressAndTCPAddressThroughEnvVar() {
environmentVariables.set(DaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, "tcp:0.0.0.1:2 udp:0.0.0.2:3");
DaemonConfiguration config = new DaemonConfiguration();
Assert.assertEquals("0.0.0.2", config.getAddressForEmitter().getHostString());
Assert.assertEquals(3, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://0.0.0.1:2", config.getEndpointForTCPConnection());
}
@Test
public void testSetUDPAddressAndTCPAddressThroughSystemProperty() {
System.setProperty(DaemonConfiguration.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "tcp:0.0.0.1:2 udp:0.0.0.2:3");
DaemonConfiguration config = new DaemonConfiguration();
Assert.assertEquals("0.0.0.2", config.getAddressForEmitter().getHostString());
Assert.assertEquals(3, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://0.0.0.1:2", config.getEndpointForTCPConnection());
}
@Test
public void testSetUDPAddressAndTCPAddressAtRuntime() {
DaemonConfiguration config = new DaemonConfiguration();
config.setDaemonAddress("udp:0.0.0.2:3 tcp:0.0.0.1:2");
Assert.assertEquals("0.0.0.2", config.getAddressForEmitter().getHostString());
Assert.assertEquals(3, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://0.0.0.1:2", config.getEndpointForTCPConnection());
}
@Test
public void testShouldNotThrowOnInvalidEnvVar() {
environmentVariables.set(DaemonConfiguration.DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, "tcp:0.0.0.1:2udp:0.0.0.2:3");
DaemonConfiguration config = new DaemonConfiguration();
Assert.assertEquals("localhost", config.getAddressForEmitter().getHostString());
Assert.assertEquals(2000, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://127.0.0.1:2000", config.getEndpointForTCPConnection());
}
@Test
public void testShouldNotThrowOnInvalidSystemProperty() {
System.setProperty(DaemonConfiguration.DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, "tcp0.0.0.1:2 udp0.0.0.2:3");
DaemonConfiguration config = new DaemonConfiguration();
Assert.assertEquals("localhost", config.getAddressForEmitter().getHostString());
Assert.assertEquals(2000, config.getAddressForEmitter().getPort());
Assert.assertEquals("http://127.0.0.1:2000", config.getEndpointForTCPConnection());
}
@Test(expected = IllegalArgumentException.class)
public void testShouldThrowOnInvalidRuntimeConfig() {
DaemonConfiguration config = new DaemonConfiguration();
config.setDaemonAddress("0.0.0.1");
}
@Test(expected = IllegalArgumentException.class)
public void testShouldThrowOnReallyInvalidRuntimeConfig() {
DaemonConfiguration config = new DaemonConfiguration();
config.setDaemonAddress("Not an address");
}
}
| 3,750 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/plugins/ECSMetadataFetcherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import com.github.tomakehurst.wiremock.junit.WireMockClassRule;
import java.util.Map;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
public class ECSMetadataFetcherTest {
@ClassRule
public static WireMockClassRule server = new WireMockClassRule(wireMockConfig().dynamicPort());
private static final String CONTAINER_METADATA =
"{\n" +
" \"DockerId\":\"efgh\",\n" +
" \"Name\":\"main\",\n" +
" \"DockerName\":\"ecs-helloworld-3-main-f69182c192af9cd71000\",\n" +
" \"Image\":\"public.ecr.aws/my-image\",\n" +
" \"ImageID\":\"sha256:937f680f89da88d36ddc3cff9ae5a70909fe149ca2d08b99208633730117ad67\",\n" +
" \"Labels\":{\n" +
" \"com.amazonaws.ecs.cluster\":\"myCluster\"\n" +
" },\n" +
" \"DesiredStatus\":\"RUNNING\",\n" +
" \"KnownStatus\":\"RUNNING\",\n" +
" \"Limits\":{\n" +
" \"CPU\":256,\n" +
" \"Memory\":0\n" +
" },\n" +
" \"CreatedAt\":\"2020-09-29T19:05:57.744432392Z\",\n" +
" \"StartedAt\":\"2020-09-29T19:05:58.656886747Z\",\n" +
" \"Type\":\"NORMAL\",\n" +
" \"LogDriver\":\"awslogs\",\n" +
" \"LogOptions\":{\n" +
" \"awslogs-group\":\"my-group\",\n" +
" \"awslogs-region\":\"ap-southeast-1\",\n" +
" \"awslogs-stream\":\"logs/main/5678\"\n" +
" },\n" +
" \"ContainerARN\":\"arn:aws:ecs:ap-southeast-1:123456789012:container/567\",\n" +
" \"Networks\":[\n" +
" {\n" +
" \"NetworkMode\":\"host\",\n" +
" \"IPv4Addresses\":[\n" +
" \"\"\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
private ECSMetadataFetcher fetcher;
@Before
public void setup() {
fetcher = new ECSMetadataFetcher("http://localhost:" + server.port());
}
@Test
public void testContainerMetadata() {
stubFor(any(urlPathEqualTo("/")).willReturn(okJson(CONTAINER_METADATA)));
Map<ECSMetadataFetcher.ECSContainerMetadata, String> metadata = this.fetcher.fetchContainer();
assertThat(metadata).containsOnly(
entry(ECSMetadataFetcher.ECSContainerMetadata.CONTAINER_ARN, "arn:aws:ecs:ap-southeast-1:123456789012:container/567"),
entry(ECSMetadataFetcher.ECSContainerMetadata.LOG_DRIVER, "awslogs"),
entry(ECSMetadataFetcher.ECSContainerMetadata.LOG_GROUP_REGION, "ap-southeast-1"),
entry(ECSMetadataFetcher.ECSContainerMetadata.LOG_GROUP_NAME, "my-group")
);
verify(getRequestedFor(urlEqualTo("/")));
}
@Test
public void testIncompleteResponse() {
stubFor(any(urlPathEqualTo("/")).willReturn(okJson("{\"DockerId\":\"efgh\"}")));
Map<ECSMetadataFetcher.ECSContainerMetadata, String> metadata = this.fetcher.fetchContainer();
assertThat(metadata).isEmpty();
verify(getRequestedFor(urlEqualTo("/")));
}
@Test
public void testErrorResponse() {
stubFor(any(urlPathEqualTo("/")).willReturn(okJson("bad json string")));
Map<ECSMetadataFetcher.ECSContainerMetadata, String> metadata = this.fetcher.fetchContainer();
assertThat(metadata).isEmpty();
verify(getRequestedFor(urlEqualTo("/")));
}
}
| 3,751 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/plugins/EKSPluginTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import static org.junit.Assert.assertEquals;
import com.amazonaws.xray.entities.AWSLogReference;
import com.amazonaws.xray.utils.ContainerInsightsUtil;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(ContainerInsightsUtil.class)
public class EKSPluginTest {
private static final String TEST_CLUSTER_NAME = "TestCluster";
private static final String TEST_LOG_GROUP = "/aws/containerinsights/TestCluster/application";
private static final String EXPECTERD_SERVICE_NAME = "eks";
private static final String EXPECTED_ORIGIN = "AWS::EKS::Container";
private final EKSPlugin plugin = new EKSPlugin(TEST_CLUSTER_NAME);
@Before
public void setUpEKS() {
PowerMockito.mockStatic(ContainerInsightsUtil.class);
}
@Test
public void testInit() {
BDDMockito.given(ContainerInsightsUtil.isK8s()).willReturn(true);
Assert.assertTrue(plugin.isEnabled());
}
@Test
public void testGenerationOfLogGroupName() {
Set<AWSLogReference> references = plugin.getLogReferences();
AWSLogReference reference = (AWSLogReference) references.toArray()[0];
assertEquals(TEST_LOG_GROUP, reference.getLogGroup());
}
@Test
public void testServiceName() {
assertEquals(EXPECTERD_SERVICE_NAME, plugin.getServiceName());
}
@Test
public void testOrigin() {
assertEquals(EXPECTED_ORIGIN, plugin.getOrigin());
}
}
| 3,752 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/plugins/EC2PluginTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.entities.AWSLogReference;
import com.amazonaws.xray.utils.JsonUtils;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({JsonUtils.class})
public class EC2PluginTest {
@Rule
public MockitoRule mocks = MockitoJUnit.rule();
@Mock
private FileSystem fakeFs;
@Mock
private EC2MetadataFetcher metadataFetcher;
private EC2Plugin ec2Plugin;
@Before
public void setUpEC2Plugin() {
Map<EC2MetadataFetcher.EC2Metadata, String> metadata = new HashMap<>();
metadata.put(EC2MetadataFetcher.EC2Metadata.INSTANCE_ID, "instance-1234");
metadata.put(EC2MetadataFetcher.EC2Metadata.AVAILABILITY_ZONE, "ap-northeast-1a");
metadata.put(EC2MetadataFetcher.EC2Metadata.INSTANCE_TYPE, "m4.xlarge");
metadata.put(EC2MetadataFetcher.EC2Metadata.AMI_ID, "ami-1234");
PowerMockito.mockStatic(JsonUtils.class);
when(metadataFetcher.fetch()).thenReturn(metadata);
ec2Plugin = new EC2Plugin(fakeFs, metadataFetcher);
}
@Test
public void testMetadataPresent() {
assertThat(ec2Plugin.isEnabled()).isTrue();
ec2Plugin.populateRuntimeContext();
assertThat(ec2Plugin.getRuntimeContext())
.containsEntry("instance_id", "instance-1234")
.containsEntry("availability_zone", "ap-northeast-1a")
.containsEntry("instance_size", "m4.xlarge")
.containsEntry("ami_id", "ami-1234");
}
@Test
public void testMetadataNotPresent() {
when(metadataFetcher.fetch()).thenReturn(Collections.emptyMap());
ec2Plugin = new EC2Plugin(fakeFs, metadataFetcher);
assertThat(ec2Plugin.isEnabled()).isFalse();
}
@Test
public void testFilePathCreationFailure() {
List<Path> pathList = new ArrayList<>();
pathList.add(Paths.get("badRoot"));
Mockito.doReturn(pathList).when(fakeFs).getRootDirectories();
Set<AWSLogReference> logReferences = ec2Plugin.getLogReferences();
assertThat(logReferences).isEmpty();
}
@Test
public void testGenerationOfLogReference() throws IOException {
List<Path> pathList = new ArrayList<>();
pathList.add(Paths.get("/"));
Mockito.doReturn(pathList).when(fakeFs).getRootDirectories();
List<String> groupList = new ArrayList<>();
groupList.add("test_group");
BDDMockito.given(JsonUtils.getMatchingListFromJsonArrayNode(Mockito.any(), Mockito.any())).willReturn(groupList);
Set<AWSLogReference> logReferences = ec2Plugin.getLogReferences();
assertThat(logReferences).hasOnlyOneElementSatisfying(
reference -> assertThat(reference.getLogGroup()).isEqualTo("test_group"));
}
@Test
public void testGenerationOfMultipleLogReferences() throws IOException {
List<Path> pathList = new ArrayList<>();
pathList.add(Paths.get("/"));
Mockito.doReturn(pathList).when(fakeFs).getRootDirectories();
List<String> groupList = new ArrayList<>();
groupList.add("test_group1");
groupList.add("test_group2");
groupList.add("test_group1"); // intentionally same for deduping
BDDMockito.given(JsonUtils.getMatchingListFromJsonArrayNode(Mockito.any(), Mockito.any())).willReturn(groupList);
Set<AWSLogReference> logReferences = ec2Plugin.getLogReferences();
assertThat(logReferences).hasSize(2);
}
}
| 3,753 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/plugins/ECSPluginTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.entities.AWSLogReference;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junitpioneer.jupiter.SetEnvironmentVariable;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class ECSPluginTest {
private static final String ECS_METADATA_KEY = "ECS_CONTAINER_METADATA_URI";
private static final String GOOD_URI = "http://172.0.0.1";
private static final String BAD_URI = "Not a URL";
@Mock
private ECSMetadataFetcher mockFetcher;
@Test
@SetEnvironmentVariable(key = ECS_METADATA_KEY, value = GOOD_URI)
void testIsEnabled() {
ECSPlugin plugin = new ECSPlugin();
assertThat(plugin.isEnabled()).isTrue();
}
@Test
@SetEnvironmentVariable(key = ECS_METADATA_KEY, value = BAD_URI)
void testBadUri() {
assertThatThrownBy(() -> new ECSPlugin()).isInstanceOf(IllegalArgumentException.class);
}
@Test
void testNotEnabledWithoutEnvironmentVariable() {
ECSPlugin plugin = new ECSPlugin();
assertThat(plugin.isEnabled()).isFalse();
}
@Test
void testLogGroupRecording() {
Map<ECSMetadataFetcher.ECSContainerMetadata, String> containerMetadata = new HashMap<>();
containerMetadata.put(ECSMetadataFetcher.ECSContainerMetadata.LOG_GROUP_REGION, "us-west-2");
containerMetadata.put(ECSMetadataFetcher.ECSContainerMetadata.LOG_GROUP_NAME, "my-log-group");
containerMetadata.put(ECSMetadataFetcher.ECSContainerMetadata.CONTAINER_ARN,
"arn:aws:ecs:us-west-2:123456789012:container-instance/my-cluster/12345");
when(mockFetcher.fetchContainer()).thenReturn(containerMetadata);
ECSPlugin plugin = new ECSPlugin(mockFetcher);
Set<AWSLogReference> references = plugin.getLogReferences();
AWSLogReference expected = new AWSLogReference();
expected.setLogGroup("my-log-group");
expected.setArn("arn:aws:logs:us-west-2:123456789012:log-group:my-log-group");
assertThat(references).containsOnly(expected);
}
}
| 3,754 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/plugins/EC2MetadataFetcherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.notFound;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import com.github.tomakehurst.wiremock.junit.WireMockClassRule;
import java.util.Map;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
public class EC2MetadataFetcherTest {
@ClassRule
public static WireMockClassRule server = new WireMockClassRule(wireMockConfig().dynamicPort());
// From https://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/instance-identity-documents.html
private static final String IDENTITY_DOCUMENT =
"{\n"
+ " \"devpayProductCodes\" : null,\n"
+ " \"marketplaceProductCodes\" : [ \"1abc2defghijklm3nopqrs4tu\" ], \n"
+ " \"availabilityZone\" : \"us-west-2b\",\n"
+ " \"privateIp\" : \"10.158.112.84\",\n"
+ " \"version\" : \"2017-09-30\",\n"
+ " \"instanceId\" : \"i-1234567890abcdef0\",\n"
+ " \"billingProducts\" : null,\n"
+ " \"instanceType\" : \"t2.micro\",\n"
+ " \"accountId\" : \"123456789012\",\n"
+ " \"imageId\" : \"ami-5fb8c835\",\n"
+ " \"pendingTime\" : \"2016-11-19T16:32:11Z\",\n"
+ " \"architecture\" : \"x86_64\",\n"
+ " \"kernelId\" : null,\n"
+ " \"ramdiskId\" : null,\n"
+ " \"region\" : \"us-west-2\"\n"
+ "}";
private EC2MetadataFetcher fetcher;
@Before
public void setUp() {
fetcher = new EC2MetadataFetcher("localhost:" + server.port());
}
@Test
public void imdsv2() {
stubFor(any(urlPathEqualTo("/latest/api/token")).willReturn(ok("token")));
stubFor(any(urlPathEqualTo("/latest/dynamic/instance-identity/document"))
.willReturn(okJson(IDENTITY_DOCUMENT)));
Map<EC2MetadataFetcher.EC2Metadata, String> metadata = fetcher.fetch();
assertThat(metadata).containsOnly(
entry(EC2MetadataFetcher.EC2Metadata.INSTANCE_ID, "i-1234567890abcdef0"),
entry(EC2MetadataFetcher.EC2Metadata.AVAILABILITY_ZONE, "us-west-2b"),
entry(EC2MetadataFetcher.EC2Metadata.INSTANCE_TYPE, "t2.micro"),
entry(EC2MetadataFetcher.EC2Metadata.AMI_ID, "ami-5fb8c835"));
verify(putRequestedFor(urlEqualTo("/latest/api/token"))
.withHeader("X-aws-ec2-metadata-token-ttl-seconds", equalTo("60")));
verify(getRequestedFor(urlEqualTo("/latest/dynamic/instance-identity/document"))
.withHeader("X-aws-ec2-metadata-token", equalTo("token")));
}
@Test
public void imdsv1() {
stubFor(any(urlPathEqualTo("/latest/api/token")).willReturn(notFound()));
stubFor(any(urlPathEqualTo("/latest/dynamic/instance-identity/document"))
.willReturn(okJson(IDENTITY_DOCUMENT)));
Map<EC2MetadataFetcher.EC2Metadata, String> metadata = fetcher.fetch();
assertThat(metadata).containsOnly(
entry(EC2MetadataFetcher.EC2Metadata.INSTANCE_ID, "i-1234567890abcdef0"),
entry(EC2MetadataFetcher.EC2Metadata.AVAILABILITY_ZONE, "us-west-2b"),
entry(EC2MetadataFetcher.EC2Metadata.INSTANCE_TYPE, "t2.micro"),
entry(EC2MetadataFetcher.EC2Metadata.AMI_ID, "ami-5fb8c835"));
verify(putRequestedFor(urlEqualTo("/latest/api/token"))
.withHeader("X-aws-ec2-metadata-token-ttl-seconds", equalTo("60")));
verify(getRequestedFor(urlEqualTo("/latest/dynamic/instance-identity/document"))
.withoutHeader("X-aws-ec2-metadata-token"));
}
@Test
public void badJson() {
stubFor(any(urlPathEqualTo("/latest/api/token")).willReturn(notFound()));
stubFor(any(urlPathEqualTo("/latest/dynamic/instance-identity/document"))
.willReturn(okJson("I'm not JSON")));
Map<EC2MetadataFetcher.EC2Metadata, String> metadata = fetcher.fetch();
assertThat(metadata).isEmpty();
verify(putRequestedFor(urlEqualTo("/latest/api/token"))
.withHeader("X-aws-ec2-metadata-token-ttl-seconds", equalTo("60")));
verify(getRequestedFor(urlEqualTo("/latest/dynamic/instance-identity/document"))
.withoutHeader("X-aws-ec2-metadata-token"));
}
}
| 3,755 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/internal/IdGeneratorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.internal;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
public class IdGeneratorTest {
@Test
public void testEntityIdPadding() {
Assert.assertEquals("0000000000000123", new TestIdGenerator(0x123L).newEntityId());
Assert.assertEquals(Long.toString(Long.MAX_VALUE, 16), new TestIdGenerator(Long.MAX_VALUE).newEntityId());
}
private static class TestIdGenerator extends IdGenerator {
private final long entityId;
private TestIdGenerator(long entityId) {
this.entityId = entityId << 1; // offset the signed right shift in `IdGenerator`
}
@Override
public String newTraceId() {
return "trace id";
}
@Override
protected long getRandomEntityId() {
return entityId;
}
}
}
| 3,756 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/internal/UnsignedXrayClientTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.internal;
import static com.amazonaws.xray.internal.UnsignedXrayClient.OBJECT_MAPPER;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.amazonaws.services.xray.model.GetSamplingRulesRequest;
import com.amazonaws.services.xray.model.GetSamplingRulesResult;
import com.amazonaws.services.xray.model.GetSamplingTargetsRequest;
import com.amazonaws.services.xray.model.GetSamplingTargetsResult;
import com.amazonaws.services.xray.model.SamplingStatisticsDocument;
import com.github.tomakehurst.wiremock.junit.WireMockClassRule;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
public class UnsignedXrayClientTest {
@ClassRule
public static WireMockClassRule server = new WireMockClassRule(wireMockConfig().dynamicPort());
private static final String SAMPLING_RULES =
"{\n"
+ " \"SamplingRuleRecords\": [\n"
+ " {\n"
+ " \"SamplingRule\": {\n"
+ " \"RuleName\": \"Default\",\n"
+ " \"RuleARN\": \"arn:aws:xray:us-east-1::sampling-rule/Default\",\n"
+ " \"ResourceARN\": \"*\",\n"
+ " \"Priority\": 10000,\n"
+ " \"FixedRate\": 0.01,\n"
+ " \"ReservoirSize\": 0,\n"
+ " \"ServiceName\": \"*\",\n"
+ " \"ServiceType\": \"*\",\n"
+ " \"Host\": \"*\",\n"
+ " \"HTTPMethod\": \"*\",\n"
+ " \"URLPath\": \"*\",\n"
+ " \"Version\": 1,\n"
+ " \"Attributes\": {}\n"
+ " },\n"
+ " \"CreatedAt\": 0.0,\n"
+ " \"ModifiedAt\": 1530558121.0\n"
+ " },\n"
+ " {\n"
+ " \"SamplingRule\": {\n"
+ " \"RuleName\": \"base-scorekeep\",\n"
+ " \"RuleARN\": \"arn:aws:xray:us-east-1::sampling-rule/base-scorekeep\",\n"
+ " \"ResourceARN\": \"*\",\n"
+ " \"Priority\": 9000,\n"
+ " \"FixedRate\": 0.1,\n"
+ " \"ReservoirSize\": 2,\n"
+ " \"ServiceName\": \"Scorekeep\",\n"
+ " \"ServiceType\": \"*\",\n"
+ " \"Host\": \"*\",\n"
+ " \"HTTPMethod\": \"*\",\n"
+ " \"URLPath\": \"*\",\n"
+ " \"Version\": 1,\n"
+ " \"Attributes\": {}\n"
+ " },\n"
+ " \"CreatedAt\": 1530573954.0,\n"
+ " \"ModifiedAt\": 1530920505.0\n"
+ " },\n"
+ " {\n"
+ " \"SamplingRule\": {\n"
+ " \"RuleName\": \"polling-scorekeep\",\n"
+ " \"RuleARN\": \"arn:aws:xray:us-east-1::sampling-rule/polling-scorekeep\",\n"
+ " \"ResourceARN\": \"*\",\n"
+ " \"Priority\": 5000,\n"
+ " \"FixedRate\": 0.003,\n"
+ " \"ReservoirSize\": 0,\n"
+ " \"ServiceName\": \"Scorekeep\",\n"
+ " \"ServiceType\": \"*\",\n"
+ " \"Host\": \"*\",\n"
+ " \"HTTPMethod\": \"GET\",\n"
+ " \"URLPath\": \"/api/state/*\",\n"
+ " \"Version\": 1,\n"
+ " \"Attributes\": {}\n"
+ " },\n"
+ " \"CreatedAt\": 1530918163.0,\n"
+ " \"ModifiedAt\": 1530918163.0\n"
+ " }\n"
+ " ]\n"
+ "}{\n"
+ " \"SamplingRuleRecords\": [\n"
+ " {\n"
+ " \"SamplingRule\": {\n"
+ " \"RuleName\": \"Default\",\n"
+ " \"RuleARN\": \"arn:aws:xray:us-east-1::sampling-rule/Default\",\n"
+ " \"ResourceARN\": \"*\",\n"
+ " \"Priority\": 10000,\n"
+ " \"FixedRate\": 0.01,\n"
+ " \"ReservoirSize\": 0,\n"
+ " \"ServiceName\": \"*\",\n"
+ " \"ServiceType\": \"*\",\n"
+ " \"Host\": \"*\",\n"
+ " \"HTTPMethod\": \"*\",\n"
+ " \"URLPath\": \"*\",\n"
+ " \"Version\": 1,\n"
+ " \"Attributes\": {}\n"
+ " },\n"
+ " \"CreatedAt\": 0.0,\n"
+ " \"ModifiedAt\": 1530558121.0\n"
+ " },\n"
+ " {\n"
+ " \"SamplingRule\": {\n"
+ " \"RuleName\": \"base-scorekeep\",\n"
+ " \"RuleARN\": \"arn:aws:xray:us-east-1::sampling-rule/base-scorekeep\",\n"
+ " \"ResourceARN\": \"*\",\n"
+ " \"Priority\": 9000,\n"
+ " \"FixedRate\": 0.1,\n"
+ " \"ReservoirSize\": 2,\n"
+ " \"ServiceName\": \"Scorekeep\",\n"
+ " \"ServiceType\": \"*\",\n"
+ " \"Host\": \"*\",\n"
+ " \"HTTPMethod\": \"*\",\n"
+ " \"URLPath\": \"*\",\n"
+ " \"Version\": 1,\n"
+ " \"Attributes\": {}\n"
+ " },\n"
+ " \"CreatedAt\": 1530573954.0,\n"
+ " \"ModifiedAt\": 1530920505.0\n"
+ " },\n"
+ " {\n"
+ " \"SamplingRule\": {\n"
+ " \"RuleName\": \"polling-scorekeep\",\n"
+ " \"RuleARN\": \"arn:aws:xray:us-east-1::sampling-rule/polling-scorekeep\",\n"
+ " \"ResourceARN\": \"*\",\n"
+ " \"Priority\": 5000,\n"
+ " \"FixedRate\": 0.003,\n"
+ " \"ReservoirSize\": 0,\n"
+ " \"ServiceName\": \"Scorekeep\",\n"
+ " \"ServiceType\": \"*\",\n"
+ " \"Host\": \"*\",\n"
+ " \"HTTPMethod\": \"GET\",\n"
+ " \"URLPath\": \"/api/state/*\",\n"
+ " \"Version\": 1,\n"
+ " \"Attributes\": {}\n"
+ " },\n"
+ " \"CreatedAt\": 1530918163.0,\n"
+ " \"ModifiedAt\": 1530918163.0\n"
+ " }\n"
+ " ]\n"
+ "}";
private static final String SAMPLING_TARGETS =
"{\n"
+ " \"SamplingTargetDocuments\": [\n"
+ " {\n"
+ " \"RuleName\": \"base-scorekeep\",\n"
+ " \"FixedRate\": 0.1,\n"
+ " \"ReservoirQuota\": 2,\n"
+ " \"ReservoirQuotaTTL\": 1530923107.0,\n"
+ " \"Interval\": 10\n"
+ " },\n"
+ " {\n"
+ " \"RuleName\": \"polling-scorekeep\",\n"
+ " \"FixedRate\": 0.003,\n"
+ " \"ReservoirQuota\": 0,\n"
+ " \"ReservoirQuotaTTL\": 1530923107.0,\n"
+ " \"Interval\": 10\n"
+ " }\n"
+ " ],\n"
+ " \"LastRuleModification\": 1530920505.0,\n"
+ " \"UnprocessedStatistics\": []\n"
+ "}{\n"
+ " \"SamplingTargetDocuments\": [\n"
+ " {\n"
+ " \"RuleName\": \"base-scorekeep\",\n"
+ " \"FixedRate\": 0.1,\n"
+ " \"ReservoirQuota\": 2,\n"
+ " \"ReservoirQuotaTTL\": 1530923107.0,\n"
+ " \"Interval\": 10\n"
+ " },\n"
+ " {\n"
+ " \"RuleName\": \"polling-scorekeep\",\n"
+ " \"FixedRate\": 0.003,\n"
+ " \"ReservoirQuota\": 0,\n"
+ " \"ReservoirQuotaTTL\": 1530923107.0,\n"
+ " \"Interval\": 10\n"
+ " }\n"
+ " ],\n"
+ " \"LastRuleModification\": 1530920505.0,\n"
+ " \"UnprocessedStatistics\": []\n"
+ "}";
private UnsignedXrayClient client;
@Before
public void setUp() {
client = new UnsignedXrayClient(server.baseUrl());
}
@Test
public void getSamplingRules() throws Exception {
stubFor(any(anyUrl()).willReturn(aResponse()
.withStatus(200)
.withBody(SAMPLING_RULES)));
GetSamplingRulesResult result = client.getSamplingRules(new GetSamplingRulesRequest());
GetSamplingRulesResult expected = OBJECT_MAPPER.readValue(SAMPLING_RULES, GetSamplingRulesResult.class);
assertThat(expected).isEqualTo(result);
verify(postRequestedFor(urlEqualTo("/GetSamplingRules"))
.withHeader("Content-Type", equalTo("application/json"))
.withRequestBody(equalToJson("{}")));
}
@Test
public void getSamplingTargets() throws Exception {
stubFor(any(anyUrl()).willReturn(aResponse()
.withStatus(200)
.withBody(SAMPLING_TARGETS)));
GetSamplingTargetsRequest request = new GetSamplingTargetsRequest()
.withSamplingStatisticsDocuments(new SamplingStatisticsDocument().withClientID("client-id"));
GetSamplingTargetsResult result = client.getSamplingTargets(request);
GetSamplingTargetsResult expected = OBJECT_MAPPER.readValue(SAMPLING_TARGETS, GetSamplingTargetsResult.class);
assertThat(expected).isEqualTo(result);
verify(postRequestedFor(urlEqualTo("/SamplingTargets"))
.withHeader("Content-Type", equalTo("application/json"))
.withRequestBody(equalToJson("{"
+ " \"SamplingStatisticsDocuments\": ["
+ " {"
+ " \"ClientID\": \"client-id\""
+ " }"
+ " ] "
+ "}")));
}
@Test
public void badStatus() {
String expectedMessage = "{\"message\": \"bad authentication\"}";
stubFor(any(anyUrl()).willReturn(aResponse()
.withStatus(500)
.withBody(expectedMessage)));
assertThatThrownBy(() -> client.getSamplingRules(new GetSamplingRulesRequest()))
.isInstanceOf(XrayClientException.class)
.hasMessageContaining(expectedMessage);
}
// This test may be flaky, it's not testing much so delete if it ever flakes.
@Test
public void cannotSend() {
client = new UnsignedXrayClient("http://localhost:" + (server.port() + 1234));
assertThatThrownBy(() -> client.getSamplingRules(new GetSamplingRulesRequest()))
.isInstanceOf(XrayClientException.class)
.hasMessageContaining("Could not serialize and send request");
}
}
| 3,757 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/utils/ByteUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.utils;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class ByteUtilsTest {
@Test
void testHexString() {
byte[] zeroArray = new byte[16];
assertThat(ByteUtils.byteArrayToHexString(zeroArray)).isEqualTo("00000000000000000000000000000000");
byte[] emptyArray = {};
assertThat(ByteUtils.byteArrayToHexString(emptyArray)).isEqualTo("");
byte[] zeroByte = {(byte) 0x00};
assertThat(ByteUtils.byteArrayToHexString(zeroByte)).isEqualTo("00");
byte[] fullByte = {(byte) 0xFF};
assertThat(ByteUtils.byteArrayToHexString(fullByte)).isEqualTo("FF");
byte[] leadingZero = {(byte) 0x0F};
assertThat(ByteUtils.byteArrayToHexString(leadingZero)).isEqualTo("0F");
byte[] longLeadingZero = {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x11};
assertThat(ByteUtils.byteArrayToHexString(longLeadingZero)).isEqualTo("00000000000011");
byte[] trailingZero = {(byte) 0x11, (byte) 0x00};
assertThat(ByteUtils.byteArrayToHexString(trailingZero)).isEqualTo("1100");
byte[] longTrailingZero = new byte[16];
longTrailingZero[0] = (byte) 0xFF;
assertThat(ByteUtils.byteArrayToHexString(longTrailingZero)).isEqualTo("FF000000000000000000000000000000");
byte[] basicArray =
{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0xF0, (byte) 0x0F, (byte) 0xFF};
assertThat(ByteUtils.byteArrayToHexString(basicArray)).isEqualTo("FFFFFF00FFF00FFF");
byte[] basicVariedArray =
{(byte) 0x82, (byte) 0xF2, (byte) 0xAB, (byte) 0xA4, (byte) 0xDE, (byte) 0x15, (byte) 0x19, (byte) 0x11};
assertThat(ByteUtils.byteArrayToHexString(basicVariedArray)).isEqualTo("82F2ABA4DE151911");
}
}
| 3,758 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/utils/DockerUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.utils;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class DockerUtilsTest {
private static final String DOCKER_ID = "79311de543c2b01bdbb7ccaf355e71a02b0726366a1427ecfceb5e1f5be81644";
@Test
void testEmptyCgroupFile() throws IOException {
DockerUtils dockerUtils = new DockerUtils(DockerUtilsTest.class.getResource("/com/amazonaws/xray/utils/emptyCgroup"));
String id = dockerUtils.getContainerId();
Assertions.assertNull(id);
}
@Test
void testInvalidCgroupFile() throws IOException {
DockerUtils dockerUtils = new DockerUtils(DockerUtilsTest.class.getResource("/com/amazonaws/xray/utils/invalidCgroup"));
String id = dockerUtils.getContainerId();
Assertions.assertNull(id);
}
@Test
void testValidFirstLineCgroupFile() throws IOException {
DockerUtils dockerUtils = new DockerUtils(DockerUtilsTest.class.getResource("/com/amazonaws/xray/utils/validCgroup"));
String id = dockerUtils.getContainerId();
Assertions.assertEquals(DOCKER_ID, id);
}
@Test
void testValidLaterLineCgroupFile() throws IOException {
DockerUtils dockerUtils = new DockerUtils(DockerUtilsTest.class.getResource(
"/com/amazonaws/xray/utils/validSecondCgroup"));
String id = dockerUtils.getContainerId();
Assertions.assertEquals(DOCKER_ID, id);
}
}
| 3,759 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/utils/JsonUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.utils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class JsonUtilsTest {
private static final String SINGLE_LOG_CONFIG = "[{\"log_group_name\":\"test_group\"}]";
private static final String MULTI_LOG_CONFIG = "[{\"log_group_name\":\"test_group1\"}, {\"log_group_name\":\"test_group2\"}, "
+ "{\"log_group_name\":\"test_group1\"}]";
private static final String SINGLE_LOG_CONFIG_WITH_STREAM = "[{\"log_group_name\":\"test_group\", "
+ "\"log_stream_name\":\"test_stream\"}]";
private static final String LOG_GROUP_NAME = "log_group_name";
private ObjectMapper mapper = new ObjectMapper();
@Test
void testGetLogGroup() throws IOException {
JsonNode node = mapper.readTree(SINGLE_LOG_CONFIG);
List<String> groupList = JsonUtils.getMatchingListFromJsonArrayNode(node, LOG_GROUP_NAME);
Assertions.assertEquals(1, groupList.size());
Assertions.assertEquals("test_group", groupList.get(0));
}
@Test
void testGetMultipleLogGroups() throws IOException {
JsonNode node = mapper.readTree(MULTI_LOG_CONFIG);
List<String> groupList = JsonUtils.getMatchingListFromJsonArrayNode(node, LOG_GROUP_NAME);
Assertions.assertEquals(3, groupList.size());
Assertions.assertTrue(groupList.contains("test_group1"));
Assertions.assertTrue(groupList.contains("test_group2"));
}
@Test
void testGetLogGroupWithStreamPresent() throws IOException {
JsonNode node = mapper.readTree(SINGLE_LOG_CONFIG_WITH_STREAM);
List<String> groupList = JsonUtils.getMatchingListFromJsonArrayNode(node, LOG_GROUP_NAME);
Assertions.assertEquals(1, groupList.size());
Assertions.assertEquals("test_group", groupList.get(0));
}
}
| 3,760 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/utils/LooseValidationsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.utils;
import static com.amazonaws.xray.utils.LooseValidations.checkNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import com.amazonaws.xray.utils.LooseValidations.ValidationMode;
import org.junit.jupiter.api.Test;
class LooseValidationsTest {
@Test
void checkNotNull_notNull() {
assertThat(checkNotNull("bar", "foo")).isTrue();
}
@Test
void checkNotNull_null() {
assertThat(checkNotNull(null, "foo")).isFalse();
}
@Test
void validationModeParsing() {
assertThat(LooseValidations.validationMode("none")).isEqualTo(ValidationMode.NONE);
assertThat(LooseValidations.validationMode("NONE")).isEqualTo(ValidationMode.NONE);
assertThat(LooseValidations.validationMode("log")).isEqualTo(ValidationMode.LOG);
// Check mixed case
assertThat(LooseValidations.validationMode("Log")).isEqualTo(ValidationMode.LOG);
assertThat(LooseValidations.validationMode("throw")).isEqualTo(ValidationMode.THROW);
assertThat(LooseValidations.validationMode("")).isEqualTo(ValidationMode.NONE);
assertThat(LooseValidations.validationMode("unknown")).isEqualTo(ValidationMode.NONE);
}
}
| 3,761 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/jakarta | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/jakarta/servlet/AWSXRayServletFilterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.jakarta.servlet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Cause;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceID;
import com.amazonaws.xray.strategy.jakarta.FixedSegmentNamingStrategy;
import com.amazonaws.xray.strategy.jakarta.SegmentNamingStrategy;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.AsyncEvent;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.runners.MethodSorters;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.powermock.reflect.Whitebox;
@FixMethodOrder(MethodSorters.JVM)
public class AWSXRayServletFilterTest {
@Rule
public EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Rule
public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
@Before
public void setupAWSXRay() {
AWSXRay.setGlobalRecorder(getMockRecorder());
AWSXRay.clearTraceEntity();
}
private AWSXRayRecorder getMockRecorder() {
Emitter blankEmitter = mock(Emitter.class);
LocalizedSamplingStrategy defaultSamplingStrategy = new LocalizedSamplingStrategy();
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
return AWSXRayRecorderBuilder.standard().withEmitter(blankEmitter).withSamplingStrategy(defaultSamplingStrategy).build();
}
private FilterChain mockChain(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FilterChain chain = mock(FilterChain.class);
AtomicReference<Entity> capturedEntity = new AtomicReference<>();
Mockito.doAnswer(a -> {
capturedEntity.set(AWSXRay.getTraceEntity());
return null;
}).when(chain).doFilter(request, response);
when(request.getAttribute("com.amazonaws.xray.entities.Entity"))
.thenAnswer(a -> Objects.requireNonNull(capturedEntity.get()));
return chain;
}
@Test
public void testAsyncServletRequestWithCompletedAsync() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("test");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenThrow(IllegalStateException.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mockChain(request, response);
AsyncEvent event = mock(AsyncEvent.class);
when(event.getSuppliedRequest()).thenReturn(request);
when(event.getSuppliedResponse()).thenReturn(response);
servletFilter.doFilter(request, response, chain);
Assert.assertNull(AWSXRay.getTraceEntity());
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(Mockito.any());
}
@Test
public void testAsyncServletRequestHasListenerAdded() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("test");
AsyncContext asyncContext = mock(AsyncContext.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenReturn(asyncContext);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
verify(asyncContext, Mockito.times(1)).addListener(Mockito.any());
}
@Test
public void testServletLazilyLoadsRecorder() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("test");
AsyncContext asyncContext = mock(AsyncContext.class);
AWSXRayRecorder customRecorder = Mockito.spy(getMockRecorder());
AWSXRay.setGlobalRecorder(customRecorder);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenReturn(asyncContext);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mockChain(request, response);
AsyncEvent event = mock(AsyncEvent.class);
when(event.getSuppliedRequest()).thenReturn(request);
when(event.getSuppliedResponse()).thenReturn(response);
servletFilter.doFilter(request, response, chain);
Assert.assertNull(AWSXRay.getTraceEntity());
AWSXRayServletAsyncListener listener = (AWSXRayServletAsyncListener) Whitebox.getInternalState(servletFilter, "listener");
listener.onComplete(event);
verify(customRecorder.getEmitter(), Mockito.times(1)).sendSegment(Mockito.any());
}
@Test
public void testServletUsesPassedInRecorder() throws IOException, ServletException {
AWSXRayRecorder customRecorder = Mockito.spy(getMockRecorder());
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter(new FixedSegmentNamingStrategy("test"), customRecorder);
AsyncContext asyncContext = mock(AsyncContext.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenReturn(asyncContext);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mockChain(request, response);
AsyncEvent event = mock(AsyncEvent.class);
when(event.getSuppliedRequest()).thenReturn(request);
when(event.getSuppliedResponse()).thenReturn(response);
servletFilter.doFilter(request, response, chain);
Assert.assertNull(AWSXRay.getTraceEntity());
AWSXRayServletAsyncListener listener = (AWSXRayServletAsyncListener) Whitebox.getInternalState(servletFilter, "listener");
listener.onComplete(event);
verify(customRecorder.getEmitter(), Mockito.times(1)).sendSegment(Mockito.any());
}
@Test
public void testAWSXRayServletAsyncListenerEmitsSegmentWhenProcessingEvent() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("test");
AsyncContext asyncContext = mock(AsyncContext.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenReturn(asyncContext);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mockChain(request, response);
AsyncEvent event = mock(AsyncEvent.class);
when(event.getSuppliedRequest()).thenReturn(request);
when(event.getSuppliedResponse()).thenReturn(response);
servletFilter.doFilter(request, response, chain);
Assert.assertNull(AWSXRay.getTraceEntity());
AWSXRayServletAsyncListener listener = (AWSXRayServletAsyncListener) Whitebox.getInternalState(servletFilter, "listener");
listener.onComplete(event);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(Mockito.any());
}
@Test
public void testNameOverrideEnvironmentVariable() throws IOException, ServletException {
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, "pass");
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Assert.assertEquals("pass", emittedSegment.getValue().getName());
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, null);
}
@Test
public void testSampledNoParent() throws IOException, ServletException {
Segment segment = doSegmentTest(null, AWSXRay.getGlobalRecorder());
assertThat(segment.isSampled()).isTrue();
assertThat(segment.getTraceId()).isNotEqualTo(TraceID.invalid());
assertThat(segment.getId()).isNotEmpty();
assertThat(segment.getParentId()).isNull();
}
@Test
public void testSampledWithParent() throws IOException, ServletException {
TraceID traceID = TraceID.create();
TraceHeader header = new TraceHeader(traceID, "1234567890123456");
Segment segment = doSegmentTest(header.toString(), AWSXRay.getGlobalRecorder());
assertThat(segment.isSampled()).isTrue();
assertThat(segment.getTraceId()).isEqualTo(traceID);
assertThat(segment.getId()).isNotEmpty();
assertThat(segment.getParentId()).isEqualTo("1234567890123456");
}
private static Segment doSegmentTest(
@Nullable String traceHeader, AWSXRayRecorder recorder) throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter(SegmentNamingStrategy.fixed("test"), recorder);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
when(request.getHeader(TraceHeader.HEADER_KEY)).thenReturn(traceHeader);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
return emittedSegment.getValue();
}
@Test
public void testNameOverrideSystemProperty() throws IOException, ServletException {
System.setProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY, "pass");
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Assert.assertEquals("pass", emittedSegment.getValue().getName());
}
@Test
public void testNameOverrideEnvironmentVariableOverridesSystemProperty() throws IOException, ServletException {
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, "pass");
System.setProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY, "fail");
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Assert.assertEquals("pass", emittedSegment.getValue().getName());
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, null);
}
@Test
public void testServletCatchesErrors() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
Error ourError = new StackOverflowError("Test");
Mockito.doThrow(ourError).when(chain).doFilter(Mockito.any(), Mockito.any());
assertThatThrownBy(() -> servletFilter.doFilter(request, response, chain)).isEqualTo(ourError);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Segment segment = emittedSegment.getValue();
Cause cause = segment.getCause();
Assert.assertEquals(1, cause.getExceptions().size());
Throwable storedThrowable = cause.getExceptions().get(0).getThrowable();
Assert.assertEquals(ourError, storedThrowable);
}
@Test
public void testServletCatchesExceptions() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
Exception ourException = new RuntimeException("Test");
Mockito.doThrow(ourException).when(chain).doFilter(Mockito.any(), Mockito.any());
assertThatThrownBy(() -> servletFilter.doFilter(request, response, chain)).isEqualTo(ourException);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Segment segment = emittedSegment.getValue();
Cause cause = segment.getCause();
Assert.assertEquals(1, cause.getExceptions().size());
Throwable storedThrowable = cause.getExceptions().get(0).getThrowable();
Assert.assertEquals(ourException, storedThrowable);
}
}
| 3,762 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/javax | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/javax/servlet/AWSXRayServletFilterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.javax.servlet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Cause;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceID;
import com.amazonaws.xray.strategy.FixedSegmentNamingStrategy;
import com.amazonaws.xray.strategy.SegmentNamingStrategy;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.runners.MethodSorters;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.powermock.reflect.Whitebox;
@FixMethodOrder(MethodSorters.JVM)
public class AWSXRayServletFilterTest {
@Rule
public EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Rule
public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
@Before
public void setupAWSXRay() {
AWSXRay.setGlobalRecorder(getMockRecorder());
AWSXRay.clearTraceEntity();
}
private AWSXRayRecorder getMockRecorder() {
Emitter blankEmitter = mock(Emitter.class);
LocalizedSamplingStrategy defaultSamplingStrategy = new LocalizedSamplingStrategy();
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
return AWSXRayRecorderBuilder.standard().withEmitter(blankEmitter).withSamplingStrategy(defaultSamplingStrategy).build();
}
private FilterChain mockChain(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FilterChain chain = mock(FilterChain.class);
AtomicReference<Entity> capturedEntity = new AtomicReference<>();
Mockito.doAnswer(a -> {
capturedEntity.set(AWSXRay.getTraceEntity());
return null;
}).when(chain).doFilter(request, response);
when(request.getAttribute("com.amazonaws.xray.entities.Entity"))
.thenAnswer(a -> Objects.requireNonNull(capturedEntity.get()));
return chain;
}
@Test
public void testAsyncServletRequestWithCompletedAsync() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("test");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenThrow(IllegalStateException.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mockChain(request, response);
AsyncEvent event = mock(AsyncEvent.class);
when(event.getSuppliedRequest()).thenReturn(request);
when(event.getSuppliedResponse()).thenReturn(response);
servletFilter.doFilter(request, response, chain);
Assert.assertNull(AWSXRay.getTraceEntity());
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(Mockito.any());
}
@Test
public void testAsyncServletRequestHasListenerAdded() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("test");
AsyncContext asyncContext = mock(AsyncContext.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenReturn(asyncContext);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
verify(asyncContext, Mockito.times(1)).addListener(Mockito.any());
}
@Test
public void testServletLazilyLoadsRecorder() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("test");
AsyncContext asyncContext = mock(AsyncContext.class);
AWSXRayRecorder customRecorder = Mockito.spy(getMockRecorder());
AWSXRay.setGlobalRecorder(customRecorder);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenReturn(asyncContext);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mockChain(request, response);
AsyncEvent event = mock(AsyncEvent.class);
when(event.getSuppliedRequest()).thenReturn(request);
when(event.getSuppliedResponse()).thenReturn(response);
servletFilter.doFilter(request, response, chain);
Assert.assertNull(AWSXRay.getTraceEntity());
AWSXRayServletAsyncListener listener = (AWSXRayServletAsyncListener) Whitebox.getInternalState(servletFilter, "listener");
listener.onComplete(event);
verify(customRecorder.getEmitter(), Mockito.times(1)).sendSegment(Mockito.any());
}
@Test
public void testServletUsesPassedInRecorder() throws IOException, ServletException {
AWSXRayRecorder customRecorder = Mockito.spy(getMockRecorder());
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter(new FixedSegmentNamingStrategy("test"), customRecorder);
AsyncContext asyncContext = mock(AsyncContext.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenReturn(asyncContext);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mockChain(request, response);
AsyncEvent event = mock(AsyncEvent.class);
when(event.getSuppliedRequest()).thenReturn(request);
when(event.getSuppliedResponse()).thenReturn(response);
servletFilter.doFilter(request, response, chain);
Assert.assertNull(AWSXRay.getTraceEntity());
AWSXRayServletAsyncListener listener = (AWSXRayServletAsyncListener) Whitebox.getInternalState(servletFilter, "listener");
listener.onComplete(event);
verify(customRecorder.getEmitter(), Mockito.times(1)).sendSegment(Mockito.any());
}
@Test
public void testAWSXRayServletAsyncListenerEmitsSegmentWhenProcessingEvent() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("test");
AsyncContext asyncContext = mock(AsyncContext.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(true);
when(request.getAsyncContext()).thenReturn(asyncContext);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mockChain(request, response);
AsyncEvent event = mock(AsyncEvent.class);
when(event.getSuppliedRequest()).thenReturn(request);
when(event.getSuppliedResponse()).thenReturn(response);
servletFilter.doFilter(request, response, chain);
Assert.assertNull(AWSXRay.getTraceEntity());
AWSXRayServletAsyncListener listener = (AWSXRayServletAsyncListener) Whitebox.getInternalState(servletFilter, "listener");
listener.onComplete(event);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(Mockito.any());
}
@Test
public void testNameOverrideEnvironmentVariable() throws IOException, ServletException {
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, "pass");
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Assert.assertEquals("pass", emittedSegment.getValue().getName());
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, null);
}
@Test
public void testSampledNoParent() throws IOException, ServletException {
Segment segment = doSegmentTest(null, AWSXRay.getGlobalRecorder());
assertThat(segment.isSampled()).isTrue();
assertThat(segment.getTraceId()).isNotEqualTo(TraceID.invalid());
assertThat(segment.getId()).isNotEmpty();
assertThat(segment.getParentId()).isNull();
}
@Test
public void testSampledWithParent() throws IOException, ServletException {
TraceID traceID = TraceID.create();
TraceHeader header = new TraceHeader(traceID, "1234567890123456");
Segment segment = doSegmentTest(header.toString(), AWSXRay.getGlobalRecorder());
assertThat(segment.isSampled()).isTrue();
assertThat(segment.getTraceId()).isEqualTo(traceID);
assertThat(segment.getId()).isNotEmpty();
assertThat(segment.getParentId()).isEqualTo("1234567890123456");
}
private static Segment doSegmentTest(
@Nullable String traceHeader, AWSXRayRecorder recorder) throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter(SegmentNamingStrategy.fixed("test"), recorder);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
when(request.getHeader(TraceHeader.HEADER_KEY)).thenReturn(traceHeader);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
return emittedSegment.getValue();
}
@Test
public void testNameOverrideSystemProperty() throws IOException, ServletException {
System.setProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY, "pass");
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Assert.assertEquals("pass", emittedSegment.getValue().getName());
}
@Test
public void testNameOverrideEnvironmentVariableOverridesSystemProperty() throws IOException, ServletException {
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, "pass");
System.setProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY, "fail");
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
servletFilter.doFilter(request, response, chain);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Assert.assertEquals("pass", emittedSegment.getValue().getName());
environmentVariables.set(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY, null);
}
@Test
public void testServletCatchesErrors() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
Error ourError = new StackOverflowError("Test");
Mockito.doThrow(ourError).when(chain).doFilter(Mockito.any(), Mockito.any());
assertThatThrownBy(() -> servletFilter.doFilter(request, response, chain)).isEqualTo(ourError);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Segment segment = emittedSegment.getValue();
Cause cause = segment.getCause();
Assert.assertEquals(1, cause.getExceptions().size());
Throwable storedThrowable = cause.getExceptions().get(0).getThrowable();
Assert.assertEquals(ourError, storedThrowable);
}
@Test
public void testServletCatchesExceptions() throws IOException, ServletException {
AWSXRayServletFilter servletFilter = new AWSXRayServletFilter("fail");
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new StringBuffer("test_url"));
when(request.getMethod()).thenReturn("TEST_METHOD");
when(request.isAsyncStarted()).thenReturn(false);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
Exception ourException = new RuntimeException("Test");
Mockito.doThrow(ourException).when(chain).doFilter(Mockito.any(), Mockito.any());
assertThatThrownBy(() -> servletFilter.doFilter(request, response, chain)).isEqualTo(ourException);
ArgumentCaptor<Segment> emittedSegment = ArgumentCaptor.forClass(Segment.class);
verify(AWSXRay.getGlobalRecorder().getEmitter(), Mockito.times(1)).sendSegment(emittedSegment.capture());
Segment segment = emittedSegment.getValue();
Cause cause = segment.getCause();
Assert.assertEquals(1, cause.getExceptions().size());
Throwable storedThrowable = cause.getExceptions().get(0).getThrowable();
Assert.assertEquals(ourException, storedThrowable);
}
}
| 3,763 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/emitters/UDPEmitterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.emitters;
import static com.amazonaws.xray.AWSXRay.getGlobalRecorder;
import static org.assertj.core.api.Assertions.assertThat;
import com.amazonaws.xray.config.DaemonConfiguration;
import com.amazonaws.xray.entities.DummySegment;
import java.net.SocketException;
import org.junit.jupiter.api.Test;
class UDPEmitterTest {
@Test
void testCustomAddress() throws SocketException {
String address = "123.4.5.6:1234";
DaemonConfiguration config = getDaemonConfiguration(address);
UDPEmitter emitter = new UDPEmitter(config);
assertThat(emitter.getUDPAddress()).isEqualTo(address);
}
@Test
void sendingSegmentShouldNotThrowExceptions() throws SocketException {
DaemonConfiguration config = getDaemonConfiguration("__udpemittertest_unresolvable__:1234");
UDPEmitter emitter = new UDPEmitter(config);
boolean success = emitter.sendSegment(new DummySegment(getGlobalRecorder()));
assertThat(success).isFalse();
}
protected DaemonConfiguration getDaemonConfiguration(final String address) {
DaemonConfiguration config = new DaemonConfiguration();
config.setDaemonAddress(address);
return config;
}
}
| 3,764 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/emitters/DelegatingEmitterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.emitters;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class DelegatingEmitterTest {
@Rule
public MockitoRule mocks = MockitoJUnit.rule();
@Mock
private Emitter emitter;
@Mock
private Segment segment;
@Mock
private Subsegment subsegment;
@Before
public void setUp() {
when(emitter.sendSegment(any())).thenReturn(true);
when(emitter.sendSubsegment(any())).thenReturn(true);
}
@Test
public void delegates() {
Emitter delegator = new DelegatingEmitter(emitter);
assertThat(delegator.sendSegment(segment)).isTrue();
verify(emitter).sendSegment(segment);
assertThat(delegator.sendSubsegment(subsegment)).isTrue();
verify(emitter).sendSubsegment(subsegment);
}
}
| 3,765 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/listeners/SegmentListenerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.listeners;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class SegmentListenerTest {
static class CustomSegmentListener implements SegmentListener {
@Override
public void onBeginSegment(Segment segment) {
segment.putAnnotation("beginTest", "isPresent");
}
@Override
public void onBeginSubsegment(Subsegment subsegment) {
subsegment.putAnnotation("subAnnotation1", "began");
}
@Override
public void beforeEndSegment(Segment segment) {
segment.putAnnotation("endTest", "isPresent");
}
@Override
public void beforeEndSubsegment(Subsegment subsegment) {
subsegment.putAnnotation("subAnnotation2", "ended");
}
}
static class SecondSegmentListener implements SegmentListener {
private int testVal = 0;
private int testVal2 = 0;
@Override
public void onBeginSegment(Segment segment) {
testVal = 1;
}
@Override
public void beforeEndSegment(Segment segment) {
testVal2 = 1;
}
int getTestVal() {
return testVal;
}
int getTestVal2() {
return testVal2;
}
}
@BeforeEach
void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.any());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.any());
CustomSegmentListener segmentListener = new CustomSegmentListener();
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard()
.withEmitter(blankEmitter)
.withSegmentListener(segmentListener)
.build());
AWSXRay.clearTraceEntity();
}
@Test
void testOnBeginSegment() {
Segment test = AWSXRay.beginSegment("test");
String beginAnnotation = test.getAnnotations().get("beginTest").toString();
Assertions.assertEquals("isPresent", beginAnnotation);
AWSXRay.endSegment();
}
@Test
void testOnEndSegment() {
Segment test = AWSXRay.beginSegment("test");
AWSXRay.endSegment();
String endAnnotation = test.getAnnotations().get("endTest").toString();
Assertions.assertEquals("isPresent", endAnnotation);
}
@Test
void testSubsegmentListeners() {
AWSXRay.beginSegment("test");
Subsegment sub = AWSXRay.beginSubsegment("testSub");
String beginAnnotation = sub.getAnnotations().get("subAnnotation1").toString();
AWSXRay.endSubsegment();
String endAnnotation = sub.getAnnotations().get("subAnnotation2").toString();
Assertions.assertEquals("began", beginAnnotation);
Assertions.assertEquals("ended", endAnnotation);
}
@Test
void testMultipleSegmentListeners() {
SecondSegmentListener secondSegmentListener = new SecondSegmentListener();
AWSXRay.getGlobalRecorder().addSegmentListener(secondSegmentListener);
Segment test = AWSXRay.beginSegment("test");
String beginAnnotation = test.getAnnotations().get("beginTest").toString();
Assertions.assertEquals(1, secondSegmentListener.getTestVal());
Assertions.assertEquals("isPresent", beginAnnotation);
AWSXRay.endSegment();
String endAnnotation = test.getAnnotations().get("endTest").toString();
Assertions.assertEquals("isPresent", endAnnotation);
Assertions.assertEquals(1, secondSegmentListener.getTestVal2());
}
}
| 3,766 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/entities/TraceIDTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.entities;
import static org.assertj.core.api.Assertions.assertThat;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import java.time.Instant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
class TraceIDTest {
@BeforeAll
static void beforeAll() {
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.defaultRecorder());
}
// Chance this test passes once even when broken but inconceivable to pass several times.
@RepeatedTest(10)
void create() {
int startTimeSecs = (int) Instant.now().getEpochSecond();
TraceID traceID = TraceID.create();
assertThat(Integer.parseInt(traceID.getStartTimeAsHex(), 16)).isGreaterThanOrEqualTo(startTimeSecs);
assertThat(Integer.parseInt(traceID.getStartTimeAsHex(), 16)).isEqualTo(traceID.getStartTime());
assertThat(traceID.getNumberAsHex()).hasSize(24).satisfies(TraceID::isHex);
assertThat(traceID.getNumberAsHex()).isEqualTo(padLeft(traceID.getNumber().toString(16), 24));
}
@Test
void fromString() {
TraceID traceID = TraceID.fromString("1-57ff426a-80c11c39b0c928905eb0828d");
assertThat(traceID.getStartTimeAsHex()).isEqualTo("57ff426a");
assertThat(traceID.getNumberAsHex()).isEqualTo("80c11c39b0c928905eb0828d");
}
@Test
void fromString_invalidLength() {
TraceID traceID = TraceID.fromString("1-57ff426a-80c11c39b0c928905eb0828d1");
// Invalid means new trace ID so epoch will not match.
assertThat(traceID.getStartTimeAsHex()).isNotEqualTo("57ff426a");
}
@Test
void fromString_invalidVersion() {
TraceID traceID = TraceID.fromString("2-57ff426a-80c11c39b0c928905eb0828d");
// Invalid means new trace ID so epoch will not match.
assertThat(traceID.getStartTimeAsHex()).isNotEqualTo("57ff426a");
}
@Test
void fromString_invalidDelimiter1() {
TraceID traceID = TraceID.fromString("2+57ff426a-80c11c39b0c928905eb0828d");
// Invalid means new trace ID so epoch will not match.
assertThat(traceID.getStartTimeAsHex()).isNotEqualTo("57ff426a");
}
@Test
void fromString_invalidDelimiter2() {
TraceID traceID = TraceID.fromString("2+57ff426a+80c11c39b0c928905eb0828d");
// Invalid means new trace ID so epoch will not match.
assertThat(traceID.getStartTimeAsHex()).isNotEqualTo("57ff426a");
}
@Test
void fromString_invalidStartTime() {
TraceID traceID = TraceID.fromString("2+57fg426a+80c11c39b0c928905eb0828d");
// Invalid means new trace ID so epoch will not match.
assertThat(traceID.getStartTimeAsHex()).isNotEqualTo("57ff426a");
}
@Test
void fromString_invalidNumber() {
TraceID traceID = TraceID.fromString("2+57ff426a+80c11c39b0c928905gb0828d");
// Invalid means new trace ID so epoch will not match.
assertThat(traceID.getStartTimeAsHex()).isNotEqualTo("57ff426a");
}
private static String padLeft(String str, int size) {
if (str.length() == size) {
return str;
}
StringBuilder padded = new StringBuilder(size);
for (int i = str.length(); i < size; i++) {
padded.append('0');
}
padded.append(str);
return padded.toString();
}
}
| 3,767 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/entities/AWSLogReferenceTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.entities;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class AWSLogReferenceTest {
AWSLogReference referenceA;
AWSLogReference referenceB;
AWSLogReference differentArn;
AWSLogReference differentGroup;
@BeforeEach
void setup() {
referenceA = new AWSLogReference();
referenceB = new AWSLogReference();
differentArn = new AWSLogReference();
differentGroup = new AWSLogReference();
referenceA.setLogGroup("TEST");
referenceA.setArn("arn:aws:test");
referenceB.setLogGroup("TEST");
referenceB.setArn("arn:aws:test");
differentArn.setLogGroup("TEST");
differentArn.setArn("arn:aws:nottest");
differentGroup.setLogGroup("NOTTEST");
differentGroup.setArn("arn:aws:test");
}
// Test case for equals.
@SuppressWarnings("SelfEquals")
@Test
void testEqualityPositive() {
Assertions.assertTrue(referenceA.equals(referenceB));
Assertions.assertTrue(referenceB.equals(referenceA));
Assertions.assertTrue(referenceA.equals(referenceA));
}
@Test
void testEqualityNegativeBecauseArn() {
Assertions.assertEquals(false, referenceA.equals(differentArn));
Assertions.assertEquals(false, differentArn.equals(referenceA));
}
@Test
void testEqualityNegativeBecauseGroup() {
Assertions.assertEquals(false, referenceA.equals(differentGroup));
Assertions.assertEquals(false, differentGroup.equals(referenceA));
}
}
| 3,768 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/entities/EntityTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.entities;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import com.amazonaws.xray.AWSXRay;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class EntityTest {
@BeforeEach
void setup() {
AWSXRay.clearTraceEntity();
}
@Test
void testDurationSerialization() {
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test");
seg.putMetadata("millisecond", Duration.ofMillis(3));
seg.putMetadata("second", Duration.ofSeconds(1));
seg.putMetadata("minute", Duration.ofMinutes(55));
String serializedSeg = seg.serialize();
String expected = "{\"default\":{\"millisecond\":0.003000000,\"second\":1.000000000,\"minute\":3300.000000000}}";
assertThat(serializedSeg).contains(expected);
}
@Test
void testTimestampSerialization() {
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test");
seg.putMetadata("instant", Instant.ofEpochSecond(1616559298));
String serializedSeg = seg.serialize();
String expected = "{\"default\":{\"instant\":1616559298.000000000}}";
assertThat(serializedSeg).contains(expected);
}
/**
* Dates are serialized into millisecond integers rather than second doubles because anything beyond millisecond
* accuracy is meaningless for Dates: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
*/
@Test
void testDateSerialization() {
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test");
seg.putMetadata("date", Date.from(Instant.ofEpochSecond(1616559298)));
String serializedSeg = seg.serialize();
String expected = "{\"default\":{\"date\":1616559298000}}";
assertThat(serializedSeg).contains(expected);
}
@Test
void testUnknownClassSerialization() {
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test");
seg.putAws("coolService", new EmptyBean());
seg.end();
seg.serialize(); // Verify we don't crash here
}
@Test
void testPrecursorIds() {
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test");
SubsegmentImpl subseg = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", seg);
subseg.addPrecursorId("myId1");
subseg.addPrecursorId("myId2");
String serializedSubSeg = subseg.serialize();
String expected = "\"precursor_ids\":[\"myId1\",\"myId2\"]";
assertThat(serializedSubSeg).contains(expected);
}
static class EmptyBean {
String otherField = "cerealization";
}
}
| 3,769 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/entities/SearchPatternTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.entities;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Random;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SearchPatternTest {
@Test
void testInvalidArgs() {
Assertions.assertFalse(SearchPattern.wildcardMatch(null, ""));
Assertions.assertFalse(SearchPattern.wildcardMatch("", null));
Assertions.assertFalse(SearchPattern.wildcardMatch("", "whatever"));
}
@Test
void testMatchExactPositive() throws Exception {
final String pat = "foo";
final String str = "foo";
assertTrue(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testMatchExactNegative() throws Exception {
final String pat = "foo";
final String str = "bar";
Assertions.assertFalse(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testSingleWildcardPositive() throws Exception {
final String pat = "fo?";
final String str = "foo";
assertTrue(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testSingleWildcardNegative() throws Exception {
final String pat = "f?o";
final String str = "boo";
Assertions.assertFalse(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testMultipleWildcardPositive() throws Exception {
final String pat = "?o?";
final String str = "foo";
assertTrue(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testMultipleWildcardNegative() throws Exception {
final String pat = "f??";
final String str = "boo";
Assertions.assertFalse(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testGlobPositive() throws Exception {
final String pat = "*oo";
final String str = "foo";
assertTrue(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testGlobPositiveZeroOrMore() throws Exception {
final String pat = "foo*";
final String str = "foo";
assertTrue(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testGlobNegativeZeroOrMore() throws Exception {
final String pat = "foo*";
final String str = "fo0";
Assertions.assertFalse(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testGlobNegative() throws Exception {
final String pat = "fo*";
final String str = "boo";
Assertions.assertFalse(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testGlobAndSinglePositive() throws Exception {
final String pat = "*o?";
final String str = "foo";
assertTrue(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testGlobAndSingleNegative() throws Exception {
final String pat = "f?*";
final String str = "boo";
Assertions.assertFalse(SearchPattern.wildcardMatch(pat, str));
}
@Test
void testPureWildcard() throws Exception {
final String pat = "*";
final String str = "foo";
assertTrue(SearchPattern.wildcardMatch(pat, str));
}
@Test
void exactMatch() throws Exception {
assertTrue(SearchPattern.wildcardMatch("6543210", "6543210"));
}
@Test
void testMisc() throws Exception {
final String animal1 = "?at";
final String animal2 = "?o?se";
final String animal3 = "*s";
final String vehicle1 = "J*";
final String vehicle2 = "????";
assertTrue(SearchPattern.wildcardMatch(animal1, "bat"));
assertTrue(SearchPattern.wildcardMatch(animal1, "cat"));
assertTrue(SearchPattern.wildcardMatch(animal2, "horse"));
assertTrue(SearchPattern.wildcardMatch(animal2, "mouse"));
assertTrue(SearchPattern.wildcardMatch(animal3, "dogs"));
assertTrue(SearchPattern.wildcardMatch(animal3, "horses"));
assertTrue(SearchPattern.wildcardMatch(vehicle1, "Jeep"));
assertTrue(SearchPattern.wildcardMatch(vehicle2, "ford"));
Assertions.assertFalse(SearchPattern.wildcardMatch(vehicle2, "chevy"));
assertTrue(SearchPattern.wildcardMatch("*", "cAr"));
assertTrue(SearchPattern.wildcardMatch("*/foo", "/bar/foo"));
}
@Test
void testCaseInsensitivity() throws Exception {
assertTrue(SearchPattern.wildcardMatch("Foo", "Foo", false));
assertTrue(SearchPattern.wildcardMatch("Foo", "Foo", true));
Assertions.assertFalse(SearchPattern.wildcardMatch("Foo", "FOO", false));
assertTrue(SearchPattern.wildcardMatch("Foo", "FOO", true));
assertTrue(SearchPattern.wildcardMatch("Fo*", "Foo0", false));
assertTrue(SearchPattern.wildcardMatch("Fo*", "Foo0", true));
Assertions.assertFalse(SearchPattern.wildcardMatch("Fo*", "FOo0", false));
assertTrue(SearchPattern.wildcardMatch("Fo*", "FOO0", true));
assertTrue(SearchPattern.wildcardMatch("Fo?", "Foo", false));
assertTrue(SearchPattern.wildcardMatch("Fo?", "Foo", true));
Assertions.assertFalse(SearchPattern.wildcardMatch("Fo?", "FOo", false));
assertTrue(SearchPattern.wildcardMatch("Fo?", "FoO", false));
assertTrue(SearchPattern.wildcardMatch("Fo?", "FOO", true));
}
@Test
void testLongStrings() throws Exception {
// This blew out the stack on a recursive version of wildcardMatch
final char[] t = new char[] { 'a', 'b', 'c', 'd' };
StringBuffer text = new StringBuffer("a");
Random r = new Random();
int size = 8192;
for (int i = 0; i < size; i++) {
text.append(t[r.nextInt(Integer.MAX_VALUE) % t.length]);
}
text.append("b");
assertTrue(SearchPattern.wildcardMatch("a*b", text.toString()));
}
@Test
void testNoGlobs() throws Exception {
Assertions.assertFalse(SearchPattern.wildcardMatch("abcd", "abc"));
}
@Test
void testEdgeCaseGlobs() throws Exception {
assertTrue(SearchPattern.wildcardMatch("", ""));
assertTrue(SearchPattern.wildcardMatch("a", "a"));
assertTrue(SearchPattern.wildcardMatch("*a", "a"));
assertTrue(SearchPattern.wildcardMatch("*a", "ba"));
assertTrue(SearchPattern.wildcardMatch("a*", "a"));
assertTrue(SearchPattern.wildcardMatch("a*", "ab"));
assertTrue(SearchPattern.wildcardMatch("a*a", "aa"));
assertTrue(SearchPattern.wildcardMatch("a*a", "aba"));
assertTrue(SearchPattern.wildcardMatch("a*a", "aaa"));
assertTrue(SearchPattern.wildcardMatch("a*a*", "aa"));
assertTrue(SearchPattern.wildcardMatch("a*a*", "aba"));
assertTrue(SearchPattern.wildcardMatch("a*a*", "aaa"));
assertTrue(SearchPattern.wildcardMatch("a*a*", "aaaaaaaaaaaaaaaaaaaaaaa"));
assertTrue(SearchPattern.wildcardMatch(
"a*b*a*b*a*b*a*b*a*",
"akljd9gsdfbkjhaabajkhbbyiaahkjbjhbuykjakjhabkjhbabjhkaabbabbaaakljdfsjklababkjbsdabab"));
Assertions.assertFalse(SearchPattern.wildcardMatch("a*na*ha", "anananahahanahana"));
}
@Test
void testMultiGlobs() throws Exception {
// Technically, '**' isn't well defined Balsa, but the wildcardMatch should do the right thing with it.
assertTrue(SearchPattern.wildcardMatch("*a", "a"));
assertTrue(SearchPattern.wildcardMatch("**a", "a"));
assertTrue(SearchPattern.wildcardMatch("***a", "a"));
assertTrue(SearchPattern.wildcardMatch("**a*", "a"));
assertTrue(SearchPattern.wildcardMatch("**a**", "a"));
assertTrue(SearchPattern.wildcardMatch("a**b", "ab"));
assertTrue(SearchPattern.wildcardMatch("a**b", "abb"));
assertTrue(SearchPattern.wildcardMatch("*?", "a"));
assertTrue(SearchPattern.wildcardMatch("*?", "aa"));
assertTrue(SearchPattern.wildcardMatch("*??", "aa"));
Assertions.assertFalse(SearchPattern.wildcardMatch("*???", "aa"));
assertTrue(SearchPattern.wildcardMatch("*?", "aaa"));
assertTrue(SearchPattern.wildcardMatch("?", "a"));
Assertions.assertFalse(SearchPattern.wildcardMatch("??", "a"));
assertTrue(SearchPattern.wildcardMatch("?*", "a"));
assertTrue(SearchPattern.wildcardMatch("*?", "a"));
Assertions.assertFalse(SearchPattern.wildcardMatch("?*?", "a"));
assertTrue(SearchPattern.wildcardMatch("?*?", "aa"));
assertTrue(SearchPattern.wildcardMatch("*?*", "a"));
Assertions.assertFalse(SearchPattern.wildcardMatch("*?*a", "a"));
assertTrue(SearchPattern.wildcardMatch("*?*a*", "ba"));
}
}
| 3,770 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/DefaultStreamingStrategyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorderBuilder;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.FacadeSegment;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.SegmentImpl;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.SubsegmentImpl;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceID;
import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
@FixMethodOrder(MethodSorters.JVM)
public class DefaultStreamingStrategyTest {
@Before
public void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
LocalizedSamplingStrategy defaultSamplingStrategy = new LocalizedSamplingStrategy();
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject());
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard()
.withEmitter(blankEmitter)
.withSamplingStrategy(defaultSamplingStrategy)
.build());
AWSXRay.clearTraceEntity();
}
@Test
public void testDefaultStreamingStrategyRequiresStreaming() {
DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1);
Segment smallSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "small");
Assert.assertFalse(defaultStreamingStrategy.requiresStreaming(smallSegment));
Segment bigSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "big");
bigSegment.addSubsegment(new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child", bigSegment));
bigSegment.addSubsegment(new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child", bigSegment));
Assert.assertTrue(defaultStreamingStrategy.requiresStreaming(bigSegment));
}
@Test
public void testDefaultStreamingStrategyDoesNotRequireStreaming() {
DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1);
Segment smallSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "small");
Assert.assertFalse(defaultStreamingStrategy.requiresStreaming(smallSegment));
}
@Test
public void testingBasicStreamingFunctionality() {
DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1);
TraceID traceId = new TraceID();
Segment segment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceId);
Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", segment);
Subsegment subsegment1 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", segment);
segment.addSubsegment(subsegment);
segment.addSubsegment(subsegment1);
segment.setStartTime(1.0);
subsegment.setStartTime(1.0);
subsegment1.setStartTime(1.0);
subsegment.end();
defaultStreamingStrategy.streamSome(segment, AWSXRay.getGlobalRecorder().getEmitter());
Assert.assertTrue(segment.getTotalSize().intValue() == 1);
}
//test to see if the correct actions are being taken in streamSome (children get removed from parent)
@Test
public void testStreamSomeChildrenRemovedFromParent() {
TraceID traceId = new TraceID();
DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1);
Segment bigSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "big", traceId);
bigSegment.setStartTime(1.0);
for (int i = 0; i < 5; i++) {
Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "child" + i, bigSegment);
subsegment.setStartTime(1.0);
bigSegment.addSubsegment(subsegment);
subsegment.end();
}
Assert.assertTrue(defaultStreamingStrategy.requiresStreaming(bigSegment));
defaultStreamingStrategy.streamSome(bigSegment, AWSXRay.getGlobalRecorder().getEmitter());
Assert.assertTrue(bigSegment.getTotalSize().intValue() == 0);
}
//test to see if the correct actions are being taken in streamSome (children do NOT get removed from parent due to subsegments
//being in progress.)
@Test
public void testStreamSomeChildrenNotRemovedFromParent() {
TraceID traceId = new TraceID();
DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1);
Segment bigSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "big", traceId);
bigSegment.setStartTime(1.0);
for (int i = 0; i < 5; i++) {
Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "child" + i, bigSegment);
subsegment.setStartTime(1.0);
bigSegment.addSubsegment(subsegment);
}
Assert.assertTrue(defaultStreamingStrategy.requiresStreaming(bigSegment));
defaultStreamingStrategy.streamSome(bigSegment, AWSXRay.getGlobalRecorder().getEmitter());
Assert.assertTrue(bigSegment.getTotalSize().intValue() == 5);
}
@Test
public void testMultithreadedStreamSome() {
DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1);
Segment segment = AWSXRay.beginSegment("big");
Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "subsegment1", segment);
subsegment.setStartTime(1.0);
segment.addSubsegment(subsegment);
subsegment.end();
Thread thread1 = new Thread(() -> {
AWSXRay.setTraceEntity(segment);
AWSXRay.beginSubsegment("thread1");
AWSXRay.endSubsegment();
});
Thread thread2 = new Thread(() -> {
AWSXRay.setTraceEntity(segment);
AWSXRay.beginSubsegment("thread2");
AWSXRay.endSubsegment();
});
thread1.start();
thread2.start();
for (Thread thread : new Thread[]{thread1, thread2}) {
try {
thread.join();
} catch (InterruptedException e) {
return;
}
}
Assert.assertTrue(AWSXRay.getTraceEntity().getName().equals("big"));
//asserts that all subsegments are added correctly.
Assert.assertTrue(AWSXRay.getTraceEntity().getTotalSize().intValue() == 3);
defaultStreamingStrategy.streamSome(segment, AWSXRay.getGlobalRecorder().getEmitter());
Assert.assertTrue(segment.getTotalSize().intValue() == 0);
}
@Test
public void testBushyandSpindlySegmentTreeStreaming() {
TraceID traceId = new TraceID();
Segment bigSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "big", traceId);
bigSegment.setStartTime(1.0);
for (int i = 0; i < 5; i++) {
Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "child" + i, bigSegment);
subsegment.setStartTime(1.0);
bigSegment.addSubsegment(subsegment);
subsegment.end();
}
SubsegmentImpl holder = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child0", bigSegment);
holder.setStartTime(1.0);
bigSegment.addSubsegment(holder);
holder.end();
SubsegmentImpl holder1 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child1", bigSegment);
holder1.setStartTime(1.0);
bigSegment.addSubsegment(holder1);
holder1.end();
SubsegmentImpl holder2 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child2", bigSegment);
holder2.setStartTime(1.0);
bigSegment.addSubsegment(holder2);
holder2.end();
DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1);
Assert.assertTrue(defaultStreamingStrategy.requiresStreaming(bigSegment));
defaultStreamingStrategy.streamSome(bigSegment, AWSXRay.getGlobalRecorder().getEmitter());
Assert.assertTrue(bigSegment.getReferenceCount() == 0);
}
@SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class)
public void testDefaultStreamingStrategyMaxSegmentSizeParameterValidation() {
DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(-1);
}
//test to see if FacadeSegment can be streamed out correctly
@Test
public void testDefaultStreamingStrategyForLambdaTraceContext() {
DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1);
//if FacadeSegment size is larger than maxSegmentSize and only the first subsegment is completed, first subsegment will be
//streamed out
FacadeSegment facadeSegmentOne = new FacadeSegment(AWSXRay.getGlobalRecorder(), new TraceID(), "",
TraceHeader.SampleDecision.SAMPLED);
Subsegment firstSubsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "FirstSubsegment", facadeSegmentOne);
Subsegment secondSubsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "SecondSubsegment", facadeSegmentOne);
facadeSegmentOne.addSubsegment(firstSubsegment);
facadeSegmentOne.addSubsegment(secondSubsegment);
firstSubsegment.end();
Assert.assertTrue(facadeSegmentOne.getTotalSize().intValue() == 2);
defaultStreamingStrategy.streamSome(facadeSegmentOne, AWSXRay.getGlobalRecorder().getEmitter());
Assert.assertTrue(facadeSegmentOne.getTotalSize().intValue() == 1);
Subsegment tempOne = facadeSegmentOne.getSubsegments().get(0);
Assert.assertEquals("SecondSubsegment", tempOne.getName());
//if FarcadeSegment size is larger than maxSegmentSize and only the second subsegment is completed, second subsegment will
//be streamed out
FacadeSegment facadeSegmentTwo = new FacadeSegment(AWSXRay.getGlobalRecorder(), new TraceID(), "",
TraceHeader.SampleDecision.SAMPLED);
Subsegment thirdSubsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "ThirdSubsegment", facadeSegmentTwo);
Subsegment fourthSubsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "FourthSubsegment", facadeSegmentTwo);
facadeSegmentTwo.addSubsegment(thirdSubsegment);
facadeSegmentTwo.addSubsegment(fourthSubsegment);
fourthSubsegment.end();
Assert.assertTrue(facadeSegmentTwo.getTotalSize().intValue() == 2);
defaultStreamingStrategy.streamSome(facadeSegmentTwo, AWSXRay.getGlobalRecorder().getEmitter());
Assert.assertTrue(facadeSegmentTwo.getTotalSize().intValue() == 1);
Subsegment tempTwo = facadeSegmentTwo.getSubsegments().get(0);
Assert.assertEquals("ThirdSubsegment", tempTwo.getName());
}
}
| 3,771 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling/SamplingRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SamplingRequestTest {
@Test
void testSuccessfulAccountIdParsing() {
SamplingRequest req = new SamplingRequest(
"arn:aws:iam::123456789123:role/sample-role",
null,
null,
null,
null,
null,
null,
null
);
Assertions.assertEquals(req.getAccountId().get(), "123456789123");
}
}
| 3,772 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling/LocalizedSamplingStrategyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling;
import com.amazonaws.xray.strategy.sampling.rule.SamplingRule;
import java.net.URL;
import java.util.ArrayList;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.powermock.reflect.Whitebox;
@FixMethodOrder(MethodSorters.JVM)
public class LocalizedSamplingStrategyTest {
@Test
public void testLocalizedSamplingStrategyWithDefaultRules() {
LocalizedSamplingStrategy localizedSamplingStrategy = new LocalizedSamplingStrategy();
assertDefaultRulesSet(localizedSamplingStrategy);
}
@Test
public void testLocalizedSamplingStrategyWithInvalidURL() {
URL emptySamplingRules = LocalizedSamplingStrategyTest.class.getResource("DoesntExist.json");
LocalizedSamplingStrategy localizedSamplingStrategy = new LocalizedSamplingStrategy(emptySamplingRules);
assertDefaultRulesSet(localizedSamplingStrategy);
}
private void assertDefaultRulesSet(LocalizedSamplingStrategy localizedSamplingStrategy) {
@SuppressWarnings("unchecked")
ArrayList<SamplingRule> internalRules = (ArrayList<SamplingRule>) Whitebox.getInternalState(localizedSamplingStrategy,
"rules");
SamplingRule defaultRule = (SamplingRule) Whitebox.getInternalState(localizedSamplingStrategy, "defaultRule");
Assert.assertEquals(0, internalRules.size());
Assert.assertNull(defaultRule.getServiceName());
Assert.assertNull(defaultRule.getHttpMethod());
Assert.assertNull(defaultRule.getUrlPath());
Assert.assertEquals(1, defaultRule.getFixedTarget());
Assert.assertEquals(0.05, defaultRule.getRate(), 0.0000001);
}
@Test(expected = RuntimeException.class)
public void testLocalizedSamplingStrategyWithoutDefaultRuleThrowsRuntimeException() {
URL emptySamplingRules = LocalizedSamplingStrategyTest.class.getResource(
"/com/amazonaws/xray/strategy/sampling/EmptySamplingRules.json");
new LocalizedSamplingStrategy(emptySamplingRules);
}
@Test(expected = RuntimeException.class)
public void testLocalizedSamplingStrategyWithExtraAttributesOnDefaultRuleThrowsRuntimeException() {
URL emptySamplingRules = LocalizedSamplingStrategyTest.class.getResource(
"/com/amazonaws/xray/strategy/sampling/ExtraAttributesOnDefaultSamplingRules.json");
new LocalizedSamplingStrategy(emptySamplingRules);
}
@Test(expected = RuntimeException.class)
public void testLocalizedSamplingStrategyWithMissingAttributesThrowsRuntimeException() {
URL emptySamplingRules = LocalizedSamplingStrategyTest.class.getResource(
"/com/amazonaws/xray/strategy/sampling/MissingAttributesSamplingRules.json");
LocalizedSamplingStrategy localizedSamplingStrategy = new LocalizedSamplingStrategy(emptySamplingRules);
SamplingRequest samplingRequest = new SamplingRequest("", "test", "/test", "test", "");
SamplingResponse sr = localizedSamplingStrategy.shouldTrace(samplingRequest);
Assert.assertFalse(sr.isSampled());
}
@Test(expected = RuntimeException.class)
public void testLocalizedSamplingStrategyWithOneRuleMissingAttributesThrowsRuntimeException() {
URL emptySamplingRules = LocalizedSamplingStrategyTest.class.getResource(
"/com/amazonaws/xray/strategy/sampling/OneRuleMissingAttributesSamplingRules.json");
LocalizedSamplingStrategy localizedSamplingStrategy = new LocalizedSamplingStrategy(emptySamplingRules);
SamplingRequest samplingRequest = new SamplingRequest("", "test", "/test", "test", "");
SamplingResponse sr = localizedSamplingStrategy.shouldTrace(samplingRequest);
Assert.assertFalse(sr.isSampled());
}
@Test
public void testLocalizedSamplingStrategyWithTwoRules() {
URL emptySamplingRules = LocalizedSamplingStrategyTest.class.getResource(
"/com/amazonaws/xray/strategy/sampling/TwoSamplingRules.json");
LocalizedSamplingStrategy localizedSamplingStrategy = new LocalizedSamplingStrategy(emptySamplingRules);
SamplingRequest r1 = new SamplingRequest("", "test", "/test", "test", "");
SamplingResponse s1 = localizedSamplingStrategy.shouldTrace(r1);
Assert.assertTrue(s1.isSampled());
SamplingRequest r2 = new SamplingRequest("", "test", "/no", "test", "");
SamplingResponse s2 = localizedSamplingStrategy.shouldTrace(r2);
Assert.assertFalse(s2.isSampled());
}
@Test
public void testLocalizedSamplingStrategyWithThreeRules() {
URL emptySamplingRules = LocalizedSamplingStrategyTest.class.getResource(
"/com/amazonaws/xray/strategy/sampling/ThreeSamplingRules.json");
LocalizedSamplingStrategy localizedSamplingStrategy = new LocalizedSamplingStrategy(emptySamplingRules);
SamplingRequest r1 = new SamplingRequest("", "test", "/test", "test", "");
SamplingResponse s1 = localizedSamplingStrategy.shouldTrace(r1);
Assert.assertFalse(s1.isSampled());
SamplingRequest r2 = new SamplingRequest("", "test2", "/test", "test", "");
SamplingResponse s2 = localizedSamplingStrategy.shouldTrace(r2);
Assert.assertTrue(s2.isSampled());
SamplingRequest r3 = new SamplingRequest("", "no", "/test", "test", "");
SamplingResponse s3 = localizedSamplingStrategy.shouldTrace(r3);
Assert.assertFalse(s3.isSampled());
}
@Test
public void testLocalizedSamplingStrategyWithFourRules() {
URL emptySamplingRules = LocalizedSamplingStrategyTest.class.getResource(
"/com/amazonaws/xray/strategy/sampling/FourSamplingRules.json");
LocalizedSamplingStrategy localizedSamplingStrategy = new LocalizedSamplingStrategy(emptySamplingRules);
SamplingRequest r1 = new SamplingRequest("", "test", "/test", "test", "");
SamplingResponse s1 = localizedSamplingStrategy.shouldTrace(r1);
Assert.assertFalse(s1.isSampled());
SamplingRequest r2 = new SamplingRequest("", "test", "/test", "rest", "");
SamplingResponse s2 = localizedSamplingStrategy.shouldTrace(r2);
Assert.assertTrue(s2.isSampled());
SamplingRequest r3 = new SamplingRequest("", "test", "/test", "no", "");
SamplingResponse s3 = localizedSamplingStrategy.shouldTrace(r3);
Assert.assertFalse(s3.isSampled());
}
@Test
public void testSamplingRequestHasNullField() {
URL samplingRules = LocalizedSamplingStrategyTest.class.getResource(
"/com/amazonaws/xray/strategy/sampling/TwoSamplingRules.json");
LocalizedSamplingStrategy localizedSamplingStrategy = new LocalizedSamplingStrategy(samplingRules);
localizedSamplingStrategy.shouldTrace(new SamplingRequest(null, null, null, null, ""));
}
}
| 3,773 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling/CentralizedReservoirTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling;
import com.amazonaws.xray.strategy.sampling.reservoir.Reservoir;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class CentralizedReservoirTest {
private static final int TEST_TIME = 1500;
private static final int INTERVAL = 100;
private int takeOverTime(Reservoir reservoir, int millis) {
int numTaken = 0;
for (int i = 0; i < millis / INTERVAL; i++) {
if (reservoir.take()) {
numTaken++;
}
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException ie) {
break;
}
}
return numTaken;
}
@Test
void testOnePerSecond() {
int perSecond = 1;
int taken = takeOverTime(new Reservoir(perSecond), TEST_TIME);
Assertions.assertTrue(Math.ceil(TEST_TIME / 1000f) <= taken);
Assertions.assertTrue(Math.ceil(TEST_TIME / 1000f) + perSecond >= taken);
}
@Test
void testTenPerSecond() {
int perSecond = 10;
int taken = takeOverTime(new Reservoir(perSecond), TEST_TIME);
Assertions.assertTrue(Math.ceil(TEST_TIME * perSecond / 1000f) <= taken);
Assertions.assertTrue(Math.ceil(TEST_TIME * perSecond / 1000f) + perSecond >= taken);
}
}
| 3,774 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling/reservoir/ReservoirTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling.reservoir;
import static com.amazonaws.xray.strategy.sampling.reservoir.Reservoir.NANOS_PER_DECISECOND;
import static com.amazonaws.xray.strategy.sampling.reservoir.Reservoir.NANOS_PER_SECOND;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.Random;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
// Added to declutter console: tells power mock not to mess with implicit classes we aren't testing
@PowerMockIgnore({"org.apache.logging.*", "javax.script.*"})
@PrepareForTest(Reservoir.class)
public class ReservoirTest {
@DataPoints public static final int[] SAMPLE_RESERVOIRS = {1, 10, 100};
@Test public void samplesOnlySpecifiedNumber() {
mockStatic(System.class);
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND);
Reservoir reservoir = new Reservoir(2);
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + 1);
assertTrue(reservoir.take());
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + 2);
assertTrue(reservoir.take());
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + 2);
assertFalse(reservoir.take());
}
@Test public void samplesFairNegativeNanoTime() {
mockStatic(System.class);
when(System.nanoTime()).thenReturn(-2 * NANOS_PER_SECOND);
Reservoir reservoir = new Reservoir(10);
when(System.nanoTime()).thenReturn(-2 * NANOS_PER_SECOND + 1);
assertTrue(reservoir.take());
when(System.nanoTime()).thenReturn(-2 * NANOS_PER_SECOND + 2);
assertTrue(reservoir.take());
when(System.nanoTime()).thenReturn(-2 * NANOS_PER_SECOND + 2);
assertFalse(reservoir.take());
}
@Test public void resetsAfterASecond() {
mockStatic(System.class);
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND);
Reservoir reservoir = new Reservoir(10);
assertTrue(reservoir.take());
assertFalse(reservoir.take());
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_DECISECOND);
assertTrue(reservoir.take());
assertFalse(reservoir.take());
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_DECISECOND * 9);
assertTrue(reservoir.take());
assertTrue(reservoir.take());
assertTrue(reservoir.take());
assertTrue(reservoir.take());
assertTrue(reservoir.take());
assertTrue(reservoir.take());
assertTrue(reservoir.take());
assertTrue(reservoir.take());
assertFalse(reservoir.take());
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_SECOND);
assertTrue(reservoir.take());
}
@Test public void allowsOddRates() {
mockStatic(System.class);
Reservoir reservoir = new Reservoir(11);
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND);
assertTrue(reservoir.take());
when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_DECISECOND * 9);
for (int i = 1; i < 11; i++) {
assertTrue("failed after " + (i + 1), reservoir.take());
}
assertFalse(reservoir.take());
}
@Test public void worksOnRollover() {
mockStatic(System.class);
when(System.nanoTime()).thenReturn(-NANOS_PER_SECOND);
Reservoir reservoir = new Reservoir(2);
assertTrue(reservoir.take());
when(System.nanoTime()).thenReturn(-NANOS_PER_SECOND / 2);
assertTrue(reservoir.take()); // second request
when(System.nanoTime()).thenReturn(-NANOS_PER_SECOND / 4);
assertFalse(reservoir.take());
when(System.nanoTime()).thenReturn(0L); // reset
assertTrue(reservoir.take());
}
@Theory public void retainsPerRate(int rate) {
Reservoir reservoir = new Reservoir(rate);
// parallel to ensure there aren't any unsynchronized race conditions
long passed = new Random().longs(100000).parallel()
.filter(i -> reservoir.take()).count();
assertEquals(rate, passed);
}
}
| 3,775 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling/manifest/CentralizedManifestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling.manifest;
import com.amazonaws.services.xray.model.SamplingRule;
import com.amazonaws.services.xray.model.SamplingStatisticsDocument;
import com.amazonaws.xray.strategy.sampling.SamplingRequest;
import com.amazonaws.xray.strategy.sampling.rand.RandImpl;
import com.amazonaws.xray.strategy.sampling.rule.CentralizedRule;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.powermock.reflect.Whitebox;
class CentralizedManifestTest {
@Test
void testEmptyManifestSize() {
CentralizedManifest manifest = new CentralizedManifest();
Assertions.assertEquals(0, manifest.size());
}
@Test
void testExpirationForNewManifest() {
Instant now = Instant.ofEpochSecond(1500000000);
CentralizedManifest manifest = new CentralizedManifest();
Assertions.assertTrue(manifest.isExpired(now));
}
@Test
void testExpirationForNewlyRefreshedManifest() {
Instant now = Instant.ofEpochSecond(1500000000);
CentralizedManifest manifest = new CentralizedManifest();
SamplingRule r1 = rule("r1");
manifest.putRules(Arrays.asList(r1), now);
Assertions.assertFalse(manifest.isExpired(now));
}
@Test
void testExpirationForOldManifest() {
Instant now = Instant.ofEpochSecond(1500000000);
CentralizedManifest manifest = new CentralizedManifest();
SamplingRule r1 = rule("r1");
manifest.putRules(Arrays.asList(r1), now);
// Increment time to be one second past expiration
now = Instant.ofEpochSecond(1500003601);
Assertions.assertTrue(manifest.isExpired(now));
}
@Test
void testPositiveMatch() {
Instant now = Instant.ofEpochSecond(1500000000);
CentralizedManifest manifest = new CentralizedManifest();
SamplingRule r1 = new SamplingRule()
.withRuleName("r1")
.withPriority(10)
.withReservoirSize(20)
.withFixedRate(0.05)
.withHost("*")
.withServiceName("*")
.withHTTPMethod("*")
.withURLPath("*")
.withResourceARN("*")
.withServiceType("*");
manifest.putRules(Arrays.asList(r1), now);
SamplingRequest req = new SamplingRequest(
"privileged",
"resourceARN",
"service",
"host",
"method",
"url",
"serviceType",
null
);
Assertions.assertEquals("r1", manifest.match(req, now).sample(now).getRuleName().get());
}
@Test
void testPositiveDefaultRuleMatch() {
Instant now = Instant.ofEpochSecond(1500000000);
CentralizedManifest manifest = new CentralizedManifest();
SamplingRule r2 = new SamplingRule()
.withRuleName(CentralizedRule.DEFAULT_RULE_NAME)
.withReservoirSize(20)
.withFixedRate(0.05);
manifest.putRules(Arrays.asList(rule("r1"), r2), now);
// Request that matches against the default rule
SamplingRequest req = new SamplingRequest(
"privileged",
"resourceARN",
"service",
"host",
"method",
"url",
"serviceType",
null
);
Assertions.assertEquals(CentralizedRule.DEFAULT_RULE_NAME, manifest.match(req, now).sample(now).getRuleName().get());
}
@Test
void testPutRules() {
Instant now = Instant.ofEpochSecond(1500000000);
CentralizedManifest manifest = new CentralizedManifest();
// Liberal sampling rule
SamplingRule r1 = new SamplingRule()
.withRuleName("r1")
.withPriority(10)
.withReservoirSize(20)
.withFixedRate(0.05)
.withHost("*")
.withServiceName("*")
.withHTTPMethod("*")
.withURLPath("*")
.withResourceARN("*")
.withServiceType("*");
manifest.putRules(Arrays.asList(r1), now);
SamplingRequest req = new SamplingRequest(
"privileged",
"resourceARN",
"service",
"host",
"method",
"url",
"serviceType",
null
);
Assertions.assertEquals("r1", manifest.match(req, now).sample(now).getRuleName().get());
}
@Test
void testRebuildOnNewRule() {
CentralizedManifest manifest = new CentralizedManifest();
manifest.putRules(Arrays.asList(rule("r1")), Instant.now());
Map<String, CentralizedRule> rules1 = Whitebox.getInternalState(manifest, "rules", CentralizedManifest.class);
manifest.putRules(Arrays.asList(rule("r1"), rule("r2")), Instant.now());
Map<String, CentralizedRule> rules2 = Whitebox.getInternalState(manifest, "rules", CentralizedManifest.class);
// The map of rules should be rebuilt, resulting in a new object
Assertions.assertFalse(rules1 == rules2);
Assertions.assertEquals(1, rules1.size());
Assertions.assertEquals(2, rules2.size());
}
@Test
void testPutRulesWithoutRebuild() {
CentralizedManifest manifest = new CentralizedManifest();
manifest.putRules(Arrays.asList(rule("r1")), Instant.now());
Map<String, CentralizedRule> rules1 = Whitebox.getInternalState(manifest, "rules", CentralizedManifest.class);
SamplingRule r = rule("r1").withResourceARN("arn3");
manifest.putRules(Arrays.asList(r), Instant.now());
Map<String, CentralizedRule> rules2 = Whitebox.getInternalState(manifest, "rules", CentralizedManifest.class);
// The map of rules should not have been rebuilt
Assertions.assertTrue(rules1 == rules2);
}
@Test
void testRebuildOnPriorityChange() {
CentralizedManifest manifest = new CentralizedManifest();
manifest.putRules(Arrays.asList(rule("r1")), Instant.now());
Map<String, CentralizedRule> rules1 = Whitebox.getInternalState(manifest, "rules", CentralizedManifest.class);
SamplingRule r = rule("r1").withPriority(200);
manifest.putRules(Arrays.asList(r), Instant.now());
Map<String, CentralizedRule> rules2 = Whitebox.getInternalState(manifest, "rules", CentralizedManifest.class);
// The map of rules should be rebuilt, resulting in a new object
Assertions.assertFalse(rules1 == rules2);
Assertions.assertEquals(1, rules1.size());
Assertions.assertEquals(1, rules2.size());
}
@Test
void testRebuildOnRuleDeletion() {
CentralizedManifest manifest = new CentralizedManifest();
manifest.putRules(Arrays.asList(rule("r1"), rule("r2")), Instant.now());
Map<String, CentralizedRule> rules1 = Whitebox.getInternalState(manifest, "rules", CentralizedManifest.class);
manifest.putRules(Arrays.asList(rule("r2")), Instant.now());
Map<String, CentralizedRule> rules2 = Whitebox.getInternalState(manifest, "rules", CentralizedManifest.class);
// The map of rules should be rebuilt, resulting in a new object
Assertions.assertFalse(rules1 == rules2);
Assertions.assertEquals(2, rules1.size());
Assertions.assertEquals(1, rules2.size());
}
@Test
void testManifestSizeWithDefaultRule() {
CentralizedManifest m = new CentralizedManifest();
SamplingRule r2 = new SamplingRule()
.withRuleName(CentralizedRule.DEFAULT_RULE_NAME)
.withReservoirSize(20)
.withFixedRate(0.05);
m.putRules(Arrays.asList(rule("r1"), r2), Instant.now());
Assertions.assertEquals(2, m.size());
}
@Test
void testManifestSizeWithoutDefaultRule() {
CentralizedManifest m = new CentralizedManifest();
SamplingRule r1 = new SamplingRule()
.withRuleName(CentralizedRule.DEFAULT_RULE_NAME)
.withReservoirSize(20)
.withFixedRate(0.05);
m.putRules(Arrays.asList(r1), Instant.now());
Assertions.assertEquals(1, m.size());
}
@Test
void testSnapshotsWithDefaultRule() {
Instant now = Instant.ofEpochSecond(1500000000);
CentralizedManifest m = new CentralizedManifest();
m.putRules(Arrays.asList(
rule("r1"),
rule("r2"),
rule(CentralizedRule.DEFAULT_RULE_NAME)
), now);
Map<String, CentralizedRule> rules = Whitebox.getInternalState(m, "rules", CentralizedManifest.class);
CentralizedRule defaultRule = Whitebox.getInternalState(m, "defaultRule", CentralizedManifest.class);
rules.forEach((key, r) -> r.sample(now));
defaultRule.sample(now);
List<SamplingStatisticsDocument> snapshots = m.snapshots(now);
Assertions.assertEquals(3, snapshots.size());
}
@Test
void testSnapshotsWithoutDefaultRule() {
Instant now = Instant.ofEpochSecond(1500000000);
CentralizedManifest m = new CentralizedManifest();
m.putRules(Arrays.asList(
rule("r1"),
rule("r2")
), now);
Map<String, CentralizedRule> rules = Whitebox.getInternalState(m, "rules", CentralizedManifest.class);
rules.forEach((key, r) -> r.sample(now));
List<SamplingStatisticsDocument> snapshots = m.snapshots(now);
Assertions.assertEquals(2, snapshots.size());
}
@Test
void testRebuild() {
Map<String, CentralizedRule> rules = new HashMap<>();
rules.put("r1", new CentralizedRule(rule("r1").withPriority(11), new RandImpl()));
rules.put("r2", new CentralizedRule(rule("r2"), new RandImpl()));
List<SamplingRule> inputs = new ArrayList<>();
inputs.add(rule("r2"));
inputs.add(rule("r1"));
inputs.add(rule("r3"));
CentralizedManifest m = new CentralizedManifest();
Map<String, CentralizedRule> rebuiltRules = m.rebuild(rules, inputs);
Assertions.assertEquals(3, rebuiltRules.size());
String[] orderedList = new String[3];
rebuiltRules.keySet().toArray(orderedList);
Assertions.assertEquals("r2", orderedList[0]);
Assertions.assertEquals("r3", orderedList[1]);
Assertions.assertEquals("r1", orderedList[2]);
}
private SamplingRule rule(String ruleName) {
SamplingRule r = new SamplingRule()
.withRuleName(ruleName)
.withPriority(10)
.withReservoirSize(20)
.withFixedRate(0.05)
.withHost("*")
.withServiceName("s2")
.withHTTPMethod("POST")
.withURLPath("/foo")
.withResourceARN("arn2");
return r;
}
}
| 3,776 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling/rule/CentralizedRuleTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling.rule;
import com.amazonaws.services.xray.model.SamplingRule;
import com.amazonaws.services.xray.model.SamplingStatisticsDocument;
import com.amazonaws.services.xray.model.SamplingTargetDocument;
import com.amazonaws.xray.strategy.sampling.SamplingResponse;
import com.amazonaws.xray.strategy.sampling.rand.Rand;
import com.amazonaws.xray.strategy.sampling.rand.RandImpl;
import com.amazonaws.xray.strategy.sampling.reservoir.CentralizedReservoir;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.reflect.Whitebox;
@RunWith(MockitoJUnitRunner.class)
public class CentralizedRuleTest {
@Mock
private Rand rand;
@Mock
private Clock clock;
@Test
public void testPositiveSampleTake() {
Clock clock = Clock.fixed(Instant.ofEpochSecond(1500000000), ZoneId.systemDefault());
SamplingRule input = createInput("r1", 300, 10, 0.0);
CentralizedRule rule = new CentralizedRule(input, new RandImpl());
SamplingTargetDocument target = createTarget(2, 0.0, 1500000010);
rule.update(target, clock.instant());
SamplingResponse response = rule.sample(clock.instant());
Assert.assertTrue(response.isSampled());
Assert.assertEquals("r1", response.getRuleName().get());
Statistics s = Whitebox.getInternalState(rule, "statistics", CentralizedRule.class);
Assert.assertEquals(1, s.getSampled());
Assert.assertEquals(1, s.getRequests());
Assert.assertEquals(0, s.getBorrowed());
}
@Test
public void testPositiveBernoulliSample() {
Clock clock = Clock.fixed(Instant.ofEpochSecond(1500000000), ZoneId.systemDefault());
SamplingRule input = createInput("r1", 300, 10, 0.0);
CentralizedRule rule = new CentralizedRule(input, rand);
Mockito.when(rand.next()).thenReturn(0.01);
SamplingTargetDocument target = createTarget(0, 0.05, 1500000010);
rule.update(target, clock.instant());
// Sample using bernoulli sampling
SamplingResponse response = rule.sample(clock.instant());
Assert.assertTrue(response.isSampled());
Assert.assertEquals("r1", response.getRuleName().get());
Statistics s = Whitebox.getInternalState(rule, "statistics", CentralizedRule.class);
Assert.assertEquals(1, s.getSampled());
Assert.assertEquals(1, s.getRequests());
Assert.assertEquals(0, s.getBorrowed());
}
@Test
public void testExpiredReservoirPositiveBernoulliSample() {
Clock clock = Clock.fixed(Instant.ofEpochSecond(1500000000), ZoneId.systemDefault());
SamplingRule input = createInput("r1", 300, 0, 0.5);
CentralizedRule rule = new CentralizedRule(input, rand);
SamplingTargetDocument target = createTarget(0, 0.5, 1499999999);
rule.update(target, clock.instant());
Mockito.when(rand.next()).thenReturn(0.2);
// BernoulliSample() from expired reservoir
SamplingResponse response = rule.sample(clock.instant());
Mockito.verify(rand).next();
Assert.assertTrue(response.isSampled());
Assert.assertEquals("r1", response.getRuleName().get());
Statistics s = Whitebox.getInternalState(rule, "statistics", CentralizedRule.class);
Assert.assertEquals(1, s.getSampled());
Assert.assertEquals(1, s.getRequests());
Assert.assertEquals(0, s.getBorrowed());
}
@Test
public void testNegativeSample() {
Clock clock = Clock.fixed(Instant.ofEpochSecond(1500000000), ZoneId.systemDefault());
SamplingRule input = createInput("r1", 300, 10, 0.0);
CentralizedRule rule = new CentralizedRule(input, rand);
SamplingTargetDocument target = createTarget(0, 0.0, 1500000010);
rule.update(target, clock.instant());
SamplingResponse response = rule.sample(clock.instant());
Assert.assertFalse(response.isSampled());
Assert.assertEquals("r1", response.getRuleName().get());
Statistics s = Whitebox.getInternalState(rule, "statistics", CentralizedRule.class);
Assert.assertEquals(0, s.getSampled());
Assert.assertEquals(1, s.getRequests());
Assert.assertEquals(0, s.getBorrowed());
}
@Test
public void testExpiredReservoirNegativeBernoulliSample() {
Clock clock = Clock.fixed(Instant.ofEpochSecond(1500000000), ZoneId.systemDefault());
SamplingRule input = createInput("r1", 300, 0, 0.2);
CentralizedRule rule = new CentralizedRule(input, rand);
SamplingTargetDocument target = createTarget(0, 0.2, 1499999999);
rule.update(target, clock.instant());
Mockito.when(rand.next()).thenReturn(0.4);
SamplingResponse response = rule.sample(clock.instant());
Assert.assertFalse(response.isSampled());
Assert.assertEquals("r1", response.getRuleName().get());
Statistics s = Whitebox.getInternalState(rule, "statistics", CentralizedRule.class);
Assert.assertEquals(0, s.getSampled());
Assert.assertEquals(1, s.getRequests());
Assert.assertEquals(0, s.getBorrowed());
}
@Test
public void testReservoirReset() {
Mockito.when(clock.instant()).thenReturn(Instant.ofEpochSecond(1500000000));
SamplingRule input = createInput("r1", 300, 10, 0.0);
CentralizedRule rule = new CentralizedRule(input, new RandImpl());
SamplingTargetDocument target = createTarget(2, 0.0, 1500000010);
rule.update(target, clock.instant());
rule.sample(clock.instant());
CentralizedReservoir reservoir = Whitebox.getInternalState(rule, "centralizedReservoir", CentralizedRule.class);
Assert.assertEquals(1, reservoir.getUsed());
Mockito.when(clock.instant()).thenReturn(Instant.ofEpochSecond(1500000001));
rule.sample(clock.instant());
// Assert to ensure reservoir was reset before being updated
Assert.assertEquals(1, reservoir.getUsed());
}
@Test
public void testSnapshot() {
Clock clock = Clock.fixed(Instant.ofEpochSecond(1500000000), ZoneId.systemDefault());
SamplingRule input = createInput("r1", 300, 10, 0.0);
CentralizedRule rule = new CentralizedRule(input, new RandImpl());
SamplingTargetDocument target = createTarget(2, 0.0, 1500000010);
rule.update(target, clock.instant());
rule.sample(clock.instant());
Statistics s = Whitebox.getInternalState(rule, "statistics", CentralizedRule.class);
// Assert statistics were updated
Assert.assertEquals(1, s.getSampled());
Assert.assertEquals(1, s.getRequests());
Assert.assertEquals(0, s.getBorrowed());
SamplingStatisticsDocument snapshot = rule.snapshot(Date.from(clock.instant()));
// Assert snapshot contains expected statistics
Assert.assertEquals("r1", snapshot.getRuleName());
Assert.assertEquals(TimeUnit.SECONDS.toMillis(1500000000), snapshot.getTimestamp().toInstant().toEpochMilli());
Assert.assertEquals(1, snapshot.getRequestCount().intValue());
Assert.assertEquals(1, snapshot.getSampledCount().intValue());
Assert.assertEquals(0, snapshot.getBorrowCount().intValue());
// Assert current statistics are empty
Assert.assertEquals(0, rule.snapshot(Date.from(clock.instant())).getRequestCount().intValue());
Assert.assertEquals(0, rule.snapshot(Date.from(clock.instant())).getSampledCount().intValue());
Assert.assertEquals(0, rule.snapshot(Date.from(clock.instant())).getBorrowCount().intValue());
}
@Test
public void testRuleUpdateWithInvalidation() {
SamplingRule input = createInput("r1", 300, 10, 0.0)
.withHTTPMethod("POST")
.withServiceName("s1")
.withURLPath("/foo/bar");
CentralizedRule r = new CentralizedRule(input, new RandImpl());
SamplingRule update = createInput("r1", 301, 5, 0.5)
.withHTTPMethod("GET")
.withServiceName("s2")
.withURLPath("/bar/foo");
boolean invalidate = r.update(update);
Matchers m = Whitebox.getInternalState(r, "matchers", CentralizedRule.class);
Assert.assertEquals("GET", Whitebox.getInternalState(m, "method", Matchers.class));
Assert.assertEquals("s2", Whitebox.getInternalState(m, "service", Matchers.class));
Assert.assertEquals("/bar/foo", Whitebox.getInternalState(m, "url", Matchers.class));
Assert.assertTrue(invalidate);
}
@Test
public void testRuleUpdateWithoutInvalidation() {
SamplingRule input = createInput("r1", 300, 10, 0.0)
.withHTTPMethod("POST")
.withServiceName("s1")
.withURLPath("/foo/bar");
CentralizedRule r = new CentralizedRule(input, new RandImpl());
SamplingRule update = createInput("r1", 300, 10, 0.0)
.withHTTPMethod("GET")
.withServiceName("s2")
.withURLPath("/bar/foo");
boolean invalidate = r.update(update);
Matchers m = Whitebox.getInternalState(r, "matchers", CentralizedRule.class);
Assert.assertEquals("GET", Whitebox.getInternalState(m, "method", Matchers.class));
Assert.assertEquals("s2", Whitebox.getInternalState(m, "service", Matchers.class));
Assert.assertEquals("/bar/foo", Whitebox.getInternalState(m, "url", Matchers.class));
Assert.assertFalse(invalidate);
}
@Test
public void testTargetUpdate() {
SamplingRule input = createInput("r1", 300, 10, 0.0);
CentralizedRule r = new CentralizedRule(input, new RandImpl());
SamplingTargetDocument update = new SamplingTargetDocument()
.withRuleName("r1")
.withFixedRate(0.5)
.withInterval(20);
r.update(update, Instant.now());
double fixedRate = Whitebox.getInternalState(r, "fixedRate", CentralizedRule.class);
Assert.assertEquals(0.5, fixedRate, 0);
}
public static SamplingRule createInput(String name, int priority, int capacity, double rate) {
SamplingRule input = new SamplingRule()
.withRuleName(name)
.withPriority(priority)
.withFixedRate(rate)
.withReservoirSize(capacity);
return input;
}
public static SamplingTargetDocument createTarget(int quota, double rate, long expiresAt) {
SamplingTargetDocument target = new SamplingTargetDocument()
.withReservoirQuota(quota)
.withReservoirQuotaTTL(Date.from(Instant.ofEpochSecond(expiresAt)))
.withFixedRate(rate)
.withInterval(10);
return target;
}
}
| 3,777 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling/rule/MatchersTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling.rule;
import com.amazonaws.services.xray.model.SamplingRule;
import com.amazonaws.xray.strategy.sampling.SamplingRequest;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class MatchersTest {
@Test
void testSimpleMatch() {
SamplingRule rule = new SamplingRule()
.withAttributes(null)
.withHost("192.168.1.1")
.withServiceName("www.foo.com")
.withHTTPMethod("POST")
.withResourceARN("arn:aws:service:us-east-1:111111111111:resource")
.withURLPath("/bar/123")
.withServiceType("AWS::EC2::Instance");
SamplingRequest req = new SamplingRequest(
"role-arn",
"arn:aws:service:us-east-1:111111111111:resource",
"www.foo.com",
"192.168.1.1",
"POST",
"/bar/123",
"AWS::EC2::Instance",
null
);
Matchers m = new Matchers(rule);
Assertions.assertTrue(m.match(req));
}
@Test
void testSimpleMismatch() {
SamplingRule rule = new SamplingRule()
.withAttributes(null)
.withHost("192.168.1.1")
.withServiceName("www.foo.com")
.withHTTPMethod("POST")
.withResourceARN("arn:aws:service:us-east-1:111111111111:resource")
.withURLPath("/bar/123")
.withServiceType("AWS::EC2::Instance");
SamplingRequest req = new SamplingRequest(
"role-arn",
"arn:aws:service:us-east-1:111111111111:resource",
"www.bar.com",
"192.168.1.1",
"POST",
"/bar/123",
"AWS::EC2::Instance",
null
);
Matchers m = new Matchers(rule);
Assertions.assertFalse(m.match(req));
}
@Test
void testFullGlobMatch() {
Map<String, String> ruleAttributes = new HashMap<>();
ruleAttributes.put("ip", "*");
ruleAttributes.put("compression", "*");
Map<String, String> reqAttributes = new HashMap<>();
reqAttributes.put("ip", "127.0.0.1");
reqAttributes.put("compression", "gzip");
reqAttributes.put("encoding", "json");
SamplingRule rule = new SamplingRule()
.withAttributes(ruleAttributes)
.withHost("*")
.withServiceName("*")
.withHTTPMethod("*")
.withResourceARN("*")
.withURLPath("*")
.withServiceType("*");
SamplingRequest req = new SamplingRequest(
"role-arn",
"arn:aws:service:us-east-1:111111111111:resource",
"www.foo.com",
"192.168.1.1",
"GET",
"/baz/bar",
"AWS::EC2::Instance",
reqAttributes
);
Matchers m = new Matchers(rule);
Assertions.assertTrue(m.match(req));
}
@Test
void testPartialGlobMatch() {
Map<String, String> ruleAttributes = new HashMap<>();
ruleAttributes.put("ip", "127.*.1");
ruleAttributes.put("compression", "*");
Map<String, String> reqAttributes = new HashMap<>();
reqAttributes.put("ip", "127.0.0.1");
reqAttributes.put("compression", "gzip");
reqAttributes.put("encoding", "json");
SamplingRule rule = new SamplingRule()
.withAttributes(ruleAttributes)
.withHost("*")
.withServiceName("*.foo.*")
.withHTTPMethod("*")
.withResourceARN("*")
.withURLPath("/bar/*")
.withServiceType("AWS::EC2::Instance");
SamplingRequest req = new SamplingRequest(
"role-arn",
"arn:aws:service:us-east-1:111111111111:resource",
"www.foo.com",
"192.168.1.1",
"GET",
"/bar/baz",
"AWS::EC2::Instance",
reqAttributes
);
Matchers m = new Matchers(rule);
Assertions.assertTrue(m.match(req));
}
@Test
void testPartialGlobMismatch() {
SamplingRule rule = new SamplingRule()
.withAttributes(null)
.withHost("*")
.withServiceName("*.foo.*")
.withHTTPMethod("*")
.withResourceARN("*")
.withURLPath("/bar/*")
.withServiceType("AWS::EC2::Instance");
SamplingRequest req = new SamplingRequest(
"role-arn",
"arn:aws:service:us-east-1:111111111111:resource",
"www.bar.com",
"192.168.1.1",
"GET",
"/foo/baz",
"AWS::EC2::Instance",
null
);
Matchers m = new Matchers(rule);
Assertions.assertFalse(m.match(req));
}
@Test
void testPartialAttributeGlobMismatch() {
Map<String, String> ruleAttributes = new HashMap<>();
ruleAttributes.put("ip", "127.*.0");
ruleAttributes.put("compression", "*");
Map<String, String> reqAttributes = new HashMap<>();
reqAttributes.put("ip", "127.0.0.1");
reqAttributes.put("compression", "gzip");
reqAttributes.put("encoding", "json");
SamplingRule rule = new SamplingRule()
.withAttributes(ruleAttributes)
.withHost("*")
.withServiceName("*")
.withHTTPMethod("*")
.withResourceARN("*")
.withURLPath("*")
.withServiceType("AWS::EC2::Instance");
SamplingRequest req = new SamplingRequest(
"role-arn",
"arn:aws:service:us-east-1:111111111111:resource",
"www.bar.com",
"192.168.1.1",
"GET",
"/foo/baz",
"AWS::EC2::Instance",
reqAttributes
);
Matchers m = new Matchers(rule);
Assertions.assertFalse(m.match(req));
}
@Test
void testPartialRequestMismatch() {
SamplingRule rule = new SamplingRule()
.withAttributes(null)
.withHost("192.168.1.1")
.withServiceName("www.foo.com")
.withHTTPMethod("POST")
.withResourceARN("arn:aws:service:us-east-1:111111111111:resource")
.withURLPath("/bar/123")
.withServiceType("AWS::EC2::Instance");
SamplingRequest req = new SamplingRequest(
"role-arn",
"arn:aws:service:us-east-1:111111111111:resource",
"www.bar.com",
null,
"POST",
"/bar/123",
"AWS::EC2::Instance",
null
);
Matchers m = new Matchers(rule);
Assertions.assertFalse(m.match(req));
}
}
| 3,778 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling/pollers/TargetPollerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling.pollers;
import static org.assertj.core.api.Assertions.assertThat;
import com.amazonaws.xray.internal.UnsignedXrayClient;
import com.amazonaws.xray.strategy.sampling.manifest.CentralizedManifest;
import java.time.Clock;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class TargetPollerTest {
@Rule
public MockitoRule mocks = MockitoJUnit.rule();
@Mock
private CentralizedManifest manifest;
@Mock
private UnsignedXrayClient client;
@Test
public void testPollerShutdown() {
TargetPoller poller = new TargetPoller(client, manifest, Clock.systemUTC());
poller.start();
poller.shutdown();
assertThat(poller.getExecutor().isShutdown()).isTrue();
}
}
| 3,779 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/test/java/com/amazonaws/xray/strategy/sampling/pollers/RulePollerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.strategy.sampling.pollers;
import static org.assertj.core.api.Assertions.assertThat;
import com.amazonaws.xray.internal.UnsignedXrayClient;
import com.amazonaws.xray.strategy.sampling.manifest.CentralizedManifest;
import java.time.Clock;
import java.util.concurrent.ScheduledExecutorService;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class RulePollerTest {
@Rule
public MockitoRule mocks = MockitoJUnit.rule();
@Mock
private UnsignedXrayClient client;
@Test
public void testPollerShutdown() {
RulePoller poller = new RulePoller(client, new CentralizedManifest(), Clock.systemUTC());
poller.start();
poller.shutdown();
ScheduledExecutorService executor = poller.getExecutor();
assertThat(executor.isShutdown()).isTrue();
}
}
| 3,780 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/AWSXRayRecorder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray;
import com.amazonaws.xray.contexts.LambdaSegmentContextResolver;
import com.amazonaws.xray.contexts.SegmentContext;
import com.amazonaws.xray.contexts.SegmentContextExecutors;
import com.amazonaws.xray.contexts.SegmentContextResolverChain;
import com.amazonaws.xray.contexts.ThreadLocalSegmentContextResolver;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.AWSLogReference;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.FacadeSegment;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.SegmentImpl;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceID;
import com.amazonaws.xray.exceptions.SegmentNotFoundException;
import com.amazonaws.xray.exceptions.SubsegmentNotFoundException;
import com.amazonaws.xray.internal.FastIdGenerator;
import com.amazonaws.xray.internal.IdGenerator;
import com.amazonaws.xray.internal.SecureIdGenerator;
import com.amazonaws.xray.listeners.SegmentListener;
import com.amazonaws.xray.strategy.ContextMissingStrategy;
import com.amazonaws.xray.strategy.DefaultContextMissingStrategy;
import com.amazonaws.xray.strategy.DefaultPrioritizationStrategy;
import com.amazonaws.xray.strategy.DefaultStreamingStrategy;
import com.amazonaws.xray.strategy.DefaultThrowableSerializationStrategy;
import com.amazonaws.xray.strategy.PrioritizationStrategy;
import com.amazonaws.xray.strategy.StreamingStrategy;
import com.amazonaws.xray.strategy.ThrowableSerializationStrategy;
import com.amazonaws.xray.strategy.sampling.DefaultSamplingStrategy;
import com.amazonaws.xray.strategy.sampling.SamplingRequest;
import com.amazonaws.xray.strategy.sampling.SamplingResponse;
import com.amazonaws.xray.strategy.sampling.SamplingStrategy;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class AWSXRayRecorder {
private static final Log logger = LogFactory.getLog(AWSXRayRecorder.class);
private static final String PROPERTIES_LOCATION = "/com/amazonaws/xray/sdk.properties";
private static final String SDK_VERSION_KEY = "awsxrayrecordersdk.version";
private static final String DEFAULT_SDK_VERSION = "unknown";
private static final String SDK = "X-Ray for Java";
private static final String CW_LOGS_KEY = "cloudwatch_logs";
private static final Map<String, Object> SDK_VERSION_INFORMATION;
private static final Map<String, Object> RUNTIME_INFORMATION;
static {
Map<String, Object> sdkVersioninformation = new HashMap<>();
Map<String, Object> runtimeInformation = new HashMap<>();
Properties properties = new Properties();
InputStream propertiesStream = AWSXRayRecorder.class.getResourceAsStream(PROPERTIES_LOCATION);
if (propertiesStream != null) {
try {
properties.load(propertiesStream);
} catch (IOException | IllegalArgumentException e) {
logger.warn("Unable to detect SDK version.", e);
}
} else {
logger.warn("SDK properties file not found.");
}
sdkVersioninformation.put("sdk", SDK);
String sdkVersion = properties.getProperty(SDK_VERSION_KEY, DEFAULT_SDK_VERSION);
sdkVersioninformation.put("sdk_version", sdkVersion);
String javaVersion = System.getProperty("java.version");
if (javaVersion != null) {
runtimeInformation.put("runtime_version", javaVersion);
}
String javaVmName = System.getProperty("java.vm.name");
if (javaVmName != null) {
runtimeInformation.put("runtime", javaVmName);
}
SDK_VERSION_INFORMATION = Collections.unmodifiableMap(sdkVersioninformation);
RUNTIME_INFORMATION = Collections.unmodifiableMap(runtimeInformation);
}
private SamplingStrategy samplingStrategy;
private StreamingStrategy streamingStrategy;
private PrioritizationStrategy prioritizationStrategy;
private ThrowableSerializationStrategy throwableSerializationStrategy;
private ContextMissingStrategy contextMissingStrategy;
private IdGenerator idGenerator;
private SegmentContextResolverChain segmentContextResolverChain;
private Emitter emitter;
private final ArrayList<SegmentListener> segmentListeners;
private final Map<String, Object> awsRuntimeContext;
private final Map<String, Object> serviceRuntimeContext;
private final Set<AWSLogReference> logReferences;
@MonotonicNonNull
private String origin;
private boolean forcedTraceIdGeneration;
public AWSXRayRecorder() {
samplingStrategy = new DefaultSamplingStrategy();
streamingStrategy = new DefaultStreamingStrategy();
prioritizationStrategy = new DefaultPrioritizationStrategy();
throwableSerializationStrategy = new DefaultThrowableSerializationStrategy();
contextMissingStrategy = new DefaultContextMissingStrategy();
idGenerator = new SecureIdGenerator();
logReferences = new HashSet<>();
Optional<ContextMissingStrategy> environmentContextMissingStrategy =
AWSXRayRecorderBuilder.contextMissingStrategyFromEnvironmentVariable();
Optional<ContextMissingStrategy> systemContextMissingStrategy =
AWSXRayRecorderBuilder.contextMissingStrategyFromSystemProperty();
if (environmentContextMissingStrategy.isPresent()) {
logger.info("Overriding contextMissingStrategy. Environment variable "
+ ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_ENVIRONMENT_VARIABLE_OVERRIDE_KEY + " has value: \""
+ System.getenv(ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_ENVIRONMENT_VARIABLE_OVERRIDE_KEY) + "\".");
contextMissingStrategy = environmentContextMissingStrategy.get();
} else if (systemContextMissingStrategy.isPresent()) {
logger.info("Overriding contextMissingStrategy. System property "
+ ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_SYSTEM_PROPERTY_OVERRIDE_KEY + " has value: \""
+ System.getProperty(ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_SYSTEM_PROPERTY_OVERRIDE_KEY) + "\".");
contextMissingStrategy = systemContextMissingStrategy.get();
}
segmentContextResolverChain = new SegmentContextResolverChain();
LambdaSegmentContextResolver lambdaSegmentContextResolver = new LambdaSegmentContextResolver();
if (lambdaSegmentContextResolver.resolve() != null) {
segmentContextResolverChain.addResolver(lambdaSegmentContextResolver);
} else {
segmentContextResolverChain.addResolver(new ThreadLocalSegmentContextResolver());
}
segmentListeners = new ArrayList<>();
awsRuntimeContext = new ConcurrentHashMap<>();
awsRuntimeContext.put("xray", SDK_VERSION_INFORMATION);
serviceRuntimeContext = new ConcurrentHashMap<>();
serviceRuntimeContext.putAll(RUNTIME_INFORMATION);
try {
emitter = Emitter.create();
} catch (IOException e) {
throw new RuntimeException("Unable to instantiate AWSXRayRecorder: ", e);
}
}
/**
* Sends a segment to the emitter if the segment is marked as sampled.
*
* @param segment
* the segment to send
* @return
* true if the segment was emitted succesfully.
*/
public boolean sendSegment(Segment segment) {
if (segment.isSampled()) {
return emitter.sendSegment(segment);
}
return false;
}
/**
* Sends a subsegment to the emitter if the subsegment's parent segment is marked as sampled.
*
* @param subsegment
* the subsegment to send
* @return
* true if the subsegment was emitted succesfully.
*/
public boolean sendSubsegment(Subsegment subsegment) {
if (subsegment.getParentSegment().isSampled()) {
return emitter.sendSubsegment(subsegment);
}
return false;
}
/**
* Begins a segment, passes it to the supplied function, and ends the segment before returning the supplied function's result.
* Intercepts exceptions, adds them to the segment, and re-throws them.
*
* @param <R>
* the type of the value returned by {@code function}
* @param name
* the name to use for the created segment
* @param function
* the function to invoke
* @return the value returned by the supplied function
*/
@Nullable
public <R> R createSegment(String name, Function<Segment, @Nullable R> function) {
Segment segment = beginSegment(name);
try {
return function.apply(segment);
} catch (Exception e) {
segment.addException(e);
throw e;
} finally {
endSegment();
}
}
/**
* Begins a segment and passes it to the supplied consumer, and ends the segment before returning the consumer's result.
* Intercepts exceptions, adds them to the segment, and re-throws them.
*
* @param name
* the name to use for the created segment
* @param consumer
* the function to invoke
*/
public void createSegment(String name, Consumer<Segment> consumer) {
Segment segment = beginSegment(name);
try {
consumer.accept(segment);
} catch (Exception e) {
segment.addException(e);
throw e;
} finally {
endSegment();
}
}
/**
* Begins a segment, invokes the provided supplier, and ends the segment before returning the supplier's result.
* Intercepts exceptions, adds them to the segment, and re-throws them.
*
* @param <R>
* the type of the value returned by {@code supplier}
* @param name
* the name to use for the created segment
* @param supplier
* the supplier to invoke
* @return the value returned by the provided supplier
*/
@Nullable
public <R> R createSegment(String name, Supplier<R> supplier) {
Segment segment = beginSegment(name);
try {
return supplier.get();
} catch (Exception e) {
segment.addException(e);
throw e;
} finally {
endSegment();
}
}
/**
* Begins a segment, runs the provided runnable, and ends the segment before returning the supplier's result.
* Intercepts exceptions, adds them to the segment, and re-throws them.
*
* @param name
* the name to use for the created segment
* @param runnable
* the runnable to run
*/
public void createSegment(String name, Runnable runnable) {
Segment segment = beginSegment(name);
try {
runnable.run();
} catch (Exception e) {
segment.addException(e);
throw e;
} finally {
endSegment();
}
}
/**
* Begins a subsegment, passes it to the supplied function, and ends the subsegment before returning the supplied function's
* result. Intercepts exceptions, adds them to the subsegment, and re-throws them.
*
* @param <R>
* the type of the value returned by {@code function}
* @param name
* the name to use for the created subsegment
* @param function
* the function to invoke
* @return the value returned by the supplied function
*/
@Nullable
public <R> R createSubsegment(String name, Function<Subsegment, @Nullable R> function) {
Subsegment subsegment = beginSubsegment(name);
try {
return function.apply(subsegment);
} catch (Exception e) {
subsegment.addException(e);
throw e;
} finally {
endSubsegment();
}
}
/**
* Begins a subsegment and passes it to the supplied consumer, and ends the subsegment before returning the consumer's result.
* Intercepts exceptions, adds them to the subsegment, and re-throws them.
*
* @param name
* the name to use for the created subsegment
* @param consumer
* the function to invoke
*/
public void createSubsegment(String name, Consumer<Subsegment> consumer) {
Subsegment subsegment = beginSubsegment(name);
try {
consumer.accept(subsegment);
} catch (Exception e) {
subsegment.addException(e);
throw e;
} finally {
endSubsegment();
}
}
/**
* Begins a subsegment, passes it to the provided supplier, and ends the subsegment before returning the supplier's result.
* Intercepts exceptions, adds them to the subsegment, and re-throws them.
*
* @param <R>
* the type of the value returned by {@code function}
* @param name
* the name to use for the created subsegment
* @param supplier
* the supplier to invoke
* @return the value returned by the provided supplier
*/
@Nullable
public <R> R createSubsegment(String name, Supplier<R> supplier) {
Subsegment subsegment = beginSubsegment(name);
try {
return supplier.get();
} catch (Exception e) {
subsegment.addException(e);
throw e;
} finally {
endSubsegment();
}
}
/**
* Begins a subsegment, runs the provided runnable, and ends the subsegment once complete. Intercepts exceptions, adds them to
* the subsegment, and re-throws them.
*
* @param name
* the name to use for the created subsegment
* @param runnable
* the runnable to run
*/
public void createSubsegment(String name, Runnable runnable) {
Subsegment subsegment = beginSubsegment(name);
try {
runnable.run();
} catch (Exception e) {
subsegment.addException(e);
throw e;
} finally {
endSubsegment();
}
}
public Segment beginSegment(String name) {
return beginSegment(new SegmentImpl(this, name));
}
/**
* Begins a new segment after applying the configured sampling strategy. This method only uses the segment name and origin
* (if defined) to compute a sampling decision.
*
* @param name the segment name, to be used for the sampling decision
* @return Returns a proper segment if a sampled decision is made, and a no-op segment otherwise.
*/
public Segment beginSegmentWithSampling(String name) {
final SamplingRequest samplingRequest = new SamplingRequest(name, null, null, null, this.origin);
final SamplingResponse samplingResponse = this.getSamplingStrategy().shouldTrace(samplingRequest);
if (samplingResponse.isSampled()) {
Segment segment = beginSegment(name);
if (samplingResponse.getRuleName().isPresent()) {
segment.setRuleName(samplingResponse.getRuleName().get());
}
return segment;
} else if (this.getSamplingStrategy().isForcedSamplingSupported()) {
Segment segment = beginSegment(name);
segment.setSampled(false);
if (samplingResponse.getRuleName().isPresent()) {
segment.setRuleName(samplingResponse.getRuleName().get());
}
return segment;
}
return beginNoOpSegment();
}
public Segment beginSegment(String name, TraceID traceId, @Nullable String parentId) {
Segment segment = new SegmentImpl(this, name, traceId);
segment.setParentId(parentId);
return beginSegment(segment);
}
/**
* Sets the current {@link Segment} to a no-op which will not record any information or be emitted. An invalid {@link TraceID}
* will be propagated downstream.
*/
public Segment beginNoOpSegment() {
return beginSegment(Segment.noOp(this.forcedTraceIdGeneration ? TraceID.create(this) : TraceID.invalid(), this));
}
/**
* Sets the current {@link Segment} to a no-op which will not record any information or be emitted. The provided
* {@link TraceID} will be propagated downstream.
*/
public Segment beginNoOpSegment(TraceID traceID) {
return beginSegment(Segment.noOp(traceID, this));
}
/**
* Sets the current segment to a new instance of {@code DummySegment}.
*
* @return the newly created {@code DummySegment}.
*
* @deprecated Use {@link #beginNoOpSegment()}.
*/
@Deprecated
public Segment beginDummySegment() {
return beginNoOpSegment();
}
/**
* @deprecated Use {@link #beginNoOpSegment(TraceID)}.
*/
@Deprecated
public Segment beginDummySegment(String name, TraceID traceId) {
return beginNoOpSegment(traceId);
}
/**
* @deprecated Use {@link #beginNoOpSegment(TraceID)}.
*/
@Deprecated
public Segment beginDummySegment(TraceID traceId) {
return beginNoOpSegment(traceId);
}
private Segment beginSegment(Segment segment) {
SegmentContext context = getSegmentContext();
if (context == null) {
// No context available, we return a no-op segment so user code does not have to work around this. Based on
// ContextMissingStrategy they will still know about the issue unless they explicitly opt-ed out.
return Segment.noOp(segment.getTraceId(), this);
}
Entity current = getTraceEntity();
if (current != null) {
logger.error("Beginning new segment while another segment exists in the segment context. Overwriting current segment "
+ "named '" + current.getName() + "' to start new segment named '" + segment.getName() + "'.");
}
segment.putAllAws(getAwsRuntimeContext());
if (origin != null) {
segment.setOrigin(origin);
}
segment.putAllService(getServiceRuntimeContext());
if (logReferences != null && !logReferences.isEmpty()) {
segment.putAws(CW_LOGS_KEY, logReferences);
}
setTraceEntity(segment);
segmentListeners.stream()
.filter(Objects::nonNull)
.forEach(listener -> listener.onBeginSegment(segment));
return context.beginSegment(this, segment);
}
/**
* Ends a segment.
*
* @throws SegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and no segment is currently in progress
*/
public void endSegment() {
SegmentContext context = getSegmentContext();
if (context != null) {
context.endSegment(this);
}
Entity current = getTraceEntity();
if (current != null) {
Segment segment = current.getParentSegment();
// Return immediately if ending a no-op segment
if (!segment.isRecording()) {
clearTraceEntity();
return;
}
logger.debug("Ending segment named '" + segment.getName() + "'.");
segmentListeners
.stream()
.filter(Objects::nonNull)
.forEach(listener -> listener.beforeEndSegment(segment));
if (segment.end()) {
sendSegment(segment);
} else {
logger.debug("Not emitting segment named '" + segment.getName() + "' as it parents in-progress subsegments.");
}
segmentListeners
.stream()
.filter(Objects::nonNull)
.forEach(listener -> listener.afterEndSegment(segment));
clearTraceEntity();
} else {
getContextMissingStrategy().contextMissing("Failed to end segment: segment cannot be found.",
SegmentNotFoundException.class);
}
}
/**
* Ends the provided subsegment. This method doesn't touch context storage and should be used when ending custom subsegments
* in asynchronous methods or other threads.
*
* @param subsegment
* the subsegment to close.
*/
public void endSubsegment(@Nullable Subsegment subsegment) {
if (subsegment == null) {
logger.debug("No input subsegment to end. No-op.");
return;
}
boolean rootReady = subsegment.end();
// First handling the special case where its direct parent is a facade segment
if (subsegment.getParent() instanceof FacadeSegment) {
if (((FacadeSegment) subsegment.getParent()).isSampled()) {
getEmitter().sendSubsegment(subsegment);
}
return;
}
// Otherwise we check the happy case where the entire segment is ready
if (rootReady && !(subsegment.getParentSegment() instanceof FacadeSegment)) {
sendSegment(subsegment.getParentSegment());
return;
}
// If not we try to stream closed subsegments regardless the root segment is facade or real
if (this.getStreamingStrategy().requiresStreaming(subsegment.getParentSegment())) {
this.getStreamingStrategy().streamSome(subsegment.getParentSegment(), this.getEmitter());
}
}
/**
* Begins a subsegment.
*
* @param name
* the name to use for the created subsegment
* @throws SegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and no segment is currently in progress
* @return the newly created subsegment, or {@code null} if {@code contextMissingStrategy} suppresses and no segment is
* currently in progress
*/
public Subsegment beginSubsegment(String name) {
SegmentContext context = getSegmentContext();
if (context == null) {
// No context available, we return a no-op subsegment so user code does not have to work around this. Based on
// ContextMissingStrategy they will still know about the issue unless they explicitly opt-ed out.
// This no-op subsegment is different from unsampled no-op subsegments only in that it should not cause trace
// context to be propagated downstream
return Subsegment.noOp(this, false);
}
return context.beginSubsegment(this, name);
}
/**
* Begins a subsegment.
*
* @param name
* the name to use for the created subsegment
* @throws SegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and no segment is currently in progress
* @return the newly created subsegment, or {@code null} if {@code contextMissingStrategy} suppresses and no segment is
* currently in progress. The subsegment will not be sampled regardless of the SamplingStrategy.
*/
public Subsegment beginSubsegmentWithoutSampling(String name) {
SegmentContext context = getSegmentContext();
if (context == null) {
// No context available, we return a no-op subsegment so user code does not have to work around this. Based on
// ContextMissingStrategy they will still know about the issue unless they explicitly opt-ed out.
// This no-op subsegment is different from unsampled no-op subsegments only in that it should not cause trace
// context to be propagated downstream
return Subsegment.noOp(this, false);
}
return context.beginSubsegmentWithoutSampling(this, name);
}
/**
* Ends a subsegment.
*
* @throws SegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and no segment is currently in progress
* @throws SubsegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and no subsegment is currently in progress
*/
public void endSubsegment() {
SegmentContext context = segmentContextResolverChain.resolve();
if (context != null) {
context.endSubsegment(this);
}
}
/**
* @throws SegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and there is no segment in progress
* @return the current segment, or {@code null} if {@code contextMissingStrategy} suppresses exceptions and there is no
* segment in progress
*/
@Nullable
public Segment getCurrentSegment() {
Optional<Segment> segment = getCurrentSegmentOptional();
if (segment.isPresent()) {
return segment.get();
}
contextMissingStrategy.contextMissing("No segment in progress.", SegmentNotFoundException.class);
return null;
}
/**
* @return the current segment, or {@code Optional.empty()} if there is no segment
*/
public Optional<Segment> getCurrentSegmentOptional() {
// explicitly do not throw context missing exceptions from optional-returning methods
SegmentContext context = segmentContextResolverChain.resolve();
if (null == context) {
return Optional.empty();
}
Entity current = context.getTraceEntity();
if (current instanceof Segment) {
return Optional.of((Segment) current);
} else if (current instanceof Subsegment) {
return Optional.of(current.getParentSegment());
} else {
return Optional.empty();
}
}
/**
* @throws SegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and the segment context cannot be found
* @throws SubsegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and the current segment has no subsegments in progress
* @return the current subsegment, or {@code null} if {@code contextMissingStrategy} suppresses exceptions and the segment
* context cannot be found or the segment has no subsegments in progress
*/
@Nullable
public Subsegment getCurrentSubsegment() {
SegmentContext context = getSegmentContext();
if (context == null) {
return null;
}
Entity current = context.getTraceEntity();
if (current == null) {
contextMissingStrategy.contextMissing("No segment in progress.", SegmentNotFoundException.class);
} else if (current instanceof Subsegment) {
return (Subsegment) current;
} else {
contextMissingStrategy.contextMissing("No subsegment in progress.", SubsegmentNotFoundException.class);
}
return null;
}
/**
* @return the current subsegment, or {@code Optional.empty()} if there is no subsegment
*/
public Optional<Subsegment> getCurrentSubsegmentOptional() {
// explicitly do not throw context missing exceptions from optional-returning methods
SegmentContext context = segmentContextResolverChain.resolve();
if (null == context) {
return Optional.empty();
}
Entity current = context.getTraceEntity();
if (current instanceof Subsegment) {
return Optional.of((Subsegment) current);
} else {
return Optional.empty();
}
}
/**
* Injects the provided {@code Entity} into the current thread's thread local context.
*
* @param entity
* the {@code Segment} or {@code Subsegment} to inject into the current thread
*
* @deprecated use {@link #setTraceEntity(Entity entity)} instead
*/
@Deprecated
public void injectThreadLocal(Entity entity) {
ThreadLocalStorage.set(entity);
}
/**
*
* @return the Entity object currently stored in the thread's ThreadLocalStorage
*
* @deprecated use {@link #getTraceEntity()} instead
*/
@Deprecated
@Nullable
public Entity getThreadLocal() {
return ThreadLocalStorage.get();
}
/**
* @deprecated use {@link #clearTraceEntity()} instead
*/
@Deprecated
public void clearThreadLocal() {
ThreadLocalStorage.clear();
}
@Nullable
private SegmentContext getSegmentContext() {
SegmentContext context = segmentContextResolverChain.resolve();
if (context == null) {
contextMissingStrategy.contextMissing("Segment context not found.", SegmentNotFoundException.class);
return null;
}
return context;
}
/**
* Sets the trace entity value using the implementation provided by the SegmentContext resolved from the
* segmentContextResolverChain.
*
* @param entity
* the trace entity to set
*
* @deprecated Use {@link Entity#run(Runnable)} or methods in {@link SegmentContextExecutors} instead of directly setting
* the trace entity so it can be restored correctly.
*/
@Deprecated
public void setTraceEntity(@Nullable Entity entity) {
SegmentContext context = getSegmentContext();
if (context == null) {
return;
}
context.setTraceEntity(entity);
}
/**
* Gets the current trace entity value using the implementation provided by the SegmentContext resolved from the
* segmentContextResolverChain.
*
* @return the current trace entity
*/
@Nullable
public Entity getTraceEntity() {
SegmentContext context = getSegmentContext();
if (context == null) {
return null;
}
return context.getTraceEntity();
}
/**
* Clears the current trace entity value using the implementation provided by the SegmentContext resolved from the
* segmentContextResolverChain.
*
*/
public void clearTraceEntity() {
SegmentContext context = getSegmentContext();
if (context == null) {
return;
}
context.clearTraceEntity();
}
public void putRuntimeContext(String key, Object value) {
if (value == null) {
value = "";
}
awsRuntimeContext.put(key, value);
}
public void addAllLogReferences(Set<AWSLogReference> logReferences) {
this.logReferences.addAll(logReferences);
}
/**
* @return the samplingStrategy
*/
public SamplingStrategy getSamplingStrategy() {
return samplingStrategy;
}
/**
* @param samplingStrategy the samplingStrategy to set
*/
public void setSamplingStrategy(SamplingStrategy samplingStrategy) {
this.samplingStrategy = samplingStrategy;
}
/**
* @return the streamingStrategy
*/
public StreamingStrategy getStreamingStrategy() {
return streamingStrategy;
}
/**
* @param streamingStrategy the streamingStrategy to set
*/
public void setStreamingStrategy(StreamingStrategy streamingStrategy) {
this.streamingStrategy = streamingStrategy;
}
/**
* @return the prioritizationStrategy
*/
public PrioritizationStrategy getPrioritizationStrategy() {
return prioritizationStrategy;
}
/**
* @param prioritizationStrategy the prioritizationStrategy to set
*/
public void setPrioritizationStrategy(PrioritizationStrategy prioritizationStrategy) {
this.prioritizationStrategy = prioritizationStrategy;
}
/**
* @return the throwableSerializationStrategy
*/
public ThrowableSerializationStrategy getThrowableSerializationStrategy() {
return throwableSerializationStrategy;
}
/**
* @param throwableSerializationStrategy the throwableSerializationStrategy to set
*/
public void setThrowableSerializationStrategy(ThrowableSerializationStrategy throwableSerializationStrategy) {
this.throwableSerializationStrategy = throwableSerializationStrategy;
}
/**
* @return the contextMissingStrategy
*/
public ContextMissingStrategy getContextMissingStrategy() {
return contextMissingStrategy;
}
/**
* @param contextMissingStrategy the contextMissingStrategy to set
*/
public void setContextMissingStrategy(ContextMissingStrategy contextMissingStrategy) {
this.contextMissingStrategy = contextMissingStrategy;
}
/**
* @return the segmentContextResolverChain
*/
public SegmentContextResolverChain getSegmentContextResolverChain() {
return segmentContextResolverChain;
}
/**
* @param segmentContextResolverChain the segmentContextResolverChain to set
*/
public void setSegmentContextResolverChain(SegmentContextResolverChain segmentContextResolverChain) {
this.segmentContextResolverChain = segmentContextResolverChain;
}
/**
* @return the emitter
*/
public Emitter getEmitter() {
return emitter;
}
/**
* @param emitter the emitter to set
*/
public void setEmitter(Emitter emitter) {
this.emitter = emitter;
}
/**
* Returns the list of SegmentListeners attached to the recorder
*
* @return the SegmentListeners
*/
public ArrayList<SegmentListener> getSegmentListeners() {
return segmentListeners;
}
/**
* Adds a single SegmentListener to the recorder
*
* @param segmentListener a SegmentListener to add
*/
public void addSegmentListener(SegmentListener segmentListener) {
this.segmentListeners.add(segmentListener);
}
/**
* Adds a Collection of SegmentListeners to the recorder
*
* @param segmentListeners a Collection of SegmentListeners to add
*/
public void addAllSegmentListeners(Collection<SegmentListener> segmentListeners) {
this.segmentListeners.addAll(segmentListeners);
}
/**
* @return the awsRuntimeContext
*/
public Map<String, Object> getAwsRuntimeContext() {
return awsRuntimeContext;
}
/**
* @return the serviceRuntimeContext
*/
public Map<String, Object> getServiceRuntimeContext() {
return serviceRuntimeContext;
}
/**
* @return the origin
*/
@Nullable
public String getOrigin() {
return origin;
}
/**
* @param origin the origin to set
*/
public void setOrigin(String origin) {
this.origin = origin;
}
/**
* Configures this {@code AWSXRayRecorder} to use a fast but cryptographically insecure random number
* generator for generating random IDs. This option should be preferred if your application does not
* rely on AWS X-Ray Trace IDs being generated from a cryptographically secure random number generator.
*
* @see #useSecureIdGenerator()
*/
public final void useFastIdGenerator() {
this.idGenerator = new FastIdGenerator();
}
/**
* Configures this {@code AWSXRayRecorder} to use a cryptographically secure random generator for
* generating random IDs. Unless your application in some way relies on AWS X-Ray trace IDs
* being generated from a cryptographically secure random number source, you should prefer
* to use {@linkplain #useFastIdGenerator() the fast ID generator}.
*
* @see #useFastIdGenerator()
*/
public final void useSecureIdGenerator() {
this.idGenerator = new SecureIdGenerator();
}
/**
* Gets this {@code AWSXRayRecorder} instance's ID generator. This method is intended for
* internal use only.
*
* @return the configured ID generator
*/
public final IdGenerator getIdGenerator() {
return idGenerator;
}
/**
* Checks whether the current {@code SamplingStrategy} supports forced sampling. Use with caution, since segments sampled in
* this manner will not count towards your sampling statistic counts.
*
* @return true if forced sampling is supported and the current segment was changed from not sampled to sampled.
*/
public boolean forceSamplingOfCurrentSegment() {
if (samplingStrategy.isForcedSamplingSupported()) {
Segment segment = getCurrentSegment();
if (segment != null && !segment.isSampled()) {
segment.setSampled(true);
return true;
}
}
return false;
}
/**
*
* @throws SegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and no segment or subsegment is currently in progress
* @return the ID of the {@code Segment} or {@code Subsegment} currently in progress, or {@code null} if
* {@code contextMissingStrategy} suppresses exceptions and no segment or subsegment is currently in progress
*/
@Nullable
public String currentEntityId() {
SegmentContext context = getSegmentContext();
if (context == null) {
return null;
}
Entity current = context.getTraceEntity();
if (current != null) {
return current.getId();
} else {
contextMissingStrategy.contextMissing("Failed to get current entity ID: segment or subsegment cannot be found.",
SegmentNotFoundException.class);
return null;
}
}
/**
*
* @throws SegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and no segment or subsegment is currently in progress
* @return the trace ID of the {@code Segment} currently in progress, or {@code null} if {@code contextMissingStrategy}
* suppresses exceptions and no segment or subsegment is currently in progress
*/
@Nullable
public TraceID currentTraceId() {
SegmentContext context = getSegmentContext();
if (context == null) {
return null;
}
Entity current = context.getTraceEntity();
if (current != null) {
return current.getParentSegment().getTraceId();
} else {
contextMissingStrategy.contextMissing("Failed to get current trace ID: segment cannot be found.",
SegmentNotFoundException.class);
return null;
}
}
/**
*
* @throws SegmentNotFoundException
* if {@code contextMissingStrategy} throws exceptions and no segment or subsegment is currently in progress
* @return the trace ID of the {@code Segment} currently in progress and the ID of the {@code Segment} or {@code Subsegment}
* in progress, joined with {@code @}, or {@code null} if {@code contextMissingStrategy} suppresses exceptions and no segment
* or subsegment is currently in progress
*/
@Nullable
public String currentFormattedId() {
SegmentContext context = getSegmentContext();
if (context == null) {
return null;
}
Entity current = context.getTraceEntity();
if (current != null) {
TraceID traceId = current.getParentSegment().getTraceId();
String entityId = current.getId();
return traceId.toString() + "@" + entityId;
} else {
contextMissingStrategy.contextMissing("Failed to get current formatted ID: segment cannot be found.",
SegmentNotFoundException.class);
return null;
}
}
/**
* Configures this {@code AWSXRayRecorder} to add valid TraceId in all segments even NoOp ones that usually have
* a fixed value.
*/
public void setForcedTraceIdGeneration(final boolean alwaysCreateTraceId) {
this.forcedTraceIdGeneration = alwaysCreateTraceId;
}
}
| 3,781 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/ThreadLocalStorage.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray;
import com.amazonaws.xray.entities.Entity;
import java.security.SecureRandom;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* @deprecated For internal use only.
*/
@SuppressWarnings("checkstyle:HideUtilityClassConstructor")
@Deprecated
public class ThreadLocalStorage {
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
static class LocalEntity extends ThreadLocal<@Nullable Entity> {
@Override
@Nullable
protected Entity initialValue() {
return null;
}
}
private static final LocalEntity CURRENT_ENTITY = new LocalEntity();
@Nullable
public static Entity get() {
return CURRENT_ENTITY.get();
}
public static boolean any() {
return CURRENT_ENTITY.get() != null;
}
public static void set(@Nullable Entity entity) {
CURRENT_ENTITY.set(entity);
}
/**
* Clears the current stored entity.
*
*/
public static void clear() {
CURRENT_ENTITY.remove();
}
@Deprecated
public static SecureRandom getRandom() {
return SECURE_RANDOM;
}
}
| 3,782 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/AWSXRayRecorderBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray;
import com.amazonaws.xray.contexts.SegmentContextResolverChain;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.AWSLogReference;
import com.amazonaws.xray.entities.StringValidator;
import com.amazonaws.xray.listeners.SegmentListener;
import com.amazonaws.xray.plugins.EC2Plugin;
import com.amazonaws.xray.plugins.ECSPlugin;
import com.amazonaws.xray.plugins.EKSPlugin;
import com.amazonaws.xray.plugins.ElasticBeanstalkPlugin;
import com.amazonaws.xray.plugins.Plugin;
import com.amazonaws.xray.strategy.ContextMissingStrategy;
import com.amazonaws.xray.strategy.IgnoreErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.LogErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.PrioritizationStrategy;
import com.amazonaws.xray.strategy.RuntimeErrorContextMissingStrategy;
import com.amazonaws.xray.strategy.StreamingStrategy;
import com.amazonaws.xray.strategy.ThrowableSerializationStrategy;
import com.amazonaws.xray.strategy.sampling.SamplingStrategy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
public class AWSXRayRecorderBuilder {
private static final Log logger =
LogFactory.getLog(AWSXRayRecorderBuilder.class);
private static final Map<String, Integer> ORIGIN_PRIORITY;
private static final String LOG_GROUP_KEY = "AWS_LOG_GROUP";
static {
HashMap<String, Integer> originPriority = new HashMap<>();
originPriority.put(ElasticBeanstalkPlugin.ORIGIN, 0);
originPriority.put(EKSPlugin.ORIGIN, 1);
originPriority.put(ECSPlugin.ORIGIN, 2);
originPriority.put(EC2Plugin.ORIGIN, 3);
ORIGIN_PRIORITY = Collections.unmodifiableMap(originPriority);
}
private final Set<Plugin> plugins;
private final List<SegmentListener> segmentListeners;
@Nullable
private SamplingStrategy samplingStrategy;
@Nullable
private StreamingStrategy streamingStrategy;
@Nullable
private PrioritizationStrategy prioritizationStrategy;
@Nullable
private ThrowableSerializationStrategy throwableSerializationStrategy;
@Nullable
private ContextMissingStrategy contextMissingStrategy;
@Nullable
private SegmentContextResolverChain segmentContextResolverChain;
@Nullable
private Emitter emitter;
private boolean useFastIdGenerator = false;
private boolean forcedTraceIdGeneration = false;
private AWSXRayRecorderBuilder() {
plugins = new HashSet<>();
segmentListeners = new ArrayList<>();
}
public static Optional<ContextMissingStrategy> contextMissingStrategyFromEnvironmentVariable() {
String contextMissingStrategyOverrideValue = System.getenv(
ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_ENVIRONMENT_VARIABLE_OVERRIDE_KEY);
return getContextMissingStrategy(contextMissingStrategyOverrideValue);
}
public static Optional<ContextMissingStrategy> contextMissingStrategyFromSystemProperty() {
String contextMissingStrategyOverrideValue = System.getProperty(
ContextMissingStrategy.CONTEXT_MISSING_STRATEGY_SYSTEM_PROPERTY_OVERRIDE_KEY);
return getContextMissingStrategy(contextMissingStrategyOverrideValue);
}
private static Optional<ContextMissingStrategy> getContextMissingStrategy(
@Nullable String contextMissingStrategyOverrideValue) {
if (contextMissingStrategyOverrideValue != null) {
if (contextMissingStrategyOverrideValue.equalsIgnoreCase(LogErrorContextMissingStrategy.OVERRIDE_VALUE)) {
return Optional.of(new LogErrorContextMissingStrategy());
} else if (contextMissingStrategyOverrideValue.equalsIgnoreCase(RuntimeErrorContextMissingStrategy.OVERRIDE_VALUE)) {
return Optional.of(new RuntimeErrorContextMissingStrategy());
} else if (contextMissingStrategyOverrideValue.equalsIgnoreCase(IgnoreErrorContextMissingStrategy.OVERRIDE_VALUE)) {
return Optional.of(new IgnoreErrorContextMissingStrategy());
}
}
return Optional.empty();
}
/**
* @return A new builder instance with all defaults set.
*/
public static AWSXRayRecorderBuilder standard() {
return new AWSXRayRecorderBuilder();
}
/**
* @return An instance of {@code AWSXRayRecorder} using the
* {@link com.amazonaws.xray.strategy.sampling.DefaultSamplingStrategy},
* {@link com.amazonaws.xray.strategy.DefaultPrioritizationStrategy}, along with other default strategies and settings.
*/
public static AWSXRayRecorder defaultRecorder() {
return standard().build();
}
/**
* Adds a plugin to the list of plugins which the builder will execute at build time. This method is execution-order
* sensitive. Values overriden by plugins later in the list will be kept (e.g. origin).
*
* @param plugin
* the plugin to add
* @return
* the builder instance, for chaining
*/
public AWSXRayRecorderBuilder withPlugin(Plugin plugin) {
plugins.add(plugin);
return this;
}
public AWSXRayRecorderBuilder withSamplingStrategy(SamplingStrategy samplingStrategy) {
this.samplingStrategy = samplingStrategy;
return this;
}
public AWSXRayRecorderBuilder withStreamingStrategy(StreamingStrategy streamingStrategy) {
this.streamingStrategy = streamingStrategy;
return this;
}
public AWSXRayRecorderBuilder withPrioritizationStrategy(PrioritizationStrategy prioritizationStrategy) {
this.prioritizationStrategy = prioritizationStrategy;
return this;
}
public AWSXRayRecorderBuilder withThrowableSerializationStrategy(
ThrowableSerializationStrategy throwableSerializationStrategy) {
this.throwableSerializationStrategy = throwableSerializationStrategy;
return this;
}
public AWSXRayRecorderBuilder withEmitter(Emitter emitter) {
this.emitter = emitter;
return this;
}
public AWSXRayRecorderBuilder withSegmentContextResolverChain(SegmentContextResolverChain segmentContextResolverChain) {
this.segmentContextResolverChain = segmentContextResolverChain;
return this;
}
/**
* Adds a SegmentListener to the list of segment listeners that will be attached to the recorder at build time.
*
* @param segmentListener
* the SegmentListener to add
* @return
* the builder instance, for chaining
*/
public AWSXRayRecorderBuilder withSegmentListener(SegmentListener segmentListener) {
this.segmentListeners.add(segmentListener);
return this;
}
/**
* Prepares this builder to build an instance of {@code AWSXRayRecorder} with the provided context missing strategy. This
* value will be overriden at {@code build()} time if either the environment variable with key
* {@code AWS_XRAY_CONTEXT_MISSING} or system property with key {@code com.amazonaws.xray.strategy.contextMissingStrategy} are
* set to a valid value.
*
* @param contextMissingStrategy
* the context missing strategy to be used if both the environment variable with key
* {@code AWS_XRAY_CONTEXT_MISSING} or system property with key
* {@code com.amazonaws.xray.strategy.contextMissingStrategy} are not set to a valid value
* @return
* the builder instance, for chaining
* @see ContextMissingStrategy
*/
public AWSXRayRecorderBuilder withContextMissingStrategy(ContextMissingStrategy contextMissingStrategy) {
this.contextMissingStrategy = contextMissingStrategy;
return this;
}
/**
* Adds all implemented plugins to the builder instance rather than requiring them to be individually added. The recorder will
* only reflect metadata from plugins that are enabled, which is checked in the build method below.
*
* @return
* The builder instance, for chaining
*/
public AWSXRayRecorderBuilder withDefaultPlugins() {
plugins.add(new EC2Plugin());
plugins.add(new ECSPlugin());
plugins.add(new EKSPlugin());
plugins.add(new ElasticBeanstalkPlugin());
return this;
}
/**
* Prepares this builder to build an {@code AWSXRayRecorder} which uses a fast but cryptographically insecure
* random number generator for generating random IDs. This option should be preferred unless your application
* relies on AWS X-Ray trace IDs being generated from a cryptographically secure random number source.
*
* @see #withSecureIdGenerator()
*/
public AWSXRayRecorderBuilder withFastIdGenerator() {
this.useFastIdGenerator = true;
return this;
}
/**
* Prepares this builder to build an {@code AWSXRayRecorder} which uses a cryptographically secure random
* generator for generating random IDs. Unless your application relies on AWS X-Ray trace IDs
* being generated from a cryptographically secure random number source, you should prefer
* to use {@linkplain #withFastIdGenerator() the fast ID generator}.
*
* @see #withFastIdGenerator()
*/
public AWSXRayRecorderBuilder withSecureIdGenerator() {
this.useFastIdGenerator = false;
return this;
}
/**
* Prepares this builder to build an {@code AWSXRayRecorder} which creates Trace ID for all Segments
* even for NoOpSegments or not sampled ones that usually include include a static invalid TraceID.
* This could be useful for example in case the Trace ID is logged to be able to aggregate all logs from a
* single request
*/
public AWSXRayRecorderBuilder withForcedTraceIdGeneration() {
this.forcedTraceIdGeneration = true;
return this;
}
/**
* Constructs and returns an AWSXRayRecorder with the provided configuration.
*
* @return a configured instance of AWSXRayRecorder
*/
public AWSXRayRecorder build() {
AWSXRayRecorder client = new AWSXRayRecorder();
if (samplingStrategy != null) {
client.setSamplingStrategy(samplingStrategy);
}
if (streamingStrategy != null) {
client.setStreamingStrategy(streamingStrategy);
}
if (prioritizationStrategy != null) {
client.setPrioritizationStrategy(prioritizationStrategy);
}
if (throwableSerializationStrategy != null) {
client.setThrowableSerializationStrategy(throwableSerializationStrategy);
}
ContextMissingStrategy contextMissingStrategy = this.contextMissingStrategy;
if (contextMissingStrategy != null &&
!AWSXRayRecorderBuilder.contextMissingStrategyFromEnvironmentVariable().isPresent() &&
!AWSXRayRecorderBuilder.contextMissingStrategyFromSystemProperty().isPresent()) {
client.setContextMissingStrategy(contextMissingStrategy);
}
if (segmentContextResolverChain != null) {
client.setSegmentContextResolverChain(segmentContextResolverChain);
}
if (emitter != null) {
client.setEmitter(emitter);
}
if (!segmentListeners.isEmpty()) {
client.addAllSegmentListeners(segmentListeners);
}
if (useFastIdGenerator) {
client.useFastIdGenerator();
} else {
client.useSecureIdGenerator();
}
if (forcedTraceIdGeneration) {
client.setForcedTraceIdGeneration(true);
}
plugins.stream().filter(Objects::nonNull).filter(p -> p.isEnabled()).forEach(plugin -> {
logger.info("Collecting trace metadata from " + plugin.getClass().getName() + ".");
try {
Map<String, @Nullable Object> runtimeContext = plugin.getRuntimeContext();
if (!runtimeContext.isEmpty()) {
client.putRuntimeContext(plugin.getServiceName(), runtimeContext);
/**
* Given several enabled plugins, the recorder should resolve a single one that's most representative of this
* environment
* Resolution order: EB > EKS > ECS > EC2
* EKS > ECS because the ECS plugin checks for an environment variable whereas the EKS plugin checks for a
* kubernetes authentication file, which is a stronger enable condition
*/
String clientOrigin = client.getOrigin();
if (clientOrigin == null ||
ORIGIN_PRIORITY.getOrDefault(plugin.getOrigin(), 0) <
ORIGIN_PRIORITY.getOrDefault(clientOrigin, 0)) {
client.setOrigin(plugin.getOrigin());
}
} else {
logger.warn(plugin.getClass().getName() + " plugin returned empty runtime context data. The recorder will "
+ "not be setting segment origin or runtime context values from this plugin.");
}
} catch (Exception e) {
logger.warn("Failed to get runtime context from " + plugin.getClass().getName() + ".", e);
}
try {
Set<AWSLogReference> logReferences = plugin.getLogReferences();
if (Objects.nonNull(logReferences)) {
if (!logReferences.isEmpty()) {
client.addAllLogReferences(logReferences);
} else {
logger.debug(plugin.getClass().getName() + " plugin returned empty Log References. The recorder will not "
+ "reflect the logs from this plugin.");
}
}
} catch (Exception e) {
logger.warn("Failed to get log references from " + plugin.getClass().getName() + ".", e);
}
});
String logGroupFromEnv = System.getenv(LOG_GROUP_KEY);
if (StringValidator.isNotNullOrBlank(logGroupFromEnv)) {
logger.info("Recording log group " + logGroupFromEnv + " from environment variable.");
AWSLogReference logReference = new AWSLogReference();
logReference.setLogGroup(logGroupFromEnv);
client.addAllLogReferences(Collections.singleton(logReference));
}
return client;
}
}
| 3,783 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/AWSXRay.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray;
import com.amazonaws.xray.contexts.SegmentContextExecutors;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceID;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static helper class which holds reference to a global client and provides a static interface for invoking methods on the
* client.
*/
public class AWSXRay {
private static AWSXRayRecorder globalRecorder = AWSXRayRecorderBuilder.defaultRecorder();
/**
* Gets the global {@code AWSXRayRecorder}. This is initialized using {@code AWSXRayRecorderBuilder.defaultRecorder()}.
*
* See {@link #setGlobalRecorder(AWSXRayRecorder)}.
*
* @return the global AWSXRayRecorder
*/
public static AWSXRayRecorder getGlobalRecorder() {
return globalRecorder;
}
/**
* Sets the global {@code AWSXRayRecorder}.
*
* See {@link #getGlobalRecorder}.
*
* @param globalRecorder
* the instance of AWSXRayRecorder to set as global
*/
public static void setGlobalRecorder(AWSXRayRecorder globalRecorder) {
AWSXRay.globalRecorder = globalRecorder;
}
@Nullable
public static <R> R createSegment(String name, Function<Segment, @Nullable R> function) {
return globalRecorder.createSegment(name, function);
}
public static void createSegment(String name, Consumer<Segment> consumer) {
globalRecorder.createSegment(name, consumer);
}
@Nullable
public static <R> R createSegment(String name, Supplier<R> supplier) {
return globalRecorder.createSegment(name, supplier);
}
public static void createSegment(String name, Runnable runnable) {
globalRecorder.createSegment(name, runnable);
}
@Nullable
public static <R> R createSubsegment(String name, Function<Subsegment, @Nullable R> function) {
return globalRecorder.createSubsegment(name, function);
}
public static void createSubsegment(String name, Consumer<Subsegment> consumer) {
globalRecorder.createSubsegment(name, consumer);
}
@Nullable
public static <R> R createSubsegment(String name, Supplier<R> supplier) {
return globalRecorder.createSubsegment(name, supplier);
}
public static void createSubsegment(String name, Runnable runnable) {
globalRecorder.createSubsegment(name, runnable);
}
public static Segment beginSegmentWithSampling(String name) {
return globalRecorder.beginSegmentWithSampling(name);
}
public static Segment beginSegment(String name) {
return globalRecorder.beginSegment(name);
}
public static Segment beginSegment(String name, TraceID traceId, String parentId) {
return globalRecorder.beginSegment(name, traceId, parentId);
}
/**
* @deprecated Use {@code AWSXRay.getGlobalRecorder().beginNoOpSegment() }.
*/
@Deprecated
public static Segment beginDummySegment() {
return globalRecorder.beginNoOpSegment();
}
public static void endSegment() {
globalRecorder.endSegment();
}
public static Subsegment beginSubsegment(String name) {
return globalRecorder.beginSubsegment(name);
}
public static Subsegment beginSubsegmentWithoutSampling(String name) {
return globalRecorder.beginSubsegmentWithoutSampling(name);
}
public static void endSubsegment() {
globalRecorder.endSubsegment();
}
public static void endSubsegment(@Nullable Subsegment subsegment) {
globalRecorder.endSubsegment(subsegment);
}
@Nullable
public String currentEntityId() {
return globalRecorder.currentEntityId();
}
@Nullable
public TraceID currentTraceId() {
return globalRecorder.currentTraceId();
}
@Nullable
public static String currentFormattedId() {
return globalRecorder.currentFormattedId();
}
@Nullable
public static Segment getCurrentSegment() {
return globalRecorder.getCurrentSegment();
}
public static Optional<Segment> getCurrentSegmentOptional() {
return globalRecorder.getCurrentSegmentOptional();
}
@Nullable
public static Subsegment getCurrentSubsegment() {
return globalRecorder.getCurrentSubsegment();
}
public static Optional<Subsegment> getCurrentSubsegmentOptional() {
return globalRecorder.getCurrentSubsegmentOptional();
}
/**
* @deprecated use {@link #setTraceEntity(Entity entity)} instead
*/
@Deprecated
public static void injectThreadLocal(Entity entity) {
globalRecorder.injectThreadLocal(entity);
}
/**
* @deprecated use {@link #getTraceEntity()} instead
*/
@Deprecated
@Nullable
public static Entity getThreadLocal() {
return globalRecorder.getThreadLocal();
}
/**
* @deprecated use {@link #clearTraceEntity()} instead
*/
@Deprecated
public static void clearThreadLocal() {
globalRecorder.clearThreadLocal();
}
/**
* @deprecated Use {@link Entity#run(Runnable)} or methods in {@link SegmentContextExecutors} instead of directly setting
* the trace entity so it can be restored correctly.
*/
@Deprecated
public static void setTraceEntity(@Nullable Entity entity) {
globalRecorder.setTraceEntity(entity);
}
@Nullable
public static Entity getTraceEntity() {
return globalRecorder.getTraceEntity();
}
public static void clearTraceEntity() {
globalRecorder.clearTraceEntity();
}
public static boolean sendSegment(Segment segment) {
return globalRecorder.sendSegment(segment);
}
/**
* @deprecated use {@link #sendSubsegment(Subsegment)} instead
*/
@Deprecated
public static boolean sendSubegment(Subsegment subsegment) {
return AWSXRay.sendSubsegment(subsegment);
}
public static boolean sendSubsegment(Subsegment subsegment) {
return globalRecorder.sendSubsegment(subsegment);
}
}
| 3,784 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/contexts/SegmentContextResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import org.checkerframework.checker.nullness.qual.Nullable;
public interface SegmentContextResolver {
@Nullable
SegmentContext resolve();
}
| 3,785 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/contexts/LambdaSegmentContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.FacadeSegment;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.SubsegmentImpl;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.entities.TraceHeader.SampleDecision;
import com.amazonaws.xray.entities.TraceID;
import com.amazonaws.xray.exceptions.SubsegmentNotFoundException;
import com.amazonaws.xray.listeners.SegmentListener;
import java.util.List;
import java.util.Objects;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class LambdaSegmentContext implements SegmentContext {
private static final Log logger = LogFactory.getLog(LambdaSegmentContext.class);
private static final String LAMBDA_TRACE_HEADER_KEY = "_X_AMZN_TRACE_ID";
// See: https://github.com/aws/aws-xray-sdk-java/issues/251
private static final String LAMBDA_TRACE_HEADER_PROP = "com.amazonaws.xray.traceHeader";
private static TraceHeader getTraceHeaderFromEnvironment() {
String lambdaTraceHeaderKey = System.getenv(LAMBDA_TRACE_HEADER_KEY);
return TraceHeader.fromString(lambdaTraceHeaderKey != null && lambdaTraceHeaderKey.length() > 0
? lambdaTraceHeaderKey
: System.getProperty(LAMBDA_TRACE_HEADER_PROP));
}
private static boolean isInitializing(TraceHeader traceHeader) {
return traceHeader.getRootTraceId() == null || traceHeader.getSampled() == null || traceHeader.getParentId() == null;
}
private static FacadeSegment newFacadeSegment(AWSXRayRecorder recorder, String name) {
TraceHeader traceHeader = getTraceHeaderFromEnvironment();
if (isInitializing(traceHeader)) {
logger.warn(LAMBDA_TRACE_HEADER_KEY + " is missing a trace ID, parent ID, or sampling decision. Subsegment "
+ name + " discarded.");
return new FacadeSegment(recorder, TraceID.create(recorder), "", SampleDecision.NOT_SAMPLED);
}
return new FacadeSegment(recorder, traceHeader.getRootTraceId(), traceHeader.getParentId(), traceHeader.getSampled());
}
@Override
public Subsegment beginSubsegment(AWSXRayRecorder recorder, String name) {
if (logger.isDebugEnabled()) {
logger.debug("Beginning subsegment named: " + name);
}
Entity entity = getTraceEntity();
if (entity == null) { // First subsgment of a subsegment branch.
Segment parentSegment = newFacadeSegment(recorder, name);
boolean isRecording = parentSegment.isRecording();
Subsegment subsegment = isRecording
? new SubsegmentImpl(recorder, name, parentSegment)
: Subsegment.noOp(parentSegment, recorder);
subsegment.setParent(parentSegment);
// Enable FacadeSegment to keep track of its subsegments for subtree streaming
parentSegment.addSubsegment(subsegment);
setTraceEntity(subsegment);
return subsegment;
} else { // Continuation of a subsegment branch.
Subsegment parentSubsegment = (Subsegment) entity;
// Ensure customers have not leaked subsegments across invocations
TraceID environmentRootTraceId = LambdaSegmentContext.getTraceHeaderFromEnvironment().getRootTraceId();
if (environmentRootTraceId != null &&
!environmentRootTraceId.equals(parentSubsegment.getParentSegment().getTraceId())) {
clearTraceEntity();
return beginSubsegment(recorder, name);
}
Segment parentSegment = parentSubsegment.getParentSegment();
boolean isRecording = parentSubsegment.isRecording();
Subsegment subsegment = isRecording
? new SubsegmentImpl(recorder, name, parentSegment)
: Subsegment.noOp(parentSegment, recorder, name);
subsegment.setParent(parentSubsegment);
parentSubsegment.addSubsegment(subsegment);
setTraceEntity(subsegment);
List<SegmentListener> segmentListeners = recorder.getSegmentListeners();
segmentListeners.stream()
.filter(Objects::nonNull)
.forEach(listener -> listener.onBeginSubsegment(subsegment));
return subsegment;
}
}
@Override
public void endSubsegment(AWSXRayRecorder recorder) {
Entity current = getTraceEntity();
if (current instanceof Subsegment) {
if (logger.isDebugEnabled()) {
if (current.getName().isEmpty() && !current.getParentSegment().isSampled()) {
logger.debug("Ending no-op subsegment");
} else {
logger.debug("Ending subsegment named: " + current.getName());
}
}
Subsegment currentSubsegment = (Subsegment) current;
List<SegmentListener> segmentListeners = recorder.getSegmentListeners();
segmentListeners
.stream()
.filter(Objects::nonNull)
.forEach(listener -> listener.beforeEndSubsegment(currentSubsegment));
currentSubsegment.end();
if (recorder.getStreamingStrategy().requiresStreaming(currentSubsegment.getParentSegment())) {
recorder.getStreamingStrategy().streamSome(currentSubsegment.getParentSegment(), recorder.getEmitter());
}
segmentListeners
.stream()
.filter(Objects::nonNull)
.forEach(listener -> listener.afterEndSubsegment(currentSubsegment));
Entity parentEntity = current.getParent();
if (parentEntity instanceof FacadeSegment) {
if (((Subsegment) current).isSampled()) {
current.getCreator().getEmitter().sendSubsegment((Subsegment) current);
}
clearTraceEntity();
} else {
setTraceEntity(current.getParent());
}
} else {
recorder.getContextMissingStrategy().contextMissing("Failed to end subsegment: subsegment cannot be found.",
SubsegmentNotFoundException.class);
}
}
}
| 3,786 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/contexts/ResolverChain.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import org.checkerframework.checker.nullness.qual.Nullable;
public interface ResolverChain<T> {
@Nullable
T resolve();
}
| 3,787 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/contexts/SegmentContextResolverChain.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
public class SegmentContextResolverChain implements ResolverChain<SegmentContext> {
private final List<SegmentContextResolver> resolvers = new ArrayList<>();
public void addResolver(SegmentContextResolver resolver) {
resolvers.add(resolver);
}
@Override
@Nullable
public SegmentContext resolve() {
for (SegmentContextResolver resolver : resolvers) {
SegmentContext ctx = resolver.resolve();
if (ctx != null) {
return ctx;
}
}
return null;
}
}
| 3,788 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/contexts/LambdaSegmentContextResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import com.amazonaws.xray.entities.StringValidator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.attribute.FileTime;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
public class LambdaSegmentContextResolver implements SegmentContextResolver {
private static final Log logger = LogFactory.getLog(LambdaSegmentContextResolver.class);
private static final String LAMBDA_TASK_ROOT_KEY = "LAMBDA_TASK_ROOT";
private static final String SDK_INITIALIZED_FILE_LOCATION = "/tmp/.aws-xray/initialized";
static {
if (StringValidator.isNotNullOrBlank(LambdaSegmentContextResolver.getLambdaTaskRoot())) {
boolean success = true;
long now = System.currentTimeMillis();
File f = new File(SDK_INITIALIZED_FILE_LOCATION);
File dir = f.getParentFile();
if (dir != null) {
dir.mkdirs();
}
try {
OutputStream out = new FileOutputStream(f);
out.close();
Files.setAttribute(f.toPath(), "lastAccessTime", FileTime.fromMillis(now));
} catch (IOException ioe) {
success = false;
}
if (!success || !f.setLastModified(now)) {
logger.warn("Unable to write to " + SDK_INITIALIZED_FILE_LOCATION + ". Failed to signal SDK initialization.");
}
}
}
@Nullable
private static String getLambdaTaskRoot() {
return System.getenv(LambdaSegmentContextResolver.LAMBDA_TASK_ROOT_KEY);
}
@Override
@Nullable
public SegmentContext resolve() {
String lambdaTaskRootValue = LambdaSegmentContextResolver.getLambdaTaskRoot();
if (StringValidator.isNotNullOrBlank(lambdaTaskRootValue)) {
logger.debug(LAMBDA_TASK_ROOT_KEY + " is set. Lambda context detected.");
return new LambdaSegmentContext();
}
return null;
}
}
| 3,789 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/contexts/SegmentContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.ThreadLocalStorage;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.internal.SamplingStrategyOverride;
import java.util.Objects;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
public interface SegmentContext {
/**
* @deprecated Will be removed.
*/
@Deprecated
Log logger = LogFactory.getLog(SegmentContext.class);
default Segment beginSegment(AWSXRayRecorder recorder, Segment segment) {
return segment;
}
default void endSegment(AWSXRayRecorder recorder) {
}
@Nullable
default Entity getTraceEntity() {
return ThreadLocalStorage.get();
}
default void setTraceEntity(@Nullable Entity entity) {
if (entity != null && entity.getCreator() != null) {
entity.getCreator().getSegmentListeners().stream().filter(Objects::nonNull).forEach(l -> {
l.onSetEntity(ThreadLocalStorage.get(), entity);
});
}
ThreadLocalStorage.set(entity);
}
default void clearTraceEntity() {
Entity oldEntity = ThreadLocalStorage.get();
if (oldEntity != null && oldEntity.getCreator() != null) {
oldEntity.getCreator().getSegmentListeners().stream().filter(Objects::nonNull).forEach(l -> {
l.onClearEntity(oldEntity);
});
}
ThreadLocalStorage.clear();
}
Subsegment beginSubsegment(AWSXRayRecorder recorder, String name);
default Subsegment beginSubsegmentWithoutSampling(
AWSXRayRecorder recorder,
String name)
{
Subsegment subsegment = beginSubsegment(recorder, name);
subsegment.setSampledFalse();
return subsegment;
}
@Deprecated
default Subsegment beginSubsegmentWithSamplingOverride(
AWSXRayRecorder recorder,
String name,
SamplingStrategyOverride samplingStrategyOverride) {
if (samplingStrategyOverride == SamplingStrategyOverride.DISABLED) {
return beginSubsegment(recorder, name);
} else {
return beginSubsegmentWithoutSampling(recorder, name);
}
}
void endSubsegment(AWSXRayRecorder recorder);
}
| 3,790 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/contexts/ThreadLocalSegmentContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.SubsegmentImpl;
import com.amazonaws.xray.exceptions.SegmentNotFoundException;
import com.amazonaws.xray.exceptions.SubsegmentNotFoundException;
import com.amazonaws.xray.listeners.SegmentListener;
import java.util.List;
import java.util.Objects;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ThreadLocalSegmentContext implements SegmentContext {
private static final Log logger =
LogFactory.getLog(ThreadLocalSegmentContext.class);
@Override
public Subsegment beginSubsegment(AWSXRayRecorder recorder, String name) {
Entity current = getTraceEntity();
if (current == null) {
recorder.getContextMissingStrategy().contextMissing("Failed to begin subsegment named '" + name
+ "': segment cannot be found.", SegmentNotFoundException.class);
return Subsegment.noOp(recorder, false);
}
if (logger.isDebugEnabled()) {
logger.debug("Beginning subsegment named: " + name);
}
Segment parentSegment = current.getParentSegment();
Subsegment subsegment = parentSegment.isRecording()
? new SubsegmentImpl(recorder, name, parentSegment)
: Subsegment.noOp(parentSegment, recorder);
subsegment.setParent(current);
current.addSubsegment(subsegment);
setTraceEntity(subsegment);
List<SegmentListener> segmentListeners = recorder.getSegmentListeners();
segmentListeners.stream()
.filter(Objects::nonNull)
.forEach(listener -> listener.onBeginSubsegment(subsegment));
return subsegment;
}
@Override
public void endSubsegment(AWSXRayRecorder recorder) {
Entity current = getTraceEntity();
if (current instanceof Subsegment) {
if (logger.isDebugEnabled()) {
if (current.getName().isEmpty() && !current.getParentSegment().isSampled()) {
logger.debug("Ending no-op subsegment");
} else {
logger.debug("Ending subsegment named: " + current.getName());
}
}
Subsegment currentSubsegment = (Subsegment) current;
List<SegmentListener> segmentListeners = recorder.getSegmentListeners();
segmentListeners
.stream()
.filter(Objects::nonNull)
.forEach(listener -> listener.beforeEndSubsegment(currentSubsegment));
if (currentSubsegment.end() && currentSubsegment.isSampled()) {
recorder.sendSegment(currentSubsegment.getParentSegment());
} else {
if (recorder.getStreamingStrategy().requiresStreaming(currentSubsegment.getParentSegment())) {
recorder.getStreamingStrategy().streamSome(currentSubsegment.getParentSegment(), recorder.getEmitter());
}
segmentListeners
.stream()
.filter(Objects::nonNull)
.forEach(listener -> listener.afterEndSubsegment(currentSubsegment));
setTraceEntity(current.getParent());
}
} else {
recorder.getContextMissingStrategy().contextMissing("Failed to end subsegment: subsegment cannot be found.",
SubsegmentNotFoundException.class);
}
}
}
| 3,791 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/contexts/ThreadLocalSegmentContextResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
public class ThreadLocalSegmentContextResolver implements SegmentContextResolver {
@Override
public SegmentContext resolve() {
return new ThreadLocalSegmentContext();
}
}
| 3,792 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/contexts/SegmentContextExecutors.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.contexts;
import static com.amazonaws.xray.utils.LooseValidations.checkNotNull;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.entities.Segment;
import java.util.concurrent.Executor;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* {@link Executor}s that will mount a segment before running a command. When switching threads, for example when instrumenting an
* asynchronous application, it is recommended to use one of these {@link Executor}s to make sure callbacks have the trace segment
* available.
*
* <pre>{@code
* DynamoDbAsyncClient client = DynamoDbAsyncClient.create();
*
* 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()); *
* }</pre>
*/
public final class SegmentContextExecutors {
private SegmentContextExecutors() {
}
/**
* Returns a new {@link Executor} which will run any tasks with the current segment mounted.
*/
public static Executor newSegmentContextExecutor() {
return newSegmentContextExecutor(AWSXRay.getCurrentSegmentOptional().orElse(null));
}
/**
* Returns a new {@link Executor} which will run any tasks with the provided {@link Segment} mounted. If {@code segment} is
* {@code null}, the executor is a no-op.
*/
public static Executor newSegmentContextExecutor(@Nullable Segment segment) {
return newSegmentContextExecutor(AWSXRay.getGlobalRecorder(), segment);
}
/**
* Returns a new {@link Executor} which will run any tasks with the provided {@link Segment} mounted in the provided
* {@link AWSXRayRecorder}. If {@code segment} is {@code null}, the executor is a no-op.
*/
public static Executor newSegmentContextExecutor(AWSXRayRecorder recorder, @Nullable Segment segment) {
if (!checkNotNull(recorder, "recorder") || segment == null) {
return Runnable::run;
}
return new SegmentContextExecutor(recorder, segment);
}
private static class SegmentContextExecutor implements Executor {
private final AWSXRayRecorder recorder;
private final Segment segment;
private SegmentContextExecutor(AWSXRayRecorder recorder, Segment segment) {
this.recorder = recorder;
this.segment = segment;
}
@Override
public void execute(Runnable command) {
segment.run(command, recorder);
}
}
}
| 3,793 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/config/DaemonConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.config;
import com.amazonaws.xray.entities.StringValidator;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
public class DaemonConfiguration {
/**
* Environment variable key used to override the address to which UDP packets will be emitted. Valid values are of the form
* `ip_address:port`. Takes precedence over any system property, constructor value, or setter value used.
*/
public static final String DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY = "AWS_XRAY_DAEMON_ADDRESS";
/**
* System property key used to override the address to which UDP packets will be emitted. Valid values are of the form
* `ip_address:port`. Takes precedence over any constructor or setter value used.
*/
public static final String DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY = "com.amazonaws.xray.emitters.daemonAddress";
private static final Log logger = LogFactory.getLog(DaemonConfiguration.class);
private static final int DEFAULT_PORT = 2000;
private static final String DEFAULT_ADDRESS = "127.0.0.1:2000";
private String tcpAddress = DEFAULT_ADDRESS;
@Deprecated
public InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), DEFAULT_PORT);
// TODO(anuraaga): Refactor to make the address initialization not rely on an uninitialized object.
@SuppressWarnings("nullness:method.invocation.invalid")
public DaemonConfiguration() {
String environmentAddress = System.getenv(DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY);
String systemAddress = System.getProperty(DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY);
if (setUDPAndTCPAddress(environmentAddress)) {
logger.info(String.format("Environment variable %s is set. Emitting to daemon on address %s.",
DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, getUdpAddress(address)));
} else if (setUDPAndTCPAddress(systemAddress)) {
logger.info(String.format("System property %s is set. Emitting to daemon on address %s.",
DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY, getUdpAddress(address)));
}
}
/**
* Sets the daemon address. If either the {@code AWS_XRAY_DAEMON_ADDRESS} environment variable or
* {@code com.amazonaws.xray.emitters.daemonAddress} system property are set to a non-empty value, calling this method does
* nothing.
*
* @param socketAddress
* A notation of '127.0.0.1:2000' or 'tcp:127.0.0.1:2000 udp:127.0.0.2:2001' are both acceptable. The former one
* means UDP and TCP are running at the same address.
*
* @throws IllegalArgumentException
* if {@code socketAddress} does not match the specified format.
*/
public void setDaemonAddress(String socketAddress) {
String environmentAddress = System.getenv(DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY);
String systemAddress = System.getProperty(DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY);
if (StringValidator.isNullOrBlank(environmentAddress) && StringValidator.isNullOrBlank(systemAddress)) {
setUDPAndTCPAddress(socketAddress, false);
} else {
logger.info(String.format("Ignoring call to setDaemonAddress as one of %s or %s is set.",
DAEMON_ADDRESS_ENVIRONMENT_VARIABLE_KEY, DAEMON_ADDRESS_SYSTEM_PROPERTY_KEY));
}
}
/**
* Force set daemon address regardless of environment variable or system property.
* It falls back to the default values if the input is invalid.
*
* @param addr
* A notation of '127.0.0.1:2000' or 'tcp:127.0.0.1:2000 udp:127.0.0.2:2001' are both acceptable. The former one means
* UDP and TCP are running at the same address.
*/
public boolean setUDPAndTCPAddress(@Nullable String addr) {
return setUDPAndTCPAddress(addr, true);
}
private boolean setUDPAndTCPAddress(@Nullable String addr, boolean ignoreInvalid) {
try {
processAddress(addr);
return true;
} catch (SecurityException | IllegalArgumentException e) {
if (ignoreInvalid) {
return false;
} else {
throw e;
}
}
}
public void setTCPAddress(String addr) {
logger.debug("TCPAddress is set to " + addr + ".");
this.tcpAddress = addr;
}
public String getTCPAddress() {
return tcpAddress;
}
public void setUDPAddress(String addr) {
int lastColonIndex = addr.lastIndexOf(':');
if (-1 == lastColonIndex) {
throw new IllegalArgumentException("Invalid value for agent address: " + addr
+ ". Value must be of form \"ip_address:port\".");
}
String[] parts = addr.split(":");
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid value for agent address: " + addr
+ ". Value must be of form \"ip_address:port\".");
}
address = new InetSocketAddress(addr.substring(0, lastColonIndex), Integer.parseInt(addr.substring(lastColonIndex + 1)));
logger.debug("UDPAddress is set to " + addr + ".");
}
public String getUDPAddress() {
return getUdpAddress(address);
}
private static String getUdpAddress(InetSocketAddress address) {
return address.getHostString() + ":" + String.valueOf(address.getPort());
}
public InetSocketAddress getAddressForEmitter() {
return address;
}
public String getEndpointForTCPConnection() {
String[] parts = getTCPAddress().split(":");
if (parts.length != 2) {
return "http://" + DEFAULT_ADDRESS;
}
return "http://" + getTCPAddress();
}
private void processAddress(@Nullable String addr) {
if (StringValidator.isNullOrBlank(addr)) {
throw new IllegalArgumentException("Cannot set null daemon address. Value must be of form \"ip_address:port\".");
}
String[] splitStr = addr.split("\\s+");
if (splitStr.length > 2) {
throw new IllegalArgumentException("Invalid value for agent address: " + addr
+ ". Value must be of form \"ip_address:port\" or \"tcp:ip_address:port udp:ip_address:port\".");
}
if (splitStr.length == 1) {
setTCPAddress(addr);
setUDPAddress(addr);
} else if (splitStr.length == 2) {
String[] part1 = splitStr[0].split(":");
String[] part2 = splitStr[1].split(":");
if (part1.length != 3 && part2.length != 3) {
throw new IllegalArgumentException("Invalid value for agent address: " + splitStr[0] + " and " + splitStr[1]
+ ". Value must be of form \"tcp:ip_address:port udp:ip_address:port\".");
}
Map<String, String[]> mapping = new HashMap<>();
mapping.put(part1[0], part1);
mapping.put(part2[0], part2);
String[] tcpInfo = mapping.get("tcp");
String[] udpInfo = mapping.get("udp");
if (tcpInfo == null || udpInfo == null) {
throw new IllegalArgumentException("Invalid value for agent address: " + splitStr[0] + " and " + splitStr[1]
+ ". Value must be of form \"tcp:ip_address:port udp:ip_address:port\".");
}
setTCPAddress(tcpInfo[1] + ":" + tcpInfo[2]);
setUDPAddress(udpInfo[1] + ":" + udpInfo[2]);
} else {
throw new IllegalArgumentException("Invalid value for agent address: " + addr
+ ". Value must be of form \"ip_address:port\" or \"tcp:ip_address:port udp:ip_address:port\".");
}
}
}
| 3,794 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/plugins/EC2Plugin.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import com.amazonaws.xray.entities.AWSLogReference;
import com.amazonaws.xray.entities.StringValidator;
import com.amazonaws.xray.utils.JsonUtils;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A plugin, for use with the {@code AWSXRayRecorderBuilder} class, which will add EC2 instance information to segments generated
* by the built {@code AWSXRayRecorder} instance.
*
* @see com.amazonaws.xray.AWSXRayRecorderBuilder#withPlugin(Plugin)
*
*/
public class EC2Plugin implements Plugin {
public static final String ORIGIN = "AWS::EC2::Instance";
private static final Log logger = LogFactory.getLog(EC2Plugin.class);
private static final String SERVICE_NAME = "ec2";
private static final String LOG_CONFIGS = "log_configs";
private static final String LOG_GROUP_NAME = "log_group_name";
private static final String WINDOWS_PROGRAM_DATA = "ProgramData";
private static final String WINDOWS_PATH = "\\Amazon\\AmazonCloudWatchAgent\\log-config.json";
private static final String LINUX_ROOT = "/";
private static final String LINUX_PATH = "opt/aws/amazon-cloudwatch-agent/etc/log-config.json";
private final Map<String, @Nullable Object> runtimeContext;
private final Set<AWSLogReference> logReferences;
private final FileSystem fs;
private final Map<EC2MetadataFetcher.EC2Metadata, String> metadata;
public EC2Plugin() {
this(FileSystems.getDefault(), new EC2MetadataFetcher());
}
public EC2Plugin(FileSystem fs, EC2MetadataFetcher metadataFetcher) {
this.fs = fs;
metadata = metadataFetcher.fetch();
runtimeContext = new LinkedHashMap<>();
logReferences = new HashSet<>();
}
@Override
public boolean isEnabled() {
return metadata.containsKey(EC2MetadataFetcher.EC2Metadata.INSTANCE_ID);
}
@Override
public String getServiceName() {
return SERVICE_NAME;
}
/**
* Reads EC2 provided metadata to include it in trace document
*/
public void populateRuntimeContext() {
runtimeContext.put("instance_id", metadata.get(EC2MetadataFetcher.EC2Metadata.INSTANCE_ID));
runtimeContext.put("availability_zone", metadata.get(EC2MetadataFetcher.EC2Metadata.AVAILABILITY_ZONE));
runtimeContext.put("instance_size", metadata.get(EC2MetadataFetcher.EC2Metadata.INSTANCE_TYPE));
runtimeContext.put("ami_id", metadata.get(EC2MetadataFetcher.EC2Metadata.AMI_ID));
}
@Override
public Map<String, @Nullable Object> getRuntimeContext() {
populateRuntimeContext();
return runtimeContext;
}
/**
* Reads the log group configuration file generated by the CloudWatch Agent to discover all log groups being used on this
* instance and populates log reference set with them to be included in trace documents.
*/
public void populateLogReferences() {
String filePath = null;
String programData = System.getenv(WINDOWS_PROGRAM_DATA);
if (StringValidator.isNullOrBlank(programData)) {
for (Path root : fs.getRootDirectories()) {
if (root.toString().equals(LINUX_ROOT)) {
filePath = LINUX_ROOT + LINUX_PATH;
break;
}
}
} else {
filePath = programData + WINDOWS_PATH;
}
if (filePath == null) {
logger.warn("X-Ray could not recognize the file system in use. Expected file system to be Linux or Windows based.");
return;
}
try {
JsonNode logConfigs = JsonUtils.getNodeFromJsonFile(filePath, LOG_CONFIGS);
List<String> logGroups = JsonUtils.getMatchingListFromJsonArrayNode(logConfigs, LOG_GROUP_NAME);
for (String logGroup : logGroups) {
AWSLogReference logReference = new AWSLogReference();
logReference.setLogGroup(logGroup);
logReferences.add(logReference);
}
} catch (IOException e) {
logger.warn("CloudWatch Agent log configuration file not found at " + filePath + ". Install the CloudWatch Agent "
+ "on this instance to record log references in X-Ray.");
} catch (RuntimeException e) {
logger.warn("An unexpected exception occurred while reading CloudWatch agent log configuration file at " + filePath
+ ":\n", e);
}
}
/**
*
* @return Set of AWS log references used by CloudWatch agent. The ARN of these log references is not available at this time.
*/
@Override
public Set<AWSLogReference> getLogReferences() {
if (logReferences.isEmpty()) {
populateLogReferences();
}
return logReferences;
}
@Override
public String getOrigin() {
return ORIGIN;
}
/**
* Determine equality of plugins using origin to uniquely identify them
*/
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof Plugin)) { return false; }
return this.getOrigin().equals(((Plugin) o).getOrigin());
}
/**
* Hash plugin object using origin to uniquely identify them
*/
@Override
public int hashCode() {
return this.getOrigin().hashCode();
}
}
| 3,795 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/plugins/EKSPlugin.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import com.amazonaws.xray.entities.AWSLogReference;
import com.amazonaws.xray.utils.ContainerInsightsUtil;
import com.amazonaws.xray.utils.DockerUtils;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A plugin, for use with the {@code AWSXRayRecorderBuilder} class, which will add Kubernetes metadata to segments.
* If the cluster uses ContainerInsights this plugin will extract log configuration information.
*
* @see com.amazonaws.xray.AWSXRayRecorderBuilder#withPlugin(Plugin)
*
*/
public class EKSPlugin implements Plugin {
public static final String ORIGIN = "AWS::EKS::Container";
private static final String SERVICE_NAME = "eks";
private static final String POD_CONTEXT_KEY = "pod";
private static final String CLUSTER_NAME_KEY = "cluster_name";
private static final String CONTAINER_ID_KEY = "container_id";
private static final Log logger = LogFactory.getLog(EKSPlugin.class);
@Nullable
private String clusterName;
private final Map<String, @Nullable Object> runtimeContext;
private final Set<AWSLogReference> logReferences;
private final DockerUtils dockerUtils;
/**
* Constructs an empty EKS plugin. The cluster name, along with other metadata, will be retrieved from the
* Container Insights endpoint automatically.
*/
public EKSPlugin() {
this(null);
}
/**
* Constructs an EKS plugin with a given cluster name.
* @param clusterName the EKS cluster name
*/
public EKSPlugin(@Nullable String clusterName) {
if (clusterName != null) {
this.clusterName = clusterName;
}
this.runtimeContext = new HashMap<>();
this.logReferences = new HashSet<>();
this.dockerUtils = new DockerUtils();
}
@Override
public boolean isEnabled() {
return ContainerInsightsUtil.isK8s();
}
@Override
public Set<AWSLogReference> getLogReferences() {
if (logReferences.isEmpty()) {
populateLogReferences();
}
return logReferences;
}
@Override
public String getServiceName() {
return SERVICE_NAME;
}
@Override
public Map<String, @Nullable Object> getRuntimeContext() {
if (runtimeContext.isEmpty()) {
populateRuntimeContext();
}
return runtimeContext;
}
/**
* Generate log references by calling K8s for Container Insights configuration data.
*/
private void populateLogReferences() {
if (clusterName == null) {
clusterName = ContainerInsightsUtil.getClusterName();
}
AWSLogReference log = new AWSLogReference();
log.setLogGroup(String.format("/aws/containerinsights/%s/application", clusterName));
logReferences.add(log);
}
/**
* Generate runtime context with pod metadata from K8s.
*/
public void populateRuntimeContext() {
if (clusterName == null) {
clusterName = ContainerInsightsUtil.getClusterName();
}
runtimeContext.put(CLUSTER_NAME_KEY, clusterName);
try {
runtimeContext.put(CONTAINER_ID_KEY, dockerUtils.getContainerId());
} catch (IOException e) {
logger.error("Failed to read full container ID from kubernetes instance.", e);
}
try {
runtimeContext.put(POD_CONTEXT_KEY, InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException uhe) {
logger.error("Could not get pod ID from hostname.", uhe);
}
}
@Override
public String getOrigin() {
return ORIGIN;
}
/**
* Determine equality of plugins using origin to uniquely identify them
*/
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof Plugin)) { return false; }
return this.getOrigin().equals(((Plugin) o).getOrigin());
}
/**
* Hash plugin object using origin to uniquely identify them
*/
@Override
public int hashCode() {
return this.getOrigin().hashCode();
}
}
| 3,796 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/plugins/EC2MetadataFetcher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class EC2MetadataFetcher {
private static final Log logger = LogFactory.getLog(EC2MetadataFetcher.class);
private static final JsonFactory JSON_FACTORY = new JsonFactory();
enum EC2Metadata {
INSTANCE_ID,
AVAILABILITY_ZONE,
INSTANCE_TYPE,
AMI_ID,
}
private static final String METADATA_SERVICE_NAME = "IMDS";
private static final String DEFAULT_IMDS_ENDPOINT = "169.254.169.254";
private final URL identityDocumentUrl;
private final URL tokenUrl;
EC2MetadataFetcher() {
this(getEndpoint());
}
EC2MetadataFetcher(String endpoint) {
String urlBase = "http://" + endpoint;
try {
this.identityDocumentUrl = new URL(urlBase + "/latest/dynamic/instance-identity/document");
this.tokenUrl = new URL(urlBase + "/latest/api/token");
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Illegal endpoint: " + endpoint);
}
}
Map<EC2Metadata, String> fetch() {
String token = fetchToken();
// If token is empty, either IMDSv2 isn't enabled or an unexpected failure happened. We can still get
// data if IMDSv1 is enabled.
String identity = fetchIdentity(token);
if (identity.isEmpty()) {
// If no identity document, assume we are not actually running on EC2.
return Collections.emptyMap();
}
Map<EC2Metadata, String> result = new HashMap<>();
try (JsonParser parser = JSON_FACTORY.createParser(identity)) {
parser.nextToken();
if (!parser.isExpectedStartObjectToken()) {
throw new IOException("Invalid JSON:" + identity);
}
while (parser.nextToken() != JsonToken.END_OBJECT) {
String value = parser.nextTextValue();
switch (parser.getCurrentName()) {
case "instanceId":
result.put(EC2Metadata.INSTANCE_ID, value);
break;
case "availabilityZone":
result.put(EC2Metadata.AVAILABILITY_ZONE, value);
break;
case "instanceType":
result.put(EC2Metadata.INSTANCE_TYPE, value);
break;
case "imageId":
result.put(EC2Metadata.AMI_ID, value);
break;
default:
parser.skipChildren();
}
if (result.size() == EC2Metadata.values().length) {
return Collections.unmodifiableMap(result);
}
}
} catch (IOException e) {
logger.warn("Could not parse identity document.", e);
return Collections.emptyMap();
}
// Getting here means the document didn't have all the metadata fields we wanted.
logger.warn("Identity document missing metadata: " + identity);
return Collections.unmodifiableMap(result);
}
private String fetchToken() {
return MetadataUtils.fetchString("PUT", tokenUrl, "", true, METADATA_SERVICE_NAME);
}
private String fetchIdentity(String token) {
return MetadataUtils.fetchString("GET", identityDocumentUrl, token, false, METADATA_SERVICE_NAME);
}
private static String getEndpoint() {
String endpointFromEnv = System.getenv("IMDS_ENDPOINT");
return endpointFromEnv != null ? endpointFromEnv : DEFAULT_IMDS_ENDPOINT;
}
}
| 3,797 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/plugins/MetadataUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
class MetadataUtils {
private static final Log logger = LogFactory.getLog(MetadataUtils.class);
private static final int CONNECT_TIMEOUT_MILLIS = 100;
private static final int READ_TIMEOUT_MILLIS = 1000;
private MetadataUtils() {
}
static String fetchString(String httpMethod, URL url, String token, boolean includeTtl, String metadataService) {
final HttpURLConnection connection;
try {
connection = (HttpURLConnection) url.openConnection();
} catch (Exception e) {
logger.debug("Error connecting to " + metadataService, e);
return "";
}
try {
connection.setRequestMethod(httpMethod);
} catch (ProtocolException e) {
logger.warn("Unknown HTTP method, this is a programming bug.", e);
return "";
}
connection.setConnectTimeout(CONNECT_TIMEOUT_MILLIS);
connection.setReadTimeout(READ_TIMEOUT_MILLIS);
if (includeTtl) {
connection.setRequestProperty("X-aws-ec2-metadata-token-ttl-seconds", "60");
}
if (token != null && !token.isEmpty()) {
connection.setRequestProperty("X-aws-ec2-metadata-token", token);
}
final int responseCode;
try {
responseCode = connection.getResponseCode();
} catch (Exception e) {
if (e instanceof SocketTimeoutException) {
logger.debug("Timed out trying to connect to " + metadataService);
} else {
logger.debug("Error connecting to " + metadataService, e);
}
return "";
}
if (responseCode != 200) {
logger.warn("Error response from " + metadataService + ": code (" +
responseCode + ") text " + readResponseString(connection));
}
return MetadataUtils.readResponseString(connection).trim();
}
static String readResponseString(HttpURLConnection connection) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try (InputStream is = connection.getInputStream()) {
readTo(is, os);
} catch (IOException e) {
// Only best effort read if we can.
}
try (InputStream is = connection.getErrorStream()) {
readTo(is, os);
} catch (IOException e) {
// Only best effort read if we can.
}
try {
return os.toString(StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 not supported can't happen.");
}
}
static void readTo(@Nullable InputStream is, ByteArrayOutputStream os) throws IOException {
if (is == null) {
return;
}
int b;
while ((b = is.read()) != -1) {
os.write(b);
}
}
}
| 3,798 |
0 | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray | Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/plugins/Plugin.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.xray.plugins;
import com.amazonaws.xray.entities.AWSLogReference;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
public interface Plugin {
/**
* Returns the name of the origin associated with this plugin.
* The {@link com.amazonaws.xray.AWSXRayRecorder} contains a prioritized list of origins from least to most specific.
*
* @return the name of the origin associated with this plugin.
*/
String getOrigin();
String getServiceName();
/**
* @return true if an environment inspection determines X-Ray is operating in the correct environment for this plugin OR
* if X-Ray cannot accurately determine if it's in this plugin's environment
*/
default boolean isEnabled() {
return true;
}
Map<String, @Nullable Object> getRuntimeContext();
default Set<AWSLogReference> getLogReferences() {
return Collections.emptySet();
}
}
| 3,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.