Search in sources :

Example 6 with AsyncHandler

use of com.amazonaws.handlers.AsyncHandler in project photon-model by vmware.

the class AWSTaskStatusChecker method runSearch.

private void runSearch(T type) {
    AmazonWebServiceRequest descRequest = buildRequest(type);
    AsyncHandler describeHandler = buildHandler(type);
    if (type instanceof Instance) {
        this.amazonEC2Client.describeInstancesAsync((DescribeInstancesRequest) descRequest, describeHandler);
    } else if (type instanceof NatGateway) {
        this.amazonEC2Client.describeNatGatewaysAsync((DescribeNatGatewaysRequest) descRequest, describeHandler);
    } else if (type instanceof Volume) {
        this.amazonEC2Client.describeVolumesAsync((DescribeVolumesRequest) descRequest, describeHandler);
    } else {
        AWSTaskStatusChecker.this.taskManager.patchTaskToFailure(new IllegalArgumentException("Invalid type " + type));
    }
}
Also used : AsyncHandler(com.amazonaws.handlers.AsyncHandler) Instance(com.amazonaws.services.ec2.model.Instance) Volume(com.amazonaws.services.ec2.model.Volume) DescribeNatGatewaysRequest(com.amazonaws.services.ec2.model.DescribeNatGatewaysRequest) NatGateway(com.amazonaws.services.ec2.model.NatGateway) AmazonWebServiceRequest(com.amazonaws.AmazonWebServiceRequest)

Example 7 with AsyncHandler

use of com.amazonaws.handlers.AsyncHandler in project photon-model by vmware.

the class AWSClientManager method getOrCreateCloudWatchClient.

/**
 * Get or create a CloudWatch Client instance that will be used to get stats from AWS.
 *
 * Note: ARN-based credentials will not be accepted unless they have already been exchanged to
 * AWS for session credentials. If unset, this method will throw a
 * {@link UnsupportedOperationException} exception in this circumstance. To enable ARN-based
 * credentials, migrate to {@link #getOrCreateCloudWatchClientAsync(AuthCredentialsServiceState,
 * String, StatelessService, boolean)}.
 *
 * @param credentials The auth credentials to be used for the client creation
 * @param regionId The region of the AWS client
 * @param service The stateless service for which the operation is being performed.
 * @param isMock Indicates if this a mock request
 * @return
 */
