software.amazon.awssdk.core.interceptor.SdkExecutionAttribute Java Examples

The following examples show how to use software.amazon.awssdk.core.interceptor.SdkExecutionAttribute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpectatorExecutionInterceptor.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes attrs) {
  logRetryAttempt(attrs);

  String serviceName = attrs.getAttribute(SdkExecutionAttribute.SERVICE_NAME);
  String opName = attrs.getAttribute(SdkExecutionAttribute.OPERATION_NAME);
  String endpoint = serviceName + "." + opName;

  SdkHttpRequest request = context.httpRequest();

  IpcLogEntry logEntry = logger.createClientEntry()
      .withOwner("aws-sdk-java-v2")
      .withProtocol(IpcProtocol.http_1)
      .withHttpMethod(request.method().name())
      .withUri(request.getUri())
      .withEndpoint(endpoint)
      .withAttempt(extractAttempt(request))
      .withAttemptFinal(false); // Don't know if it is the final attempt

  request.headers().forEach((k, vs) -> vs.forEach(v -> logEntry.addRequestHeader(k, v)));

  attrs.putAttribute(LOG_ENTRY, logEntry.markStart());
}
 
Example #2
Source File: TracingInterceptor.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
    AWSXRayRecorder recorder = getRecorder();
    Entity origin = recorder.getTraceEntity();

    Subsegment subsegment = recorder.beginSubsegment(executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME));
    if (subsegment == null) {
        return;
    }
    subsegment.setNamespace(Namespace.AWS.toString());
    subsegment.putAws(EntityDataKeys.AWS.OPERATION_KEY,
                      executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME));
    Region region = executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION);
    if (region != null) {
        subsegment.putAws(EntityDataKeys.AWS.REGION_KEY, region.id());
    }
    subsegment.putAllAws(extractRequestParameters(context, executionAttributes));
    if (accountId != null) {
        subsegment.putAws(EntityDataKeys.AWS.ACCOUNT_ID_SUBSEGMENT_KEY, accountId);
    }

    recorder.setTraceEntity(origin);
    // store the subsegment in the AWS SDK's executionAttributes so it can be accessed across threads
    executionAttributes.putAttribute(entityKey, subsegment);
}
 
Example #3
Source File: TracingExecutionInterceptor.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
/**
 * Before an individual http request is finalized. This is only called once per operation, meaning
 * we can only have one span per operation.
 */
@Override public SdkHttpRequest modifyHttpRequest(
    Context.ModifyHttpRequest context,
    ExecutionAttributes executionAttributes
) {
  HttpClientRequest request = new HttpClientRequest(context.httpRequest());

  Span span = handler.handleSend(request);
  executionAttributes.putAttribute(SPAN, span);

  String serviceName = executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME);
  String operation = getAwsOperationNameFromRequestClass(context.request());
  // TODO: This overwrites user configuration. We don't do this in other layered tools such
  // as WebMVC. Instead, we add tags (such as we do here) and neither overwrite the name, nor
  // remoteServiceName. Users can always remap in an span handler using tags!
  span.name(operation)
      .remoteServiceName(serviceName)
      .tag("aws.service_name", serviceName)
      .tag("aws.operation", operation);

  return request.build();
}
 
Example #4
Source File: EventStreamAsyncResponseTransformer.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Handle the event stream message according to it's type.
 *
 * @param m Decoded message.
 */
private void handleMessage(Message m) {
    try {
        if (isEvent(m)) {
            if (m.getHeaders().get(":event-type").getString().equals("initial-response")) {
                eventStreamResponseHandler.responseReceived(
                    initialResponseHandler.handle(adaptMessageToResponse(m, false),
                                                  EMPTY_EXECUTION_ATTRIBUTES));
            } else {
                // Add to queue to be delivered later by the executor
                eventsToDeliver.add(eventResponseHandler.handle(adaptMessageToResponse(m, false),
                                                                EMPTY_EXECUTION_ATTRIBUTES));
            }
        } else if (isError(m) || isException(m)) {
            SdkHttpFullResponse errorResponse = adaptMessageToResponse(m, true);
            Throwable exception = exceptionResponseHandler.handle(
                errorResponse, new ExecutionAttributes().putAttribute(SdkExecutionAttribute.SERVICE_NAME, serviceName));
            runAndLogError(log, "Error thrown from exceptionOccurred, ignoring.", () -> exceptionOccurred(exception));
        }
    } catch (Exception e) {
        throw SdkClientException.builder().cause(e).build();
    }
}
 
