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/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/ECSMetadataFetcher.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; import org.checkerframework.checker.nullness.qual.Nullable; class ECSMetadataFetcher { private static final Log logger = LogFactory.getLog(ECSMetadataFetcher.class); private static final String METADATA_SERVICE_NAME = "TMDE"; private static final JsonFactory JSON_FACTORY = new JsonFactory(); @Nullable private final URL containerUrl; // TODO: Record additional attributes in runtime context from Task Metadata Endpoint enum ECSContainerMetadata { LOG_DRIVER, LOG_GROUP_REGION, LOG_GROUP_NAME, CONTAINER_ARN, } ECSMetadataFetcher(@Nullable String endpoint) { if (endpoint == null) { this.containerUrl = null; return; } try { this.containerUrl = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("Illegal endpoint: " + endpoint); } } Map<ECSContainerMetadata, String> fetchContainer() { if (this.containerUrl == null) { return Collections.emptyMap(); } String metadata = MetadataUtils.fetchString("GET", this.containerUrl, "", false, METADATA_SERVICE_NAME); Map<ECSContainerMetadata, String> result = new HashMap<>(); try (JsonParser parser = JSON_FACTORY.createParser(metadata)) { parser.nextToken(); parseContainerJson(parser, result); } catch (IOException e) { logger.warn("Could not parse container metadata.", e); return Collections.emptyMap(); } // This means the document didn't have all the metadata fields we wanted. if (result.size() != ECSContainerMetadata.values().length) { logger.debug("Container metadata response missing metadata: " + metadata); } return Collections.unmodifiableMap(result); } // Helper method to shallow-parse a JSON object, assuming the parser is located at the start of an object, // and record the desired fields in the result map in-place private void parseContainerJson(JsonParser parser, Map<ECSContainerMetadata, String> result) throws IOException { if (!parser.isExpectedStartObjectToken()) { logger.warn("Container metadata endpoint returned invalid JSON"); return; } while (parser.nextToken() != JsonToken.END_OBJECT) { String value = parser.nextTextValue(); switch (parser.getCurrentName()) { case "LogDriver": result.put(ECSContainerMetadata.LOG_DRIVER, value); break; case "ContainerARN": result.put(ECSContainerMetadata.CONTAINER_ARN, value); break; case "awslogs-group": result.put(ECSContainerMetadata.LOG_GROUP_NAME, value); break; case "awslogs-region": result.put(ECSContainerMetadata.LOG_GROUP_REGION, value); break; case "LogOptions": parseContainerJson(parser, result); // Parse the LogOptions object for log fields break; default: parser.skipChildren(); } if (result.size() == ECSContainerMetadata.values().length) { return; } } } }
3,800
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/ElasticBeanstalkPlugin.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.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; 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; /** * A plugin, for use with the {@code AWSXRayRecorderBuilder} class, which will add Elastic Beanstalk environment information to * segments generated by the built {@code AWSXRayRecorder} instance. * * @see com.amazonaws.xray.AWSXRayRecorderBuilder#withPlugin(Plugin) * */ public class ElasticBeanstalkPlugin implements Plugin { public static final String ORIGIN = "AWS::ElasticBeanstalk::Environment"; private static final Log logger = LogFactory.getLog(ElasticBeanstalkPlugin.class); private static final String CONF_PATH = "/var/elasticbeanstalk/xray/environment.conf"; private static final String SERVICE_NAME = "elastic_beanstalk"; private Map<String, Object> runtimeContext; public ElasticBeanstalkPlugin() { runtimeContext = new HashMap<>(); } @Override public String getServiceName() { return SERVICE_NAME; } @Override public boolean isEnabled() { return Files.exists(Paths.get(CONF_PATH)); } public void populateRuntimeContext() { byte[] manifestBytes = new byte[0]; ObjectMapper mapper = new ObjectMapper(); try { manifestBytes = Files.readAllBytes(Paths.get(CONF_PATH)); } catch (IOException | OutOfMemoryError | SecurityException e) { logger.warn("Unable to read Beanstalk configuration at path " + CONF_PATH + " : " + e.getMessage()); return; } try { TypeReference<HashMap<String, Object>> typeReference = new TypeReference<HashMap<String, Object>>() {}; runtimeContext = mapper.readValue(manifestBytes, typeReference); } catch (IOException e) { logger.warn("Unable to read Beanstalk configuration at path " + CONF_PATH + " : " + e.getMessage()); return; } } @Override public Map<String, @Nullable Object> getRuntimeContext() { if (runtimeContext.isEmpty()) { populateRuntimeContext(); } return (Map<String, @Nullable Object>) runtimeContext; } @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,801
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/ECSPlugin.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.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 ECS container information to segments generated * by the built {@code AWSXRayRecorder} instance. * * @see com.amazonaws.xray.AWSXRayRecorderBuilder#withPlugin(Plugin) * */ public class ECSPlugin implements Plugin { public static final String ORIGIN = "AWS::ECS::Container"; private static final Log logger = LogFactory.getLog(ECSPlugin.class); private static final String SERVICE_NAME = "ecs"; private static final String ECS_METADATA_V3_KEY = "ECS_CONTAINER_METADATA_URI"; private static final String ECS_METADATA_V4_KEY = "ECS_CONTAINER_METADATA_URI_V4"; private static final String CONTAINER_ID_KEY = "container_id"; private static final String CONTAINER_NAME_KEY = "container"; private static final String CONTAINER_ARN_KEY = "container_arn"; private final ECSMetadataFetcher fetcher; private final HashMap<String, @Nullable Object> runtimeContext; private final DockerUtils dockerUtils; private final Set<AWSLogReference> logReferences; private final Map<ECSMetadataFetcher.ECSContainerMetadata, String> containerMetadata; @SuppressWarnings("nullness:method.invocation.invalid") public ECSPlugin() { runtimeContext = new HashMap<>(); dockerUtils = new DockerUtils(); logReferences = new HashSet<>(); fetcher = new ECSMetadataFetcher(getTmdeFromEnv()); containerMetadata = this.fetcher.fetchContainer(); } // Exposed for testing ECSPlugin(ECSMetadataFetcher fetcher) { runtimeContext = new HashMap<>(); dockerUtils = new DockerUtils(); logReferences = new HashSet<>(); this.fetcher = fetcher; containerMetadata = this.fetcher.fetchContainer(); } /** * Returns true if the environment variable added by ECS is present and contains a valid URI */ @Override public boolean isEnabled() { String ecsMetadataUri = getTmdeFromEnv(); return ecsMetadataUri != null && ecsMetadataUri.startsWith("http://"); } @Override public String getServiceName() { return SERVICE_NAME; } public void populateRuntimeContext() { try { runtimeContext.put(CONTAINER_NAME_KEY, InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException uhe) { logger.error("Could not get docker container ID from hostname.", uhe); } try { runtimeContext.put(CONTAINER_ID_KEY, dockerUtils.getContainerId()); } catch (IOException e) { logger.error("Failed to read full container ID from container instance.", e); } if (containerMetadata.containsKey(ECSMetadataFetcher.ECSContainerMetadata.CONTAINER_ARN)) { runtimeContext.put(CONTAINER_ARN_KEY, containerMetadata.get(ECSMetadataFetcher.ECSContainerMetadata.CONTAINER_ARN)); } } @Override public Map<String, @Nullable Object> getRuntimeContext() { populateRuntimeContext(); return runtimeContext; } @Override public Set<AWSLogReference> getLogReferences() { if (logReferences.isEmpty()) { populateLogReferences(); } return logReferences; } // See: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-ids private void populateLogReferences() { String logGroup = containerMetadata.get(ECSMetadataFetcher.ECSContainerMetadata.LOG_GROUP_NAME); if (logGroup == null) { return; } AWSLogReference logReference = new AWSLogReference(); logReference.setLogGroup(logGroup); String logRegion = containerMetadata.get(ECSMetadataFetcher.ECSContainerMetadata.LOG_GROUP_REGION); String containerArn = containerMetadata.get(ECSMetadataFetcher.ECSContainerMetadata.CONTAINER_ARN); String logAccount = containerArn != null ? containerArn.split(":")[4] : null; if (logRegion != null && logAccount != null) { logReference.setArn("arn:aws:logs:" + logRegion + ":" + logAccount + ":log-group:" + logGroup); } logReferences.add(logReference); } @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(); } /** * @return V4 Metadata endpoint if present, otherwise V3 endpoint if present, otherwise null */ @Nullable private String getTmdeFromEnv() { String ecsMetadataUri = System.getenv(ECS_METADATA_V4_KEY); if (ecsMetadataUri == null) { ecsMetadataUri = System.getenv(ECS_METADATA_V3_KEY); } return ecsMetadataUri; } }
3,802
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/internal/FastIdGenerator.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 com.amazonaws.xray.utils.ByteUtils; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /** * Generates random IDs using a fast but cryptographically insecure random number * generator. This should be the default random generator, unless your application * relies on AWS X-Ray trace IDs being generated from a cryptographically secure random number * source. * * <p>This class is internal-only and its API may receive breaking changes at any time. Do not directly * depend on or use this class. * * @see SecureIdGenerator */ public final class FastIdGenerator extends IdGenerator { @Override public String newTraceId() { Random random = ThreadLocalRandom.current(); return ByteUtils.numberToBase16String(random.nextInt(), random.nextLong()); } @Override protected long getRandomEntityId() { return ThreadLocalRandom.current().nextLong(); } }
3,803
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/internal/IdGenerator.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 java.util.Arrays; /** * An internal base class for unifying the potential ID generators. * * <p>This class is internal-only and its API may receive breaking changes at any time. Do not directly * depend on or use this class. */ public abstract class IdGenerator { /** * @return a new ID suitable for use in a {@link com.amazonaws.xray.entities.TraceID TraceID} */ public abstract String newTraceId(); /** * @return a new ID suitable for use in any {@link com.amazonaws.xray.entities.Entity Entity} implementation */ public final String newEntityId() { String id = Long.toString(getRandomEntityId() >>> 1, 16); int idLength = id.length(); if (idLength >= 16) { return id; } StringBuilder idWithPad = new StringBuilder(16); int padLength = 16 - idLength; char[] pad = RecyclableBuffers.chars(padLength); Arrays.fill(pad, 0, padLength, '0'); idWithPad.append(pad, 0, padLength); idWithPad.append(id); return idWithPad.toString(); } /** * @return a random long to use as an entity ID */ protected abstract long getRandomEntityId(); }
3,804
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/internal/SecureIdGenerator.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.utils.ByteUtils.bytesToBase16String; import com.amazonaws.xray.ThreadLocalStorage; /** * Generates for IDs using a cryptographically secure random number generator. * This can be much more expensive than the alternative {@linkplain FastIdGenerator}. This * generator should only be used if your application relies on AWS X-Ray IDs being * generated from a cryptographically secure random number source. * * <p>This class is internal-only and its API may receive breaking changes at any time. Do not directly * depend on or use this class. * * @see FastIdGenerator */ public final class SecureIdGenerator extends IdGenerator { @Override public String newTraceId() { // nextBytes much faster than calling nextInt multiple times when using SecureRandom byte[] randomBytes = RecyclableBuffers.bytes(12); ThreadLocalStorage.getRandom().nextBytes(randomBytes); return bytesToBase16String(randomBytes); } @Override protected long getRandomEntityId() { return ThreadLocalStorage.getRandom().nextLong(); } }
3,805
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/internal/RecyclableBuffers.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.checkerframework.checker.nullness.qual.Nullable; /** * {@link ThreadLocal} buffers for use when creating new derived objects such as {@link String}s. * These buffers are reused within a single thread - it is _not safe_ to use the buffer to generate * multiple derived objects at the same time because the same memory will be used. In general, you * should get a temporary buffer, fill it with data, and finish by converting into the derived * object within the same method to avoid multiple usages of the same buffer. */ public final class RecyclableBuffers { private static final ThreadLocal<@Nullable StringBuilder> STRING_BUILDER = new ThreadLocal<>(); @SuppressWarnings("nullness:type.argument.type.incompatible") private static final ThreadLocal<char[]> CHARS = new ThreadLocal<>(); @SuppressWarnings("nullness:type.argument.type.incompatible") private static final ThreadLocal<byte[]> BYTES = new ThreadLocal<>(); /** * A {@link ThreadLocal} {@link StringBuilder}. Take care when filling a large value into this buffer * because the memory will remain for the lifetime of the thread. */ public static StringBuilder stringBuilder() { StringBuilder buffer = STRING_BUILDER.get(); if (buffer == null) { buffer = new StringBuilder(); STRING_BUILDER.set(buffer); } buffer.setLength(0); return buffer; } /** * A {@link ThreadLocal} {@code char[]} of length {@code length}. The array is not zeroed in any way - every character of * a resulting {@link String} must be set explicitly. The array returned may be longer than {@code length} - always explicitly * set the length when using the result, for example by calling {@link String#valueOf(char[], int, int)}. */ public static char[] chars(int length) { char[] buffer = CHARS.get(); if (buffer == null || buffer.length < length) { buffer = new char[length]; CHARS.set(buffer); } return buffer; } /** * A {@link ThreadLocal} {@code byte[]} of length {@code length}. The array is not zeroed in any way. */ public static byte[] bytes(int length) { byte[] buffer = BYTES.get(); if (buffer == null || buffer.length < length) { buffer = new byte[length]; BYTES.set(buffer); } return buffer; } private RecyclableBuffers() { } }
3,806
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/internal/XrayClientException.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; /** * A {@link RuntimeException} thrown when we fail to send HTTP requests to the X-Ray daemon. */ class XrayClientException extends RuntimeException { private static final long serialVersionUID = -32616082201202518L; XrayClientException(String message) { super(message); } XrayClientException(String message, Throwable cause) { super(message, cause); } }
3,807
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/internal/TimeUtils.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 java.util.concurrent.TimeUnit.MILLISECONDS; public final class TimeUtils { /** * @return the current epoch second */ public static long currentEpochSecond() { return MILLISECONDS.toSeconds(System.currentTimeMillis()); } private TimeUtils() { } }
3,808
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/internal/SamplingStrategyOverride.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; public enum SamplingStrategyOverride { DISABLED, // Does not override the SamplingStrategy. FALSE, // Overrides the SamplingStrategy and always chooses NOT to sample. }
3,809
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/internal/UnsignedXrayClient.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 com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.AmazonWebServiceResult; import com.amazonaws.SdkClientException; 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.xray.config.DaemonConfiguration; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyName; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.introspect.AnnotatedMember; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Date; import org.checkerframework.checker.nullness.qual.Nullable; /** * A simple client for sending API requests via the X-Ray daemon. Requests do not have to be * signed, so we can avoid having a strict dependency on the full AWS SDK in instrumentation. This * is an internal utility and not meant to represent the entire X-Ray API nor be particularly * efficient as we only use it in long poll loops. */ public class UnsignedXrayClient { private static final PropertyName HTTP_METHOD = PropertyName.construct("HTTPMethod"); private static final PropertyName URL_PATH = PropertyName.construct("URLPath"); // Visible for testing static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() .setSerializationInclusion(Include.NON_EMPTY) // Use deprecated field to support older Jackson versions for now. .setPropertyNamingStrategy(PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE) .registerModule(new SimpleModule().addDeserializer(Date.class, new FloatDateDeserializer())) .setAnnotationIntrospector(new JacksonAnnotationIntrospector() { @Override public boolean hasIgnoreMarker(AnnotatedMember m) { // This is a somewhat hacky way of having ObjectMapper only serialize the fields in our // model classes instead of the base class that comes from the SDK. In the future, we will // remove the SDK dependency itself and the base classes and this hack will go away. if (m.getDeclaringClass() == AmazonWebServiceRequest.class || m.getDeclaringClass() == AmazonWebServiceResult.class) { return true; } return super.hasIgnoreMarker(m); } @Override public PropertyName findNameForDeserialization(Annotated a) { if (a.getName().equals("hTTPMethod")) { return HTTP_METHOD; } if (a.getName().equals("uRLPath")) { return URL_PATH; } return super.findNameForDeserialization(a); } }); private static final int TIME_OUT_MILLIS = 2000; private final URL getSamplingRulesEndpoint; private final URL getSamplingTargetsEndpoint; public UnsignedXrayClient() { this(new DaemonConfiguration().getEndpointForTCPConnection()); } // Visible for testing UnsignedXrayClient(String endpoint) { try { getSamplingRulesEndpoint = new URL(endpoint + "/GetSamplingRules"); getSamplingTargetsEndpoint = new URL(endpoint + "/SamplingTargets"); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid URL: " + endpoint, e); } } public GetSamplingRulesResult getSamplingRules(GetSamplingRulesRequest request) { return sendRequest(getSamplingRulesEndpoint, request, GetSamplingRulesResult.class); } public GetSamplingTargetsResult getSamplingTargets(GetSamplingTargetsRequest request) { return sendRequest(getSamplingTargetsEndpoint, request, GetSamplingTargetsResult.class); } private <T> T sendRequest(URL endpoint, Object request, Class<T> responseClass) { final HttpURLConnection connection; try { connection = (HttpURLConnection) endpoint.openConnection(); } catch (IOException e) { throw new XrayClientException("Could not connect to endpoint " + endpoint, e); } connection.setConnectTimeout(TIME_OUT_MILLIS); connection.setReadTimeout(TIME_OUT_MILLIS); try { connection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new IllegalStateException("Invalid protocol, can't happen."); } connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); try (OutputStream outputStream = connection.getOutputStream()) { OBJECT_MAPPER.writeValue(outputStream, request); } catch (IOException | IllegalArgumentException e) { throw new XrayClientException("Could not serialize and send request.", e); } final int responseCode; try { responseCode = connection.getResponseCode(); } catch (IOException e) { throw new XrayClientException("Could not read response code.", e); } if (responseCode != 200) { throw new XrayClientException("Error response from X-Ray: " + readResponseString(connection)); } try { return OBJECT_MAPPER.readValue(connection.getInputStream(), responseClass); } catch (IOException e) { throw new XrayClientException("Error reading response.", e); } } private 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."); } } private static void readTo(@Nullable InputStream is, ByteArrayOutputStream os) throws IOException { // It is possible for getErrorStream to return null, though since we don't read it for success cases in practice it // shouldn't happen. Check just in case. if (is == null) { return; } int b; while ((b = is.read()) != -1) { os.write(b); } } private static class FloatDateDeserializer extends StdDeserializer<Date> { private static final int AWS_DATE_MILLI_SECOND_PRECISION = 3; private FloatDateDeserializer() { super(Date.class); } @Override public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { return parseServiceSpecificDate(p.getText()); } // Copied from AWS SDK https://github.com/aws/aws-sdk-java/blob/7b1e5b87b0bf03456df9e77716b14731adf9a7a7/aws-java-sdk-core/src/main/java/com/amazonaws/util/DateUtils.java#L239https://github.com/aws/aws-sdk-java/blob/7b1e5b87b0bf03456df9e77716b14731adf9a7a7/aws-java-sdk-core/src/main/java/com/amazonaws/util/DateUtils.java#L239 /** * Parses the given date string returned by the AWS service into a Date * object. */ private static Date parseServiceSpecificDate(String dateString) { try { BigDecimal dateValue = new BigDecimal(dateString); return new Date(dateValue.scaleByPowerOfTen(AWS_DATE_MILLI_SECOND_PRECISION).longValue()); } catch (NumberFormatException nfe) { throw new SdkClientException("Unable to parse date : " + dateString, nfe); } } } }
3,810
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/utils/ByteUtils.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.amazonaws.xray.internal.RecyclableBuffers; import org.checkerframework.checker.nullness.qual.Nullable; @SuppressWarnings("checkstyle:HideUtilityClassConstructor") public class ByteUtils { static final String HEXES = "0123456789ABCDEF"; private static final int BYTE_BASE16 = 2; private static final String ALPHABET = "0123456789abcdef"; private static final char[] ENCODING = buildEncodingArray(); private static char[] buildEncodingArray() { char[] encoding = new char[512]; for (int i = 0; i < 256; ++i) { encoding[i] = ALPHABET.charAt(i >>> 4); encoding[i | 0x100] = ALPHABET.charAt(i & 0xF); } return encoding; } /** * ref: https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java * * Converts the input byte array into a hexadecimal string. * @param raw - Byte array * @return String - Hexadecimal representation of the byte array. */ @Nullable public static String byteArrayToHexString(byte[] raw) { if (raw == null) { return null; } final StringBuilder hex = new StringBuilder(2 * raw.length); for (final byte b : raw) { hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F))); } return hex.toString(); } public static String bytesToBase16String(byte[] bytes) { char[] dest = RecyclableBuffers.chars(24); for (int i = 0; i < 12; i++) { byteToBase16(bytes[i], dest, i * BYTE_BASE16); } return new String(dest, 0, 24); } public static String numberToBase16String(int hi, long lo) { char[] dest = RecyclableBuffers.chars(24); byteToBase16((byte) (hi >> 24 & 0xFFL), dest, 0); byteToBase16((byte) (hi >> 16 & 0xFFL), dest, BYTE_BASE16); byteToBase16((byte) (hi >> 8 & 0xFFL), dest, 2 * BYTE_BASE16); byteToBase16((byte) (hi & 0xFFL), dest, 3 * BYTE_BASE16); byteToBase16((byte) (lo >> 56 & 0xFFL), dest, 4 * BYTE_BASE16); byteToBase16((byte) (lo >> 48 & 0xFFL), dest, 5 * BYTE_BASE16); byteToBase16((byte) (lo >> 40 & 0xFFL), dest, 6 * BYTE_BASE16); byteToBase16((byte) (lo >> 32 & 0xFFL), dest, 7 * BYTE_BASE16); byteToBase16((byte) (lo >> 24 & 0xFFL), dest, 8 * BYTE_BASE16); byteToBase16((byte) (lo >> 16 & 0xFFL), dest, 9 * BYTE_BASE16); byteToBase16((byte) (lo >> 8 & 0xFFL), dest, 10 * BYTE_BASE16); byteToBase16((byte) (lo & 0xFFL), dest, 11 * BYTE_BASE16); return new String(dest, 0, 24); } public static String intToBase16String(long value) { char[] dest = RecyclableBuffers.chars(8); byteToBase16((byte) (value >> 24 & 0xFFL), dest, 0); byteToBase16((byte) (value >> 16 & 0xFFL), dest, BYTE_BASE16); byteToBase16((byte) (value >> 8 & 0xFFL), dest, 2 * BYTE_BASE16); byteToBase16((byte) (value & 0xFFL), dest, 3 * BYTE_BASE16); return new String(dest, 0, 8); } private static void byteToBase16(byte value, char[] dest, int destOffset) { int b = value & 0xFF; dest[destOffset] = ENCODING[b]; dest[destOffset + 1] = ENCODING[b | 0x100]; } }
3,811
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/utils/DockerUtils.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.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URISyntaxException; 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.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Utility class to get metadata for dockerized containers */ public class DockerUtils { private static final Log logger = LogFactory.getLog(DockerUtils.class); private static final String CGROUP_PATH = "/proc/self/cgroup"; private static final int CONTAINER_ID_LENGTH = 64; @MonotonicNonNull private URL cgroupLocation; public DockerUtils() { try { this.cgroupLocation = new File(CGROUP_PATH).toURI().toURL(); } catch (MalformedURLException e) { logger.warn("Failed to read container ID because " + CGROUP_PATH + " does not exist."); } } public DockerUtils(URL cgroupLocation) { this.cgroupLocation = cgroupLocation; } /** * Reads the docker-generated cgroup file that lists the full (untruncated) docker container ID at the end of each line. This * method takes advantage of that fact by just reading the 64-character ID from the end of the first line. * * @throws IOException if the file cannot be read * @return the untruncated Docker container ID, or null if it can't be read */ @Nullable public String getContainerId() throws IOException { if (cgroupLocation == null) { return null; } final File procFile; try { procFile = new File(cgroupLocation.toURI()); } catch (URISyntaxException e) { logger.warn("Failed to read container ID because " + cgroupLocation.toString() + " didn't contain an ID."); return null; } if (procFile.exists()) { try (InputStream inputStream = new FileInputStream(procFile); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { String line; do { line = reader.readLine(); if (line == null) { logger.warn("Failed to read container ID because " + cgroupLocation.toString() + " didn't contain an ID."); } else if (line.length() > CONTAINER_ID_LENGTH) { return line.substring(line.length() - CONTAINER_ID_LENGTH); } } while (line != null); } } else { logger.warn("Failed to read container ID because " + cgroupLocation.toString() + " does not exist."); } return null; } }
3,812
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/utils/LooseValidations.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.util.function.Supplier; import javax.annotation.CheckReturnValue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Utilities for validating parameters loosely. By default, validation is disabled. Enable error logging by setting the system * property {@code -Dcom.amazonaws.xray.validationMode=log} or throwing exceptions by setting the system property * {@code -Dcom.amazonaws.xray.validationMode=throw}. */ public final class LooseValidations { private static final Log logger = LogFactory.getLog(LooseValidations.class); // Visible for testing enum ValidationMode { NONE, LOG, THROW, } private static final ValidationMode VALIDATION_MODE = validationMode(); private LooseValidations() { } /** * Returns whether {@code obj} is {@code null}. */ @CheckReturnValue public static boolean checkNotNull(Object obj, String message) { if (obj != null) { return true; } handleError(() -> new NullPointerException(message)); return false; } private static void handleError(Supplier<RuntimeException> exception) { switch (VALIDATION_MODE) { case LOG: logger.error(exception.get()); break; case THROW: throw exception.get(); case NONE: default: break; } } private static ValidationMode validationMode() { return validationMode(System.getProperty("com.amazonaws.xray.validationMode", "")); } // Visible for testing static ValidationMode validationMode(String config) { try { return ValidationMode.valueOf(config.toUpperCase()); } catch (IllegalArgumentException e) { return ValidationMode.NONE; } } }
3,813
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/utils/ContainerInsightsUtil.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.ObjectMapper; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.Collection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.checkerframework.checker.nullness.qual.Nullable; /** * Utility class for querying configuration information from ContainerInsights enabled Kubernetes clusters. * * @deprecated For internal use only. */ @Deprecated @SuppressWarnings("checkstyle:HideUtilityClassConstructor") public class ContainerInsightsUtil { private static final String K8S_CRED_FOLDER = "/var/run/secrets/kubernetes.io/serviceaccount"; private static final String K8S_CRED_TOKEN_SUFFIX = "token"; private static final String K8S_CRED_CERT_SUFFIX = "ca.crt"; private static final String K8S_URL = "https://kubernetes.default.svc"; private static final String CI_CONFIGMAP_PATH = "/api/v1/namespaces/amazon-cloudwatch/configmaps/cluster-info"; private static final String AUTH_HEADER_NAME = "Authorization"; private static final int HTTP_TIMEOUT = 5; private static final Log logger = LogFactory.getLog(ContainerInsightsUtil.class); /** * Return the cluster name from ContainerInsights configMap via the K8S API and the pod's system account. * * @return the name */ @Nullable public static String getClusterName() { if (isK8s()) { CloseableHttpClient client = getHttpClient(); HttpGet getRequest = new HttpGet(K8S_URL + CI_CONFIGMAP_PATH); String k8sCredentialHeader = getK8sCredentialHeader(); if (k8sCredentialHeader != null) { getRequest.setHeader(AUTH_HEADER_NAME, k8sCredentialHeader); } try { CloseableHttpResponse response = client.execute(getRequest); try { HttpEntity entity = response.getEntity(); String json = EntityUtils.toString(entity); ObjectMapper mapper = new ObjectMapper(); String clusterName = mapper.readTree(json).at("/data/cluster.name").asText(); if (logger.isDebugEnabled()) { logger.debug("Container Insights Cluster Name: " + clusterName); } return clusterName; } catch (IOException e) { logger.error("Error parsing response from Kubernetes", e); } finally { response.close(); } client.close(); } catch (IOException e) { logger.error("Error querying for Container Insights ConfigMap", e); } } return null; } private static CloseableHttpClient getHttpClient() { KeyStore k8sTrustStore = getK8sKeystore(); try { if (k8sTrustStore != null) { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(k8sTrustStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers != null) { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustManagers, new SecureRandom()); return HttpClients.custom().setSSLContext(context).build(); } } } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { logger.debug("Unable to create HTTP client with K8s CA certs, using default trust store.", e); } RequestConfig config = RequestConfig.custom() .setConnectTimeout(HTTP_TIMEOUT * 1000) .setConnectionRequestTimeout(HTTP_TIMEOUT * 1000) .setSocketTimeout(HTTP_TIMEOUT * 1000).build(); return HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } @Nullable private static KeyStore getK8sKeystore() { InputStream certificateFile = null; try { KeyStore k8sTrustStore = null; File caFile = Paths.get(K8S_CRED_FOLDER, K8S_CRED_CERT_SUFFIX).toFile(); if (caFile.exists()) { k8sTrustStore = KeyStore.getInstance(KeyStore.getDefaultType()); k8sTrustStore.load(null, null); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); certificateFile = new FileInputStream(caFile); Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(certificateFile); if (certificates.isEmpty()) { throw new IllegalArgumentException("K8s cert file contained no certificates."); } for (Certificate certificate : certificates) { k8sTrustStore.setCertificateEntry("k8sca", certificate); } } else { logger.debug("K8s CA Cert file does not exists."); } return k8sTrustStore; } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { logger.warn("Unable to load K8s CA certificate.", e); return null; } finally { if (certificateFile != null) { try { certificateFile.close(); } catch (IOException e) { logger.error("Can't close K8s CA certificate file.", e); } } } } @Nullable private static String getK8sCredentialHeader() { BufferedReader tokenReader = null; try { File tokenFile = Paths.get(K8S_CRED_FOLDER, K8S_CRED_TOKEN_SUFFIX).toFile(); tokenReader = new BufferedReader(new InputStreamReader(new FileInputStream(tokenFile), StandardCharsets.UTF_8)); return String.format("Bearer %s", tokenReader.readLine()); } catch (IOException e) { logger.warn("Unable to read K8s credential file.", e); } finally { if (tokenReader != null) { try { tokenReader.close(); } catch (IOException e) { logger.error("Can't close K8s credential file.", e); } } } return null; } public static boolean isK8s() { return Paths.get(K8S_CRED_FOLDER, K8S_CRED_TOKEN_SUFFIX).toFile().exists(); } }
3,814
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/utils/JsonUtils.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.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @deprecated For internal use only. */ @Deprecated @SuppressWarnings("checkstyle:HideUtilityClassConstructor") public class JsonUtils { private static final JsonFactory JSON_FACTORY = new JsonFactory(); /** * Parses given file for an array field and returns that array as a JSON node. * @param filePath - The path to the JSON file to parse. * @param fieldName - The name of the field in the JSON document to retrieve. Must be a field pointing to an array. * @return A node containing an array object, or null if the field cannot be found. * @throws IOException */ public static JsonNode getNodeFromJsonFile(String filePath, String fieldName) throws IOException { JsonParser jp = JSON_FACTORY.createParser(new File(filePath)); jp.setCodec(new ObjectMapper()); JsonNode jsonNode = jp.readValueAsTree(); return jsonNode.findValue(fieldName); } /** * Finds all immediate children entries mapped to a given field name in a JSON object. * @param rootNode - The node to search for entries. Must be an array node. * @param fieldName - The name of the key to search for in rootNode's children. * @return A list of values that were mapped to the given field name. */ public static List<String> getMatchingListFromJsonArrayNode(JsonNode rootNode, String fieldName) { List<String> retList = new ArrayList<>(); Iterator<JsonNode> ite = rootNode.elements(); if (ite == null || !ite.hasNext()) { return retList; } ite.forEachRemaining(field -> { JsonNode stringNode = field.get(fieldName); // Check if fieldName is present and a valid string if (stringNode != null && !stringNode.textValue().isEmpty()) { retList.add(stringNode.textValue()); } }); return retList; } }
3,815
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/exceptions/SegmentNotFoundException.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.exceptions; public class SegmentNotFoundException extends RuntimeException { private static final long serialVersionUID = -3341201172459643090L; public SegmentNotFoundException() { } public SegmentNotFoundException(String message) { super(message); } public SegmentNotFoundException(Throwable cause) { super(cause); } public SegmentNotFoundException(String message, Throwable cause) { super(message, cause); } }
3,816
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/exceptions/AlreadyEmittedException.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.exceptions; public class AlreadyEmittedException extends RuntimeException { private static final long serialVersionUID = 6215061243115294496L; public AlreadyEmittedException() { } public AlreadyEmittedException(String message) { super(message); } public AlreadyEmittedException(Throwable cause) { super(cause); } public AlreadyEmittedException(String message, Throwable cause) { super(message, cause); } }
3,817
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/exceptions/SubsegmentNotFoundException.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.exceptions; public class SubsegmentNotFoundException extends RuntimeException { private static final long serialVersionUID = 3598661533525244324L; public SubsegmentNotFoundException() { } public SubsegmentNotFoundException(String message) { super(message); } public SubsegmentNotFoundException(Throwable cause) { super(cause); } public SubsegmentNotFoundException(String message, Throwable cause) { super(message, cause); } }
3,818
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/jakarta
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/jakarta/servlet/AWSXRayServletFilter.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 com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.StringValidator; import com.amazonaws.xray.entities.TraceHeader; import com.amazonaws.xray.entities.TraceHeader.SampleDecision; import com.amazonaws.xray.entities.TraceID; import com.amazonaws.xray.strategy.jakarta.DynamicSegmentNamingStrategy; import com.amazonaws.xray.strategy.jakarta.FixedSegmentNamingStrategy; import com.amazonaws.xray.strategy.jakarta.SegmentNamingStrategy; import com.amazonaws.xray.strategy.sampling.SamplingRequest; import com.amazonaws.xray.strategy.sampling.SamplingResponse; import com.amazonaws.xray.strategy.sampling.SamplingStrategy; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Optional; 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 AWSXRayServletFilter implements jakarta.servlet.Filter { private static final Log logger = LogFactory.getLog(AWSXRayServletFilter.class); @Nullable private String segmentOverrideName; @Nullable private String segmentDefaultName; @MonotonicNonNull private SegmentNamingStrategy segmentNamingStrategy; @MonotonicNonNull private AWSXRayRecorder recorder; private final AWSXRayServletAsyncListener listener; /** * Warning: this no-args constructor should not be used directly. This constructor is made available for use from within * {@code web.xml} and other declarative file-based instantiations. */ public AWSXRayServletFilter() { this((SegmentNamingStrategy) null); } public AWSXRayServletFilter(String fixedSegmentName) { this(SegmentNamingStrategy.fixed(fixedSegmentName)); } public AWSXRayServletFilter(@Nullable SegmentNamingStrategy segmentNamingStrategy) { this(segmentNamingStrategy, null); } // TODO(anuraaga): Better define lifecycle relationship between this listener and the filter. @SuppressWarnings("nullness") public AWSXRayServletFilter(@Nullable SegmentNamingStrategy segmentNamingStrategy, @Nullable AWSXRayRecorder recorder) { // Will be configured by web.xml otherwise. if (segmentNamingStrategy != null) { this.segmentNamingStrategy = segmentNamingStrategy; } // Will be configured by web.xml otherwise. if (recorder != null) { this.recorder = recorder; } this.listener = new AWSXRayServletAsyncListener(this, recorder); } /** * @return the segmentOverrideName */ @Nullable public String getSegmentOverrideName() { return segmentOverrideName; } /** * @param segmentOverrideName * the segmentOverrideName to set */ public void setSegmentOverrideName(String segmentOverrideName) { this.segmentOverrideName = segmentOverrideName; } /** * @return the segmentDefaultName */ @Nullable public String getSegmentDefaultName() { return segmentDefaultName; } /** * @param segmentDefaultName * the segmentDefaultName to set */ public void setSegmentDefaultName(String segmentDefaultName) { this.segmentDefaultName = segmentDefaultName; } /** * * * @param config * the filter configuration. There are various init-params which may be passed on initialization. The values in init-params * will create segment naming strategies which override those passed in constructors. * * <ul> * * <li> * <b>fixedName</b> A String value used as the fixedName parameter for a created * {@link FixedSegmentNamingStrategy}. Used only if the {@code dynamicNamingFallbackName} * init-param is not set. * </li> * * <li> * <b>dynamicNamingFallbackName</b> A String value used as the fallbackName parameter for a created * {@link DynamicSegmentNamingStrategy}. * </li> * * <li> * <b>dynamicNamingRecognizedHosts</b> A String value used as the recognizedHosts parameter for a created * {@link DynamicSegmentNamingStrategy}. * </li> * * </ul> * * @throws ServletException * when a segment naming strategy is not provided in constructor arguments nor in init-params. */ @Override public void init(FilterConfig config) throws ServletException { String fixedName = config.getInitParameter("fixedName"); String dynamicNamingFallbackName = config.getInitParameter("dynamicNamingFallbackName"); String dynamicNamingRecognizedHosts = config.getInitParameter("dynamicNamingRecognizedHosts"); if (StringValidator.isNotNullOrBlank(dynamicNamingFallbackName)) { if (StringValidator.isNotNullOrBlank(dynamicNamingRecognizedHosts)) { segmentNamingStrategy = SegmentNamingStrategy.dynamic(dynamicNamingFallbackName, dynamicNamingRecognizedHosts); } else { segmentNamingStrategy = SegmentNamingStrategy.dynamic(dynamicNamingFallbackName); } } else if (StringValidator.isNotNullOrBlank(fixedName)) { segmentNamingStrategy = SegmentNamingStrategy.fixed(fixedName); } else if (null == segmentNamingStrategy) { throw new ServletException( "The AWSXRayServletFilter requires either a fixedName init-param or an instance of SegmentNamingStrategy. " + "Add an init-param tag to the AWSXRayServletFilter's declaration in web.xml, using param-name: 'fixedName'. " + "Alternatively, pass an instance of SegmentNamingStrategy to the AWSXRayServletFilter constructor."); } } @Override public void destroy() { } @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("AWSXRayServletFilter is beginning to process request: " + request.toString()); } Segment segment = preFilter(request, response); try { chain.doFilter(request, response); } catch (Throwable e) { segment.addException(e); throw e; } finally { if (request.isAsyncStarted()) { request.setAttribute(AWSXRayServletAsyncListener.ENTITY_ATTRIBUTE_KEY, segment); try { request.getAsyncContext().addListener(listener); if (recorder != null) { recorder.clearTraceEntity(); } } catch (IllegalStateException ise) { // race condition that occurs when async processing finishes before adding the listener postFilter(request, response); } } else { postFilter(request, response); } if (logger.isDebugEnabled()) { logger.debug("AWSXRayServletFilter is finished processing request: " + request.toString()); } } } @Nullable private HttpServletRequest castServletRequest(ServletRequest request) { try { return (HttpServletRequest) request; } catch (ClassCastException cce) { logger.warn("Unable to cast ServletRequest to HttpServletRequest.", cce); } return null; } @Nullable private HttpServletResponse castServletResponse(ServletResponse response) { try { return (HttpServletResponse) response; } catch (ClassCastException cce) { logger.warn("Unable to cast ServletResponse to HttpServletResponse.", cce); } return null; } private Optional<TraceHeader> getTraceHeader(HttpServletRequest request) { String traceHeaderString = request.getHeader(TraceHeader.HEADER_KEY); if (null != traceHeaderString) { return Optional.of(TraceHeader.fromString(traceHeaderString)); } return Optional.empty(); } private Optional<String> getHost(HttpServletRequest request) { return Optional.ofNullable(request.getHeader("Host")); } private Optional<String> getClientIp(HttpServletRequest request) { return Optional.ofNullable(request.getRemoteAddr()); } private Optional<String> getXForwardedFor(HttpServletRequest request) { String forwarded = request.getHeader("X-Forwarded-For"); if (forwarded != null) { return Optional.of(forwarded.split(",")[0].trim()); } return Optional.empty(); } private Optional<String> getUserAgent(HttpServletRequest request) { String userAgentHeaderString = request.getHeader("User-Agent"); if (null != userAgentHeaderString) { return Optional.of(userAgentHeaderString); } return Optional.empty(); } private Optional<Integer> getContentLength(HttpServletResponse response) { String contentLengthString = response.getHeader("Content-Length"); if (null != contentLengthString && !contentLengthString.isEmpty()) { try { return Optional.of(Integer.parseInt(contentLengthString)); } catch (NumberFormatException nfe) { logger.debug("Unable to parse Content-Length header from HttpServletResponse.", nfe); } } return Optional.empty(); } private String getSegmentName(HttpServletRequest httpServletRequest) { if (segmentNamingStrategy == null) { throw new RuntimeException( "The AWSXRayServletFilter requires either a fixedName init-param or an instance of SegmentNamingStrategy. " + "Add an init-param tag to the AWSXRayServletFilter's declaration in web.xml, using param-name: 'fixedName'. " + "Alternatively, pass an instance of SegmentNamingStrategy to the AWSXRayServletFilter constructor."); } return segmentNamingStrategy.nameForRequest(httpServletRequest); } private SamplingResponse fromSamplingStrategy(HttpServletRequest httpServletRequest) { AWSXRayRecorder recorder = getRecorder(); SamplingRequest samplingRequest = new SamplingRequest( getSegmentName(httpServletRequest), getHost(httpServletRequest).orElse(null), httpServletRequest.getRequestURI(), httpServletRequest.getMethod(), recorder.getOrigin()); SamplingResponse sample = recorder.getSamplingStrategy().shouldTrace(samplingRequest); return sample; } private SampleDecision getSampleDecision(SamplingResponse sample) { if (sample.isSampled()) { logger.debug("Sampling strategy decided SAMPLED."); return SampleDecision.SAMPLED; } else { logger.debug("Sampling strategy decided NOT_SAMPLED."); return SampleDecision.NOT_SAMPLED; } } private AWSXRayRecorder getRecorder() { if (recorder == null) { recorder = AWSXRay.getGlobalRecorder(); } return recorder; } public Segment preFilter(ServletRequest request, ServletResponse response) { AWSXRayRecorder recorder = getRecorder(); HttpServletRequest httpServletRequest = castServletRequest(request); if (httpServletRequest == null) { logger.warn("Null value for incoming HttpServletRequest. Beginning NoOpSegment."); return recorder.beginNoOpSegment(); } Optional<TraceHeader> incomingHeader = getTraceHeader(httpServletRequest); SamplingStrategy samplingStrategy = recorder.getSamplingStrategy(); if (logger.isDebugEnabled() && incomingHeader.isPresent()) { logger.debug("Incoming trace header received: " + incomingHeader.get().toString()); } SamplingResponse samplingResponse = fromSamplingStrategy(httpServletRequest); SampleDecision sampleDecision = incomingHeader.isPresent() ? incomingHeader.get().getSampled() : getSampleDecision(samplingResponse); if (SampleDecision.REQUESTED.equals(sampleDecision) || SampleDecision.UNKNOWN.equals(sampleDecision)) { sampleDecision = getSampleDecision(samplingResponse); } TraceID traceId = null; String parentId = null; if (incomingHeader.isPresent()) { TraceHeader header = incomingHeader.get(); traceId = header.getRootTraceId(); parentId = header.getParentId(); } final Segment created; if (SampleDecision.SAMPLED.equals(sampleDecision)) { String segmentName = getSegmentName(httpServletRequest); created = traceId != null ? recorder.beginSegment(segmentName, traceId, parentId) : recorder.beginSegment(segmentName); if (samplingResponse.getRuleName().isPresent()) { logger.debug("Sampling strategy decided to use rule named: " + samplingResponse.getRuleName().get() + "."); created.setRuleName(samplingResponse.getRuleName().get()); } } else { //NOT_SAMPLED String segmentName = getSegmentName(httpServletRequest); if (samplingStrategy.isForcedSamplingSupported()) { created = traceId != null ? recorder.beginSegment(segmentName, traceId, parentId) : recorder.beginSegment(segmentName); created.setSampled(false); } else { logger.debug("Creating Dummy Segment"); created = traceId != null ? recorder.beginNoOpSegment(traceId) : recorder.beginNoOpSegment(); } } Map<String, Object> requestAttributes = new HashMap<String, Object>(); requestAttributes.put("url", httpServletRequest.getRequestURL().toString()); requestAttributes.put("method", httpServletRequest.getMethod()); Optional<String> userAgent = getUserAgent(httpServletRequest); if (userAgent.isPresent()) { requestAttributes.put("user_agent", userAgent.get()); } Optional<String> xForwardedFor = getXForwardedFor(httpServletRequest); if (xForwardedFor.isPresent()) { requestAttributes.put("client_ip", xForwardedFor.get()); requestAttributes.put("x_forwarded_for", true); } else { Optional<String> clientIp = getClientIp(httpServletRequest); if (clientIp.isPresent()) { requestAttributes.put("client_ip", clientIp.get()); } } created.putHttp("request", requestAttributes); HttpServletResponse httpServletResponse = castServletResponse(response); if (httpServletResponse == null) { return created; } final TraceHeader responseHeader; if (incomingHeader.isPresent()) { // create a new header, and use the incoming header so we know what to do in regards to sending back the sampling // decision. responseHeader = new TraceHeader(created.getTraceId()); if (SampleDecision.REQUESTED == incomingHeader.get().getSampled()) { responseHeader.setSampled(created.isSampled() ? SampleDecision.SAMPLED : SampleDecision.NOT_SAMPLED); } } else { // Create a new header, we're the tracing root. We wont return the sampling decision. responseHeader = new TraceHeader(created.getTraceId()); } httpServletResponse.addHeader(TraceHeader.HEADER_KEY, responseHeader.toString()); return created; } public void postFilter(ServletRequest request, ServletResponse response) { AWSXRayRecorder recorder = getRecorder(); Segment segment = recorder.getCurrentSegment(); if (null != segment) { HttpServletResponse httpServletResponse = castServletResponse(response); if (null != httpServletResponse) { Map<String, Object> responseAttributes = new HashMap<String, Object>(); int responseCode = httpServletResponse.getStatus(); switch (responseCode / 100) { case 4: segment.setError(true); if (responseCode == 429) { segment.setThrottle(true); } break; case 5: segment.setFault(true); break; default: break; } responseAttributes.put("status", responseCode); Optional<Integer> contentLength = getContentLength(httpServletResponse); if (contentLength.isPresent()) { responseAttributes.put("content_length", contentLength.get()); } segment.putHttp("response", responseAttributes); } recorder.endSegment(); } } }
3,819
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/jakarta
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/jakarta/servlet/AWSXRayServletAsyncListener.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 com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.entities.Entity; import jakarta.servlet.AsyncEvent; import jakarta.servlet.AsyncListener; import java.io.IOException; import org.checkerframework.checker.initialization.qual.UnderInitialization; import org.checkerframework.checker.nullness.qual.Nullable; class AWSXRayServletAsyncListener implements AsyncListener { public static final String ENTITY_ATTRIBUTE_KEY = "com.amazonaws.xray.entities.Entity"; @Nullable private AWSXRayRecorder recorder; private final AWSXRayServletFilter filter; // TODO(anuraaga): Better define lifecycle relationship between this listener and the filter. @SuppressWarnings("nullness") AWSXRayServletAsyncListener(@UnderInitialization AWSXRayServletFilter filter, @Nullable AWSXRayRecorder recorder) { this.filter = filter; this.recorder = recorder; } private void processEvent(AsyncEvent event) throws IOException { Entity entity = (Entity) event.getSuppliedRequest().getAttribute(ENTITY_ATTRIBUTE_KEY); entity.run(() -> { if (event.getThrowable() != null) { entity.addException(event.getThrowable()); } filter.postFilter(event.getSuppliedRequest(), event.getSuppliedResponse()); }); } @Override public void onComplete(AsyncEvent event) throws IOException { processEvent(event); } @Override public void onTimeout(AsyncEvent event) throws IOException { processEvent(event); } @Override public void onError(AsyncEvent event) throws IOException { processEvent(event); } @Override public void onStartAsync(AsyncEvent event) throws IOException { } }
3,820
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/serializers/StackTraceElementSerializer.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.serializers; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; public class StackTraceElementSerializer extends JsonSerializer<StackTraceElement> { public StackTraceElementSerializer() { super(); } @Override public void serialize( StackTraceElement element, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeStartObject(); String filename = element.getFileName(); if (filename != null) { jsonGenerator.writeStringField("path", filename); } else { jsonGenerator.writeNullField("path"); } jsonGenerator.writeNumberField("line", element.getLineNumber()); jsonGenerator.writeStringField("label", element.getClassName() + "." + element.getMethodName()); jsonGenerator.writeEndObject(); } }
3,821
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/serializers/CauseSerializer.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.serializers; import com.amazonaws.xray.entities.Cause; import com.amazonaws.xray.entities.ThrowableDescription; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; import org.checkerframework.checker.nullness.qual.Nullable; public class CauseSerializer extends JsonSerializer<Cause> { private final JsonSerializer<Object> objectSerializer; /** * @deprecated Use {@link #CauseSerializer(JsonSerializer)}. */ @Deprecated // This constructor that is breaking our nullness requirements shouldn't be used and will be deleted. @SuppressWarnings("nullness") public CauseSerializer() { this(null); } public CauseSerializer(JsonSerializer<Object> objectSerializer) { this.objectSerializer = objectSerializer; } @Override public void serialize(Cause cause, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { if (!cause.getExceptions().isEmpty()) { ThrowableDescription first = cause.getExceptions().get(0); String causeDescription = first.getCause(); if (first.getId() == null && causeDescription != null) { jsonGenerator.writeString(causeDescription); return; } } objectSerializer.serialize(cause, jsonGenerator, serializerProvider); } @Override public boolean isEmpty(SerializerProvider serializerProvider, @Nullable Cause cause) { return cause == null || (cause.getExceptions().isEmpty() && cause.getId() == null && cause.getMessage() == null); } }
3,822
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/javax
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/javax/servlet/AWSXRayServletFilter.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 com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.StringValidator; import com.amazonaws.xray.entities.TraceHeader; import com.amazonaws.xray.entities.TraceHeader.SampleDecision; import com.amazonaws.xray.entities.TraceID; import com.amazonaws.xray.strategy.DynamicSegmentNamingStrategy; import com.amazonaws.xray.strategy.FixedSegmentNamingStrategy; import com.amazonaws.xray.strategy.SegmentNamingStrategy; 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.util.HashMap; import java.util.Map; import java.util.Optional; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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 AWSXRayServletFilter implements javax.servlet.Filter { private static final Log logger = LogFactory.getLog(AWSXRayServletFilter.class); @Nullable private String segmentOverrideName; @Nullable private String segmentDefaultName; @MonotonicNonNull private SegmentNamingStrategy segmentNamingStrategy; @MonotonicNonNull private AWSXRayRecorder recorder; private final AWSXRayServletAsyncListener listener; /** * Warning: this no-args constructor should not be used directly. This constructor is made available for use from within * {@code web.xml} and other declarative file-based instantiations. */ public AWSXRayServletFilter() { this((SegmentNamingStrategy) null); } public AWSXRayServletFilter(String fixedSegmentName) { this(new FixedSegmentNamingStrategy(fixedSegmentName)); } public AWSXRayServletFilter(@Nullable SegmentNamingStrategy segmentNamingStrategy) { this(segmentNamingStrategy, null); } // TODO(anuraaga): Better define lifecycle relationship between this listener and the filter. @SuppressWarnings("nullness") public AWSXRayServletFilter(@Nullable SegmentNamingStrategy segmentNamingStrategy, @Nullable AWSXRayRecorder recorder) { // Will be configured by web.xml otherwise. if (segmentNamingStrategy != null) { this.segmentNamingStrategy = segmentNamingStrategy; } // Will be configured by web.xml otherwise. if (recorder != null) { this.recorder = recorder; } this.listener = new AWSXRayServletAsyncListener(this, recorder); } /** * @return the segmentOverrideName */ @Nullable public String getSegmentOverrideName() { return segmentOverrideName; } /** * @param segmentOverrideName * the segmentOverrideName to set */ public void setSegmentOverrideName(String segmentOverrideName) { this.segmentOverrideName = segmentOverrideName; } /** * @return the segmentDefaultName */ @Nullable public String getSegmentDefaultName() { return segmentDefaultName; } /** * @param segmentDefaultName * the segmentDefaultName to set */ public void setSegmentDefaultName(String segmentDefaultName) { this.segmentDefaultName = segmentDefaultName; } /** * * * @param config * the filter configuration. There are various init-params which may be passed on initialization. The values in init-params * will create segment naming strategies which override those passed in constructors. * * <ul> * * <li> * <b>fixedName</b> A String value used as the fixedName parameter for a created * {@link com.amazonaws.xray.strategy.FixedSegmentNamingStrategy}. Used only if the {@code dynamicNamingFallbackName} * init-param is not set. * </li> * * <li> * <b>dynamicNamingFallbackName</b> A String value used as the fallbackName parameter for a created * {@link com.amazonaws.xray.strategy.DynamicSegmentNamingStrategy}. * </li> * * <li> * <b>dynamicNamingRecognizedHosts</b> A String value used as the recognizedHosts parameter for a created * {@link com.amazonaws.xray.strategy.DynamicSegmentNamingStrategy}. * </li> * * </ul> * * @throws ServletException * when a segment naming strategy is not provided in constructor arguments nor in init-params. */ @Override public void init(FilterConfig config) throws ServletException { String fixedName = config.getInitParameter("fixedName"); String dynamicNamingFallbackName = config.getInitParameter("dynamicNamingFallbackName"); String dynamicNamingRecognizedHosts = config.getInitParameter("dynamicNamingRecognizedHosts"); if (StringValidator.isNotNullOrBlank(dynamicNamingFallbackName)) { if (StringValidator.isNotNullOrBlank(dynamicNamingRecognizedHosts)) { segmentNamingStrategy = new DynamicSegmentNamingStrategy(dynamicNamingFallbackName, dynamicNamingRecognizedHosts); } else { segmentNamingStrategy = new DynamicSegmentNamingStrategy(dynamicNamingFallbackName); } } else if (StringValidator.isNotNullOrBlank(fixedName)) { segmentNamingStrategy = new FixedSegmentNamingStrategy(fixedName); } else if (null == segmentNamingStrategy) { throw new ServletException( "The AWSXRayServletFilter requires either a fixedName init-param or an instance of SegmentNamingStrategy. " + "Add an init-param tag to the AWSXRayServletFilter's declaration in web.xml, using param-name: 'fixedName'. " + "Alternatively, pass an instance of SegmentNamingStrategy to the AWSXRayServletFilter constructor."); } } @Override public void destroy() { } @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("AWSXRayServletFilter is beginning to process request: " + request.toString()); } Segment segment = preFilter(request, response); try { chain.doFilter(request, response); } catch (Throwable e) { segment.addException(e); throw e; } finally { if (request.isAsyncStarted()) { request.setAttribute(AWSXRayServletAsyncListener.ENTITY_ATTRIBUTE_KEY, segment); try { request.getAsyncContext().addListener(listener); if (recorder != null) { recorder.clearTraceEntity(); } } catch (IllegalStateException ise) { // race condition that occurs when async processing finishes before adding the listener postFilter(request, response); } } else { postFilter(request, response); } if (logger.isDebugEnabled()) { logger.debug("AWSXRayServletFilter is finished processing request: " + request.toString()); } } } @Nullable private HttpServletRequest castServletRequest(ServletRequest request) { try { return (HttpServletRequest) request; } catch (ClassCastException cce) { logger.warn("Unable to cast ServletRequest to HttpServletRequest.", cce); } return null; } @Nullable private HttpServletResponse castServletResponse(ServletResponse response) { try { return (HttpServletResponse) response; } catch (ClassCastException cce) { logger.warn("Unable to cast ServletResponse to HttpServletResponse.", cce); } return null; } private Optional<TraceHeader> getTraceHeader(HttpServletRequest request) { String traceHeaderString = request.getHeader(TraceHeader.HEADER_KEY); if (null != traceHeaderString) { return Optional.of(TraceHeader.fromString(traceHeaderString)); } return Optional.empty(); } private Optional<String> getHost(HttpServletRequest request) { return Optional.ofNullable(request.getHeader("Host")); } private Optional<String> getClientIp(HttpServletRequest request) { return Optional.ofNullable(request.getRemoteAddr()); } private Optional<String> getXForwardedFor(HttpServletRequest request) { String forwarded = request.getHeader("X-Forwarded-For"); if (forwarded != null) { return Optional.of(forwarded.split(",")[0].trim()); } return Optional.empty(); } private Optional<String> getUserAgent(HttpServletRequest request) { String userAgentHeaderString = request.getHeader("User-Agent"); if (null != userAgentHeaderString) { return Optional.of(userAgentHeaderString); } return Optional.empty(); } private Optional<Integer> getContentLength(HttpServletResponse response) { String contentLengthString = response.getHeader("Content-Length"); if (null != contentLengthString && !contentLengthString.isEmpty()) { try { return Optional.of(Integer.parseInt(contentLengthString)); } catch (NumberFormatException nfe) { logger.debug("Unable to parse Content-Length header from HttpServletResponse.", nfe); } } return Optional.empty(); } private String getSegmentName(HttpServletRequest httpServletRequest) { if (segmentNamingStrategy == null) { throw new RuntimeException( "The AWSXRayServletFilter requires either a fixedName init-param or an instance of SegmentNamingStrategy. " + "Add an init-param tag to the AWSXRayServletFilter's declaration in web.xml, using param-name: 'fixedName'. " + "Alternatively, pass an instance of SegmentNamingStrategy to the AWSXRayServletFilter constructor."); } return segmentNamingStrategy.nameForRequest(httpServletRequest); } private SamplingResponse fromSamplingStrategy(HttpServletRequest httpServletRequest) { AWSXRayRecorder recorder = getRecorder(); SamplingRequest samplingRequest = new SamplingRequest( getSegmentName(httpServletRequest), getHost(httpServletRequest).orElse(null), httpServletRequest.getRequestURI(), httpServletRequest.getMethod(), recorder.getOrigin()); SamplingResponse sample = recorder.getSamplingStrategy().shouldTrace(samplingRequest); return sample; } private SampleDecision getSampleDecision(SamplingResponse sample) { if (sample.isSampled()) { logger.debug("Sampling strategy decided SAMPLED."); return SampleDecision.SAMPLED; } else { logger.debug("Sampling strategy decided NOT_SAMPLED."); return SampleDecision.NOT_SAMPLED; } } private AWSXRayRecorder getRecorder() { if (recorder == null) { recorder = AWSXRay.getGlobalRecorder(); } return recorder; } public Segment preFilter(ServletRequest request, ServletResponse response) { AWSXRayRecorder recorder = getRecorder(); HttpServletRequest httpServletRequest = castServletRequest(request); if (httpServletRequest == null) { logger.warn("Null value for incoming HttpServletRequest. Beginning NoOpSegment."); return recorder.beginNoOpSegment(); } Optional<TraceHeader> incomingHeader = getTraceHeader(httpServletRequest); SamplingStrategy samplingStrategy = recorder.getSamplingStrategy(); if (logger.isDebugEnabled() && incomingHeader.isPresent()) { logger.debug("Incoming trace header received: " + incomingHeader.get().toString()); } SamplingResponse samplingResponse = fromSamplingStrategy(httpServletRequest); SampleDecision sampleDecision = incomingHeader.isPresent() ? incomingHeader.get().getSampled() : getSampleDecision(samplingResponse); if (SampleDecision.REQUESTED.equals(sampleDecision) || SampleDecision.UNKNOWN.equals(sampleDecision)) { sampleDecision = getSampleDecision(samplingResponse); } TraceID traceId = null; String parentId = null; if (incomingHeader.isPresent()) { TraceHeader header = incomingHeader.get(); traceId = header.getRootTraceId(); parentId = header.getParentId(); } final Segment created; if (SampleDecision.SAMPLED.equals(sampleDecision)) { String segmentName = getSegmentName(httpServletRequest); created = traceId != null ? recorder.beginSegment(segmentName, traceId, parentId) : recorder.beginSegment(segmentName); if (samplingResponse.getRuleName().isPresent()) { logger.debug("Sampling strategy decided to use rule named: " + samplingResponse.getRuleName().get() + "."); created.setRuleName(samplingResponse.getRuleName().get()); } } else { //NOT_SAMPLED String segmentName = getSegmentName(httpServletRequest); if (samplingStrategy.isForcedSamplingSupported()) { created = traceId != null ? recorder.beginSegment(segmentName, traceId, parentId) : recorder.beginSegment(segmentName); created.setSampled(false); } else { logger.debug("Creating Dummy Segment"); created = traceId != null ? recorder.beginNoOpSegment(traceId) : recorder.beginNoOpSegment(); } } Map<String, Object> requestAttributes = new HashMap<String, Object>(); requestAttributes.put("url", httpServletRequest.getRequestURL().toString()); requestAttributes.put("method", httpServletRequest.getMethod()); Optional<String> userAgent = getUserAgent(httpServletRequest); if (userAgent.isPresent()) { requestAttributes.put("user_agent", userAgent.get()); } Optional<String> xForwardedFor = getXForwardedFor(httpServletRequest); if (xForwardedFor.isPresent()) { requestAttributes.put("client_ip", xForwardedFor.get()); requestAttributes.put("x_forwarded_for", true); } else { Optional<String> clientIp = getClientIp(httpServletRequest); if (clientIp.isPresent()) { requestAttributes.put("client_ip", clientIp.get()); } } created.putHttp("request", requestAttributes); HttpServletResponse httpServletResponse = castServletResponse(response); if (httpServletResponse == null) { return created; } final TraceHeader responseHeader; if (incomingHeader.isPresent()) { // create a new header, and use the incoming header so we know what to do in regards to sending back the sampling // decision. responseHeader = new TraceHeader(created.getTraceId()); if (SampleDecision.REQUESTED == incomingHeader.get().getSampled()) { responseHeader.setSampled(created.isSampled() ? SampleDecision.SAMPLED : SampleDecision.NOT_SAMPLED); } } else { // Create a new header, we're the tracing root. We wont return the sampling decision. responseHeader = new TraceHeader(created.getTraceId()); } httpServletResponse.addHeader(TraceHeader.HEADER_KEY, responseHeader.toString()); return created; } public void postFilter(ServletRequest request, ServletResponse response) { AWSXRayRecorder recorder = getRecorder(); Segment segment = recorder.getCurrentSegment(); if (null != segment) { HttpServletResponse httpServletResponse = castServletResponse(response); if (null != httpServletResponse) { Map<String, Object> responseAttributes = new HashMap<String, Object>(); int responseCode = httpServletResponse.getStatus(); switch (responseCode / 100) { case 4: segment.setError(true); if (responseCode == 429) { segment.setThrottle(true); } break; case 5: segment.setFault(true); break; default: break; } responseAttributes.put("status", responseCode); Optional<Integer> contentLength = getContentLength(httpServletResponse); if (contentLength.isPresent()) { responseAttributes.put("content_length", contentLength.get()); } segment.putHttp("response", responseAttributes); } recorder.endSegment(); } } }
3,823
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/javax
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/javax/servlet/AWSXRayServletAsyncListener.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 com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.entities.Entity; import java.io.IOException; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import org.checkerframework.checker.initialization.qual.UnderInitialization; import org.checkerframework.checker.nullness.qual.Nullable; class AWSXRayServletAsyncListener implements AsyncListener { public static final String ENTITY_ATTRIBUTE_KEY = "com.amazonaws.xray.entities.Entity"; @Nullable private AWSXRayRecorder recorder; private final AWSXRayServletFilter filter; // TODO(anuraaga): Better define lifecycle relationship between this listener and the filter. @SuppressWarnings("nullness") AWSXRayServletAsyncListener(@UnderInitialization AWSXRayServletFilter filter, @Nullable AWSXRayRecorder recorder) { this.filter = filter; this.recorder = recorder; } private void processEvent(AsyncEvent event) throws IOException { Entity entity = (Entity) event.getSuppliedRequest().getAttribute(ENTITY_ATTRIBUTE_KEY); entity.run(() -> { if (event.getThrowable() != null) { entity.addException(event.getThrowable()); } filter.postFilter(event.getSuppliedRequest(), event.getSuppliedResponse()); }); } @Override public void onComplete(AsyncEvent event) throws IOException { processEvent(event); } @Override public void onTimeout(AsyncEvent event) throws IOException { processEvent(event); } @Override public void onError(AsyncEvent event) throws IOException { processEvent(event); } @Override public void onStartAsync(AsyncEvent event) throws IOException { } }
3,824
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/emitters/DelegatingEmitter.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 java.util.Objects.requireNonNull; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; /** * An {@link Emitter} which delegates all calls to another {@link Emitter}. * Extend from this class to customize when segments and subsegments are sent. * * <pre>{@code * class CircuitBreakingEmitter extends DelegatingEmitter { * * private final CircuitBreaker circuitBreaker; * * CircuitBreakingEmitter() { * super(Emitter.create()); * circuitBreaker = CircuitBreaker.create(); * } * * {@literal @}Override * public boolean sendSegment(Segment segment) { * if (circuitBreaker.isOpen()) { * return super.sendSegment(segment); * } * return false; * } * } * }</pre> */ public class DelegatingEmitter extends Emitter { private final Emitter delegate; /** * Constructs a new {@link DelegatingEmitter} that delegates all calls to the provided {@link Emitter}. */ protected DelegatingEmitter(Emitter delegate) { this.delegate = requireNonNull(delegate, "delegate"); } @Override public boolean sendSegment(Segment segment) { return delegate.sendSegment(segment); } @Override public boolean sendSubsegment(Subsegment subsegment) { return delegate.sendSubsegment(subsegment); } }
3,825
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/emitters/UDPEmitter.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 com.amazonaws.xray.config.DaemonConfiguration; import com.amazonaws.xray.entities.Entity; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Optional; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @deprecated Use {@link Emitter#create()}. */ @Deprecated public class UDPEmitter extends Emitter { private static final Log logger = LogFactory.getLog(UDPEmitter.class); private static final int UDP_PACKET_LIMIT = 63 * 1024; private DatagramSocket daemonSocket; private DaemonConfiguration config; private byte[] sendBuffer = new byte[DAEMON_BUF_RECEIVE_SIZE]; /** * Constructs a UDPEmitter. Sets the daemon address to the value of the {@code AWS_XRAY_DAEMON_ADDRESS} environment variable * or {@code com.amazonaws.xray.emitters.daemonAddress} system property, if either are set to a non-empty value. Otherwise, * points to {@code InetAddress.getLoopbackAddress()} at port {@code 2000}. * * @throws SocketException * if an error occurs while instantiating a {@code DatagramSocket}. */ public UDPEmitter() throws SocketException { this(new DaemonConfiguration()); } /** * Constructs a UDPEmitter. This overload allows you to specify the configuration. * * @param config The {@link DaemonConfiguration} for the Emitter. * @throws SocketException * if an error occurs while instantiating a {@code DatagramSocket}. */ public UDPEmitter(DaemonConfiguration config) throws SocketException { this.config = config; try { daemonSocket = new DatagramSocket(); } catch (SocketException e) { logger.error("Exception while instantiating daemon socket.", e); throw e; } } public String getUDPAddress() { return config.getUDPAddress(); } /** * {@inheritDoc} * * @see Emitter#sendSegment(Segment) */ @Override public boolean sendSegment(Segment segment) { if (logger.isDebugEnabled()) { logger.debug(segment.prettySerialize()); } byte[] bytes = (PROTOCOL_HEADER + PROTOCOL_DELIMITER + segment.serialize()).getBytes(StandardCharsets.UTF_8); if (bytes.length > UDP_PACKET_LIMIT) { List<Subsegment> subsegments = segment.getSubsegmentsCopy(); logger.debug("Segment too large, sending subsegments to daemon first. bytes " + bytes.length + " subsegemnts " + subsegments.size()); for (Subsegment subsegment : subsegments) { sendSubsegment(subsegment); segment.removeSubsegment(subsegment); } bytes = (PROTOCOL_HEADER + PROTOCOL_DELIMITER + segment.serialize()).getBytes(StandardCharsets.UTF_8); logger.debug("New segment size. bytes " + bytes.length); } return sendData(bytes, segment); } /** * {@inheritDoc} * * @see Emitter#sendSubsegment(Subsegment) */ @Override public boolean sendSubsegment(Subsegment subsegment) { if (logger.isDebugEnabled()) { logger.debug(subsegment.prettyStreamSerialize()); } return sendData((PROTOCOL_HEADER + PROTOCOL_DELIMITER + subsegment.streamSerialize()).getBytes(StandardCharsets.UTF_8), subsegment); } private boolean sendData(byte[] data, Entity entity) { try { DatagramPacket packet = new DatagramPacket(sendBuffer, DAEMON_BUF_RECEIVE_SIZE, config.getAddressForEmitter()); packet.setData(data); logger.debug("Sending UDP packet."); daemonSocket.send(packet); } catch (Exception e) { String segmentName = Optional.ofNullable(entity.getParent()).map(this::nameAndId).orElse("[no parent segment]"); logger.error("Exception while sending segment (" + entity.getClass().getSimpleName() + ") over UDP for entity " + nameAndId(entity) + " on segment " + segmentName + ". Bytes: " + data.length, e); return false; } return true; } private String nameAndId(Entity entity) { return entity.getName() + " [" + entity.getId() + "]"; } }
3,826
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/emitters/DefaultEmitter.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 java.net.SocketException; /** * @deprecated Use {@link Emitter#create()}. */ @Deprecated public class DefaultEmitter extends UDPEmitter { public DefaultEmitter() throws SocketException { super(); } }
3,827
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/emitters/Emitter.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 com.amazonaws.xray.config.DaemonConfiguration; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; import java.io.IOException; /** * An emitter of segments and subsegments to X-Ray. */ public abstract class Emitter { protected static final String PROTOCOL_HEADER = "{\"format\": \"json\", \"version\": 1}"; protected static final String PRIORITY_PROTOCOL_HEADER = "{\"format\": \"json\", \"version\": 1}"; protected static final char PROTOCOL_DELIMITER = '\n'; protected static final int DAEMON_BUF_RECEIVE_SIZE = 256 * 1024; // daemon.go#line-15 /** * Returns an {@link Emitter} that uses a default {@link DaemonConfiguration}. * * @throws IOException if an error occurs while instantiating the {@link Emitter} (e.g., socket failure). */ public static Emitter create() throws IOException { return new UDPEmitter(); } /** * Returns an {@link Emitter} that uses the provided {@link DaemonConfiguration}. * * @throws IOException if an error occurs while instantiating the {@link Emitter} (e.g., socket failure). */ public static Emitter create(DaemonConfiguration configuration) throws IOException { return new UDPEmitter(configuration); } /** * Sends a segment to the X-Ray daemon. * * @param segment * the segment to send * @return true if the send operation was successful */ public abstract boolean sendSegment(Segment segment); /** * Sends a subsegment to the X-Ray daemon. * * @param subsegment * the subsegment to send * @return * true if the send operation was successful * */ public abstract boolean sendSubsegment(Subsegment subsegment); }
3,828
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/listeners/SegmentListener.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.entities.Entity; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; import org.checkerframework.checker.nullness.qual.Nullable; /** * An interface to intercept lifecycle events, namely the beginning and ending, of segments produced by the AWSXRayRecorder. * Implementations should only contain cheap operations, since they'll be run very frequently. * */ public interface SegmentListener { /** * onBeginSegment is invoked immediately after a segment is created by the recorder. * The segment can be manipulated, e.g. with putAnnotation. * * @param segment * The segment that has just begun */ default void onBeginSegment(Segment segment) { } /** * onBeginSubsegment is invoked immediately after a subsegment is created by the recorder. * The subsegment can be manipulated, e.g. with putAnnotation. * * @param subsegment * The subsegment that has just begun */ default void onBeginSubsegment(Subsegment subsegment) { } /** * beforeEndSegment is invoked just before a segment is ended by the recorder. * The segment can be manipulated, e.g. with putAnnotation. * * @param segment * The segment that has just ended */ default void beforeEndSegment(Segment segment) { } /** * afterEndSegment is invoked after a segment is ended by the recorder and emitted to the daemon. * The segment must not be modified since it has already been sent to X-Ray's backend. * Attempts to do so will raise an {@code AlreadyEmittedException}. * * @param segment * The segment that has just ended */ default void afterEndSegment(Segment segment) { } /** * beforeEndSubsegment is invoked just before a subsegment is ended by the recorder. * The subsegment can be manipulated, e.g. with putAnnotation. * * @param subsegment * The subsegment that has just ended */ default void beforeEndSubsegment(Subsegment subsegment) { } /** * afterEndSubsegment is invoked after a subsegment is ended by the recorder and emitted to the daemon. * The subsegment must not be modified since it has already been sent to X-Ray's backend. * Attempts to do so will raise an {@code AlreadyEmittedException}. * * @param subsegment * The subsegment that has just ended */ default void afterEndSubsegment(Subsegment subsegment) { } /** * onSetEntity is invoked immediately before the SegmentContext is updated with a new entity. * Both the new entity and the previous entity (or null if unset) are passed. * * @param previousEntity * @param newEntity */ default void onSetEntity(@Nullable Entity previousEntity, Entity newEntity) { } /** * onClearEntity is invoked just before the SegmentContext is cleared. * * @param previousEntity */ default void onClearEntity(Entity previousEntity) { } }
3,829
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/entities/AWSLogReference.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 com.fasterxml.jackson.annotation.JsonInclude; import java.util.Objects; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents a link between a trace segment and supporting CloudWatch logs. * */ @JsonInclude(JsonInclude.Include.NON_NULL) public class AWSLogReference { @Nullable private String logGroup; @Nullable private String arn; /** * Returns the log group name associated with the segment. */ @Nullable public String getLogGroup() { return logGroup; } /** * Set the log group for this reference. */ public void setLogGroup(final String logGroup) { this.logGroup = logGroup; } /** * Returns the ARN of the log group associated with this reference, or null if not provided by the AWS Runtime. */ @Nullable public String getArn() { return arn; } /** * Set the ARN for this reference. */ public void setArn(final String arn) { this.arn = arn; } /** * Compares ARN and log group between references to determine equality. * @return */ @Override public boolean equals(@Nullable Object o) { if (!(o instanceof AWSLogReference)) { return false; } AWSLogReference reference = (AWSLogReference) o; return (Objects.equals(getArn(), reference.getArn()) && Objects.equals(getLogGroup(), reference.getLogGroup())); } /** * Generates unique hash for each LogReference object. Used to check equality in Sets. */ @Override public int hashCode() { String arn = this.arn; String logGroup = this.logGroup; if (arn != null) { return arn.hashCode(); } else if (logGroup != null) { return logGroup.hashCode(); } else { return "".hashCode(); } } }
3,830
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/entities/NoOpReentrantLock.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 java.util.Collection; import java.util.Collections; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import org.checkerframework.checker.nullness.qual.Nullable; /** * A {@link ReentrantLock} that does nothing. */ class NoOpReentrantLock extends ReentrantLock { static ReentrantLock get() { return INSTANCE; } private static final NoOpReentrantLock INSTANCE = new NoOpReentrantLock(); @Override public void lock() { } @Override public void lockInterruptibly() throws InterruptedException { } @Override public boolean tryLock() { return true; } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return true; } @Override public void unlock() { } @Override public int getHoldCount() { return 0; } @Override public boolean isHeldByCurrentThread() { return false; } @Override public boolean isLocked() { return false; } // Seems to be wrongly annotated by checker framework, likely since no one is crazy enough to implement a no-op lock like this @SuppressWarnings("nullness") @Override @Nullable protected Thread getOwner() { return null; } @Override protected Collection<Thread> getQueuedThreads() { return Collections.emptyList(); } @Override public boolean hasWaiters(Condition condition) { return false; } @Override public int getWaitQueueLength(Condition condition) { return 0; } @Override protected Collection<Thread> getWaitingThreads(Condition condition) { return Collections.emptyList(); } }
3,831
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/entities/Segment.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 com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.exceptions.AlreadyEmittedException; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Map; public interface Segment extends Entity { static Segment noOp(TraceID traceId, AWSXRayRecorder recorder) { return new NoOpSegment(traceId, recorder); } /** * Ends the segment. Sets the end time to the current time. Sets inProgress to false. * * @return true if 1) the reference count is less than or equal to zero and 2) sampled is true */ boolean end(); /** * Returns {@code} if this {@link Segment} is recording events and will be emitted. Any operations on a {@link Segment} * which is not recording are effectively no-op. */ @JsonIgnore boolean isRecording(); /** * @param sampled * the sampled to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void setSampled(boolean sampled); /** * @return the resourceArn */ String getResourceArn(); /** * @param resourceArn * the resourceArn to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void setResourceArn(String resourceArn); /** * @return the user */ String getUser(); /** * @param user * the user to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void setUser(String user); /** * @return the origin */ String getOrigin(); /** * @param origin * the origin to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void setOrigin(String origin); /** * @return the service */ Map<String, Object> getService(); /** * @param service * the service to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void setService(Map<String, Object> service); /** * @return the annotations */ @Override Map<String, Object> getAnnotations(); /** * Puts information about this service. * * @param key * the key under which the service information is stored * @param object * the service information * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putService(String key, Object object); /** * Puts information about this service. * * @param all * the service information to set. * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putAllService(Map<String, Object> all); void setRuleName(String name); @Override Segment getParentSegment(); @Override void close(); }
3,832
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/entities/Namespace.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; public enum Namespace { REMOTE("remote"), AWS("aws"); private final String value; Namespace(String value) { this.value = value; } @Override public String toString() { return value; } }
3,833
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/entities/Cause.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 java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.checkerframework.checker.nullness.qual.Nullable; /** * A representation of what issues caused this (sub)segment to include a failure / error. Can include exceptions or references to * other exceptions. * */ public class Cause { private static final Log logger = LogFactory.getLog(Cause.class); @Nullable private String workingDirectory; @Nullable private String id; @Nullable private String message; @Nullable private Collection<String> paths; private final List<ThrowableDescription> exceptions; public Cause() { this(new ArrayList<>(), new ArrayList<>()); } Cause(List<String> paths, List<ThrowableDescription> exceptions) { this.paths = paths; this.exceptions = exceptions; } /** * @return the workingDirectory */ @Nullable public String getWorkingDirectory() { return workingDirectory; } /** * @param workingDirectory the workingDirectory to set */ public void setWorkingDirectory(@Nullable String workingDirectory) { this.workingDirectory = workingDirectory; } /** * @return the id */ @Nullable public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the message */ @Nullable public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } /** * @return the paths */ @Nullable public Collection<String> getPaths() { return paths; } /** * @param paths the paths to set */ public void setPaths(Collection<String> paths) { this.paths = paths; } /** * @return the exceptions */ public List<ThrowableDescription> getExceptions() { return exceptions; } public void addException(ThrowableDescription descriptor) { if (exceptions.isEmpty()) { addWorkingDirectoryAndPaths(); } exceptions.add(descriptor); } public void addExceptions(List<ThrowableDescription> descriptors) { if (exceptions.isEmpty()) { addWorkingDirectoryAndPaths(); } exceptions.addAll(descriptors); } private void addWorkingDirectoryAndPaths() { try { setWorkingDirectory(System.getProperty("user.dir")); } catch (SecurityException se) { logger.warn("Unable to set working directory.", se); } } }
3,834
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/entities/SearchPattern.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.checkerframework.checker.nullness.qual.Nullable; /** * @deprecated For internal use only. */ @SuppressWarnings("checkstyle:HideUtilityClassConstructor") @Deprecated public class SearchPattern { /** * Performs a case-insensitive wildcard match against two strings. This method works with pseduo-regex chars; specifically ? * and * are supported. * <ul> * <li>An asterisk (*) represents any combination of characters</li> * <li>A question mark (?) represents any single character</li> * </ul> * * @param pattern * the regex-like pattern to be compared against * @param text * the string to compare against the pattern * @return whether the text matches the pattern */ public static boolean wildcardMatch(@Nullable String pattern, @Nullable String text) { return wildcardMatch(pattern, text, true); } public static boolean wildcardMatch(@Nullable String pattern, @Nullable String text, boolean caseInsensitive) { if (pattern == null || text == null) { return false; } int patternLength = pattern.length(); int textLength = text.length(); if (patternLength == 0) { return textLength == 0; } // Check the special case of a single * pattern, as it's common if (isWildcardGlob(pattern)) { return true; } if (caseInsensitive) { pattern = pattern.toLowerCase(); text = text.toLowerCase(); } // Infix globs are relatively rare, and the below search is expensive especially when // Balsa is used a lot. Check for infix globs and, in their absence, do the simple thing int indexOfGlob = pattern.indexOf('*'); if (indexOfGlob == -1 || indexOfGlob == patternLength - 1) { return simpleWildcardMatch(pattern, text); } /* * The res[i] is used to record if there is a match * between the first i chars in text and the first j chars in pattern. * So will return res[textLength+1] in the end * Loop from the beginning of the pattern * case not '*': if text[i]==pattern[j] or pattern[j] is '?', and res[i] is true, * set res[i+1] to true, otherwise false * case '*': since '*' can match any globing, as long as there is a true in res before i * all the res[i+1], res[i+2],...,res[textLength] could be true */ boolean[] res = new boolean[textLength + 1]; res[0] = true; for (int j = 0; j < patternLength; j++) { char p = pattern.charAt(j); if (p != '*') { for (int i = textLength - 1; i >= 0; i--) { char t = text.charAt(i); res[i + 1] = res[i] && (p == '?' || (p == t)); } } else { int i = 0; while (i <= textLength && !res[i]) { i++; } for (; i <= textLength; i++) { res[i] = true; } } res[0] = res[0] && p == '*'; } return res[textLength]; } private static boolean simpleWildcardMatch(String pattern, String text) { int j = 0; int patternLength = pattern.length(); int textLength = text.length(); for (int i = 0; i < patternLength; i++) { char p = pattern.charAt(i); if (p == '*') { // Presumption for this method is that globs only occur at end return true; } else if (p == '?') { if (j == textLength) { return false; // No character to match } j++; } else { if (j >= textLength) { return false; } char t = text.charAt(j); if (p != t) { return false; } j++; } } // Ate up all the pattern and didn't end at a glob, so a match will have consumed all // the text return j == textLength; } /** * indicates whether the passed pattern is a single wildcard glob * (i.e., "*") */ private static boolean isWildcardGlob(String pattern) { return pattern.length() == 1 && pattern.charAt(0) == '*'; } }
3,835
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/entities/TraceHeader.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 com.amazonaws.xray.internal.RecyclableBuffers; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.checkerframework.checker.nullness.qual.Nullable; public class TraceHeader { public static final String HEADER_KEY = "X-Amzn-Trace-Id"; private static final String DELIMITER = ";"; private static final char EQUALS = '='; private static final String ROOT_PREFIX = "Root="; private static final String PARENT_PREFIX = "Parent="; private static final String SAMPLED_PREFIX = "Sampled="; private static final String SELF_PREFIX = "Self="; private static final String MALFORMED_ERROR_MESSAGE = "Malformed TraceHeader String input."; private static final Log logger = LogFactory.getLog(TraceHeader.class); public enum SampleDecision { SAMPLED("Sampled=1"), NOT_SAMPLED("Sampled=0"), UNKNOWN(""), REQUESTED("Sampled=?"); private final String value; SampleDecision(String value) { this.value = value; } @Override public String toString() { return value; } public static SampleDecision fromString(String text) { for (SampleDecision decision : SampleDecision.values()) { if (decision.toString().equalsIgnoreCase(text)) { return decision; } } return UNKNOWN; } } @Nullable private TraceID rootTraceId; @Nullable private String parentId; private SampleDecision sampled; private Map<String, String> additionalParams = new ConcurrentHashMap<>(); public TraceHeader() { this(null, null, SampleDecision.UNKNOWN); } public TraceHeader(@Nullable TraceID rootTraceId) { this(rootTraceId, null, SampleDecision.UNKNOWN); } public TraceHeader(@Nullable TraceID rootTraceId, @Nullable String parentId) { this(rootTraceId, parentId, SampleDecision.UNKNOWN); } public TraceHeader(@Nullable TraceID rootTraceId, @Nullable String parentId, SampleDecision sampled) { this.rootTraceId = rootTraceId; this.parentId = parentId; this.sampled = sampled; if (sampled == null) { throw new IllegalArgumentException("Sample decision can not be null."); } } public static TraceHeader fromEntity(Entity entity) { return new TraceHeader( entity.getTraceId(), entity.isSampled() ? entity.getId() : null, entity.isSampled() ? SampleDecision.SAMPLED : SampleDecision.NOT_SAMPLED); } /** * Creates a TraceHeader object from a String. Note that this will silently ignore any "Self=" trace ids injected from ALB. * * @param string * the string from an incoming trace-id header * @return the TraceHeader object */ public static TraceHeader fromString(@Nullable String string) { TraceHeader traceHeader = new TraceHeader(); if (string == null) { return traceHeader; } int pos = 0; while (pos < string.length()) { int delimiterIndex = string.indexOf(';', pos); final String part; if (delimiterIndex >= 0) { part = string.substring(pos, delimiterIndex); pos = delimiterIndex + 1; } else { // Last part. part = string.substring(pos); pos = string.length(); } String trimmedPart = part.trim(); int equalsIndex = trimmedPart.indexOf('='); if (equalsIndex < 0) { logger.error(MALFORMED_ERROR_MESSAGE); continue; } String value = trimmedPart.substring(equalsIndex + 1); if (trimmedPart.startsWith(ROOT_PREFIX)) { traceHeader.setRootTraceId(TraceID.fromString(value)); } else if (trimmedPart.startsWith(PARENT_PREFIX)) { traceHeader.setParentId(value); } else if (trimmedPart.startsWith(SAMPLED_PREFIX)) { traceHeader.setSampled(SampleDecision.fromString(trimmedPart)); } else if (!trimmedPart.startsWith(SELF_PREFIX)) { String key = trimmedPart.substring(0, equalsIndex); traceHeader.putAdditionalParam(key, value); } } return traceHeader; } /** * Serializes the TraceHeader object into a String. * * @return the String representation of this TraceHeader */ @Override public String toString() { StringBuilder buffer = RecyclableBuffers.stringBuilder(); if (rootTraceId != null) { buffer.append(ROOT_PREFIX).append(rootTraceId).append(DELIMITER); } if (StringValidator.isNotNullOrBlank(parentId)) { buffer.append(PARENT_PREFIX).append(parentId).append(DELIMITER); } buffer.append(sampled).append(DELIMITER); additionalParams.forEach((key, value) -> { buffer.append(key).append(EQUALS).append(value).append(DELIMITER); }); buffer.setLength(buffer.length() - DELIMITER.length()); return buffer.toString(); } /** * @return the rootTraceId */ @Nullable public TraceID getRootTraceId() { return rootTraceId; } /** * @param rootTraceId the rootTraceId to set */ public void setRootTraceId(TraceID rootTraceId) { this.rootTraceId = rootTraceId; } /** * @return the parentId */ @Nullable public String getParentId() { return parentId; } /** * @param parentId the parentId to set */ public void setParentId(String parentId) { this.parentId = parentId; } /** * @return the sampled */ public SampleDecision getSampled() { return sampled; } /** * Sets the sample decision. * @param sampled * the non-null SampleDecision to set * * @throws IllegalArgumentException * if sampled is null */ public void setSampled(SampleDecision sampled) { if (sampled == null) { throw new IllegalArgumentException("Sample decision can not be null. Please use SampleDecision.UNKNOWN instead."); } this.sampled = sampled; } /** * @return the additionalParams */ public Map<String, String> getAdditionalParams() { return additionalParams; } /** * @param additionalParams the additionalParams to set */ public void setAdditionalParams(Map<String, String> additionalParams) { this.additionalParams = additionalParams; } /** * * Puts an additional parameter into the {@code additionalParam} map. * @param key * the key to put into * @param value * the value to put */ public void putAdditionalParam(String key, String value) { additionalParams.put(key, value); } }
3,836
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/entities/NoOpMap.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 java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; /** * An empty {@link Map} which does nothing, but unlike {@link Collections#emptyMap()} won't throw * {@link UnsupportedOperationException}. */ // We don't actually use the type parameters so nullness annotations would be ignored anyways so no need to annotate. @SuppressWarnings("all") class NoOpMap implements Map<Object, Object> { static <K, V> Map<K, V> get() { return (Map<K, V>) INSTANCE; } private static final NoOpMap INSTANCE = new NoOpMap(); @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean containsKey(Object key) { return false; } @Override public boolean containsValue(Object value) { return false; } @Override public Object get(Object key) { return null; } @Override public Object put(Object key, Object value) { return null; } @Override public Object remove(Object key) { return null; } @Override public void putAll(Map<? extends Object, ? extends Object> m) { } @Override public void clear() { } @Override public Collection<Object> values() { return NoOpList.get(); } @Override public Set<Object> keySet() { return NoOpSet.get(); } @Override public Set<Entry<Object, Object>> entrySet() { return NoOpSet.get(); } }
3,837
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/entities/EntityHeaderKeys.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; public final class EntityHeaderKeys { public static final class AWS { public static final String EXTENDED_REQUEST_ID_HEADER = "x-amz-id-2"; private AWS() { } } public static final class HTTP { public static final String CONTENT_LENGTH_HEADER = "Content-Length"; private HTTP() { } } private EntityHeaderKeys() { } }
3,838
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/entities/DummySubsegment.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 com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.internal.SamplingStrategyOverride; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.ReentrantLock; import org.checkerframework.checker.nullness.qual.Nullable; /** * @deprecated Use {@link Subsegment#noOp(AWSXRayRecorder, boolean)}. */ @Deprecated public class DummySubsegment implements Subsegment { private Cause cause = new Cause(); private Map<String, Object> map = new ConcurrentHashMap<>(); private Map<String, Map<String, Object>> metadataMap = new ConcurrentHashMap<>(); private List<Subsegment> list = new ArrayList<>(); private Set<String> set = new HashSet<>(); private ReentrantLock lock = new ReentrantLock(); private AWSXRayRecorder creator; private TraceID traceId; private Segment parentSegment; @JsonIgnore private boolean isSampled; @JsonIgnore private boolean isRecording; @JsonIgnore private SamplingStrategyOverride samplingStrategyOverride; public DummySubsegment(AWSXRayRecorder creator) { this(creator, TraceID.create(creator)); } public DummySubsegment(AWSXRayRecorder creator, TraceID traceId) { this(creator, traceId, SamplingStrategyOverride.DISABLED); } @Deprecated public DummySubsegment(AWSXRayRecorder creator, TraceID traceId, SamplingStrategyOverride samplingStrategyOverride) { this.creator = creator; this.traceId = traceId; this.parentSegment = new DummySegment(creator); this.isSampled = samplingStrategyOverride == SamplingStrategyOverride.DISABLED ? parentSegment.isSampled() : false; this.isRecording = isSampled; this.samplingStrategyOverride = samplingStrategyOverride; } @Override public String getName() { return ""; } @Override public String getId() { return ""; } @Override public void setId(String id) { } @Override public double getStartTime() { return 0; } @Override public void setStartTime(double startTime) { } @Override public double getEndTime() { return 0; } @Override public void setEndTime(double endTime) { } @Override public boolean isFault() { return false; } @Override public void setFault(boolean fault) { } @Override public boolean isError() { return false; } @Override public void setError(boolean error) { } @Override public String getNamespace() { return ""; } @Override public void setNamespace(String namespace) { } @Override public Cause getCause() { return cause; } @Override public Map<String, Object> getHttp() { return map; } @Override public void setHttp(Map<String, Object> http) { } @Override public Map<String, Object> getAws() { return map; } @Override public void setAws(Map<String, Object> aws) { } @Override public Map<String, Object> getSql() { return map; } @Override public void setSql(Map<String, Object> sql) { } @Override public Map<String, Map<String, Object>> getMetadata() { return metadataMap; } @Override public void setMetadata(Map<String, Map<String, Object>> metadata) { } @Override public void setAnnotations(Map<String, Object> annotations) { } @Override public Entity getParent() { return this; } @Override public void setParent(Entity parent) { } @Override public boolean isThrottle() { return false; } @Override public void setThrottle(boolean throttle) { } @Override public boolean isInProgress() { return false; } @Override public void setInProgress(boolean inProgress) { } @Override public TraceID getTraceId() { return traceId; } @Override public void setTraceId(TraceID traceId) { } /** * @return the creator */ @Override public AWSXRayRecorder getCreator() { return creator; } /** * @param creator the creator to set */ @Override public void setCreator(AWSXRayRecorder creator) { this.creator = creator; } @Override public String getParentId() { return ""; } @Override public void setParentId(@Nullable String parentId) { } @Override public List<Subsegment> getSubsegments() { return list; } @Override public List<Subsegment> getSubsegmentsCopy() { return new ArrayList<>(list); } @Override public void addSubsegment(Subsegment subsegment) { } @Override public void addException(Throwable exception) { } @Override public void putHttp(String key, Object value) { } @Override public void putAllHttp(Map<String, Object> all) { } @Override public void putAws(String key, Object value) { } @Override public void putAllAws(Map<String, Object> all) { } @Override public void putSql(String key, Object value) { } @Override public void putAllSql(Map<String, Object> all) { } @Override public void putAnnotation(String key, String value) { } @Override public void putAnnotation(String key, Number value) { } @Override public void putAnnotation(String key, Boolean value) { } @Override public void putMetadata(String key, Object object) { } @Override public void putMetadata(String namespace, String key, Object object) { } @Override public boolean isEmitted() { return false; } @Override public void setEmitted(boolean emitted) { } @Override public boolean compareAndSetEmitted(boolean current, boolean next) { return false; } @Override public String serialize() { return ""; } @Override public String prettySerialize() { return ""; } @Override public boolean end() { return false; } @Override public Map<String, Object> getAnnotations() { return map; } @Override public Segment getParentSegment() { return parentSegment; } @Override public void close() { } @Override public void setParentSegment(Segment parentSegment) { } @Override public Set<String> getPrecursorIds() { return set; } @Override public void setPrecursorIds(Set<String> precursorIds) { } @Override public void addPrecursorId(String precursorId) { } @Override public boolean shouldPropagate() { return false; } @Override public String streamSerialize() { return ""; } @Override public String prettyStreamSerialize() { return ""; } @Override public ReentrantLock getSubsegmentsLock() { return lock; } @Override public void setSubsegmentsLock(ReentrantLock subsegmentsLock) { } @Override public int getReferenceCount() { return 0; } @Override public LongAdder getTotalSize() { return parentSegment.getTotalSize(); } @Override public void incrementReferenceCount() { } @Override public boolean decrementReferenceCount() { return false; } @Override public void removeSubsegment(Subsegment subsegment) { } @Override @JsonIgnore public boolean isSampled() { return isSampled; } @Override @JsonIgnore public boolean isRecording() { return isRecording; } @Override @JsonIgnore public void setSampledFalse() { isSampled = false; isRecording = false; } @Override @Deprecated public SamplingStrategyOverride getSamplingStrategyOverride() { return samplingStrategyOverride; } }
3,839
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/entities/StringValidator.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.checkerframework.checker.nullness.qual.EnsuresNonNullIf; import org.checkerframework.checker.nullness.qual.Nullable; /** * @deprecated For internal use only. */ @SuppressWarnings("checkstyle:HideUtilityClassConstructor") @Deprecated public class StringValidator { @EnsuresNonNullIf(expression = "#1", result = true) public static boolean isNotNullOrBlank(@Nullable String string) { return string != null && !string.trim().isEmpty(); } @EnsuresNonNullIf(expression = "#1", result = false) public static boolean isNullOrBlank(@Nullable String string) { return string == null || string.trim().isEmpty(); } public static void throwIfNullOrBlank(@Nullable String string, String validationErrorMessage) { if (string == null || string.trim().isEmpty()) { throw new RuntimeException(validationErrorMessage); } } }
3,840
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/entities/DummySegment.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 com.amazonaws.xray.AWSXRayRecorder; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.ReentrantLock; import org.checkerframework.checker.nullness.qual.Nullable; /** * @deprecated Use {@link Segment#noOp(TraceID, AWSXRayRecorder)}. */ @Deprecated public class DummySegment implements Segment { private Cause cause = new Cause(); private Map<String, Object> map = new ConcurrentHashMap<>(); private Map<String, Map<String, Object>> metadataMap = new ConcurrentHashMap<>(); private List<Subsegment> list = new ArrayList<>(); private LongAdder longAdder = new LongAdder(); private ReentrantLock lock = new ReentrantLock(); private String name = ""; private String origin = ""; private double startTime; private double endTime; @JsonInclude(JsonInclude.Include.NON_DEFAULT) private boolean fault; @JsonInclude(JsonInclude.Include.NON_DEFAULT) private boolean error; @JsonInclude(JsonInclude.Include.NON_DEFAULT) private boolean throttle; private AWSXRayRecorder creator; private TraceID traceId; public DummySegment(AWSXRayRecorder creator, String name, TraceID traceId) { this(creator, traceId); this.name = name; } public DummySegment(AWSXRayRecorder creator) { this(creator, TraceID.create(creator)); } public DummySegment(AWSXRayRecorder creator, TraceID traceId) { this.startTime = System.currentTimeMillis() / 1000.0d; this.creator = creator; this.traceId = traceId; } @Override public String getName() { return name; } @Override public String getId() { return ""; } @Override public void setId(String id) { } @Override public double getStartTime() { return startTime; } @Override public void setStartTime(double startTime) { this.startTime = startTime; } @Override public double getEndTime() { return endTime; } @Override public void setEndTime(double endTime) { this.endTime = endTime; } @Override public boolean isFault() { return fault; } @Override public void setFault(boolean fault) { this.fault = fault; } @Override public boolean isError() { return error; } @Override public void setError(boolean error) { this.error = error; } @Override public String getNamespace() { return ""; } @Override public void setNamespace(String namespace) { } @Override public Cause getCause() { return cause; } @Override public Map<String, Object> getHttp() { return map; } @Override public void setHttp(Map<String, Object> http) { } @Override public Map<String, Object> getAws() { return map; } @Override public void setAws(Map<String, Object> aws) { } @Override public Map<String, Object> getSql() { return map; } @Override public void setSql(Map<String, Object> sql) { } @Override public Map<String, Map<String, Object>> getMetadata() { return metadataMap; } @Override public void setMetadata(Map<String, Map<String, Object>> metadata) { } @Override public void setAnnotations(Map<String, Object> annotations) { } @Override public Entity getParent() { return this; } @Override public void setParent(Entity parent) { } @Override public boolean isThrottle() { return throttle; } @Override public void setThrottle(boolean throttle) { this.throttle = throttle; } @Override public boolean isInProgress() { return false; } @Override public void setInProgress(boolean inProgress) { } @Override public TraceID getTraceId() { return traceId; } @Override public void setTraceId(TraceID traceId) { } /** * @return the creator */ @Override public AWSXRayRecorder getCreator() { return creator; } /** * @param creator the creator to set */ @Override public void setCreator(AWSXRayRecorder creator) { this.creator = creator; } @Override public String getParentId() { return ""; } @Override public void setParentId(@Nullable String parentId) { } @Override public List<Subsegment> getSubsegments() { return list; } @Override public List<Subsegment> getSubsegmentsCopy() { return new ArrayList<>(list); } @Override public void addSubsegment(Subsegment subsegment) { } @Override public void addException(Throwable exception) { } @Override public void putHttp(String key, Object value) { } @Override public void putAllHttp(Map<String, Object> all) { } @Override public void putAws(String key, Object value) { } @Override public void putAllAws(Map<String, Object> all) { } @Override public void putSql(String key, Object value) { } @Override public void putAllSql(Map<String, Object> all) { } @Override public void putAnnotation(String key, String value) { } @Override public void putAnnotation(String key, Number value) { } @Override public void putAnnotation(String key, Boolean value) { } @Override public void putMetadata(String key, Object object) { } @Override public void putMetadata(String namespace, String key, Object object) { } @Override public boolean isEmitted() { return false; } @Override public void setEmitted(boolean emitted) { } @Override public boolean compareAndSetEmitted(boolean current, boolean next) { return false; } @Override public String serialize() { return ""; } @Override public String prettySerialize() { return ""; } @Override public boolean end() { if (getEndTime() < Double.MIN_NORMAL) { setEndTime(System.currentTimeMillis() / 1000.0d); } return false; } @Override public boolean isRecording() { return false; } @Override public void putService(String key, Object object) { } @Override public boolean isSampled() { return false; } @Override public void setSampled(boolean sampled) { } @Override public int getReferenceCount() { return 0; } @Override public LongAdder getTotalSize() { return longAdder; } @Override public void incrementReferenceCount() { } @Override public boolean decrementReferenceCount() { return false; } @Override public String getResourceArn() { return ""; } @Override public void setResourceArn(String resourceArn) { } @Override public String getUser() { return ""; } @Override public void setUser(String user) { } @Override public String getOrigin() { return origin; } @Override public void setOrigin(String origin) { this.origin = origin; } @Override public Map<String, Object> getService() { return map; } @Override public Map<String, Object> getAnnotations() { return map; } @Override public Segment getParentSegment() { return this; } @Override public void close() { } @Override public ReentrantLock getSubsegmentsLock() { return lock; } @Override public void setSubsegmentsLock(ReentrantLock subsegmentsLock) { } @Override public void putAllService(Map<String, Object> all) { } @Override public void setService(Map<String, Object> service) { } @Override public void removeSubsegment(Subsegment subsegment) { } @Override public void setRuleName(String name) { } }
3,841
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/entities/NoOpList.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 java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; /** * An empty {@link Map} which does nothing, but unlike {@link Collections#emptyList()} won't throw * {@link UnsupportedOperationException}. */ // We don't actually use the type parameter so nullness annotations would be ignored anyways so no need to annotate. @SuppressWarnings("all") class NoOpList implements List<Object> { static <T> List<T> get() { return (List<T>) INSTANCE; } private static final NoOpList INSTANCE = new NoOpList(); private static final Object[] EMPTY_ARRAY = new Object[0]; @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(Object o) { return false; } @Override public Iterator<Object> iterator() { return Collections.emptyIterator(); } @Override public Object[] toArray() { return EMPTY_ARRAY; } @Override public <T> T[] toArray(T[] a) { return a; } @Override public boolean add(Object o) { return true; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<?> c) { return false; } @Override public boolean addAll(int index, Collection<?> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } @Override public Object get(int index) { return null; } @Override public Object set(int index, Object element) { return null; } @Override public void add(int index, Object element) { } @Override public Object remove(int index) { return null; } @Override public int indexOf(Object o) { return -1; } @Override public int lastIndexOf(Object o) { return -1; } @Override public ListIterator<Object> listIterator() { return Collections.emptyListIterator(); } @Override public ListIterator<Object> listIterator(int index) { return Collections.emptyListIterator(); } @Override public List<Object> subList(int fromIndex, int toIndex) { return NoOpList.get(); } }
3,842
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/entities/NoOpSet.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 java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; /** * An empty {@link Set} which does nothing, but unlike {@link Collections#emptySet()} won't throw * {@link UnsupportedOperationException}. */ // We don't actually use the type parameter so nullness annotations would be ignored anyways so no need to annotate. @SuppressWarnings("all") class NoOpSet implements Set<Object> { static <T> Set<T> get() { return (Set<T>) INSTANCE; } private static final NoOpSet INSTANCE = new NoOpSet(); private static final Object[] EMPTY_ARRAY = new Object[0]; @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(Object o) { return false; } @Override public Iterator<Object> iterator() { return Collections.emptyIterator(); } @Override public Object[] toArray() { return EMPTY_ARRAY; } @Override public <T> T[] toArray(T[] a) { return a; } @Override public boolean add(Object t) { return true; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<? extends Object> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public void clear() { } }
3,843
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/entities/EntityDataKeys.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; public final class EntityDataKeys { public static final class AWS { public static final String ACCOUNT_ID_SUBSEGMENT_KEY = "account_id"; public static final String EXTENDED_REQUEST_ID_KEY = "id_2"; public static final String OPERATION_KEY = "operation"; public static final String REGION_KEY = "region"; public static final String REQUEST_ID_KEY = "request_id"; public static final String RETRIES_KEY = "retries"; private AWS() { } } public static final class HTTP { public static final String CONTENT_LENGTH_KEY = "content_length"; public static final String RESPONSE_KEY = "response"; public static final String STATUS_CODE_KEY = "status"; private HTTP() { } } private EntityDataKeys() { } }
3,844
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/entities/NoOpSegment.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 com.amazonaws.xray.AWSXRayRecorder; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.ReentrantLock; import org.checkerframework.checker.nullness.qual.Nullable; class NoOpSegment implements Segment { private final TraceID traceId; private final AWSXRayRecorder creator; NoOpSegment(TraceID traceId, AWSXRayRecorder creator) { this.traceId = traceId; this.creator = creator; } @Override public boolean end() { return false; } @Override public boolean isRecording() { return false; } @Override public boolean isSampled() { return false; } @Override public void setSampled(boolean sampled) { } @Override public String getResourceArn() { return ""; } @Override public void setResourceArn(String resourceArn) { } @Override public String getUser() { return ""; } @Override public void setUser(String user) { } @Override public String getOrigin() { return ""; } @Override public void setOrigin(String origin) { } @Override public Map<String, Object> getService() { return NoOpMap.get(); } @Override public void setService(Map<String, Object> service) { } @Override public String getName() { return ""; } @Override public String getId() { return ""; } @Override public void setId(String id) { } @Override public double getStartTime() { return 0; } @Override public void setStartTime(double startTime) { } @Override public double getEndTime() { return 0; } @Override public void setEndTime(double endTime) { } @Override public boolean isFault() { return false; } @Override public void setFault(boolean fault) { } @Override public boolean isError() { return false; } @Override public void setError(boolean error) { } @Override public String getNamespace() { return ""; } @Override public void setNamespace(String namespace) { } @Override public ReentrantLock getSubsegmentsLock() { return NoOpReentrantLock.get(); } @Override public void setSubsegmentsLock(ReentrantLock subsegmentsLock) { } @Override public Cause getCause() { // It should not be common for this to be called on an unsampled segment so we lazily initialize here. return new Cause(NoOpList.get(), NoOpList.get()); } @Override public Map<String, Object> getHttp() { return NoOpMap.get(); } @Override public void setHttp(Map<String, Object> http) { } @Override public Map<String, Object> getAws() { return NoOpMap.get(); } @Override public void setAws(Map<String, Object> aws) { } @Override public Map<String, Object> getSql() { return NoOpMap.get(); } @Override public void setSql(Map<String, Object> sql) { } @Override public Map<String, Map<String, Object>> getMetadata() { return NoOpMap.get(); } @Override public void setMetadata(Map<String, Map<String, Object>> metadata) { } @Override public Map<String, Object> getAnnotations() { return NoOpMap.get(); } @Override public void setAnnotations(Map<String, Object> annotations) { } @Override public Entity getParent() { return this; } @Override public void setParent(Entity parent) { } @Override public boolean isThrottle() { return false; } @Override public void setThrottle(boolean throttle) { } @Override public boolean isInProgress() { return false; } @Override public void setInProgress(boolean inProgress) { } @Override public TraceID getTraceId() { return traceId; } @Override public void setTraceId(TraceID traceId) { } @Override public @Nullable String getParentId() { return null; } @Override public void setParentId(@Nullable String parentId) { } @Override public AWSXRayRecorder getCreator() { return creator; } @Override public void setCreator(AWSXRayRecorder creator) { } @Override public void putService(String key, Object object) { } @Override public void putAllService(Map<String, Object> all) { } @Override public void setRuleName(String name) { } @Override public Segment getParentSegment() { return this; } @Override public List<Subsegment> getSubsegments() { return NoOpList.get(); } @Override public List<Subsegment> getSubsegmentsCopy() { return NoOpList.get(); } @Override public void addSubsegment(Subsegment subsegment) { } @Override public void addException(Throwable exception) { } @Override public int getReferenceCount() { return 0; } @Override public LongAdder getTotalSize() { // It should not be common for this to be called on an unsampled segment so we lazily initialize here. return new LongAdder(); } @Override public void incrementReferenceCount() { } @Override public boolean decrementReferenceCount() { return false; } @Override public void putHttp(String key, Object value) { } @Override public void putAllHttp(Map<String, Object> all) { } @Override public void putAws(String key, Object value) { } @Override public void putAllAws(Map<String, Object> all) { } @Override public void putSql(String key, Object value) { } @Override public void putAllSql(Map<String, Object> all) { } @Override public void putAnnotation(String key, String value) { } @Override public void putAnnotation(String key, Number value) { } @Override public void putAnnotation(String key, Boolean value) { } @Override public void putMetadata(String key, Object object) { } @Override public void putMetadata(String namespace, String key, Object object) { } @Override public void removeSubsegment(Subsegment subsegment) { } @Override public boolean isEmitted() { return false; } @Override public void setEmitted(boolean emitted) { } @Override public boolean compareAndSetEmitted(boolean current, boolean next) { return false; } @Override public String serialize() { return ""; } @Override public String prettySerialize() { return ""; } @Override public void close() { } }
3,845
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/entities/ThrowableDescription.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 com.fasterxml.jackson.annotation.JsonIgnore; import org.checkerframework.checker.nullness.qual.Nullable; public class ThrowableDescription { @Nullable private String id; @Nullable private String message; @Nullable private String type; private boolean remote; @Nullable private StackTraceElement[] stack; private int truncated; private int skipped; @Nullable private String cause; @JsonIgnore @Nullable private Throwable throwable; // TODO(anuraaga): Investigate why stack is not being treated as nullable @SuppressWarnings("nullness:initialization.fields.uninitialized") public ThrowableDescription() { } // TODO(anuraaga): Investigate why stack is not being treated as nullable @SuppressWarnings("nullness:initialization.fields.uninitialized") public ThrowableDescription(Throwable throwable) { this.throwable = throwable; } /** * @return the id */ @Nullable public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the message */ @Nullable public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(@Nullable String message) { this.message = message; } /** * @return the type */ @Nullable public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the remote */ public boolean isRemote() { return remote; } /** * @param remote the remote to set */ public void setRemote(boolean remote) { this.remote = remote; } /** * @return the stack */ @Nullable public StackTraceElement[] getStack() { return stack; } /** * @param stack the stack to set */ public void setStack(@Nullable StackTraceElement[] stack) { this.stack = stack; } /** * @return the truncated */ public int getTruncated() { return truncated; } /** * @param truncated the truncated to set */ public void setTruncated(int truncated) { this.truncated = truncated; } /** * @return the skipped */ public int getSkipped() { return skipped; } /** * @param skipped the skipped to set */ public void setSkipped(int skipped) { this.skipped = skipped; } /** * @return the cause */ @Nullable public String getCause() { return cause; } /** * @param cause the cause to set */ public void setCause(@Nullable String cause) { this.cause = cause; } /** * @return the throwable */ @Nullable public Throwable getThrowable() { return throwable; } /** * @param throwable the throwable to set */ public void setThrowable(Throwable throwable) { this.throwable = throwable; } }
3,846
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/entities/FacadeSegment.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 com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.entities.TraceHeader.SampleDecision; import java.util.Map; import java.util.concurrent.atomic.LongAdder; import org.checkerframework.checker.nullness.qual.Nullable; public class FacadeSegment extends EntityImpl implements Segment { private static final String MUTATION_UNSUPPORTED_MESSAGE = "FacadeSegments cannot be mutated."; private static final String INFORMATION_UNAVAILABLE_MESSAGE = "This information is unavailable."; protected String resourceArn; protected String user; protected String origin; protected Map<String, Object> service; private final boolean sampled; // TODO(anuraaga): Refactor the entity relationship. There isn't a great reason to use a type hierarchy for data classes and // it makes the code to hard to reason about e.g., nullness. @SuppressWarnings("nullness") public FacadeSegment( AWSXRayRecorder recorder, @Nullable TraceID traceId, @Nullable String id, @Nullable SampleDecision sampleDecision) { super(recorder, "facade"); if (traceId != null) { super.setTraceId(traceId); } if (id != null) { super.setId(id); } this.sampled = (SampleDecision.SAMPLED == sampleDecision); } /** * Unsupported as FacadeSegments cannot be mutated. * * @throws UnsupportedOperationException in all cases */ @Override public void close() { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * * @throws UnsupportedOperationException in all cases */ @Override public boolean end() { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } @Override public boolean isRecording() { return sampled; } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putService(String key, Object object) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * @return a LongAdder with a value of 0, as the total size of a FacadeSegment is not tracked. */ @Override public LongAdder getTotalSize() { return totalSize; } @Override public boolean isSampled() { return sampled; } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setSampled(boolean sampled) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments are not aware of their resource ARN. * @throws UnsupportedOperationException in all cases */ @Override public String getResourceArn() { throw new UnsupportedOperationException(INFORMATION_UNAVAILABLE_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setResourceArn(String resourceArn) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments are not aware of their user. * @throws UnsupportedOperationException in all cases */ @Override public String getUser() { throw new UnsupportedOperationException(INFORMATION_UNAVAILABLE_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setUser(String user) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments are not aware of their origin. * @throws UnsupportedOperationException in all cases */ @Override public String getOrigin() { throw new UnsupportedOperationException(INFORMATION_UNAVAILABLE_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setOrigin(String origin) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments are not aware of their service. * @throws UnsupportedOperationException in all cases */ @Override public Map<String, Object> getService() { throw new UnsupportedOperationException(INFORMATION_UNAVAILABLE_MESSAGE); } @Override public Segment getParentSegment() { return this; } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setId(String id) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setStartTime(double startTime) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setEndTime(double endTime) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setFault(boolean fault) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setError(boolean error) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setNamespace(String namespace) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setHttp(Map<String, Object> http) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setAws(Map<String, Object> aws) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setSql(Map<String, Object> sql) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setMetadata(Map<String, Map<String, Object>> metadata) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setAnnotations(Map<String, Object> annotations) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setParent(Entity parent) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setCreator(AWSXRayRecorder creator) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setThrottle(boolean throttle) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setInProgress(boolean inProgress) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setTraceId(@Nullable TraceID traceId) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setParentId(@Nullable String parentId) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void addException(Throwable exception) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putHttp(String key, Object value) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putAllHttp(Map<String, Object> all) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putAws(String key, Object value) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putAllAws(Map<String, Object> all) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putSql(String key, Object value) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putAllSql(Map<String, Object> all) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putAnnotation(String key, String value) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putAnnotation(String key, Number value) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putAnnotation(String key, Boolean value) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putMetadata(String key, Object object) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putMetadata(String namespace, String key, Object object) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void putAllService(Map<String, Object> all) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } /** * Unsupported as FacadeSegments cannot be mutated. * @throws UnsupportedOperationException in all cases */ @Override public void setService(Map<String, Object> service) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } @Override public void setRuleName(String name) { throw new UnsupportedOperationException(MUTATION_UNSUPPORTED_MESSAGE); } }
3,847
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/entities/NoOpSubSegment.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 com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.internal.SamplingStrategyOverride; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.ReentrantLock; import org.checkerframework.checker.nullness.qual.Nullable; class NoOpSubSegment implements Subsegment { private final Segment parentSegment; private final AWSXRayRecorder creator; private final boolean shouldPropagate; private volatile Entity parent; @JsonIgnore private boolean isSampled; @JsonIgnore private boolean isRecording; @JsonIgnore private String name; @JsonIgnore @Nullable private String namespace; @JsonIgnore private SamplingStrategyOverride samplingStrategyOverride; NoOpSubSegment(Segment parentSegment, AWSXRayRecorder creator, String name) { this(parentSegment, creator); this.name = name; } NoOpSubSegment(Segment parentSegment, AWSXRayRecorder creator) { this(parentSegment, creator, true); } NoOpSubSegment(Segment parentSegment, AWSXRayRecorder creator, boolean shouldPropagate) { this(parentSegment, creator, shouldPropagate, SamplingStrategyOverride.DISABLED); } @Deprecated NoOpSubSegment(Segment parentSegment, AWSXRayRecorder creator, SamplingStrategyOverride samplingStrategyOverride) { this(parentSegment, creator, true, samplingStrategyOverride); } @Deprecated NoOpSubSegment( Segment parentSegment, AWSXRayRecorder creator, boolean shouldPropagate, SamplingStrategyOverride samplingStrategyOverride) { this.parentSegment = parentSegment; this.creator = creator; this.shouldPropagate = shouldPropagate; parent = parentSegment; name = ""; namespace = ""; this.isSampled = false; this.isRecording = false; this.samplingStrategyOverride = samplingStrategyOverride; } @Override public boolean end() { return false; } @Override public String getName() { return name; } @Override public String getId() { return ""; } @Override public void setId(String id) { } @Override public double getStartTime() { return 0; } @Override public void setStartTime(double startTime) { } @Override public double getEndTime() { return 0; } @Override public void setEndTime(double endTime) { } @Override public boolean isFault() { return false; } @Override public void setFault(boolean fault) { } @Override public boolean isError() { return false; } @Override public void setError(boolean error) { } @Override @Nullable public String getNamespace() { return namespace; } @Override public void setNamespace(String namespace) { this.namespace = namespace; } @Override public ReentrantLock getSubsegmentsLock() { return NoOpReentrantLock.get(); } @Override public void setSubsegmentsLock(ReentrantLock subsegmentsLock) { } @Override public Cause getCause() { // It should not be common for this to be called on an unsampled segment so we lazily initialize here. return new Cause(NoOpList.get(), NoOpList.get()); } @Override public Map<String, Object> getHttp() { return NoOpMap.get(); } @Override public void setHttp(Map<String, Object> http) { } @Override public Map<String, Object> getAws() { return NoOpMap.get(); } @Override public void setAws(Map<String, Object> aws) { } @Override public Map<String, Object> getSql() { return NoOpMap.get(); } @Override public void setSql(Map<String, Object> sql) { } @Override public Map<String, Map<String, Object>> getMetadata() { return NoOpMap.get(); } @Override public void setMetadata(Map<String, Map<String, Object>> metadata) { } @Override public Map<String, Object> getAnnotations() { return NoOpMap.get(); } @Override public void setAnnotations(Map<String, Object> annotations) { } @Override public Entity getParent() { return parent; } @Override public void setParent(Entity parent) { this.parent = parent; } @Override public boolean isThrottle() { return false; } @Override public void setThrottle(boolean throttle) { } @Override public boolean isInProgress() { return false; } @Override public void setInProgress(boolean inProgress) { } @Override public TraceID getTraceId() { return parentSegment.getTraceId(); } @Override public void setTraceId(TraceID traceId) { } @Override public @Nullable String getParentId() { return null; } @Override public void setParentId(@Nullable String parentId) { } @Override public AWSXRayRecorder getCreator() { return creator; } @Override public void setCreator(AWSXRayRecorder creator) { } @Override public Segment getParentSegment() { return parentSegment; } @Override public List<Subsegment> getSubsegments() { return NoOpList.get(); } @Override public List<Subsegment> getSubsegmentsCopy() { return NoOpList.get(); } @Override public void addSubsegment(Subsegment subsegment) { } @Override public void addException(Throwable exception) { } @Override public int getReferenceCount() { return 0; } @Override public LongAdder getTotalSize() { // It should not be common for this to be called on an unsampled segment so we lazily initialize here. return new LongAdder(); } @Override public void incrementReferenceCount() { } @Override public boolean decrementReferenceCount() { return false; } @Override public void putHttp(String key, Object value) { } @Override public void putAllHttp(Map<String, Object> all) { } @Override public void putAws(String key, Object value) { } @Override public void putAllAws(Map<String, Object> all) { } @Override public void putSql(String key, Object value) { } @Override public void putAllSql(Map<String, Object> all) { } @Override public void putAnnotation(String key, String value) { } @Override public void putAnnotation(String key, Number value) { } @Override public void putAnnotation(String key, Boolean value) { } @Override public void putMetadata(String key, Object object) { } @Override public void putMetadata(String namespace, String key, Object object) { } @Override public void removeSubsegment(Subsegment subsegment) { } @Override public boolean isEmitted() { return false; } @Override public void setEmitted(boolean emitted) { } @Override public boolean compareAndSetEmitted(boolean current, boolean next) { return false; } @Override public String serialize() { return ""; } @Override public String prettySerialize() { return ""; } @Override public void setParentSegment(Segment parentSegment) { } @Override public Set<String> getPrecursorIds() { return NoOpSet.get(); } @Override public void setPrecursorIds(Set<String> precursorIds) { } @Override public void addPrecursorId(String precursorId) { } @Override public boolean shouldPropagate() { return this.shouldPropagate; } @Override public String streamSerialize() { return ""; } @Override public String prettyStreamSerialize() { return ""; } @Override public void close() { } @Override @JsonIgnore public boolean isSampled() { return isSampled; } @Override @JsonIgnore public boolean isRecording() { return isRecording; } @Override @JsonIgnore public void setSampledFalse() { isSampled = false; isRecording = false; } @Override @Deprecated public SamplingStrategyOverride getSamplingStrategyOverride() { return samplingStrategyOverride; } }
3,848
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/entities/Entity.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 com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.exceptions.AlreadyEmittedException; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.ReentrantLock; import org.checkerframework.checker.nullness.qual.Nullable; public interface Entity extends AutoCloseable { /** * @deprecated Use the {@link com.amazonaws.xray.internal.IdGenerator ID generator} configured on this * entity's creator instead */ @Deprecated static String generateId() { return AWSXRay.getGlobalRecorder().getIdGenerator().newEntityId(); } /** * Immediately runs the provided {@link Runnable} with this {@link Segment} as the current entity. */ default void run(Runnable runnable) { run(runnable, getCreator()); } /** * Immediately runs the provided {@link Runnable} with this {@link Segment} as the current entity. */ default void run(Runnable runnable, AWSXRayRecorder recorder) { Entity previous = recorder.getTraceEntity(); recorder.setTraceEntity(this); try { runnable.run(); } finally { recorder.setTraceEntity(previous); } } String getName(); /** * @return the id */ String getId(); /** * @param id * the id to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setId(String id); /** * @return the startTime */ double getStartTime(); /** * @param startTime * the startTime to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setStartTime(double startTime); /** * @return the endTime */ double getEndTime(); /** * @param endTime * the endTime to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setEndTime(double endTime); /** * @return the fault */ boolean isFault(); /** * @param fault * the fault to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setFault(boolean fault); /** * @return the error */ boolean isError(); /** * Sets the error value of the entity. * * @param error * the error to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setError(boolean error); /** * @return the namespace */ @Nullable String getNamespace(); /** * @param namespace * the namespace to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setNamespace(String namespace); /** * @return the subsegmentsLock * * @deprecated This is for internal use of the SDK and will be made private. */ @Deprecated ReentrantLock getSubsegmentsLock(); /** * @param subsegmentsLock * the subsegmentsLock to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * * @deprecated This is for internal use of the SDK and will be made private */ @Deprecated void setSubsegmentsLock(ReentrantLock subsegmentsLock); /** * @return the cause */ Cause getCause(); /** * @return the http */ Map<String, Object> getHttp(); /** * @param http * the http to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setHttp(Map<String, Object> http); /** * @return the aws */ Map<String, Object> getAws(); /** * @param aws * the aws to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setAws(Map<String, Object> aws); /** * @return the sql */ Map<String, Object> getSql(); /** * @param sql * the sql to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setSql(Map<String, Object> sql); /** * @return the metadata */ Map<String, Map<String, Object>> getMetadata(); /** * @param metadata * the metadata to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setMetadata(Map<String, Map<String, Object>> metadata); /** * @return the annotations */ Map<String, Object> getAnnotations(); /** * @param annotations * the annotations to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setAnnotations(Map<String, Object> annotations); /** * @return the parent */ Entity getParent(); /** * @param parent * the parent to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setParent(Entity parent); /** * @return the throttle */ boolean isThrottle(); /** * Sets the throttle value. When setting to true, error is also set to true and fault set to false. * * @param throttle * the throttle to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setThrottle(boolean throttle); /** * @return the inProgress */ boolean isInProgress(); /** * @param inProgress * the inProgress to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setInProgress(boolean inProgress); /** * @return the traceId */ TraceID getTraceId(); /** * @param traceId * the traceId to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setTraceId(TraceID traceId); /** * @return the parentId */ @Nullable String getParentId(); /** * @param parentId * the parentId to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setParentId(@Nullable String parentId); /** * @return the creator */ AWSXRayRecorder getCreator(); /** * @param creator * the creator to set * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void setCreator(AWSXRayRecorder creator); @JsonIgnore Segment getParentSegment(); /** * @return the subsegments * * @deprecated Use {@link #getSubsegmentsCopy()}. */ @Deprecated List<Subsegment> getSubsegments(); /** * Returns a copy of the currently added subsegments. Updates to the returned {@link List} will not be reflected in the * {@link Entity}. */ List<Subsegment> getSubsegmentsCopy(); /** * Adds a subsegment. * * @param subsegment * the subsegment to add * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void addSubsegment(Subsegment subsegment); /** * Adds an exception to the entity's cause and sets fault to true. * * @param exception * the exception to add * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void addException(Throwable exception); /** * Returns the reference count of the segment. This number represents how many open subsegments are children of this segment. * The segment is emitted when its reference count reaches 0. * * @return the reference count */ int getReferenceCount(); /** * @return the totalSize */ LongAdder getTotalSize(); /** * Increments the subsegment-reference counter. * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ void incrementReferenceCount(); /** * Decrements the subsegment-reference counter. * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * * @return true if the segment is no longer in progress and the reference count is less than or equal to zero. */ boolean decrementReferenceCount(); /** * Puts HTTP information. * * @param key * the key under which the HTTP information is stored * @param value * the HTTP information * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putHttp(String key, Object value); /** * Puts HTTP information. * * @param all * the HTTP information to put * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putAllHttp(Map<String, Object> all); /** * Puts AWS information. * * @param key * the key under which the AWS information is stored * @param value * the AWS information * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putAws(String key, Object value); /** * Puts AWS information. * * @param all * the AWS information to put * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putAllAws(Map<String, Object> all); /** * Puts SQL information. * * @param key * the key under which the SQL information is stored * @param value * the SQL information * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putSql(String key, Object value); /** * Puts SQL information. * * @param all * the SQL information to put * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putAllSql(Map<String, Object> all); /** * Puts a String annotation. * * @param key * the key under which the annotation is stored * @param value * the String annotation * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putAnnotation(String key, String value); /** * Puts a Number annotation. * * @param key * the key under which the annotation is stored * @param value * the Number annotation * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putAnnotation(String key, Number value); /** * Puts a Boolean annotation. * * @param key * the key under which the annotation is stored * @param value * the Boolean annotation * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putAnnotation(String key, Boolean value); /** * Puts metadata under the namespace 'default'. * * @param key * the key under which the metadata is stored * @param object * the metadata * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putMetadata(String key, Object object); /** * Puts metadata. * * @param namespace * the namespace under which the metadata is stored * @param key * the key under which the metadata is stored * @param object * the metadata * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions */ void putMetadata(String namespace, String key, Object object); /** * Removes a subsegment from the subsegment list. Decrements the total size of the parentSegment. Marks the removed subsegment * as emitted future modification on this subsegment may raise an AlreadyEmittedException. * * @param subsegment * the subsegment to remove */ void removeSubsegment(Subsegment subsegment); boolean isEmitted(); boolean isSampled(); /** * Sets emitted on the entity. */ void setEmitted(boolean emitted); /** * Checks whether this {@link Entity} currently has emitted state of {@code current} and if so, set emitted state to * {@code next}. Returns {@code true} if the state was updated, or {@code false} otherwise. * * @deprecated Use {@link #setEmitted(boolean)} */ @Deprecated boolean compareAndSetEmitted(boolean current, boolean next); String serialize(); String prettySerialize(); }
3,849
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/entities/SubsegmentImpl.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 com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.internal.SamplingStrategyOverride; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.checkerframework.checker.nullness.qual.Nullable; public class SubsegmentImpl extends EntityImpl implements Subsegment { private static final Log logger = LogFactory.getLog(SubsegmentImpl.class); @Nullable private String namespace; private Segment parentSegment; private Set<String> precursorIds; private boolean shouldPropagate; @JsonIgnore private boolean isSampled; @JsonIgnore private boolean isRecording; @JsonIgnore private SamplingStrategyOverride samplingStrategyOverride; @SuppressWarnings("nullness") private SubsegmentImpl() { super(); } // default constructor for jackson public SubsegmentImpl(AWSXRayRecorder creator, String name, Segment parentSegment) { this(creator, name, parentSegment, SamplingStrategyOverride.DISABLED); } @Deprecated public SubsegmentImpl(AWSXRayRecorder creator, String name, Segment parentSegment, SamplingStrategyOverride samplingStrategyOverride) { super(creator, name); this.parentSegment = parentSegment; parentSegment.incrementReferenceCount(); this.precursorIds = Collections.newSetFromMap(new ConcurrentHashMap<>()); this.shouldPropagate = true; this.isSampled = samplingStrategyOverride == SamplingStrategyOverride.DISABLED ? parentSegment.isSampled() : false; this.isRecording = isSampled; this.samplingStrategyOverride = samplingStrategyOverride; } @Override public boolean end() { if (logger.isDebugEnabled()) { logger.debug("Subsegment named '" + getName() + "' ending. Parent segment named '" + parentSegment.getName() + "' has reference count " + parentSegment.getReferenceCount()); } if (getEndTime() < Double.MIN_NORMAL) { setEndTime(System.currentTimeMillis() / 1000d); } setInProgress(false); boolean shouldEmit = parentSegment.decrementReferenceCount() && isSampled(); if (shouldEmit) { checkAlreadyEmitted(); setEmitted(true); } return shouldEmit; } @Override @JsonIgnore public TraceID getTraceId() { return parentSegment.getTraceId(); } @Override @Nullable public String getNamespace() { return namespace; } @Override public void setNamespace(String namespace) { checkAlreadyEmitted(); this.namespace = namespace; } @Override public Segment getParentSegment() { return parentSegment; } @Override public void setParentSegment(Segment parentSegment) { checkAlreadyEmitted(); this.parentSegment = parentSegment; } @Override public void addPrecursorId(String precursorId) { checkAlreadyEmitted(); this.precursorIds.add(precursorId); } @Override public Set<String> getPrecursorIds() { return precursorIds; } @Override public void setPrecursorIds(Set<String> precursorIds) { checkAlreadyEmitted(); this.precursorIds = precursorIds; } @Override public boolean shouldPropagate() { return shouldPropagate; } private ObjectNode getStreamSerializeObjectNode() { ObjectNode obj = (ObjectNode) mapper.valueToTree(this); obj.put("type", "subsegment"); obj.put("parent_id", getParent().getId()); obj.put("trace_id", parentSegment.getTraceId().toString()); return obj; } @Override public String streamSerialize() { String ret = ""; try { ret = mapper.writeValueAsString(getStreamSerializeObjectNode()); } catch (JsonProcessingException jpe) { logger.error("Exception while serializing entity.", jpe); } return ret; } @Override public String prettyStreamSerialize() { String ret = ""; try { ret = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(getStreamSerializeObjectNode()); } catch (JsonProcessingException jpe) { logger.error("Exception while serializing entity.", jpe); } return ret; } @Override public void close() { getCreator().endSubsegment(); } @Override @JsonIgnore public boolean isSampled() { return isSampled; } @Override @JsonIgnore public boolean isRecording() { return isRecording; } @Override @JsonIgnore public void setSampledFalse() { checkAlreadyEmitted(); isSampled = false; isRecording = false; } @Override @Deprecated public SamplingStrategyOverride getSamplingStrategyOverride() { return samplingStrategyOverride; } }
3,850
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/entities/SegmentImpl.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 com.amazonaws.xray.AWSXRayRecorder; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class SegmentImpl extends EntityImpl implements Segment { protected String resourceArn; protected String user; protected String origin; protected Map<String, Object> service; @JsonIgnore private boolean sampled; @SuppressWarnings({ "unused", "nullness" }) private SegmentImpl() { super(); } // default constructor for jackson // TODO(anuraaga): Refactor the entity relationship. There isn't a great reason to use a type hierarchy for data classes and // it makes the code to hard to reason about e.g., nullness. @SuppressWarnings("nullness") public SegmentImpl(AWSXRayRecorder creator, String name) { this(creator, name, TraceID.create(creator)); } // TODO(anuraaga): Refactor the entity relationship. There isn't a great reason to use a type hierarchy for data classes and // it makes the code to hard to reason about e.g., nullness. @SuppressWarnings("nullness") public SegmentImpl(AWSXRayRecorder creator, String name, TraceID traceId) { super(creator, name); if (traceId == null) { traceId = TraceID.create(creator); } setTraceId(traceId); this.service = new ConcurrentHashMap<>(); this.sampled = true; } @Override public boolean end() { if (getEndTime() < Double.MIN_NORMAL) { setEndTime(System.currentTimeMillis() / 1000d); } setInProgress(false); boolean shouldEmit = referenceCount.intValue() <= 0; if (shouldEmit) { checkAlreadyEmitted(); setEmitted(true); } return shouldEmit; } @Override public boolean isRecording() { return true; } @Override public boolean isSampled() { return sampled; } @Override public void setSampled(boolean sampled) { checkAlreadyEmitted(); this.sampled = sampled; } @Override public String getResourceArn() { return resourceArn; } @Override public void setResourceArn(String resourceArn) { checkAlreadyEmitted(); this.resourceArn = resourceArn; } @Override public String getUser() { return user; } @Override public void setUser(String user) { checkAlreadyEmitted(); this.user = user; } @Override public String getOrigin() { return origin; } @Override public void setOrigin(String origin) { checkAlreadyEmitted(); this.origin = origin; } @Override public Map<String, Object> getService() { return service; } @Override public void setService(Map<String, Object> service) { checkAlreadyEmitted(); this.service = service; } @Override public void putService(String key, Object object) { checkAlreadyEmitted(); service.put(key, object); } @Override public void putAllService(Map<String, Object> all) { checkAlreadyEmitted(); service.putAll(all); } @Override public void setRuleName(String ruleName) { checkAlreadyEmitted(); if (getAws().get("xray") instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> a = (Map<String, Object>) getAws().get("xray"); HashMap<String, Object> referA = new HashMap<>(); if (a != null) { referA.putAll(a); } referA.put("rule_name", ruleName); this.putAws("xray", referA); } } @Override public Segment getParentSegment() { return this; } @Override public void close() { getCreator().endSegment(); } }
3,851
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/entities/EntityImpl.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 com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.exceptions.AlreadyEmittedException; import com.amazonaws.xray.serializers.CauseSerializer; import com.amazonaws.xray.serializers.StackTraceElementSerializer; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationConfig; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.checkerframework.checker.nullness.qual.EnsuresNonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * The base class from which {@code Segment} and {@code Subsegment} extend. * */ public abstract class EntityImpl implements Entity { /** * @deprecated For internal use only. */ @SuppressWarnings("checkstyle:ConstantName") @Deprecated protected static final ObjectMapper mapper = new ObjectMapper() .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY); private static final Log logger = LogFactory.getLog(EntityImpl.class); private static final String DEFAULT_METADATA_NAMESPACE = "default"; /* * Reference counter to track how many subsegments are in progress on this entity. Starts with a value of 0. */ @JsonIgnore protected LongAdder referenceCount; @JsonIgnore protected LongAdder totalSize; private String name; private String id; @Nullable private String parentId; private double startTime; @JsonInclude(Include.NON_DEFAULT) @JsonSerialize(using = ToStringSerializer.class) private TraceID traceId; @JsonInclude(Include.NON_DEFAULT) private double endTime; @JsonInclude(Include.NON_DEFAULT) private boolean fault; @JsonInclude(Include.NON_DEFAULT) private boolean error; @JsonInclude(Include.NON_DEFAULT) private boolean throttle; @JsonInclude(Include.NON_DEFAULT) private boolean inProgress; @Nullable private String namespace; // TODO(anuraaga): Check final for other variables, for now this is most important since it's also a lock. private final List<Subsegment> subsegments; private Cause cause; private Map<String, Object> http; private Map<String, Object> aws; private Map<String, Object> sql; private Map<String, Map<String, Object>> metadata; private Map<String, Object> annotations; @JsonIgnore private Entity parent; @JsonIgnore private AWSXRayRecorder creator; @JsonIgnore private ReentrantLock subsegmentsLock; @JsonIgnore private boolean emitted = false; static { for (Module module: mapper.findModules()) { try { mapper.registerModule(module); logger.debug("Registered module: " + module.getModuleName()); } catch (Throwable t) { logger.error("Exception registering module: " + module.getModuleName(), t); } } /* * Inject the CauseSerializer and StackTraceElementSerializer classes into the local mapper such that they will serialize * their respective object types. */ mapper.registerModule(new SimpleModule() { private static final long serialVersionUID = 545800949242254918L; @Override public void setupModule(SetupContext setupContext) { super.setupModule(setupContext); setupContext.addBeanSerializerModifier(new BeanSerializerModifier() { @SuppressWarnings("unchecked") @Override public JsonSerializer<?> modifySerializer( SerializationConfig serializationConfig, BeanDescription beanDescription, JsonSerializer<?> jsonSerializer) { Class<?> beanClass = beanDescription.getBeanClass(); if (Cause.class.isAssignableFrom(beanClass)) { return new CauseSerializer((JsonSerializer<Object>) jsonSerializer); } else if (StackTraceElement.class.isAssignableFrom(beanClass)) { return new StackTraceElementSerializer(); } return jsonSerializer; } }); } }); } // default constructor for Jackson, so it can understand the default values to compare when using the Include.NON_DEFAULT // annotation. @SuppressWarnings("nullness") protected EntityImpl() { // TODO(anuraaga): Check this is working as intended, empty lists are currently serialized. subsegments = null; } // TODO(anuraaga): Refactor the entity relationship. There isn't a great reason to use a type hierarchy for data classes and // it makes the code to hard to reason about e.g., nullness. @SuppressWarnings("nullness") protected EntityImpl(AWSXRayRecorder creator, String name) { StringValidator.throwIfNullOrBlank(name, "(Sub)segment name cannot be null or blank."); validateNotNull(creator); this.creator = creator; this.name = name; this.subsegments = new ArrayList<>(); this.subsegmentsLock = new ReentrantLock(); this.cause = new Cause(); this.http = new ConcurrentHashMap<>(); this.aws = new ConcurrentHashMap<>(); this.sql = new ConcurrentHashMap<>(); this.annotations = new ConcurrentHashMap<>(); this.metadata = new ConcurrentHashMap<>(); this.startTime = System.currentTimeMillis() / 1000d; this.id = creator.getIdGenerator().newEntityId(); this.inProgress = true; this.referenceCount = new LongAdder(); this.totalSize = new LongAdder(); } /** * Checks if the entity has already been emitted to the X-Ray daemon. * * @throws AlreadyEmittedException * if the entity has already been emitted to the X-Ray daemon and the ContextMissingStrategy of the * AWSXRayRecorder used to create this entity is configured to throw exceptions * */ protected void checkAlreadyEmitted() { if (emitted) { getCreator().getContextMissingStrategy().contextMissing("Segment " + getName() + " has already been emitted.", AlreadyEmittedException.class); } } @Override public String getName() { return name; } @Override public String getId() { return id; } @Override public void setId(String id) { checkAlreadyEmitted(); this.id = id; } @Override public double getStartTime() { return startTime; } @Override public void setStartTime(double startTime) { checkAlreadyEmitted(); this.startTime = startTime; } @Override public double getEndTime() { return endTime; } @Override public void setEndTime(double endTime) { checkAlreadyEmitted(); this.endTime = endTime; } @Override public boolean isFault() { return fault; } @Override public void setFault(boolean fault) { checkAlreadyEmitted(); this.fault = fault; } @Override public boolean isError() { return error; } @Override public void setError(boolean error) { checkAlreadyEmitted(); this.error = error; } @Override @Nullable public String getNamespace() { return namespace; } @Override public void setNamespace(String namespace) { checkAlreadyEmitted(); this.namespace = namespace; } @Override public ReentrantLock getSubsegmentsLock() { return subsegmentsLock; } @Override public void setSubsegmentsLock(ReentrantLock subsegmentsLock) { checkAlreadyEmitted(); this.subsegmentsLock = subsegmentsLock; } @Override public Cause getCause() { return cause; } @Override public Map<String, Object> getHttp() { return http; } @Override public void setHttp(Map<String, Object> http) { checkAlreadyEmitted(); this.http = http; } @Override public Map<String, Object> getAws() { return aws; } @Override public void setAws(Map<String, Object> aws) { checkAlreadyEmitted(); this.aws = aws; } @Override public Map<String, Object> getSql() { return sql; } @Override public void setSql(Map<String, Object> sql) { checkAlreadyEmitted(); this.sql = sql; } @Override public Map<String, Map<String, Object>> getMetadata() { return metadata; } @Override public void setMetadata(Map<String, Map<String, Object>> metadata) { checkAlreadyEmitted(); this.metadata = metadata; } @Override public Map<String, Object> getAnnotations() { return annotations; } @Override public void setAnnotations(Map<String, Object> annotations) { checkAlreadyEmitted(); this.annotations = annotations; } @Override public Entity getParent() { return parent; } @Override public void setParent(Entity parent) { checkAlreadyEmitted(); this.parent = parent; } /** * @return the creator */ @Override public AWSXRayRecorder getCreator() { return creator; } /** * @param creator the creator to set */ @Override public void setCreator(AWSXRayRecorder creator) { checkAlreadyEmitted(); this.creator = creator; } @Override public boolean isThrottle() { return throttle; } @Override public void setThrottle(boolean throttle) { checkAlreadyEmitted(); if (throttle) { this.fault = false; this.error = true; } this.throttle = throttle; } @Override public boolean isInProgress() { return inProgress; } @Override public void setInProgress(boolean inProgress) { checkAlreadyEmitted(); this.inProgress = inProgress; } @Override public TraceID getTraceId() { return traceId; } @Override @EnsuresNonNull("this.traceId") public void setTraceId(TraceID traceId) { checkAlreadyEmitted(); this.traceId = traceId; } @Override @Nullable public String getParentId() { return parentId; } @Override public void setParentId(@Nullable String parentId) { checkAlreadyEmitted(); this.parentId = parentId; } @JsonIgnore @Override public abstract Segment getParentSegment(); @Override public List<Subsegment> getSubsegments() { return subsegments; } @JsonIgnore @Override public List<Subsegment> getSubsegmentsCopy() { return new ArrayList<>(subsegments); } @Override public void addSubsegment(Subsegment subsegment) { checkAlreadyEmitted(); getSubsegmentsLock().lock(); try { subsegments.add(subsegment); } finally { getSubsegmentsLock().unlock(); } } @Override public void addException(Throwable exception) { checkAlreadyEmitted(); setFault(true); getSubsegmentsLock().lock(); try { cause.addExceptions(creator.getThrowableSerializationStrategy() .describeInContext(this, exception, subsegments)); } finally { getSubsegmentsLock().unlock(); } } @Override public void putHttp(String key, Object value) { checkAlreadyEmitted(); validateNotNull(key); validateNotNull(value); http.put(key, value); } @Override public void putAllHttp(Map<String, Object> all) { checkAlreadyEmitted(); validateNotNull(all); http.putAll(all); } @Override public void putAws(String key, Object value) { checkAlreadyEmitted(); validateNotNull(key); validateNotNull(value); aws.put(key, value); } @Override public void putAllAws(Map<String, Object> all) { checkAlreadyEmitted(); validateNotNull(all); aws.putAll(all); } @Override public void putSql(String key, Object value) { checkAlreadyEmitted(); validateNotNull(key); validateNotNull(value); sql.put(key, value); } @Override public void putAllSql(Map<String, Object> all) { checkAlreadyEmitted(); validateNotNull(all); sql.putAll(all); } @Override public void putAnnotation(String key, String value) { checkAlreadyEmitted(); validateNotNull(key); validateNotNull(value); annotations.put(key, value); } @Override public void putAnnotation(String key, Number value) { checkAlreadyEmitted(); validateNotNull(key); validateNotNull(value); annotations.put(key, value); } @Override public void putAnnotation(String key, Boolean value) { checkAlreadyEmitted(); validateNotNull(key); validateNotNull(value); annotations.put(key, value); } @Override public void putMetadata(String key, Object object) { checkAlreadyEmitted(); putMetadata(DEFAULT_METADATA_NAMESPACE, key, object); } @Override public void putMetadata(String namespace, String key, Object object) { checkAlreadyEmitted(); validateNotNull(namespace); validateNotNull(key); if (null == object) { object = NullNode.instance; } metadata.computeIfAbsent(namespace, (n) -> { return new ConcurrentHashMap<String, Object>(); }).put(key, object); } @Override public void incrementReferenceCount() { checkAlreadyEmitted(); referenceCount.increment(); totalSize.increment(); } @Override public boolean decrementReferenceCount() { checkAlreadyEmitted(); referenceCount.decrement(); return !isInProgress() && referenceCount.intValue() <= 0; } /** * Returns the reference count of the segment. This number represents how many open subsegments are children of this segment. * The segment is emitted when its reference count reaches 0. * * @return the reference count */ @Override public int getReferenceCount() { return referenceCount.intValue(); } /** * @return the totalSize */ @Override public LongAdder getTotalSize() { return totalSize; } /** * @return the emitted */ @Override public boolean isEmitted() { return emitted; } /** * @param emitted * the emitted to set */ @Override public void setEmitted(boolean emitted) { checkAlreadyEmitted(); this.emitted = emitted; } @Override public boolean compareAndSetEmitted(boolean current, boolean next) { checkAlreadyEmitted(); if (emitted == current) { emitted = next; return true; } return false; } @Override public String serialize() { try { return mapper.writeValueAsString(this); } catch (JsonProcessingException jpe) { logger.error("Exception while serializing entity.", jpe); } return ""; } @Override public String prettySerialize() { try { return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this); } catch (JsonProcessingException jpe) { logger.error("Exception while serializing segment.", jpe); } return ""; } @Override public void removeSubsegment(Subsegment subsegment) { getSubsegmentsLock().lock(); try { subsegments.remove(subsegment); } finally { getSubsegmentsLock().unlock(); } getParentSegment().getTotalSize().decrement(); } public static void validateNotNull(Object object) { if (null == object) { throw new NullPointerException(); } } }
3,852
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/entities/TraceID.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 com.amazonaws.xray.utils.ByteUtils.intToBase16String; import static com.amazonaws.xray.utils.ByteUtils.numberToBase16String; import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.internal.TimeUtils; import java.math.BigInteger; import org.checkerframework.checker.nullness.qual.Nullable; public class TraceID { private static final String INVALID_START_TIME = "00000000"; private static final String INVALID_NUMBER = "000000000000000000000000"; private static final TraceID INVALID = new TraceID(INVALID_START_TIME, INVALID_NUMBER); /** * Returns a new {@link TraceID} which represents the start of a new trace. This new ID * is generated according to the settings provided by the global AWSXRayRecorder instance * returned by {@link AWSXRay#getGlobalRecorder}. * * @see #create(AWSXRayRecorder) */ public static TraceID create() { return new TraceID(TimeUtils.currentEpochSecond(), AWSXRay.getGlobalRecorder()); } /** * Returns a new {@code TraceID} which represents the start of a new trace. This new * ID is generated according to the settings provided by the AWSXRayRecorder instance * that created it. */ public static TraceID create(AWSXRayRecorder creator) { return new TraceID(TimeUtils.currentEpochSecond(), creator); } /** * Returns the {@link TraceID} parsed out of the {@link String}. If the parse fails, a new {@link TraceID} will be returned, * effectively restarting the trace. */ public static TraceID fromString(String xrayTraceId) { xrayTraceId = xrayTraceId.trim(); if (xrayTraceId.length() != TRACE_ID_LENGTH) { return TraceID.create(); } // Check version trace id version if (xrayTraceId.charAt(0) != VERSION) { return TraceID.create(); } // Check delimiters if (xrayTraceId.charAt(TRACE_ID_DELIMITER_INDEX_1) != DELIMITER || xrayTraceId.charAt(TRACE_ID_DELIMITER_INDEX_2) != DELIMITER) { return TraceID.create(); } String startTimePart = xrayTraceId.substring(TRACE_ID_DELIMITER_INDEX_1 + 1, TRACE_ID_DELIMITER_INDEX_2); if (!isHex(startTimePart)) { return TraceID.create(); } String randomPart = xrayTraceId.substring(TRACE_ID_DELIMITER_INDEX_2 + 1, TRACE_ID_LENGTH); if (!isHex(randomPart)) { return TraceID.create(); } return new TraceID(startTimePart, randomPart); } /** * Returns an invalid {@link TraceID} which can be used when an ID is needed outside the context of a trace, for example for * an unsampled segment. */ public static TraceID invalid() { return INVALID; } private static final int TRACE_ID_LENGTH = 35; private static final int TRACE_ID_DELIMITER_INDEX_1 = 1; private static final int TRACE_ID_DELIMITER_INDEX_2 = 10; private static final char VERSION = '1'; private static final char DELIMITER = '-'; private String numberHex; private String startTimeHex; /** * @deprecated Use {@link #create()} or {@link #create(AWSXRayRecorder)} */ @Deprecated public TraceID() { this(TimeUtils.currentEpochSecond()); } /** * @deprecated Use {@link #create()} or {@link #create(AWSXRayRecorder)} */ @Deprecated public TraceID(long startTime) { this(startTime, AWSXRay.getGlobalRecorder()); } private TraceID(long startTime, AWSXRayRecorder creator) { this(intToBase16String((int) startTime), creator.getIdGenerator().newTraceId()); } private TraceID(String startTimeHex, String numberHex) { this.startTimeHex = startTimeHex; this.numberHex = numberHex; } @Override public String toString() { return "" + VERSION + DELIMITER + startTimeHex + DELIMITER + numberHex; } /** * @return the number * * @deprecated use {@link #getNumberAsHex()}. */ @Deprecated public BigInteger getNumber() { return new BigInteger(numberHex, 16); } /** * Returns the number component of this {@link TraceID} as a hexadecimal string. */ public String getNumberAsHex() { return numberHex; } /** * @param number the number to set * * @deprecated TraceID is effectively immutable and this will be removed */ @Deprecated public void setNumber(@Nullable BigInteger number) { if (number != null) { this.numberHex = numberToBase16String(number.shiftRight(64).intValue(), number.longValue()); } } /** * @return the startTime * * @deprecated Use {@link #getStartTimeAsHex()}. */ public long getStartTime() { return Long.parseLong(startTimeHex, 16); } /** * Returns the start time of this {@link TraceID} as a hexadecimal string representing the number of seconds since * the epoch. */ public String getStartTimeAsHex() { return startTimeHex; } /** * @param startTime the startTime to set * * @deprecated TraceID is effectively immutable and this will be removed */ @Deprecated public void setStartTime(long startTime) { this.startTimeHex = intToBase16String(startTime); } @Override public int hashCode() { return 31 * numberHex.hashCode() + startTimeHex.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (!(obj instanceof TraceID)) { return false; } TraceID other = (TraceID) obj; return numberHex.equals(other.numberHex) && startTimeHex.equals(other.startTimeHex); } // Visible for testing static boolean isHex(String value) { for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (!isDigit(c) && !isLowercaseHexCharacter(c)) { return false; } } return true; } private static boolean isLowercaseHexCharacter(char b) { return 'a' <= b && b <= 'f'; } private static boolean isDigit(char b) { return '0' <= b && b <= '9'; } }
3,853
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/entities/Subsegment.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 com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.internal.SamplingStrategyOverride; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; public interface Subsegment extends Entity { static Subsegment noOp(AWSXRayRecorder recorder) { return new NoOpSubSegment(Segment.noOp(TraceID.invalid(), recorder), recorder); } @Deprecated static Subsegment noOp(AWSXRayRecorder recorder, boolean shouldPropagate, SamplingStrategyOverride samplingStrategyOverride) { return new NoOpSubSegment(Segment.noOp(TraceID.invalid(), recorder), recorder, shouldPropagate, samplingStrategyOverride); } @Deprecated static Subsegment noOp(Segment parent, AWSXRayRecorder recorder, SamplingStrategyOverride samplingStrategyOverride) { return new NoOpSubSegment(parent, recorder, samplingStrategyOverride); } static Subsegment noOp(AWSXRayRecorder recorder, boolean shouldPropagate) { return new NoOpSubSegment(Segment.noOp(TraceID.invalid(), recorder), recorder, shouldPropagate); } static Subsegment noOp(Segment parent, AWSXRayRecorder recorder, String name) { return new NoOpSubSegment(parent, recorder, name); } static Subsegment noOp(Segment parent, AWSXRayRecorder recorder) { return new NoOpSubSegment(parent, recorder); } /** * Ends the subsegment. Sets the end time to the current time. Sets inProgress to false. Decrements its parent segment's * segment-reference counter. * * @return * true if 1) the parent segment now has a ref. count of zero and 2) the parent segment is sampled */ boolean end(); /** * @return the namespace */ @Override @Nullable String getNamespace(); /** * @param namespace * the namespace to set */ @Override void setNamespace(String namespace); /** * @return the parentSegment */ @Override Segment getParentSegment(); /** * @param parentSegment the parentSegment to set */ void setParentSegment(Segment parentSegment); /** * @return the precursorIds */ Set<String> getPrecursorIds(); /** * @param precursorIds the precursorIds to set */ void setPrecursorIds(Set<String> precursorIds); /** * @param precursorId the precursor ID to add to the set */ void addPrecursorId(String precursorId); /** * Determines if this subsegment should propagate its trace context downstream * @return true if its trace context should be propagated downstream, false otherwise */ boolean shouldPropagate(); /** * Serializes the subsegment as a standalone String with enough information for the subsegment to be streamed on its own. * @return * the string representation of the subsegment with enough information for it to be streamed */ String streamSerialize(); /** * Pretty-serializes the subsegment as a standalone String with enough information for the subsegment to be streamed on its * own. Only used for debugging. * * @return * the pretty string representation of the subsegment with enough information for it to be streamed */ String prettyStreamSerialize(); /** * Implements the {@link AutoCloseable} interface. * * Warning. This method is intended to be private to the xray library and should not be used externally. Instead, use * {@link com.amazonaws.xray.AWSXRay#endSubsegment(Subsegment)}. */ @Override void close(); @JsonIgnore boolean isRecording(); @JsonIgnore void setSampledFalse(); SamplingStrategyOverride getSamplingStrategyOverride(); }
3,854
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/strategy/DynamicSegmentNamingStrategy.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.entities.SearchPattern; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @deprecated Use {@link SegmentNamingStrategy#dynamic(String)}. */ @Deprecated public class DynamicSegmentNamingStrategy implements SegmentNamingStrategy { private static final Log logger = LogFactory.getLog(DynamicSegmentNamingStrategy.class); private final String recognizedHosts; private final String fallbackName; /** * Creates an instance of {@code DynamicSegmentNamingStrategy} with the provided {@code fallbackName} and a * {@code recognizedHosts} value of "*". * * @param fallbackName * the fallback segment name used when no host header is included in the incoming request. This will be overriden by the * value of the {@code AWS_XRAY_TRACING_NAME} environment variable or {@code com.amazonaws.xray.strategy.tracingName} system * property, if either are set to a non-empty value. * * @deprecated Use {@link SegmentNamingStrategy#dynamic(String)}. */ @Deprecated public DynamicSegmentNamingStrategy(String fallbackName) { this(fallbackName, "*"); } /** * Creates an instance of {@code DynamicSegmentNamingStrategy} with the provided {@code fallbackName} and * {@code recognizedHosts} values. * * @param fallbackName * the fallback segment name used when no host header is included in the incoming request or the incoming host header value * does not match the provided pattern. This will be overriden by the value of the {@code AWS_XRAY_TRACING_NAME} environment * variable or {@code com.amazonaws.xray.strategy.tracingName} system property, if either are set to a non-empty value. * @param recognizedHosts * the pattern to match the incoming host header value against. This pattern is compared against the incoming host header * using the {@link com.amazonaws.xray.entities.SearchPattern#wildcardMatch(String, String)} method. * * @deprecated Use {@link SegmentNamingStrategy#dynamic(String, String)}. */ // Instance method is called before the class is initialized. This can cause undefined behavior, e.g., if getOverrideName // accesses fallbackName. This class doesn't really need to be exposed to users so we suppress for now and will clean up after // hiding. @SuppressWarnings("nullness") @Deprecated public DynamicSegmentNamingStrategy(String fallbackName, String recognizedHosts) { String overrideName = getOverrideName(); if (overrideName != null) { this.fallbackName = getOverrideName(); if (logger.isInfoEnabled()) { logger.info("Environment variable " + NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY + " or system property " + NAME_OVERRIDE_SYSTEM_PROPERTY_KEY + " set. Overriding DynamicSegmentNamingStrategy constructor argument. Segments generated with this " + "strategy will be named: " + this.fallbackName + " when the host header is unavilable or does not match the provided recognizedHosts pattern."); } } else { this.fallbackName = fallbackName; } this.recognizedHosts = recognizedHosts; } /** * * Returns the derived segment name for an incoming request. Attempts to get the {@code Host} header from the * {@code HttpServletRequest}. If the {@code Host} header has a value and if the value matches the optionally provided * {@code recognizedHosts} pattern, then this value is returned as the segment name. Otherwise, {@code fallbackName} is * returned. * * * @param request * the incoming request * @return * the segment name for the incoming request. */ @Override public String nameForRequest(HttpServletRequest request) { Optional<String> hostHeaderValue = Optional.ofNullable(request.getHeader("Host")); if (hostHeaderValue.isPresent() && (null == recognizedHosts || SearchPattern.wildcardMatch(recognizedHosts, hostHeaderValue.get()))) { return hostHeaderValue.get(); } return fallbackName; } }
3,855
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/strategy/StreamingStrategy.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.emitters.Emitter; import com.amazonaws.xray.entities.Entity; import com.amazonaws.xray.entities.Segment; public interface StreamingStrategy { /** * Determines whether or not the provided segment requires any subsegment streaming. * * @param segment * the segment to inspect * @return true if the segment should be streaming. */ boolean requiresStreaming(Segment segment); /** * Streams (and removes) some subsegment children from the provided segment or subsegment. * * @param entity * the segment or subsegment to stream children from * @param emitter * the emitter to send the child subsegments to */ void streamSome(Entity entity, Emitter emitter); }
3,856
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/strategy/PrioritizationStrategy.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; public interface PrioritizationStrategy { }
3,857
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/strategy/ContextMissingStrategy.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; public interface ContextMissingStrategy { /** * Environment variable key used to override the default {@code ContextMissingStrategy} used in new instances of * {@code AWSXRayRecorder}. Valid values for this environment variable are (case-insensitive) {@code RUNTIME_ERROR}, * {@code LOG_ERROR} and {@code IGNORE_ERROR}. Invalid values will be ignored. Takes precedence over any system property or * builder value used for the {@code DefaultContextMissingStrategy}. */ String CONTEXT_MISSING_STRATEGY_ENVIRONMENT_VARIABLE_OVERRIDE_KEY = "AWS_XRAY_CONTEXT_MISSING"; /** * System property key used to override the default {@code ContextMissingStrategy} used in new instances of * {@code AWSXRayRecorder}. Valid values for this system property are (case-insensitive) {@code RUNTIME_ERROR}, * {@code LOG_ERROR} and {@code IGNORE_ERROR}. Invalid values will be ignored. Takes precedence over any builder value used * for the {@code DefaultContextMissingStrategy}. */ String CONTEXT_MISSING_STRATEGY_SYSTEM_PROPERTY_OVERRIDE_KEY = "com.amazonaws.xray.strategy.contextMissingStrategy"; void contextMissing(String message, Class<? extends RuntimeException> exceptionClass); }
3,858
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/strategy/DefaultThrowableSerializationStrategy.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.AmazonServiceException; import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Entity; import com.amazonaws.xray.entities.Subsegment; import com.amazonaws.xray.entities.ThrowableDescription; import com.amazonaws.xray.internal.IdGenerator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; /** * Default implementation of {@code ThrowableSerializationStrategy}. * This class auto-registers the {@code AmazonServiceException} class as a remote exception class if no set of remote exception * classes is provided in the constructor. */ public class DefaultThrowableSerializationStrategy implements ThrowableSerializationStrategy { private static final int DEFAULT_MAX_STACK_TRACE_LENGTH = 50; private static final Set<Class<? extends Throwable>> DEFAULT_REMOTE_EXCEPTION_CLASSES = Collections.singleton(AmazonServiceException.class); private final int maxStackTraceLength; private final Set<Class<? extends Throwable>> remoteExceptionClasses; public DefaultThrowableSerializationStrategy() { this(DEFAULT_MAX_STACK_TRACE_LENGTH); } /** * Constructs a new instance of {@code DefaultThrowableSerializationStrategy}, overriding the max stack trace length default * value of 50. Use this constructor to include more or less stack trace * information in (sub)segments. * * @param maxStackTraceLength * the maximum number of stack trace elements to include in a single (sub)segment. */ public DefaultThrowableSerializationStrategy(int maxStackTraceLength) { this(maxStackTraceLength, DEFAULT_REMOTE_EXCEPTION_CLASSES); } /** * Constructs a new instance of {@code DefaultThrowableSerializationStrategy}, overriding the max stack trace length default * value of 50, and overriding the Throwable classes considered 'remote'. Use this constructor to include more or less stack * trace information in (sub)segments. * * @param maxStackTraceLength * the maximum number of stack trace elements to include in a single (sub)segment. * @param remoteExceptionClasses * the superclasses which extend {@code Throwable} for which exceptions should be considered remote. */ public DefaultThrowableSerializationStrategy( int maxStackTraceLength, Set<Class<? extends Throwable>> remoteExceptionClasses) { this.maxStackTraceLength = maxStackTraceLength; this.remoteExceptionClasses = remoteExceptionClasses; } private boolean isRemote(Throwable throwable) { return remoteExceptionClasses.parallelStream().anyMatch(remoteExceptionClass -> { return remoteExceptionClass.isInstance(throwable); }); } private Optional<ThrowableDescription> referenceInChildren(Throwable throwable, List<Subsegment> subsegments) { return subsegments.parallelStream() .flatMap(subsegment -> subsegment.getCause().getExceptions().stream()) .filter(throwableDescription -> throwable.equals(throwableDescription.getThrowable())) .findAny(); } private ThrowableDescription describeThrowable(Throwable throwable, String id) { ThrowableDescription description = new ThrowableDescription(); description.setId(id); description.setMessage(throwable.getMessage()); description.setType(throwable.getClass().getName()); StackTraceElement[] stackTrace = throwable.getStackTrace(); if (stackTrace != null && stackTrace.length > maxStackTraceLength) { description.setStack(Arrays.copyOfRange(stackTrace, 0, maxStackTraceLength)); description.setTruncated(stackTrace.length - maxStackTraceLength); } else { description.setStack(stackTrace); } description.setThrowable(throwable); if (isRemote(throwable)) { description.setRemote(true); } return description; } @Override public List<ThrowableDescription> describeInContext(Throwable throwable, List<Subsegment> subsegments) { return describeInContext(null, throwable, subsegments); } @Override public List<ThrowableDescription> describeInContext( @Nullable Entity entity, Throwable throwable, List<Subsegment> subsegments ) { List<ThrowableDescription> result = new ArrayList<>(); IdGenerator idGenerator; // We could fall back on ThreadLocalStorage#get if we were confident that no `SegmentContext` implementations // override the default get/setTraceEntity implementations, but we can't make that guarantee. if (entity != null) { idGenerator = entity.getCreator().getIdGenerator(); } else if (!subsegments.isEmpty()) { idGenerator = subsegments.get(0).getCreator().getIdGenerator(); } else { idGenerator = AWSXRay.getGlobalRecorder().getIdGenerator(); } /* * Visit each node in the cause chain. For each node: * Determine if it has already been described in one of the child subsegments' causes. If so, link there. * Otherwise, describe it and add it to the result. */ ThrowableDescription description = new ThrowableDescription(); Optional<ThrowableDescription> exceptionReferenced = referenceInChildren(throwable, subsegments); if (exceptionReferenced.isPresent()) { //already described, we can link to this one by ID. Get the id from the child's Throwabledescription (if it has one). //Use the cause otherwise. ThrowableDescription exception = exceptionReferenced.get(); description.setCause(exception.getId() != null ? exception.getId() : exception.getCause()); description.setThrowable(throwable); result.add(description); return result; } else { description = describeThrowable(throwable, idGenerator.newEntityId()); result.add(description); } Throwable nextNode = throwable.getCause(); while (null != nextNode) { final Throwable currentNode = nextNode; exceptionReferenced = referenceInChildren(currentNode, subsegments); if (exceptionReferenced.isPresent()) { description.setCause(null == exceptionReferenced.get().getId() ? exceptionReferenced.get().getCause() : exceptionReferenced.get().getId()); } else { //Link it, and start a new description String newId = idGenerator.newEntityId(); description.setCause(newId); description = describeThrowable(currentNode, newId); } result.add(description); nextNode = nextNode.getCause(); } return result; } /** * @return the maxStackTraceLength */ public int getMaxStackTraceLength() { return maxStackTraceLength; } }
3,859
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/strategy/SegmentNamingStrategy.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.entities.StringValidator; import javax.servlet.http.HttpServletRequest; import org.checkerframework.checker.nullness.qual.Nullable; public interface SegmentNamingStrategy { /** * Environment variable key used to override the default segment name used by implementors of {@code SegmentNamingStrategy}. * Takes precedence over any system property, web.xml configuration value, or constructor value used for a fixed segment name. */ String NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY = "AWS_XRAY_TRACING_NAME"; /** * System property key used to override the default segment name used by implementors of {@code SegmentNamingStrategy}. * Takes precedence over any web.xml configuration value or constructor value used for a fixed segment name. */ String NAME_OVERRIDE_SYSTEM_PROPERTY_KEY = "com.amazonaws.xray.strategy.tracingName"; /** * Returns a {@link SegmentNamingStrategy} that assigns the provided {@code name} to all segments generated for incoming * requests. This will be ignored and will use the the value of the {@code AWS_XRAY_TRACING_NAME} environment variable or * {@code com.amazonaws.xray.strategy.tracingName} system property if set. */ static SegmentNamingStrategy fixed(String name) { return new FixedSegmentNamingStrategy(name); } /** * Returns a {@link SegmentNamingStrategy} that names segments based on the {@code Host} header of incoming requests, * accepting any {@code Host} header value. * * @param fallbackName * the fallback segment name used when no host header is included in the incoming request or the incoming host header value * does not match the provided pattern. This will be overriden by the value of the {@code AWS_XRAY_TRACING_NAME} environment * variable or {@code com.amazonaws.xray.strategy.tracingName} system property, if either are set to a non-empty value. */ static SegmentNamingStrategy dynamic(String fallbackName) { return dynamic(fallbackName, "*"); } /** * Returns a {@link SegmentNamingStrategy} that names segments based on the {@code Host} header of incoming requests, * accepting only recognized {@code Host} header values. * * @param fallbackName * the fallback segment name used when no host header is included in the incoming request or the incoming host header value * does not match the provided pattern. This will be overriden by the value of the {@code AWS_XRAY_TRACING_NAME} environment * variable or {@code com.amazonaws.xray.strategy.tracingName} system property, if either are set to a non-empty value. * @param recognizedHosts * the pattern to match the incoming host header value against. This pattern is compared against the incoming host header * using the {@link com.amazonaws.xray.entities.SearchPattern#wildcardMatch(String, String)} method. */ static SegmentNamingStrategy dynamic(String fallbackName, String recognizedHosts) { return new DynamicSegmentNamingStrategy(fallbackName, recognizedHosts); } String nameForRequest(HttpServletRequest request); @Nullable default String getOverrideName() { String environmentNameOverrideValue = System.getenv(NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY); String systemNameOverrideValue = System.getProperty(NAME_OVERRIDE_SYSTEM_PROPERTY_KEY); if (StringValidator.isNotNullOrBlank(environmentNameOverrideValue)) { return environmentNameOverrideValue; } else if (StringValidator.isNotNullOrBlank(systemNameOverrideValue)) { return systemNameOverrideValue; } return null; } }
3,860
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/strategy/RuntimeErrorContextMissingStrategy.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 java.lang.reflect.InvocationTargetException; public class RuntimeErrorContextMissingStrategy implements ContextMissingStrategy { public static final String OVERRIDE_VALUE = "RUNTIME_ERROR"; /** * Constructs an instance of {@code exceptionClass} and throws it. * @param message the message to use when constructing an instance of {@code exceptionClass} * @param exceptionClass the type of exception thrown due to missing context */ @Override public void contextMissing(String message, Class<? extends RuntimeException> exceptionClass) { try { throw exceptionClass.getConstructor(String.class).newInstance(message); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(message); } } }
3,861
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/strategy/DefaultStreamingStrategy.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.emitters.Emitter; import com.amazonaws.xray.entities.Entity; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; import java.util.ArrayList; public class DefaultStreamingStrategy implements StreamingStrategy { private static final int DEFAULT_MAX_SEGMENT_SIZE = 100; private final int maxSegmentSize; /** * Constructs an instance of DefaultStreamingStrategy using the default {@code maxSegmentSize} of 100. * */ public DefaultStreamingStrategy() { this(DEFAULT_MAX_SEGMENT_SIZE); } /** * Constructs an instance of DefaultStreamingStrategy using the provided {@code maxSegmentSize}. * * @param maxSegmentSize * the maximum number of subsegment nodes a segment tree may have before {@code requiresStreaming} will return true * * @throws IllegalArgumentException * when {@code maxSegmentSize} is a negative integer * */ public DefaultStreamingStrategy(int maxSegmentSize) { if (maxSegmentSize < 0) { throw new IllegalArgumentException("maxSegmentSize must be a non-negative integer."); } this.maxSegmentSize = maxSegmentSize; } public int getMaxSegmentSize() { return maxSegmentSize; } /** * {@inheritDoc} * * Indicates that the provided segment requires streaming when it has been marked for sampling and its tree of subsegments * reaches a size greater than {@code maxSegmentSize}. * * @see StreamingStrategy#requiresStreaming(Segment) */ @Override public boolean requiresStreaming(Segment segment) { if (segment.isSampled() && null != segment.getTotalSize()) { return segment.getTotalSize().intValue() > maxSegmentSize; } return false; } /** * {@inheritDoc} * * Performs Subtree Subsegment Streaming to stream completed subsegment subtrees. Serializes these subtrees of subsegments, * streams them to the daemon, and removes them from their parents. * * @see StreamingStrategy#streamSome(Entity,Emitter) */ @Override public void streamSome(Entity entity, Emitter emitter) { if (entity.getSubsegmentsLock().tryLock()) { try { stream(entity, emitter); } finally { entity.getSubsegmentsLock().unlock(); } } } private boolean stream(Entity entity, Emitter emitter) { ArrayList<Subsegment> children = new ArrayList<>(entity.getSubsegments()); ArrayList<Subsegment> streamable = new ArrayList<>(); //Gather children and in the condition they are ready to stream, add them to the streamable list. if (children.size() > 0) { for (Subsegment child : children) { if (child.getSubsegmentsLock().tryLock()) { try { if (stream(child, emitter)) { streamable.add(child); } } finally { child.getSubsegmentsLock().unlock(); } } } } //A subsegment is marked streamable if all of its children are streamable and the entity itself is not in progress. if (children.size() == streamable.size() && !entity.isInProgress()) { return true; } //Stream the subtrees that are ready. for (Subsegment child : streamable) { emitter.sendSubsegment(child); child.setEmitted(true); entity.removeSubsegment(child); } return false; } }
3,862
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/strategy/IgnoreErrorContextMissingStrategy.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; public class IgnoreErrorContextMissingStrategy implements ContextMissingStrategy { public static final String OVERRIDE_VALUE = "IGNORE_ERROR"; /** * Ignore the error * @param message not used * @param exceptionClass not used */ @Override public void contextMissing(String message, Class<? extends RuntimeException> exceptionClass) { // do nothing } }
3,863
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/strategy/FixedSegmentNamingStrategy.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 javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @deprecated Use {@link SegmentNamingStrategy#fixed(String)}. */ @Deprecated public class FixedSegmentNamingStrategy implements SegmentNamingStrategy { private static final Log logger = LogFactory.getLog(FixedSegmentNamingStrategy.class); private final String fixedName; /** * @deprecated Use {@link SegmentNamingStrategy#fixed(String)}. */ // Instance method is called before the class is initialized. This can cause undefined behavior, e.g., if getOverrideName // accesses fixedName. This class doesn't really need to be exposed to users so we suppress for now and will clean up after // hiding. @SuppressWarnings("nullness") @Deprecated public FixedSegmentNamingStrategy(String name) { String overrideName = getOverrideName(); if (overrideName != null) { this.fixedName = overrideName; if (logger.isInfoEnabled()) { logger.info("Environment variable " + NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY + " or system property " + NAME_OVERRIDE_SYSTEM_PROPERTY_KEY + " set. Overriding FixedSegmentNamingStrategy constructor argument. Segments generated with this " + "strategy will be named: " + this.fixedName + "."); } } else { this.fixedName = name; } } /** * Returns a segment name for an incoming request. * * @param request * the incoming request * @return * the name for the segment representing the request. */ @Override public String nameForRequest(HttpServletRequest request) { return fixedName; } }
3,864
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/strategy/LogErrorContextMissingStrategy.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 org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class LogErrorContextMissingStrategy implements ContextMissingStrategy { public static final String OVERRIDE_VALUE = "LOG_ERROR"; private static final Log logger = LogFactory.getLog(LogErrorContextMissingStrategy .class); /** * Logs {@code message} on the {@code error} level, and a stacktrace at {@code debug} level. * @param message the message to log * @param exceptionClass the type of exception suppressed in favor of logging {@code message} */ @Override public void contextMissing(String message, Class<? extends RuntimeException> exceptionClass) { logger.error("Suppressing AWS X-Ray context missing exception (" + exceptionClass.getSimpleName() + "): " + message); if (logger.isDebugEnabled()) { logger.debug("Attempted to find context at:", new RuntimeException(message)); } } }
3,865
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/strategy/DefaultPrioritizationStrategy.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; public class DefaultPrioritizationStrategy implements PrioritizationStrategy { }
3,866
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/strategy/ThrowableSerializationStrategy.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.entities.Entity; import com.amazonaws.xray.entities.Subsegment; import com.amazonaws.xray.entities.ThrowableDescription; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; public interface ThrowableSerializationStrategy { /** * Serializes a {@code Throwable} into a {@code ThrowableDescription}. Uses the provided subsegments to chain exceptions where * possible. * * @param throwable * the Throwable to serialize * @param subsegments * the list of subsegment children in which to look for the same {@code Throwable} object, for chaining * * @return a list of {@code ThrowableDescription}s which represent the provided {@code Throwable} */ List<ThrowableDescription> describeInContext(Throwable throwable, List<Subsegment> subsegments); /** * Serializes a {@code Throwable} into a {@code ThrowableDescription}. Uses the provided subsegments to chain exceptions where * possible. * * @param entity * the current entity. May be null. * @param throwable * the Throwable to serialize * @param subsegments * the list of subsegment children in which to look for the same {@code Throwable} object, for chaining * * @return a list of {@code ThrowableDescription}s which represent the provided {@code Throwable} */ default List<ThrowableDescription> describeInContext( @Nullable Entity entity, Throwable throwable, List<Subsegment> subsegments ) { return describeInContext(throwable, subsegments); } }
3,867
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/strategy/DefaultContextMissingStrategy.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; public class DefaultContextMissingStrategy extends LogErrorContextMissingStrategy { }
3,868
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/SamplingRequest.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 java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents the input request to the sampler. Contains attributes relevant to * making sampling decisions. */ public class SamplingRequest { private static final String ARN_SEPARATOR = ":"; private static final int ACCOUNT_INDEX = 4; private String roleArn; @Nullable private String resourceArn; @Nullable private final String service; @Nullable private final String host; @Nullable private final String method; @Nullable private final String url; @Nullable private String serviceType; private final Map<String, String> attributes; /** * @param roleArn * the role of the customer requesting a sampling decision. Must * not be null. * @param resourceArn * the resource for which a sampling decision is being requested. * Ex. "arn:aws:execute-api:us-east-1:1234566789012:qsxrty/test/GET/foo/bar/*". * @param service * the service name for which a sampling decision is being requested. * Ex. "www.foo.com". * @param host * the host name extracted from the incoming request Host header. * @param method * the Http Method extracted from the Request-Line. * @param url * the URL extracted from the Request-Line. * @param serviceType * the service type. * @param attributes * list of key-value pairs generated on a per-request basis. */ public SamplingRequest( String roleArn, @Nullable String resourceArn, @Nullable String service, @Nullable String host, @Nullable String method, @Nullable String url, @Nullable String serviceType, @Nullable Map<String, String> attributes ) { Objects.requireNonNull(roleArn, "RoleARN can not be null"); this.roleArn = roleArn; this.resourceArn = resourceArn; this.service = service; this.host = host; this.method = method; this.url = url; this.serviceType = serviceType; this.attributes = attributes != null ? attributes : Collections.emptyMap(); } public SamplingRequest( @Nullable String service, @Nullable String host, @Nullable String url, @Nullable String method, @Nullable String serviceType) { this.service = service; this.host = host; this.url = url; this.method = method; this.serviceType = serviceType; roleArn = ""; attributes = Collections.emptyMap(); } public Optional<String> getAccountId() { String[] splits = roleArn.split(ARN_SEPARATOR, ACCOUNT_INDEX + 2); if (splits.length < ACCOUNT_INDEX + 2) { return Optional.empty(); } return Optional.of(splits[ACCOUNT_INDEX]); } public String getRoleARN() { return roleArn; } public Optional<String> getResourceARN() { return Optional.ofNullable(resourceArn); } public Optional<String> getService() { return Optional.ofNullable(service); } public Optional<String> getMethod() { return Optional.ofNullable(method); } public Optional<String> getUrl() { return Optional.ofNullable(url); } public Optional<String> getHost() { return Optional.ofNullable(host); } public Optional<String> getServiceType() { return Optional.ofNullable(serviceType); } public Map<String, String> getAttributes() { return attributes; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } }
3,869
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/LocalizedSamplingStrategy.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.manifest.SamplingRuleManifest; import com.amazonaws.xray.strategy.sampling.rule.SamplingRule; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.checkerframework.checker.nullness.qual.Nullable; public class LocalizedSamplingStrategy implements SamplingStrategy { private static final Log logger = LogFactory.getLog(LocalizedSamplingStrategy.class); private final boolean forcedSamplingSupport; // Visible for other sampling strategies static final URL DEFAULT_RULES; static { URL defaultRules = LocalizedSamplingStrategy.class.getResource("/com/amazonaws/xray/strategy/sampling/DefaultSamplingRules.json"); if (defaultRules == null) { throw new IllegalStateException("Could not find DefaultSamplingRules.json on the classpath. This is a packaging bug " + "- did you correctly shade this library?"); } DEFAULT_RULES = defaultRules; } private static final ObjectMapper MAPPER = new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(JsonParser.Feature.ALLOW_COMMENTS, true); private static final List<Integer> SUPPORTED_VERSIONS = Arrays.asList(1, 2); @Nullable private final URL samplingRulesLocation; @Nullable private List<SamplingRule> rules; @Nullable private SamplingRule defaultRule; public LocalizedSamplingStrategy() { this(DEFAULT_RULES, false); } public LocalizedSamplingStrategy(@Nullable URL ruleLocation) { this(ruleLocation, false); } public LocalizedSamplingStrategy(boolean forcedSamplingSupport) { this(DEFAULT_RULES, forcedSamplingSupport); } public LocalizedSamplingStrategy(@Nullable URL ruleLocation, boolean forcedSamplingSupport) { this.samplingRulesLocation = ruleLocation; this.forcedSamplingSupport = forcedSamplingSupport; SamplingRuleManifest manifest = getRuleManifest(ruleLocation); if (manifest != null) { defaultRule = manifest.getDefaultRule(); rules = processRuleManifest(manifest); } } @Nullable public URL getSamplingManifestURL() { return samplingRulesLocation; } private static SamplingRuleManifest getRuleManifest(@Nullable URL ruleLocation) { if (ruleLocation == null) { logger.error("Unable to parse null URL. Falling back to default rule set: " + LocalizedSamplingStrategy.DEFAULT_RULES.getPath()); return getDefaultRuleManifest(); } try { return MAPPER.readValue(ruleLocation, SamplingRuleManifest.class); } catch (IOException ioe) { logger.error("Unable to parse " + ruleLocation.getPath() + ". Falling back to default rule set: " + LocalizedSamplingStrategy.DEFAULT_RULES.getPath(), ioe); return getDefaultRuleManifest(); } } private static SamplingRuleManifest getDefaultRuleManifest() { try { return MAPPER.readValue(LocalizedSamplingStrategy.DEFAULT_RULES, SamplingRuleManifest.class); } catch (IOException ioe) { throw new RuntimeException("Unable to parse " + LocalizedSamplingStrategy.DEFAULT_RULES + ".", ioe); } } private static List<SamplingRule> processRuleManifest(SamplingRuleManifest manifest) { SamplingRule defaultRule = manifest.getDefaultRule(); if (!SUPPORTED_VERSIONS.contains(manifest.getVersion())) { throw newInvalidSamplingRuleManifestException("Manifest version: " + manifest.getVersion() + " is not supported."); } if (defaultRule != null) { if (defaultRule.getUrlPath() != null || defaultRule.getHost() != null || defaultRule.getHttpMethod() != null) { throw newInvalidSamplingRuleManifestException( "The default rule must not specify values for url_path, host, or http_method."); } else if (defaultRule.getFixedTarget() < 0 || defaultRule.getRate() < 0) { throw newInvalidSamplingRuleManifestException( "The default rule must specify non-negative values for fixed_target and rate."); } List<SamplingRule> rules = manifest.getRules(); if (rules != null) { for (SamplingRule rule : rules) { if (manifest.getVersion() == 1) { rule.setHost(rule.getServiceName()); } if (rule.getUrlPath() == null || rule.getHost() == null || rule.getHttpMethod() == null) { throw newInvalidSamplingRuleManifestException( "All rules must have values for url_path, host, and http_method."); } else if (rule.getFixedTarget() < 0 || rule.getRate() < 0) { throw newInvalidSamplingRuleManifestException( "All rules must have non-negative values for fixed_target and rate."); } } return rules; } else { return new ArrayList<>(); } } else { throw newInvalidSamplingRuleManifestException("A default rule must be provided."); } } private static RuntimeException newInvalidSamplingRuleManifestException(String detail) { return new RuntimeException("Invalid sampling rule manifest provided. " + detail); } @Override public SamplingResponse shouldTrace(SamplingRequest samplingRequest) { if (logger.isDebugEnabled()) { logger.debug("Determining shouldTrace decision for:\n\thost: " + samplingRequest.getHost().orElse("") + "\n\tpath: " + samplingRequest.getUrl().orElse("") + "\n\tmethod: " + samplingRequest.getMethod().orElse("")); } SamplingResponse sampleResponse = new SamplingResponse(); SamplingRule firstApplicableRule = null; if (rules != null) { firstApplicableRule = rules.stream() .filter(rule -> rule.appliesTo(samplingRequest.getHost().orElse(""), samplingRequest.getUrl().orElse(""), samplingRequest.getMethod().orElse(""))) .findFirst().orElse(null); } sampleResponse.setSampled(firstApplicableRule == null ? shouldTrace(defaultRule) : shouldTrace(firstApplicableRule)); return sampleResponse; } private boolean shouldTrace(@Nullable SamplingRule samplingRule) { if (logger.isDebugEnabled()) { logger.debug("Applicable sampling rule: " + samplingRule); } if (samplingRule == null) { return false; } if (samplingRule.getReservoir().take()) { return true; } else { return ThreadLocalRandom.current().nextFloat() < samplingRule.getRate(); } } @Override public boolean isForcedSamplingSupported() { return forcedSamplingSupport; } }
3,870
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/CentralizedSamplingStrategy.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.internal.UnsignedXrayClient; import com.amazonaws.xray.strategy.sampling.manifest.CentralizedManifest; import com.amazonaws.xray.strategy.sampling.pollers.RulePoller; import com.amazonaws.xray.strategy.sampling.pollers.TargetPoller; import com.amazonaws.xray.strategy.sampling.rule.CentralizedRule; import com.amazonaws.xray.utils.ByteUtils; import java.net.URL; import java.security.SecureRandom; import java.time.Clock; import java.time.Instant; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.checkerframework.checker.nullness.qual.Nullable; public class CentralizedSamplingStrategy implements SamplingStrategy { private static final Log logger = LogFactory.getLog(TargetPoller.class); // Initialize random ClientID. We use the same ClientID for all GetSamplingTargets calls. Conflicts are avoided // because IDs are scoped to a single account. private static final String clientID; static { SecureRandom rand = new SecureRandom(); byte[] bytes = new byte[12]; rand.nextBytes(bytes); String clientId = ByteUtils.byteArrayToHexString(bytes); if (clientId == null) { // Satisfy checker framework. throw new IllegalStateException(); } clientID = clientId; } private final CentralizedManifest manifest; private final LocalizedSamplingStrategy fallback; private final RulePoller rulePoller; private final TargetPoller targetPoller; private final boolean forcedSamplingSupport; private boolean isStarted = false; public CentralizedSamplingStrategy() { this(LocalizedSamplingStrategy.DEFAULT_RULES, false); } public CentralizedSamplingStrategy(@Nullable URL ruleLocation) { this(ruleLocation, false); } public CentralizedSamplingStrategy(boolean forcedSamplingSupport) { this(LocalizedSamplingStrategy.DEFAULT_RULES, forcedSamplingSupport); } public CentralizedSamplingStrategy(@Nullable URL ruleLocation, boolean forcedSamplingSupport) { this.manifest = new CentralizedManifest(); this.fallback = new LocalizedSamplingStrategy(ruleLocation); UnsignedXrayClient client = new UnsignedXrayClient(); this.rulePoller = new RulePoller(client, manifest, Clock.systemUTC()); this.targetPoller = new TargetPoller(client, manifest, Clock.systemUTC()); this.forcedSamplingSupport = forcedSamplingSupport; } @Nullable public URL getSamplingManifestURL() { return this.fallback.getSamplingManifestURL(); } @Override public SamplingResponse shouldTrace(SamplingRequest samplingRequest) { if (!isStarted) { startPoller(); } SamplingResponse sampleResponse; if (logger.isDebugEnabled()) { logger.debug("Determining shouldTrace decision for:\n\tserviceName: " + samplingRequest.getService().orElse("") + "\n\thost: " + samplingRequest.getHost().orElse("") + "\n\tpath: " + samplingRequest.getUrl().orElse("") + "\n\tmethod: " + samplingRequest.getMethod().orElse("") + "\n\tserviceType: " + samplingRequest.getServiceType().orElse("")); } if (manifest.isExpired(Instant.now())) { logger.debug("Centralized sampling data expired. Using fallback sampling strategy."); return fallback.shouldTrace(samplingRequest); } for (CentralizedRule rule : manifest.getRules().values()) { boolean applicable = rule.match(samplingRequest); if (!applicable) { continue; } if (logger.isDebugEnabled()) { logger.debug("Applicable rule:" + rule.getName()); } SamplingResponse response = rule.sample(Instant.now()); if (logger.isDebugEnabled()) { logger.debug("Segment " + samplingRequest.getService().orElse("") + " has" + (response.isSampled() ? " " : " NOT ") + "been sampled."); } return response; } // Match against default rule CentralizedRule dRule = manifest.getDefaultRule(); if (dRule != null) { logger.debug("Applicable default rule: " + dRule.getName()); return dRule.sample(Instant.now()); } logger.debug("Centralized default sampling rule unavailable. Using fallback sampling strategy."); sampleResponse = fallback.shouldTrace(samplingRequest); return sampleResponse; } @Override /** * Shutdown all poller threads immediately regardless of the pending work for clean exit. */ public void shutdown() { rulePoller.shutdown(); targetPoller.shutdown(); } public static String getClientID() { return clientID; } // This method needs to be thread-safe. private synchronized void startPoller() { if (isStarted) { return; } rulePoller.start(); targetPoller.start(); isStarted = true; } @Override public boolean isForcedSamplingSupported() { return forcedSamplingSupport; } }
3,871
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/DefaultSamplingStrategy.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; public class DefaultSamplingStrategy extends CentralizedSamplingStrategy { public DefaultSamplingStrategy() { super(); } }
3,872
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/XRayClient.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.ClientConfiguration; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.AnonymousAWSCredentials; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.xray.AWSXRay; import com.amazonaws.services.xray.AWSXRayClientBuilder; import com.amazonaws.xray.config.DaemonConfiguration; /** * @deprecated aws-xray-recorder only supports communicating with the X-Ray daemon, which does not * require the usual AWS API signatures so we have stopped using the SDK X-Ray client. */ @Deprecated public final class XRayClient { private static final AWSCredentialsProvider ANONYMOUS_CREDENTIALS = new AWSStaticCredentialsProvider( new AnonymousAWSCredentials()); private static final String DUMMY_REGION = "us-west-1"; // Ignored because we use anonymous credentials private static final int TIME_OUT = 2000; // Milliseconds private XRayClient() { } /** * * @deprecated aws-xray-recorder only supports communicating with the X-Ray daemon, which does * not require the usual AWS API signatures so we have stopped using the SDK X-Ray client. */ @Deprecated public static AWSXRay newClient() { DaemonConfiguration config = new DaemonConfiguration(); ClientConfiguration clientConfig = new ClientConfiguration() .withRequestTimeout(TIME_OUT); AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration( config.getEndpointForTCPConnection(), DUMMY_REGION ); return AWSXRayClientBuilder.standard() .withEndpointConfiguration(endpointConfig) .withClientConfiguration(clientConfig) .withCredentials(ANONYMOUS_CREDENTIALS) // This will entirely skip signing too .build(); } }
3,873
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/AllSamplingStrategy.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; /** * A sampling strategy for which {@code shouldTrace} always returns true. Use this sampling strategy to trace every request. * */ public class AllSamplingStrategy implements SamplingStrategy { @Override public SamplingResponse shouldTrace(SamplingRequest samplingRequest) { SamplingResponse sampleResponse = new SamplingResponse(true); return sampleResponse; } @Override public boolean isForcedSamplingSupported() { return false; } }
3,874
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/NoSamplingStrategy.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; /** * A sampling strategy for which {@code shouldTrace} always returns false. Use this sampling strategy to completely disable * tracing. * */ public class NoSamplingStrategy implements SamplingStrategy { @Override public SamplingResponse shouldTrace(SamplingRequest samplingRequest) { SamplingResponse sampleResponse = new SamplingResponse(false, ""); return sampleResponse; } @Override public boolean isForcedSamplingSupported() { return false; } }
3,875
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/SamplingStrategy.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; public interface SamplingStrategy { SamplingResponse shouldTrace(SamplingRequest sampleRequest); /** * Returns whether or not this sampling strategy supports 'forced sampling'. * * Forced sampling allows a segment's initial non-sampled decision to be later overriden to sampled. Supporting this feature * requires that all segments, sampled or otherwise, be kept in memory for the duration of their existence. Not supporting * this feature saves memory and computational capacity. * * @return whether or not forced sampling is supported */ boolean isForcedSamplingSupported(); /** * Shutdown additional resources created by advanced sampling strategies. */ default void shutdown() { } }
3,876
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/SamplingResponse.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 java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents the sampling decision output by the sampler. Used by the SDK to * decide whether or not a segment should be emitted. */ public class SamplingResponse { private boolean sampled; @Nullable private String ruleName; /** * @param sampled * the boolean sampling decision * @param ruleName * the name of the rule used to make the sampling decision */ public SamplingResponse(boolean sampled, String ruleName) { this.sampled = sampled; this.ruleName = ruleName; } public SamplingResponse(String ruleName) { this.ruleName = ruleName; } public SamplingResponse(boolean sampled) { this.sampled = sampled; } public SamplingResponse() { } public boolean isSampled() { return sampled; } public Optional<String> getRuleName() { return Optional.ofNullable(ruleName); } public SamplingResponse setSampled(boolean sampled) { this.sampled = sampled; return this; } }
3,877
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/reservoir/CentralizedReservoir.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 com.amazonaws.services.xray.model.SamplingRule; import com.amazonaws.services.xray.model.SamplingTargetDocument; import java.time.Instant; public class CentralizedReservoir { private static final long DEFAULT_INTERVAL = 10; // Seconds private long capacity; private long quota; private long used; private long currentEpoch; private long interval; private boolean borrow; private Instant refreshedAt; private Instant expiresAt; public CentralizedReservoir(long capacity) { this.capacity = capacity; this.expiresAt = Instant.EPOCH; this.refreshedAt = Instant.EPOCH; this.interval = DEFAULT_INTERVAL; } public void update(SamplingRule r) { capacity = r.getReservoirSize().longValue(); } public boolean isExpired(Instant now) { return now.isAfter(expiresAt); } public boolean isBorrow(Instant now) { if (now.getEpochSecond() != currentEpoch) { reset(now); } boolean b = borrow; borrow = true; return !b && capacity != 0; } public boolean isStale(Instant now) { return now.isAfter(refreshedAt.plusSeconds(interval)); } public void update(SamplingTargetDocument target, Instant now) { if (target.getReservoirQuota() != null) { quota = target.getReservoirQuota(); } if (target.getReservoirQuotaTTL() != null) { expiresAt = target.getReservoirQuotaTTL().toInstant(); } if (target.getInterval() != null) { interval = target.getInterval(); } refreshedAt = now; } public boolean take(Instant now) { // We have moved to a new epoch. Reset reservoir. if (now.getEpochSecond() != currentEpoch) { reset(now); } if (quota > used) { used++; return true; } return false; } void reset(Instant now) { currentEpoch = now.getEpochSecond(); used = 0; borrow = false; } public long getQuota() { return quota; } public long getUsed() { return used; } public long getCurrentEpoch() { return currentEpoch; } public long getInterval() { return interval; } }
3,878
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/reservoir/Reservoir.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 java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public class Reservoir { static final long NANOS_PER_SECOND = TimeUnit.SECONDS.toNanos(1); static final int NANOS_PER_DECISECOND = (int) (NANOS_PER_SECOND / 10); private final int tracesPerSecond; private final MaxFunction maxFunction; private final AtomicInteger usage = new AtomicInteger(0); private final AtomicLong nextReset; public Reservoir() { this(0); } public Reservoir(int tracesPerSecond) { this.tracesPerSecond = tracesPerSecond; this.maxFunction = tracesPerSecond < 10 ? new LessThan10(tracesPerSecond) : new AtLeast10(tracesPerSecond); long now = System.nanoTime(); this.nextReset = new AtomicLong(now + NANOS_PER_SECOND); } public boolean take() { long now = System.nanoTime(); long updateAt = nextReset.get(); long nanosUntilReset = -(now - updateAt); // because nanoTime can be negative boolean shouldReset = nanosUntilReset <= 0; if (shouldReset) { if (nextReset.compareAndSet(updateAt, now + NANOS_PER_SECOND)) { usage.set(0); } } int max = maxFunction.max(shouldReset ? 0 : nanosUntilReset); int prev; int next; do { // same form as java 8 AtomicLong.getAndUpdate prev = usage.get(); next = prev + 1; if (next > max) { return false; } } while (!usage.compareAndSet(prev, next)); return true; } /** * @return the tracesPerSecond */ public int getTracesPerSecond() { return tracesPerSecond; } abstract static class MaxFunction { /** @param nanosUntilReset zero if was just reset */ abstract int max(long nanosUntilReset); } /** For a reservoir of less than 10, we permit draining it completely at any time in the second */ static final class LessThan10 extends MaxFunction { final int tracesPerSecond; LessThan10(int tracesPerSecond) { this.tracesPerSecond = tracesPerSecond; } @Override int max(long nanosUntilReset) { return tracesPerSecond; } } /** * For a reservoir of at least 10, we permit draining up to a decisecond watermark. Because the * rate could be odd, we may have a remainder, which is arbitrarily available. We allow any * remainders in the 1st decisecond or any time thereafter. * * <p>Ex. If the rate is 10/s then you can use 1 in the first decisecond, another 1 in the 2nd, * or up to 10 by the last. * * <p>Ex. If the rate is 103/s then you can use 13 in the first decisecond, another 10 in the * 2nd, or up to 103 by the last. */ static final class AtLeast10 extends MaxFunction { final int[] max; AtLeast10(int tracesPerSecond) { int tracesPerDecisecond = tracesPerSecond / 10; int remainder = tracesPerSecond % 10; max = new int[10]; max[0] = tracesPerDecisecond + remainder; for (int i = 1; i < 10; i++) { max[i] = max[i - 1] + tracesPerDecisecond; } } @Override int max(long nanosUntilReset) { if (nanosUntilReset == 0) { return max[0]; } int decisecondsUntilReset = Math.max((int) nanosUntilReset / NANOS_PER_DECISECOND, 1); int index = 10 - decisecondsUntilReset; return max[index]; } } }
3,879
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/manifest/SamplingRuleManifest.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.xray.strategy.sampling.rule.SamplingRule; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; public class SamplingRuleManifest { @Nullable private List<SamplingRule> rules; @JsonProperty("default") // default is a reserved word @Nullable private SamplingRule defaultRule; private int version; /** * @return the rules */ @Nullable public List<SamplingRule> getRules() { return rules; } /** * @param rules the rules to set */ public void setRules(List<SamplingRule> rules) { this.rules = rules; } /** * @return the defaultRule */ @Nullable public SamplingRule getDefaultRule() { return defaultRule; } /** * @param defaultRule the defaultRule to set */ public void setDefaultRule(SamplingRule defaultRule) { this.defaultRule = defaultRule; } /** * @return the version */ public int getVersion() { return version; } /** * @param version the version to set */ public void setVersion(int version) { this.version = version; } }
3,880
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/manifest/Manifest.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.xray.strategy.sampling.SamplingRequest; import com.amazonaws.xray.strategy.sampling.rule.Rule; import java.time.Instant; import org.checkerframework.checker.nullness.qual.Nullable; public interface Manifest { @Nullable Rule match(SamplingRequest req, Instant now); }
3,881
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/manifest/CentralizedManifest.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.services.xray.model.SamplingTargetDocument; import com.amazonaws.xray.strategy.sampling.CentralizedSamplingStrategy; import com.amazonaws.xray.strategy.sampling.SamplingRequest; import com.amazonaws.xray.strategy.sampling.rand.RandImpl; import com.amazonaws.xray.strategy.sampling.rule.CentralizedRule; import com.amazonaws.xray.strategy.sampling.rule.Rule; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; public class CentralizedManifest implements Manifest { private static final long TTL = 3600; // Seconds // Map of customer-defined rules. Does not include customer default rule. Sorted by rule priority. private volatile LinkedHashMap<String, CentralizedRule> rules; // Customer default rule that matches against everything. @MonotonicNonNull private volatile CentralizedRule defaultRule; // Timestamp of last known valid refresh. Kept volatile for swapping with new timestamp on refresh. private volatile Instant refreshedAt; public CentralizedManifest() { this.rules = new LinkedHashMap<>(0); this.refreshedAt = Instant.EPOCH; } public LinkedHashMap<String, CentralizedRule> getRules() { return rules; } @Nullable public CentralizedRule getDefaultRule() { return defaultRule; } public boolean isExpired(Instant now) { return refreshedAt.plusSeconds(TTL).isBefore(now); } public int size() { if (defaultRule != null) { return rules.size() + 1; } return rules.size(); } @Override // TODO(anuraaga): It seems like this should never return null, check where defaultRule is guaranteed to be present and remove @Nullable public Rule match(SamplingRequest req, Instant now) { for (CentralizedRule r : rules.values()) { if (!r.match(req)) { continue; } return r; } return defaultRule; } public void putRules(List<SamplingRule> inputs, Instant now) { // Set to true if we see a new or deleted rule or a change in the priority of an existing rule. boolean invalidate = false; Map<String, CentralizedRule> rules = this.rules; List<String> inputNames = new ArrayList<>(inputs.size()); for (SamplingRule i : inputs) { if (i.getRuleName().equals(CentralizedRule.DEFAULT_RULE_NAME)) { putDefaultRule(i); } else { inputNames.add(i.getRuleName()); invalidate = putCustomRule(rules, i); } } // Check if any rule was removed if (!invalidate) { for (CentralizedRule rule : rules.values()) { if (!inputNames.contains(rule.getName())) { invalidate = true; break; } } } if (invalidate) { this.rules = rebuild(rules, inputs); } this.refreshedAt = now; } public List<SamplingStatisticsDocument> snapshots(Instant now) { List<SamplingStatisticsDocument> snapshots = new ArrayList<>(rules.size() + 1); Date date = Date.from(now); for (CentralizedRule rule : rules.values()) { if (!rule.isStale(now)) { continue; } SamplingStatisticsDocument snapshot = rule.snapshot(date); snapshot.withClientID(CentralizedSamplingStrategy.getClientID()); snapshots.add(snapshot); } if (defaultRule != null && defaultRule.isStale(now)) { SamplingStatisticsDocument snapshot = defaultRule.snapshot(date); snapshot.withClientID(CentralizedSamplingStrategy.getClientID()); snapshots.add(snapshot); } return snapshots; } public void putTargets(List<SamplingTargetDocument> targets, Instant now) { Map<String, CentralizedRule> rules = this.rules; for (SamplingTargetDocument t : targets) { CentralizedRule r = null; if (rules.containsKey(t.getRuleName())) { r = rules.get(t.getRuleName()); } else if (t.getRuleName().equals(CentralizedRule.DEFAULT_RULE_NAME)) { r = defaultRule; } if (r == null) { continue; } r.update(t, now); } } private boolean putCustomRule(Map<String, CentralizedRule> rules, SamplingRule i) { CentralizedRule r = rules.get(i.getRuleName()); if (r == null) { return true; } return r.update(i); } private void putDefaultRule(SamplingRule i) { if (defaultRule == null) { defaultRule = new CentralizedRule(i, new RandImpl()); } else { defaultRule.update(i); } } LinkedHashMap<String, CentralizedRule> rebuild(Map<String, CentralizedRule> old, List<SamplingRule> inputs) { List<CentralizedRule> rules = new ArrayList<>(inputs.size() - 1); for (SamplingRule i : inputs) { if (i.getRuleName().equals(CentralizedRule.DEFAULT_RULE_NAME)) { continue; } CentralizedRule r = old.get(i.getRuleName()); if (r == null) { r = new CentralizedRule(i, new RandImpl()); } rules.add(r); } Collections.sort(rules); LinkedHashMap<String, CentralizedRule> current = new LinkedHashMap<>(rules.size()); for (CentralizedRule r: rules) { current.put(r.getName(), r); } return current; } }
3,882
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/rule/SamplingRule.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.xray.entities.SearchPattern; import com.amazonaws.xray.strategy.sampling.reservoir.Reservoir; import org.checkerframework.checker.nullness.qual.Nullable; public class SamplingRule { @Nullable private String host; @Nullable private String serviceName; @Nullable private String httpMethod; @Nullable private String urlPath; private int fixedTarget = -1; private float rate = -1.0f; private Reservoir reservoir; public SamplingRule() { this.reservoir = new Reservoir(); } /** * Constructs a new {@code SamplingRule}. Patterns are supported in the {@code host}, {@code httpMethod}, and {@code urlPath} * parameters. Patterns are matched using the {@link com.amazonaws.xray.entities.SearchPattern} class. * * @param host * the host name for which the rule should apply * @param serviceName * the service name for which the rule should apply * @param httpMethod * the http method for which the rule should apply * @param urlPath * the urlPath for which the rule should apply * @param fixedTarget * the number of traces per any given second for which the sampling rule will sample * @param rate * the rate at which the rule should sample, after the fixedTarget has been reached */ public SamplingRule(String host, String serviceName, String httpMethod, String urlPath, int fixedTarget, float rate) { this.host = host; this.serviceName = serviceName; this.httpMethod = httpMethod; this.urlPath = urlPath; this.fixedTarget = fixedTarget; this.rate = rate; this.reservoir = new Reservoir(fixedTarget); } /** * @return the serviceName */ @Nullable public String getServiceName() { return serviceName; } /** * @param serviceName * the serviceName to set */ public void setServiceName(String serviceName) { this.serviceName = serviceName; } /** * @return the host */ @Nullable public String getHost() { return host; } /** * @param host * the host to set */ public void setHost(@Nullable String host) { this.host = host; } /** * @return the httpMethod */ @Nullable public String getHttpMethod() { return httpMethod; } /** * @param httpMethod * the httpMethod to set */ public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; } /** * @return the urlPath */ @Nullable public String getUrlPath() { return urlPath; } /** * @param urlPath * the urlPath to set */ public void setUrlPath(String urlPath) { this.urlPath = urlPath; } /** * @return the fixedTarget */ public int getFixedTarget() { return fixedTarget; } /** * @param fixedTarget * the fixedTarget to set */ public void setFixedTarget(int fixedTarget) { this.fixedTarget = fixedTarget; this.reservoir = new Reservoir(fixedTarget); } /** * @return the rate */ public float getRate() { return rate; } /** * @param rate * the rate to set */ public void setRate(float rate) { this.rate = rate; } /** * @return the reservoir */ public Reservoir getReservoir() { return reservoir; } @Override public String toString() { return "\n\thost: " + host + "\n\thttp_method: " + httpMethod + "\n\turl_path: " + urlPath + "\n\tfixed_target: " + fixedTarget + "\n\trate: " + rate; } /** * Determines whether or not this sampling rule applies to the incoming request based on some of the request's parameters. Any * null parameters provided will be considered an implicit match. For example, {@code appliesTo(null, null, null)} will always * return {@code true}, for any rule. * * @param requestHost * the host name for the incoming request. * @param requestPath * the path from the incoming request * @param requestMethod * the method used to make the incoming request * @return whether or not this rule applies to the incoming request */ public boolean appliesTo(String requestHost, String requestPath, String requestMethod) { return (requestHost == null || SearchPattern.wildcardMatch(host, requestHost)) && (requestPath == null || SearchPattern.wildcardMatch(urlPath, requestPath)) && (requestMethod == null || SearchPattern.wildcardMatch(httpMethod, requestMethod)); } }
3,883
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/rule/Matchers.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.entities.SearchPattern; import com.amazonaws.xray.strategy.sampling.SamplingRequest; import java.util.Collections; import java.util.Map; public class Matchers { private Map<String, String> attributes; private String service; private String method; private String host; private String url; private String serviceType; public Matchers(SamplingRule r) { this.host = r.getHost(); this.service = r.getServiceName(); this.method = r.getHTTPMethod(); this.url = r.getURLPath(); this.serviceType = r.getServiceType(); this.attributes = r.getAttributes() == null ? Collections.emptyMap() : r.getAttributes(); } boolean match(SamplingRequest req) { // Comparing against the full list of matchers can be expensive. We try to short-circuit the req as quickly // as possible by comparing against matchers with high variance and moving down to matchers that are almost // always "*". Map<String, String> requestAttributes = req.getAttributes(); // Ensure that each defined attribute in the sampling rule is satisfied by the request. It is okay for the // request to have attributes with no corresponding match in the sampling rule. for (Map.Entry<String, String> a : attributes.entrySet()) { if (!requestAttributes.containsKey(a.getKey())) { return false; } if (!SearchPattern.wildcardMatch(a.getValue(), requestAttributes.get(a.getKey()))) { return false; } } // Missing string parameters from the sampling request are replaced with ""s to ensure they match against * // matchers. return SearchPattern.wildcardMatch(url, req.getUrl().orElse("")) && SearchPattern.wildcardMatch(service, req.getService().orElse("")) && SearchPattern.wildcardMatch(method, req.getMethod().orElse("")) && SearchPattern.wildcardMatch(host, req.getHost().orElse("")) && SearchPattern.wildcardMatch(serviceType, req.getServiceType().orElse("")); } }
3,884
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/rule/Statistics.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; /** * Per-Rule statistics maintained by the sampler. Used for making sampling * decisions and for reporting rule usage to X-Ray. */ public class Statistics { private int requests; private int sampled; private int borrowed; public void reset() { requests = 0; sampled = 0; borrowed = 0; } public void incRequest() { requests++; } public void incSampled() { sampled++; } public void incBorrowed() { borrowed++; } public int getRequests() { return requests; } public int getSampled() { return sampled; } public int getBorrowed() { return borrowed; } }
3,885
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/rule/CentralizedRule.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.SamplingRequest; import com.amazonaws.xray.strategy.sampling.SamplingResponse; import com.amazonaws.xray.strategy.sampling.rand.Rand; import com.amazonaws.xray.strategy.sampling.reservoir.CentralizedReservoir; import java.time.Instant; import java.util.Date; import java.util.Objects; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents a customer-defined sampling rule. A rule contains the matchers * required to determine if an incoming request can use the rule, and sampling * targets which determine the sampling behavior once a request has been * matched. * * A rule also maintains usage statistics which are periodically reported to * X-Ray. */ public class CentralizedRule implements Rule, Comparable<CentralizedRule> { public static final String DEFAULT_RULE_NAME = "Default"; private static final Log logger = LogFactory.getLog(CentralizedRule.class); private int priority = 10000; // Default // Rule Name identifying this rule. private final String name; private final CentralizedReservoir centralizedReservoir; private double fixedRate; private final Statistics statistics; // Null for customer default rule. @Nullable private Matchers matchers; private final Rand rand; private final ReadWriteLock lock; public CentralizedRule(SamplingRule input, Rand rand) { this.name = input.getRuleName(); this.centralizedReservoir = new CentralizedReservoir(input.getReservoirSize()); this.fixedRate = input.getFixedRate(); this.statistics = new Statistics(); if (!input.getRuleName().equals(DEFAULT_RULE_NAME)) { this.matchers = new Matchers(input); this.priority = input.getPriority(); } this.rand = rand; this.lock = new ReentrantReadWriteLock(); } public boolean update(SamplingRule i) { boolean rebuild = false; Matchers m = new Matchers(i); lock.writeLock().lock(); try { fixedRate = i.getFixedRate(); if (priority != i.getPriority()) { rebuild = true; } priority = i.getPriority(); fixedRate = i.getFixedRate(); matchers = m; centralizedReservoir.update(i); } finally { lock.writeLock().unlock(); } return rebuild; } // Returns true if the rule is due for a target refresh. False otherwise. public boolean isStale(Instant now) { lock.readLock().lock(); try { return statistics.getRequests() > 0 && centralizedReservoir.isStale(now); } finally { lock.readLock().unlock(); } } public static boolean isValid(SamplingRule rule) { if (rule.getRuleName() == null || rule.getPriority() == null || rule.getReservoirSize() == null || rule.getFixedRate() == null || rule.getVersion() != 1) { logger.error("Detect invalid rule. Please check sampling rule format."); return false; } if (!rule.getResourceARN().equals("*") || !rule.getAttributes().isEmpty()) { logger.error("Detect invalid rule. Please check sampling rule format."); return false; } if (rule.getHost() == null || rule.getServiceName() == null || rule.getHTTPMethod() == null || rule.getURLPath() == null || rule.getServiceType() == null) { logger.error("Detect invalid rule. Please check sampling rule format."); return false; } if (rule.getRuleName().equals(DEFAULT_RULE_NAME)) { return true; } return true; } public void update(SamplingTargetDocument t, Instant now) { lock.writeLock().lock(); try { centralizedReservoir.update(t, now); fixedRate = t.getFixedRate(); } finally { lock.writeLock().unlock(); } } public SamplingStatisticsDocument snapshot(Date now) { SamplingStatisticsDocument s = new SamplingStatisticsDocument() .withRuleName(name) .withTimestamp(now); lock.writeLock().lock(); try { s.setRequestCount(statistics.getRequests()); s.setSampledCount(statistics.getSampled()); s.setBorrowCount(statistics.getBorrowed()); statistics.reset(); } finally { lock.writeLock().unlock(); } return s; } public boolean match(SamplingRequest r) { lock.readLock().lock(); try { return matchers != null ? matchers.match(r) : true; } finally { lock.readLock().unlock(); } } @Override public SamplingResponse sample(Instant now) { SamplingResponse res = new SamplingResponse(name); double rn = rand.next(); lock.writeLock().lock(); try { return doSample(now, res, rn); } finally { lock.writeLock().unlock(); } } private SamplingResponse doSample(Instant now, SamplingResponse res, double random) { statistics.incRequest(); return doSampleCustomerRule(now, res, random); } private SamplingResponse doSampleCustomerRule(Instant now, SamplingResponse res, double random) { if (centralizedReservoir.isExpired(now)) { // Attempt to borrow request if (centralizedReservoir.isBorrow(now)) { logger.debug("Sampling target has expired for rule " + getName() + ". Borrowing a request."); statistics.incBorrowed(); res.setSampled(true); return res; } if (logger.isDebugEnabled()) { logger.debug("Sampling target has expired for rule " + getName() + ". Using fixed rate of " + (int) (fixedRate * 100) + " percent."); } // Fallback to bernoulli sampling if (random < fixedRate) { statistics.incSampled(); res.setSampled(true); return res; } return res; } // CentralizedReservoir has a valid quota. Consume a unit, if available. if (centralizedReservoir.take(now)) { statistics.incSampled(); res.setSampled(true); logger.debug("Sampling target has been exhausted for rule " + getName() + ". Using fixed request."); return res; } // Fallback to bernoulli sampling if (random < fixedRate) { statistics.incSampled(); res.setSampled(true); return res; } return res; } @Override public int compareTo(CentralizedRule other) { lock.readLock().lock(); try { if (this.priority < other.priority) { return -1; } else if (this.priority > other.priority) { return 1; } return this.getName().compareTo(other.getName()); } finally { lock.readLock().unlock(); } } public String getName() { return name; } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (!(o instanceof CentralizedRule)) { return false; } CentralizedRule that = (CentralizedRule) o; if (priority != that.priority) { return false; } if (Double.compare(that.fixedRate, fixedRate) != 0) { return false; } if (!name.equals(that.name)) { return false; } if (!centralizedReservoir.equals(that.centralizedReservoir)) { return false; } if (!statistics.equals(that.statistics)) { return false; } return Objects.equals(matchers, that.matchers); } @Override public int hashCode() { int result; long temp; result = name.hashCode(); result = 31 * result + priority; result = 31 * result + centralizedReservoir.hashCode(); temp = Double.doubleToLongBits(fixedRate); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + statistics.hashCode(); result = 31 * result + (matchers != null ? matchers.hashCode() : 0); return result; } }
3,886
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/rule/Rule.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.xray.strategy.sampling.SamplingResponse; import java.time.Instant; public interface Rule { SamplingResponse sample(Instant now); }
3,887
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/rand/RandImpl.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.rand; import java.util.Random; public class RandImpl implements Rand { private Random rand; public RandImpl() { this.rand = new Random(System.nanoTime()); } @Override public double next() { return rand.nextDouble(); } }
3,888
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/rand/Rand.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.rand; public interface Rand { double next(); }
3,889
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/pollers/TargetPoller.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 com.amazonaws.services.xray.AWSXRay; import com.amazonaws.services.xray.model.GetSamplingTargetsRequest; import com.amazonaws.services.xray.model.GetSamplingTargetsResult; import com.amazonaws.services.xray.model.SamplingStatisticsDocument; import com.amazonaws.xray.internal.UnsignedXrayClient; import com.amazonaws.xray.strategy.sampling.manifest.CentralizedManifest; import com.amazonaws.xray.strategy.sampling.rand.Rand; import com.amazonaws.xray.strategy.sampling.rand.RandImpl; import java.time.Clock; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.checkerframework.checker.nullness.qual.Nullable; public class TargetPoller { private static final Log logger = LogFactory.getLog(TargetPoller.class); private static final long PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(10); private static final long MAX_JITTER_MILLIS = 100; private final UnsignedXrayClient client; private final CentralizedManifest manifest; private final Clock clock; private final ScheduledExecutorService executor; @Nullable private volatile ScheduledFuture<?> pollFuture; /** * @deprecated Use {@link #TargetPoller(UnsignedXrayClient, CentralizedManifest, Clock)}. */ @Deprecated public TargetPoller(CentralizedManifest manifest, AWSXRay unused, Clock clock) { this(new UnsignedXrayClient(), manifest, clock); } public TargetPoller(UnsignedXrayClient client, CentralizedManifest manifest, Clock clock) { this.client = client; this.manifest = manifest; this.clock = clock; executor = Executors.newSingleThreadScheduledExecutor(); } public void start() { pollFuture = executor.scheduleAtFixedRate(() -> { try { pollManifest(); } catch (Throwable t) { logger.info("Encountered error polling GetSamplingTargets: ", t); // Propagate if Error so executor stops executing. // TODO(anuraaga): Many Errors aren't fatal, this should probably be more restricted, e.g. // https://github.com/openzipkin/brave/blob/master/brave/src/main/java/brave/internal/Throwables.java if (t instanceof Error) { throw t; } } }, PERIOD_MILLIS, getIntervalWithJitter(), TimeUnit.MILLISECONDS); } public void shutdown() { if (pollFuture != null) { pollFuture.cancel(true); } executor.shutdownNow(); } // Visible for testing ScheduledExecutorService getExecutor() { return executor; } private void pollManifest() { List<SamplingStatisticsDocument> statistics = manifest.snapshots(clock.instant()); if (statistics.size() == 0) { logger.trace("No statistics to report. Not refreshing sampling targets."); return; } logger.debug("Polling sampling targets."); GetSamplingTargetsRequest req = new GetSamplingTargetsRequest() .withSamplingStatisticsDocuments(statistics); GetSamplingTargetsResult result = client.getSamplingTargets(req); manifest.putTargets(result.getSamplingTargetDocuments(), clock.instant()); } private long getIntervalWithJitter() { Rand random = new RandImpl(); return Math.round(random.next() * MAX_JITTER_MILLIS) + PERIOD_MILLIS; } }
3,890
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/sampling/pollers/RulePoller.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 com.amazonaws.services.xray.AWSXRay; import com.amazonaws.services.xray.model.GetSamplingRulesRequest; import com.amazonaws.services.xray.model.GetSamplingRulesResult; import com.amazonaws.services.xray.model.SamplingRule; import com.amazonaws.services.xray.model.SamplingRuleRecord; import com.amazonaws.xray.internal.UnsignedXrayClient; import com.amazonaws.xray.strategy.sampling.manifest.CentralizedManifest; import com.amazonaws.xray.strategy.sampling.rand.Rand; import com.amazonaws.xray.strategy.sampling.rand.RandImpl; import com.amazonaws.xray.strategy.sampling.rule.CentralizedRule; import java.time.Clock; import java.time.Instant; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.checkerframework.checker.nullness.qual.Nullable; public class RulePoller { private static final Log logger = LogFactory.getLog(RulePoller.class); private static final long PERIOD = 300; // Seconds private static final long MAX_JITTER = 5; // Seconds private final UnsignedXrayClient client; private final CentralizedManifest manifest; private final Clock clock; private final ScheduledExecutorService executor; @Nullable private volatile ScheduledFuture<?> pollFuture; /** * @deprecated Use {@link #RulePoller(UnsignedXrayClient, CentralizedManifest, Clock)}. */ @Deprecated public RulePoller(CentralizedManifest manifest, AWSXRay unused, Clock clock) { this(new UnsignedXrayClient(), manifest, clock); } public RulePoller(UnsignedXrayClient client, CentralizedManifest manifest, Clock clock) { this.client = client; this.manifest = manifest; this.clock = clock; executor = Executors.newSingleThreadScheduledExecutor(); } public void start() { pollFuture = executor.scheduleAtFixedRate(() -> { try { pollRule(); } catch (Throwable t) { logger.info("Encountered error polling GetSamplingRules: ", t); // Propagate if Error so executor stops executing. // TODO(anuraaga): Many Errors aren't fatal, this should probably be more restricted, e.g. // https://github.com/openzipkin/brave/blob/master/brave/src/main/java/brave/internal/Throwables.java if (t instanceof Error) { throw t; } } }, 0, getIntervalWithJitter(), TimeUnit.SECONDS); } public void shutdown() { if (pollFuture != null) { pollFuture.cancel(true); } executor.shutdownNow(); } // Visible for testing ScheduledExecutorService getExecutor() { return executor; } private void pollRule() { Instant now = clock.instant(); logger.info("Polling sampling rules."); GetSamplingRulesRequest req = new GetSamplingRulesRequest(); GetSamplingRulesResult records = client.getSamplingRules(req); List<SamplingRule> rules = records.getSamplingRuleRecords() .stream() .map(SamplingRuleRecord::getSamplingRule) .filter(CentralizedRule::isValid) .collect(Collectors.toList()); manifest.putRules(rules, now); } private long getIntervalWithJitter() { Rand random = new RandImpl(); return Math.round(random.next() * MAX_JITTER) + PERIOD; } }
3,891
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/jakarta/DynamicSegmentNamingStrategy.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.jakarta; import com.amazonaws.xray.entities.SearchPattern; import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @deprecated Use {@link SegmentNamingStrategy#dynamic(String)}. */ @Deprecated public class DynamicSegmentNamingStrategy implements SegmentNamingStrategy { private static final Log logger = LogFactory.getLog(DynamicSegmentNamingStrategy.class); private final String recognizedHosts; private final String fallbackName; /** * Creates an instance of {@code DynamicSegmentNamingStrategy} with the provided {@code fallbackName} and a * {@code recognizedHosts} value of "*". * * @param fallbackName * the fallback segment name used when no host header is included in the incoming request. This will be overriden by the * value of the {@code AWS_XRAY_TRACING_NAME} environment variable or {@code com.amazonaws.xray.strategy.tracingName} system * property, if either are set to a non-empty value. * * @deprecated Use {@link SegmentNamingStrategy#dynamic(String)}. */ @Deprecated public DynamicSegmentNamingStrategy(String fallbackName) { this(fallbackName, "*"); } /** * Creates an instance of {@code DynamicSegmentNamingStrategy} with the provided {@code fallbackName} and * {@code recognizedHosts} values. * * @param fallbackName * the fallback segment name used when no host header is included in the incoming request or the incoming host header value * does not match the provided pattern. This will be overriden by the value of the {@code AWS_XRAY_TRACING_NAME} environment * variable or {@code com.amazonaws.xray.strategy.tracingName} system property, if either are set to a non-empty value. * @param recognizedHosts * the pattern to match the incoming host header value against. This pattern is compared against the incoming host header * using the {@link SearchPattern#wildcardMatch(String, String)} method. * * @deprecated Use {@link SegmentNamingStrategy#dynamic(String, String)}. */ // Instance method is called before the class is initialized. This can cause undefined behavior, e.g., if getOverrideName // accesses fallbackName. This class doesn't really need to be exposed to users so we suppress for now and will clean up after // hiding. @SuppressWarnings("nullness") @Deprecated public DynamicSegmentNamingStrategy(String fallbackName, String recognizedHosts) { String overrideName = getOverrideName(); if (overrideName != null) { this.fallbackName = getOverrideName(); if (logger.isInfoEnabled()) { logger.info("Environment variable " + NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY + " or system property " + NAME_OVERRIDE_SYSTEM_PROPERTY_KEY + " set. Overriding DynamicSegmentNamingStrategy constructor argument. Segments generated with this " + "strategy will be named: " + this.fallbackName + " when the host header is unavilable or does not match the provided recognizedHosts pattern."); } } else { this.fallbackName = fallbackName; } this.recognizedHosts = recognizedHosts; } /** * * Returns the derived segment name for an incoming request. Attempts to get the {@code Host} header from the * {@code HttpServletRequest}. If the {@code Host} header has a value and if the value matches the optionally provided * {@code recognizedHosts} pattern, then this value is returned as the segment name. Otherwise, {@code fallbackName} is * returned. * * * @param request * the incoming request * @return * the segment name for the incoming request. */ @Override public String nameForRequest(HttpServletRequest request) { Optional<String> hostHeaderValue = Optional.ofNullable(request.getHeader("Host")); if (hostHeaderValue.isPresent() && (null == recognizedHosts || SearchPattern.wildcardMatch(recognizedHosts, hostHeaderValue.get()))) { return hostHeaderValue.get(); } return fallbackName; } }
3,892
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/jakarta/SegmentNamingStrategy.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.jakarta; import com.amazonaws.xray.entities.StringValidator; import jakarta.servlet.http.HttpServletRequest; import org.checkerframework.checker.nullness.qual.Nullable; public interface SegmentNamingStrategy { /** * Environment variable key used to override the default segment name used by implementors of {@code SegmentNamingStrategy}. * Takes precedence over any system property, web.xml configuration value, or constructor value used for a fixed segment name. */ String NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY = "AWS_XRAY_TRACING_NAME"; /** * System property key used to override the default segment name used by implementors of {@code SegmentNamingStrategy}. * Takes precedence over any web.xml configuration value or constructor value used for a fixed segment name. */ String NAME_OVERRIDE_SYSTEM_PROPERTY_KEY = "com.amazonaws.xray.strategy.tracingName"; /** * Returns a {@link SegmentNamingStrategy} that assigns the provided {@code name} to all segments generated for incoming * requests. This will be ignored and will use the the value of the {@code AWS_XRAY_TRACING_NAME} environment variable or * {@code com.amazonaws.xray.strategy.tracingName} system property if set. */ static SegmentNamingStrategy fixed(String name) { return new FixedSegmentNamingStrategy(name); } /** * Returns a {@link SegmentNamingStrategy} that names segments based on the {@code Host} header of incoming requests, * accepting any {@code Host} header value. * * @param fallbackName * the fallback segment name used when no host header is included in the incoming request or the incoming host header value * does not match the provided pattern. This will be overriden by the value of the {@code AWS_XRAY_TRACING_NAME} environment * variable or {@code com.amazonaws.xray.strategy.tracingName} system property, if either are set to a non-empty value. */ static SegmentNamingStrategy dynamic(String fallbackName) { return dynamic(fallbackName, "*"); } /** * Returns a {@link SegmentNamingStrategy} that names segments based on the {@code Host} header of incoming requests, * accepting only recognized {@code Host} header values. * * @param fallbackName * the fallback segment name used when no host header is included in the incoming request or the incoming host header value * does not match the provided pattern. This will be overriden by the value of the {@code AWS_XRAY_TRACING_NAME} environment * variable or {@code com.amazonaws.xray.strategy.tracingName} system property, if either are set to a non-empty value. * @param recognizedHosts * the pattern to match the incoming host header value against. This pattern is compared against the incoming host header * using the {@link com.amazonaws.xray.entities.SearchPattern#wildcardMatch(String, String)} method. */ static SegmentNamingStrategy dynamic(String fallbackName, String recognizedHosts) { return new DynamicSegmentNamingStrategy(fallbackName, recognizedHosts); } String nameForRequest(HttpServletRequest request); @Nullable default String getOverrideName() { String environmentNameOverrideValue = System.getenv(NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY); String systemNameOverrideValue = System.getProperty(NAME_OVERRIDE_SYSTEM_PROPERTY_KEY); if (StringValidator.isNotNullOrBlank(environmentNameOverrideValue)) { return environmentNameOverrideValue; } else if (StringValidator.isNotNullOrBlank(systemNameOverrideValue)) { return systemNameOverrideValue; } return null; } }
3,893
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/strategy/jakarta/FixedSegmentNamingStrategy.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.jakarta; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @deprecated Use {@link SegmentNamingStrategy#fixed(String)}. */ @Deprecated public class FixedSegmentNamingStrategy implements SegmentNamingStrategy { private static final Log logger = LogFactory.getLog(FixedSegmentNamingStrategy.class); private final String fixedName; /** * @deprecated Use {@link SegmentNamingStrategy#fixed(String)}. */ // Instance method is called before the class is initialized. This can cause undefined behavior, e.g., if getOverrideName // accesses fixedName. This class doesn't really need to be exposed to users so we suppress for now and will clean up after // hiding. @SuppressWarnings("nullness") @Deprecated public FixedSegmentNamingStrategy(String name) { String overrideName = getOverrideName(); if (overrideName != null) { this.fixedName = overrideName; if (logger.isInfoEnabled()) { logger.info("Environment variable " + NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY + " or system property " + NAME_OVERRIDE_SYSTEM_PROPERTY_KEY + " set. Overriding FixedSegmentNamingStrategy constructor argument. Segments generated with this " + "strategy will be named: " + this.fixedName + "."); } } else { this.fixedName = name; } } /** * Returns a segment name for an incoming request. * * @param request * the incoming request * @return * the name for the segment representing the request. */ @Override public String nameForRequest(HttpServletRequest request) { return fixedName; } }
3,894
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-lambda/src/test/java/com/amazonaws/xray
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-lambda/src/test/java/com/amazonaws/xray/lambda/SQSMessageHelperTest.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.lambda; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import java.util.Collections; import org.junit.jupiter.api.Test; public class SQSMessageHelperTest { @Test public void testSampled() { testTrue("Root=1-632BB806-bd862e3fe1be46a994272793;Sampled=1"); testTrue("Root=1-5759e988-bd862e3fe1be46a994272793;Sampled=1"); testTrue("Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1"); testFalse("Root=1-632BB806-bd862e3fe1be46a994272793"); testFalse("Root=1-632BB806-bd862e3fe1be46a994272793;Sampled=0"); testFalse("Root=1-5759e988-bd862e3fe1be46a994272793;Sampled=0"); testFalse("Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=0"); } public void testTrue(String traceHeader) { SQSEvent.SQSMessage sqsMessage = new SQSEvent.SQSMessage(); sqsMessage.setAttributes(Collections.singletonMap("AWSTraceHeader", traceHeader)); assertTrue(SQSMessageHelper.isSampled(sqsMessage)); } public void testFalse(String traceHeader) { SQSEvent.SQSMessage sqsMessage = new SQSEvent.SQSMessage(); sqsMessage.setAttributes(Collections.singletonMap("AWSTraceHeader", traceHeader)); assertFalse(SQSMessageHelper.isSampled(sqsMessage)); } }
3,895
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-lambda/src/main/java/com/amazonaws/xray
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-lambda/src/main/java/com/amazonaws/xray/lambda/SQSMessageHelper.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.lambda; import com.amazonaws.services.lambda.runtime.events.SQSEvent; public final class SQSMessageHelper { private SQSMessageHelper() { } public static boolean isSampled(SQSEvent.SQSMessage message) { if (!message.getAttributes().containsKey("AWSTraceHeader")) { return false; } return message.getAttributes().get("AWSTraceHeader").contains("Sampled=1"); } }
3,896
0
Create_ds/aws-xray-sdk-java/smoke-tests/src/test/java/com/amazonaws/xray
Create_ds/aws-xray-sdk-java/smoke-tests/src/test/java/com/amazonaws/xray/smoketests/SimpleSmokeTest.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.smoketests; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.amazonaws.xray.AWSXRayRecorder; import com.amazonaws.xray.AWSXRayRecorderBuilder; import com.amazonaws.xray.emitters.Emitter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class SimpleSmokeTest { @Mock private Emitter emitter; @Test void emits() { AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard() .withEmitter(emitter) .build(); recorder.beginSegment("test"); recorder.endSegment(); verify(emitter, times(1)).sendSegment(any()); } }
3,897
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-log4j/src/test/java/com/amazonaws/xray
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-log4j/src/test/java/com/amazonaws/xray/log4j/Log4JSegmentListenerTest.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.log4j; 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.SegmentImpl; import com.amazonaws.xray.entities.Subsegment; import com.amazonaws.xray.entities.SubsegmentImpl; import com.amazonaws.xray.entities.TraceID; import org.apache.logging.log4j.ThreadContext; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class Log4JSegmentListenerTest { private static final TraceID TRACE_ID = TraceID.fromString("1-1-d0a73661177562839f503b9f"); private static final String TRACE_ID_KEY = "AWS-XRAY-TRACE-ID"; @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()); Log4JSegmentListener segmentListener = new Log4JSegmentListener(); AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard() .withEmitter(blankEmitter) .withSegmentListener(segmentListener) .build()); AWSXRay.clearTraceEntity(); ThreadContext.clearAll(); } @Test void testDefaultPrefix() { Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0); Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID); listener.onSetEntity(null, seg); Assertions.assertEquals(TRACE_ID_KEY + ": " + TRACE_ID.toString() + "@" + seg.getId(), ThreadContext.get(TRACE_ID_KEY)); } @Test void testSetPrefix() { Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0); listener.setPrefix(""); Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID); listener.onSetEntity(null, seg); Assertions.assertEquals(TRACE_ID.toString() + "@" + seg.getId(), ThreadContext.get(TRACE_ID_KEY)); } @Test void testSegmentInjection() { Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0); listener.setPrefix(""); Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID); listener.onSetEntity(null, seg); Assertions.assertEquals(TRACE_ID.toString() + "@" + seg.getId(), ThreadContext.get(TRACE_ID_KEY)); } @Test void testUnsampledSegmentInjection() { Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0); listener.setPrefix(""); Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID); seg.setSampled(false); listener.onSetEntity(null, seg); Assertions.assertNull(ThreadContext.get(TRACE_ID_KEY)); } @Test void testSubsegmentInjection() { Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0); listener.setPrefix(""); Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID); listener.onSetEntity(null, seg); Subsegment sub = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", seg); listener.onSetEntity(seg, sub); Assertions.assertEquals(TRACE_ID.toString() + "@" + sub.getId(), ThreadContext.get(TRACE_ID_KEY)); } @Test void testNestedSubsegmentInjection() { Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0); listener.setPrefix(""); Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID); listener.onSetEntity(null, seg); Subsegment sub1 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test1", seg); listener.onSetEntity(seg, sub1); Subsegment sub2 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test2", seg); listener.onSetEntity(sub1, sub2); Assertions.assertEquals(TRACE_ID.toString() + "@" + sub2.getId(), ThreadContext.get(TRACE_ID_KEY)); } }
3,898
0
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-log4j/src/main/java/com/amazonaws/xray
Create_ds/aws-xray-sdk-java/aws-xray-recorder-sdk-log4j/src/main/java/com/amazonaws/xray/log4j/Log4JSegmentListener.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.log4j; import com.amazonaws.xray.entities.Entity; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.StringValidator; import com.amazonaws.xray.listeners.SegmentListener; import org.apache.logging.log4j.ThreadContext; /** * Implementation of SegmentListener that's used for Trace ID injection into logs that are recorded using the Log4J frontend API. * * To inject the X-Ray trace ID into your logging events, insert <code>%X{AWS-XRAY-TRACE-ID}</code> wherever you feel comfortable * in the layout pattern of your logging events. This is can be done wherever you configure Log4J for your project. Refer to the * Log4J <a href="https://logging.apache.org/log4j/2.x/manual/configuration.html">configuration documentation</a> for more * details. */ public class Log4JSegmentListener implements SegmentListener { private static final String TRACE_ID_KEY = "AWS-XRAY-TRACE-ID"; private String prefix; /** * Returns a default {@code Log4JSegmentListener} using {@code AWS-XRAY-TRACE-ID} as the prefix for trace ID injections */ public Log4JSegmentListener() { this(TRACE_ID_KEY); } /** * Returns a {@code Log4JSegmentListener} using the provided prefix for trace ID injections * @param prefix */ public Log4JSegmentListener(String prefix) { this.prefix = prefix; } public String getPrefix() { return prefix; } /** * Sets the trace ID injection prefix to provided value. A colon and space separate the prefix and trace ID, unless * the {@code prefix} is null or blank. * @param prefix */ public void setPrefix(String prefix) { this.prefix = prefix; } /** * Maps the AWS-XRAY-TRACE-ID key to the formatted ID of the entity that's just been created in the Log4J ThreadContext. * Does not perform injection if entity is not available or not sampled, since then the given entity would not be displayed * in X-Ray console. * * @param oldEntity the previous entity or null * @param newEntity the new entity, either a subsegment or segment */ @Override public void onSetEntity(Entity oldEntity, Entity newEntity) { if (newEntity == null) { ThreadContext.remove(TRACE_ID_KEY); return; } Segment segment = newEntity instanceof Segment ? ((Segment) newEntity) : newEntity.getParentSegment(); if (segment != null && segment.getTraceId() != null && segment.isSampled() && newEntity.getId() != null) { String fullPrefix = StringValidator.isNullOrBlank(this.prefix) ? "" : this.prefix + ": "; ThreadContext.put(TRACE_ID_KEY, fullPrefix + segment.getTraceId() + "@" + newEntity.getId()); } else { ThreadContext.remove(TRACE_ID_KEY); // Ensure traces don't spill over to unlinked messages } } /** * Removes the AWS-XRAY-TRACE-ID key from the ThreadContext upon the completion of each segment. * * @param entity * The segment that has just ended */ @Override public void onClearEntity(Entity entity) { ThreadContext.remove(TRACE_ID_KEY); } }
3,899