public AmazonCloudWatchAsyncClient getOrCreateCloudWatchClient(AuthCredentialsServiceState credentials, String regionId, StatelessService service, boolean isMock, Consumer<Throwable> failConsumer) {
    if (this.awsClientType != AwsClientType.CLOUD_WATCH) {
        throw new UnsupportedOperationException("This client manager supports only AWS " + this.awsClientType + " clients.");
    }
    if (isArnCredentials(credentials) && !isSetCredentials(credentials)) {
        throw new UnsupportedOperationException("For ARN-based credentials, exchange for session-based access key/secret key first before retrieving the client.");
    }
    String cacheKey = createCredentialRegionCacheKey(credentials, regionId);
    if (isCloudWatchClientInvalid(cacheKey)) {
        failConsumer.accept(new IllegalStateException("Invalid cloud watch client for key: " + cacheKey));
        return null;
    }
    AmazonCloudWatchAsyncClient amazonCloudWatchClient = null;
    try {
        amazonCloudWatchClient = this.cloudWatchClientCache.computeIfAbsent(cacheKey, key -> {
            AmazonCloudWatchAsyncClient client = AWSUtils.getStatsAsyncClient(credentials, regionId, getExecutor(), isMock);
            client.describeAlarmsAsync(new AsyncHandler<DescribeAlarmsRequest, DescribeAlarmsResult>() {

                @Override
                public void onError(Exception exception) {
                    markCloudWatchClientInvalid(service, cacheKey);
                }

                @Override
                public void onSuccess(DescribeAlarmsRequest request, DescribeAlarmsResult result) {
                // noop
                }
            });
            return client;
        });
    } catch (Throwable e) {
        service.logSevere(e);
        failConsumer.accept(e);
    }
    return amazonCloudWatchClient;
}
Also used : S3_TM_CLIENT_CACHE_INITIAL_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.S3_TM_CLIENT_CACHE_INITIAL_SIZE) TransferManager(com.amazonaws.services.s3.transfer.TransferManager) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) LRUCache(com.vmware.photon.controller.model.adapters.util.LRUCache) OperationContext(com.vmware.xenon.common.OperationContext) INVALID_CLIENT_CACHE_INITIAL_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.INVALID_CLIENT_CACHE_INITIAL_SIZE) AmazonCloudWatchAsyncClient(com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClient) HashMap(java.util.HashMap) S3_CLIENT_CACHE_INITIAL_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.S3_CLIENT_CACHE_INITIAL_SIZE) AWSUtils.isArnCredentials(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.isArnCredentials) Utils(com.vmware.xenon.common.Utils) UriPaths(com.vmware.photon.controller.model.UriPaths) CW_CLIENT_CACHE_INITIAL_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.CW_CLIENT_CACHE_INITIAL_SIZE) Map(java.util.Map) INVALID_CLIENT_CACHE_MAX_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.INVALID_CLIENT_CACHE_MAX_SIZE) EXTERNAL_ID_KEY(com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.EXTERNAL_ID_KEY) AwsClientType(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AwsClientType) EC2_CLIENT_CACHE_MAX_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.EC2_CLIENT_CACHE_MAX_SIZE) LB_CLIENT_CACHE_INITIAL_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.LB_CLIENT_CACHE_INITIAL_SIZE) ExecutorService(java.util.concurrent.ExecutorService) AWSUtils.awsSessionCredentialsToAuthCredentialsState(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.awsSessionCredentialsToAuthCredentialsState) EC2_CLIENT_CACHE_INITIAL_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.EC2_CLIENT_CACHE_INITIAL_SIZE) AWSUtils.getArnSessionCredentialsAsync(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.getArnSessionCredentialsAsync) DescribeAlarmsRequest(com.amazonaws.services.cloudwatch.model.DescribeAlarmsRequest) StatelessService(com.vmware.xenon.common.StatelessService) TILDA(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.TILDA) CompletionException(java.util.concurrent.CompletionException) AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) S3_CLIENT_CACHE_MAX_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.S3_CLIENT_CACHE_MAX_SIZE) AWSUtils(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CW_CLIENT_CACHE_MAX_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.CW_CLIENT_CACHE_MAX_SIZE) AmazonElasticLoadBalancingAsyncClient(com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingAsyncClient) ARN_KEY(com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.ARN_KEY) DescribeAlarmsResult(com.amazonaws.services.cloudwatch.model.DescribeAlarmsResult) S3_TM_CLIENT_CACHE_MAX_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.S3_TM_CLIENT_CACHE_MAX_SIZE) AsyncHandler(com.amazonaws.handlers.AsyncHandler) DeferredResult(com.vmware.xenon.common.DeferredResult) LB_CLIENT_CACHE_MAX_SIZE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.LB_CLIENT_CACHE_MAX_SIZE) Collections(java.util.Collections) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) AsyncHandler(com.amazonaws.handlers.AsyncHandler) DescribeAlarmsResult(com.amazonaws.services.cloudwatch.model.DescribeAlarmsResult) AmazonCloudWatchAsyncClient(com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClient) DescribeAlarmsRequest(com.amazonaws.services.cloudwatch.model.DescribeAlarmsRequest) CompletionException(java.util.concurrent.CompletionException)

Example 8 with AsyncHandler

use of com.amazonaws.handlers.AsyncHandler in project spring-integration-aws by spring-projects.

the class KinesisMessageHandlerTests method testKinesisMessageHandler.