Example #5
Source File: BaseClientHandler.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
protected <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext createExecutionContext(
    ClientExecutionParams<InputT, OutputT> params, ExecutionAttributes executionAttributes) {

    SdkRequest originalRequest = params.getInput();

    executionAttributes
        .putAttribute(SdkExecutionAttribute.SERVICE_CONFIG,
                      clientConfiguration.option(SdkClientOption.SERVICE_CONFIGURATION))
        .putAttribute(SdkExecutionAttribute.SERVICE_NAME, clientConfiguration.option(SdkClientOption.SERVICE_NAME));

    ExecutionInterceptorChain interceptorChain =
            new ExecutionInterceptorChain(clientConfiguration.option(SdkClientOption.EXECUTION_INTERCEPTORS));

    return ExecutionContext.builder()
                           .interceptorChain(interceptorChain)
                           .interceptorContext(InterceptorContext.builder()
                                                                 .request(originalRequest)
                                                                 .build())
                           .executionAttributes(executionAttributes)
                           .signer(clientConfiguration.option(SdkAdvancedClientOption.SIGNER))
                           .build();
}
 
Example #6
Source File: AwsJsonProtocolErrorUnmarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Build the {@link AwsErrorDetails} from the metadata in the response.
 *
 * @param response HTTP response.
 * @param executionAttributes Execution attributes.
 * @param jsonContent Parsed JSON content.
 * @param errorCode Parsed error code/type.
 * @param errorMessage Parsed error message.
 * @return AwsErrorDetails
 */
private AwsErrorDetails extractAwsErrorDetails(SdkHttpFullResponse response,
                                               ExecutionAttributes executionAttributes,
                                               JsonContent jsonContent,
                                               String errorCode,
                                               String errorMessage) {
    AwsErrorDetails.Builder errorDetails =
        AwsErrorDetails.builder()
                       .errorCode(errorCode)
                       .serviceName(executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME))
                       .sdkHttpResponse(response);

    if (jsonContent.getRawContent() != null) {
        errorDetails.rawResponse(SdkBytes.fromByteArray(jsonContent.getRawContent()));
    }

    errorDetails.errorMessage(errorMessage);
    return errorDetails.build();
}
 
Example #7
Source File: EndpointAddressInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
                                        ExecutionAttributes executionAttributes) {
    ConfiguredS3SdkHttpRequest configuredRequest =
        S3EndpointUtils.applyEndpointConfiguration(
                context.httpRequest(),
                context.request(),
                executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION),
                (S3Configuration) executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG),
                Boolean.TRUE.equals(executionAttributes.getAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN)));

    configuredRequest.signingRegionModification().ifPresent(
        region -> executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, region));

    return configuredRequest.sdkHttpRequest();
}
 
Example #8
Source File: ChecksumsEnabledValidator.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that checksums should be enabled based on {@link ClientType} and the presence
 * or S3 specific headers.
 *
 * @param expectedClientType - The expected client type for enabling checksums
 * @param executionAttributes - {@link ExecutionAttributes} to determine the actual client type
 * @return If trailing checksums should be enabled for this request.
 */
public static boolean shouldRecordChecksum(SdkRequest sdkRequest,
                                           ClientType expectedClientType,
                                           ExecutionAttributes executionAttributes,
                                           SdkHttpRequest httpRequest) {
    if (!(sdkRequest instanceof PutObjectRequest)) {
        return false;
    }

    ClientType actualClientType = executionAttributes.getAttribute(SdkExecutionAttribute.CLIENT_TYPE);

    if (!expectedClientType.equals(actualClientType)) {
        return false;
    }


    if (hasServerSideEncryptionHeader(httpRequest)) {
        return false;
    }

    return checksumEnabledPerConfig(executionAttributes);
}
 
Example #9
Source File: TracingInterceptor.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
private AWSOperationHandler getOperationHandler(ExecutionAttributes executionAttributes) {
    String serviceName = executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME);
    String operationName = executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME);

    if (awsServiceHandlerManifest == null) {
        return null;
    }
    AWSOperationHandlerManifest operationManifest = awsServiceHandlerManifest.getOperationHandlerManifest(serviceName);
    if (operationManifest == null) {
        return null;
    }
    return operationManifest.getOperationHandler(operationName);
}
 
Example #10
Source File: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = SdkClientException.class)
public void modifyHttpRequest_ThrowsException_NoAccountId() {
    EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor();

    S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder()
                                                                        .dualstackEnabled(true)
                                                                        .build();
    ExecutionAttributes executionAttributes = new ExecutionAttributes();
    executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration);

    interceptor.modifyHttpRequest(new Context(request.toBuilder().removeHeader(X_AMZ_ACCOUNT_ID).build()),
                                  executionAttributes);
}
 
Example #11
Source File: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = SdkClientException.class)
public void modifyHttpRequest_ThrowsException_NonStandardEndpoint() {
    EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor();

    S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder()
                                                                        .dualstackEnabled(true)
                                                                        .build();
    ExecutionAttributes executionAttributes = new ExecutionAttributes();
    executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration);

    interceptor.modifyHttpRequest(new Context(request.toBuilder().host("some-garbage").build()),
                                  executionAttributes);
}
 
Example #12
Source File: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = SdkClientException.class)
public void modifyHttpRequest_ThrowsException_FipsAndDualstack() {
    EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor();

    S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder()
                                                                        .fipsModeEnabled(true)
                                                                        .dualstackEnabled(true)
                                                                        .build();
    ExecutionAttributes executionAttributes = new ExecutionAttributes();
    executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration);

    interceptor.modifyHttpRequest(new Context(request), executionAttributes);
}
 
Example #13
Source File: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyHttpRequest_ResolvesCorrectHost_Fips() {
    EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor();

    S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder().fipsModeEnabled(true).build();
    ExecutionAttributes executionAttributes = new ExecutionAttributes();
    executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration);

    SdkHttpRequest modified = interceptor.modifyHttpRequest(new Context(request), executionAttributes);
    assertThat(modified.host()).isEqualTo(ACCOUNT_ID + ".s3-control-fips.us-east-1.amazonaws.com");
}
 
Example #14
Source File: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyHttpRequest_ResolvesCorrectHost_Dualstack() {
    EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor();

    S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder().dualstackEnabled(true).build();
    ExecutionAttributes executionAttributes = new ExecutionAttributes();
    executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration);

    SdkHttpRequest modified = interceptor.modifyHttpRequest(new Context(request), executionAttributes);
    assertThat(modified.host()).isEqualTo(ACCOUNT_ID + ".s3-control.dualstack.us-east-1.amazonaws.com");
}
 
Example #15
Source File: DefaultPollyPresigner.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private ExecutionAttributes createExecutionAttributes(PresignRequest presignRequest, PollyRequest requestToPresign) {
    Instant signatureExpiration = Instant.now().plus(presignRequest.signatureDuration());
    AwsCredentials credentials = resolveCredentialsProvider(requestToPresign).resolveCredentials();
    Validate.validState(credentials != null, "Credential providers must never return null.");

    return new ExecutionAttributes()
            .putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, credentials)
            .putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, SIGNING_NAME)
            .putAttribute(AwsExecutionAttribute.AWS_REGION, region())
            .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, region())
            .putAttribute(SdkInternalExecutionAttribute.IS_FULL_DUPLEX, false)
            .putAttribute(SdkExecutionAttribute.CLIENT_TYPE, ClientType.SYNC)
            .putAttribute(SdkExecutionAttribute.SERVICE_NAME, SERVICE_NAME)
            .putAttribute(PRESIGNER_EXPIRATION, signatureExpiration);
}
 
Example #16
Source File: TracingExecutionInterceptor.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeExecution(BeforeExecution context, ExecutionAttributes executionAttributes) {
  final Span span = GlobalTracer.get().buildSpan(context.request().getClass().getSimpleName())
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.PEER_SERVICE, executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME))
    .withTag(Tags.COMPONENT, COMPONENT_NAME).start();

  executionAttributes.putAttribute(SPAN_ATTRIBUTE, span);
}
 