@Test
@SuppressWarnings("unchecked")
public void testKinesisMessageHandler() throws Exception {
    Message<?> message = MessageBuilder.withPayload("message").build();
    try {
        this.kinesisSendChannel.send(message);
    } catch (Exception e) {
        assertThat(e).isInstanceOf(MessageHandlingException.class);
        assertThat(e.getCause()).isInstanceOf(IllegalStateException.class);
        assertThat(e.getMessage()).contains("'stream' must not be null for sending a Kinesis record");
    }
    this.kinesisMessageHandler.setStream("foo");
    try {
        this.kinesisSendChannel.send(message);
    } catch (Exception e) {
        assertThat(e).isInstanceOf(MessageHandlingException.class);
        assertThat(e.getCause()).isInstanceOf(IllegalStateException.class);
        assertThat(e.getMessage()).contains("'partitionKey' must not be null for sending a Kinesis record");
    }
    message = MessageBuilder.fromMessage(message).setHeader(AwsHeaders.PARTITION_KEY, "fooKey").setHeader(AwsHeaders.SEQUENCE_NUMBER, "10").setHeader("foo", "bar").build();
    this.kinesisSendChannel.send(message);
    ArgumentCaptor<PutRecordRequest> putRecordRequestArgumentCaptor = ArgumentCaptor.forClass(PutRecordRequest.class);
    ArgumentCaptor<AsyncHandler<PutRecordRequest, PutRecordResult>> asyncHandlerArgumentCaptor = ArgumentCaptor.forClass((Class<AsyncHandler<PutRecordRequest, PutRecordResult>>) (Class<?>) AsyncHandler.class);
    verify(this.amazonKinesis).putRecordAsync(putRecordRequestArgumentCaptor.capture(), asyncHandlerArgumentCaptor.capture());
    PutRecordRequest putRecordRequest = putRecordRequestArgumentCaptor.getValue();
    assertThat(putRecordRequest.getStreamName()).isEqualTo("foo");
    assertThat(putRecordRequest.getPartitionKey()).isEqualTo("fooKey");
    assertThat(putRecordRequest.getSequenceNumberForOrdering()).isEqualTo("10");
    assertThat(putRecordRequest.getExplicitHashKey()).isNull();
    Message<?> messageToCheck = new EmbeddedJsonHeadersMessageMapper().toMessage(putRecordRequest.getData().array());
    assertThat(messageToCheck.getHeaders()).contains(entry("foo", "bar"));
    assertThat(messageToCheck.getPayload()).isEqualTo("message".getBytes());
    AsyncHandler<?, ?> asyncHandler = asyncHandlerArgumentCaptor.getValue();
    RuntimeException testingException = new RuntimeException("testingException");
    asyncHandler.onError(testingException);
    verify(this.asyncHandler).onError(eq(testingException));
    message = new GenericMessage<>(new PutRecordsRequest().withStreamName("myStream").withRecords(new PutRecordsRequestEntry().withData(ByteBuffer.wrap("test".getBytes())).withPartitionKey("testKey")));
    this.kinesisSendChannel.send(message);
    ArgumentCaptor<PutRecordsRequest> putRecordsRequestArgumentCaptor = ArgumentCaptor.forClass(PutRecordsRequest.class);
    verify(this.amazonKinesis).putRecordsAsync(putRecordsRequestArgumentCaptor.capture(), any(AsyncHandler.class));
    PutRecordsRequest putRecordsRequest = putRecordsRequestArgumentCaptor.getValue();
    assertThat(putRecordsRequest.getStreamName()).isEqualTo("myStream");
    assertThat(putRecordsRequest.getRecords()).containsExactlyInAnyOrder(new PutRecordsRequestEntry().withData(ByteBuffer.wrap("test".getBytes())).withPartitionKey("testKey"));
}
Also used : AsyncHandler(com.amazonaws.handlers.AsyncHandler) PutRecordsRequestEntry(com.amazonaws.services.kinesis.model.PutRecordsRequestEntry) PutRecordRequest(com.amazonaws.services.kinesis.model.PutRecordRequest) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) EmbeddedJsonHeadersMessageMapper(org.springframework.integration.support.json.EmbeddedJsonHeadersMessageMapper) PutRecordsRequest(com.amazonaws.services.kinesis.model.PutRecordsRequest) Test(org.junit.Test)

Aggregations

AsyncHandler (com.amazonaws.handlers.AsyncHandler)8 AmazonEC2AsyncClient (com.amazonaws.services.ec2.AmazonEC2AsyncClient)3 OperationContext (com.vmware.xenon.common.OperationContext)3 StatelessService (com.vmware.xenon.common.StatelessService)3 AmazonWebServiceRequest (com.amazonaws.AmazonWebServiceRequest)2 Instance (com.amazonaws.services.ec2.model.Instance)2 NatGateway (com.amazonaws.services.ec2.model.NatGateway)2 StartInstancesRequest (com.amazonaws.services.ec2.model.StartInstancesRequest)2 StartInstancesResult (com.amazonaws.services.ec2.model.StartInstancesResult)2 StopInstancesRequest (com.amazonaws.services.ec2.model.StopInstancesRequest)2 StopInstancesResult (com.amazonaws.services.ec2.model.StopInstancesResult)2 Volume (com.amazonaws.services.ec2.model.Volume)2 ComputePowerRequest (com.vmware.photon.controller.model.adapterapi.ComputePowerRequest)2 ClientConfig (com.amazon.dax.client.dynamodbv2.ClientConfig)1 ClusterDaxAsyncClient (com.amazon.dax.client.dynamodbv2.ClusterDaxAsyncClient)1 AmazonServiceException (com.amazonaws.AmazonServiceException)1 AmazonWebServiceResult (com.amazonaws.AmazonWebServiceResult)1 ProfileCredentialsProvider (com.amazonaws.auth.profile.ProfileCredentialsProvider)1 Regions (com.amazonaws.regions.Regions)1 AmazonCloudWatchAsyncClient (com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClient)1