Example #17
Source File: AwsJsonProtocolErrorUnmarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private Duration getClockSkew(ExecutionAttributes executionAttributes) {
    Integer timeOffset = executionAttributes.getAttribute(SdkExecutionAttribute.TIME_OFFSET);
    return timeOffset == null ? null : Duration.ofSeconds(timeOffset);
}
 
Example #18
Source File: AwsXmlErrorUnmarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private Duration getClockSkew(ExecutionAttributes executionAttributes) {
    Integer timeOffset = executionAttributes.getAttribute(SdkExecutionAttribute.TIME_OFFSET);
    return timeOffset == null ? null : Duration.ofSeconds(timeOffset);
}
 
Example #19
Source File: SigningStage.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
/**
 * Always use the client level timeOffset.
 */
private void adjustForClockSkew(ExecutionAttributes attributes) {
    attributes.putAttribute(SdkExecutionAttribute.TIME_OFFSET, dependencies.timeOffset());
}
 
Example #20
Source File: AwsClientHandlerUtils.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
static <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext createExecutionContext(
    ClientExecutionParams<InputT, OutputT> executionParams,
    SdkClientConfiguration clientConfig,
    ExecutionAttributes executionAttributes) {

    SdkRequest originalRequest = executionParams.getInput();
    AwsCredentialsProvider clientCredentials = clientConfig.option(AwsClientOption.CREDENTIALS_PROVIDER);
    AwsCredentialsProvider credentialsProvider = originalRequest.overrideConfiguration()
                                                                .filter(c -> c instanceof AwsRequestOverrideConfiguration)
                                                                .map(c -> (AwsRequestOverrideConfiguration) c)
                                                                .flatMap(AwsRequestOverrideConfiguration::credentialsProvider)
                                                                .orElse(clientCredentials);

    AwsCredentials credentials = credentialsProvider.resolveCredentials();

    Validate.validState(credentials != null, "Credential providers must never return null.");

    executionAttributes
        .putAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG, clientConfig.option(SdkClientOption.SERVICE_CONFIGURATION))
        .putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, credentials)
        .putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME,
                      clientConfig.option(AwsClientOption.SERVICE_SIGNING_NAME))
        .putAttribute(AwsExecutionAttribute.AWS_REGION, clientConfig.option(AwsClientOption.AWS_REGION))
        .putAttribute(AwsExecutionAttribute.ENDPOINT_PREFIX, clientConfig.option(AwsClientOption.ENDPOINT_PREFIX))
        .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, clientConfig.option(AwsClientOption.SIGNING_REGION))
        .putAttribute(SdkInternalExecutionAttribute.IS_FULL_DUPLEX, executionParams.isFullDuplex())
        .putAttribute(SdkExecutionAttribute.CLIENT_TYPE, clientConfig.option(SdkClientOption.CLIENT_TYPE))
        .putAttribute(SdkExecutionAttribute.SERVICE_NAME, clientConfig.option(SdkClientOption.SERVICE_NAME))
        .putAttribute(SdkExecutionAttribute.OPERATION_NAME, executionParams.getOperationName())
        .putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN,
                      clientConfig.option(SdkClientOption.ENDPOINT_OVERRIDDEN));

    ExecutionInterceptorChain executionInterceptorChain =
            new ExecutionInterceptorChain(clientConfig.option(SdkClientOption.EXECUTION_INTERCEPTORS));
    return ExecutionContext.builder()
                           .interceptorChain(executionInterceptorChain)
                           .interceptorContext(InterceptorContext.builder()
                                                                 .request(originalRequest)
                                                                 .asyncRequestBody(executionParams.getAsyncRequestBody())
                                                                 .requestBody(executionParams.getRequestBody())
                                                                 .build())
                           .executionAttributes(executionAttributes)
                           .signer(computeSigner(originalRequest, clientConfig))
                           .build();
}
 
Example #21
Source File: SpectatorExecutionInterceptorTest.java    From spectator with Apache License 2.0 4 votes vote down vote up
private ExecutionAttributes createAttributes(String service, String op) {
  ExecutionAttributes attrs = new ExecutionAttributes();
  attrs.putAttribute(SdkExecutionAttribute.SERVICE_NAME, service);
  attrs.putAttribute(SdkExecutionAttribute.OPERATION_NAME, op);
  return attrs;
}