Search in sources :

Example 1 with AsyncHandler

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

the class AWSPowerService method powerOn.

private void powerOn(AmazonEC2AsyncClient client, ComputePowerRequest pr, DefaultAdapterContext c) {
    OperationContext opContext = OperationContext.getOperationContext();
    StartInstancesRequest request = new StartInstancesRequest();
    request.withInstanceIds(c.child.id);
    client.startInstancesAsync(request, new AsyncHandler<StartInstancesRequest, StartInstancesResult>() {

        @Override
        public void onSuccess(StartInstancesRequest request, StartInstancesResult result) {
            AWSUtils.waitForTransitionCompletion(getHost(), result.getStartingInstances(), "running", client, (is, e) -> {
                OperationContext.restoreOperationContext(opContext);
                if (e != null) {
                    onError(e);
                    return;
                }
                updateComputeState(pr, c);
            });
        }

        @Override
        public void onError(Exception e) {
            OperationContext.restoreOperationContext(opContext);
            c.taskManager.patchTaskToFailure(e);
        }
    });
}
Also used : OperationContext(com.vmware.xenon.common.OperationContext) ComputePowerRequest(com.vmware.photon.controller.model.adapterapi.ComputePowerRequest) OperationContext(com.vmware.xenon.common.OperationContext) StopInstancesResult(com.amazonaws.services.ec2.model.StopInstancesResult) StatelessService(com.vmware.xenon.common.StatelessService) Operation(com.vmware.xenon.common.Operation) StartInstancesResult(com.amazonaws.services.ec2.model.StartInstancesResult) BaseAdapterStage(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.BaseAdapterStage) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) DefaultAdapterContext(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.DefaultAdapterContext) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) OFF(com.vmware.photon.controller.model.resources.ComputeService.PowerState.OFF) AsyncHandler(com.amazonaws.handlers.AsyncHandler) AWSClientManagerFactory(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory) AWSClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) StartInstancesResult(com.amazonaws.services.ec2.model.StartInstancesResult) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest)

Example 2 with AsyncHandler

use of com.amazonaws.handlers.AsyncHandler in project aws-doc-sdk-examples by awsdocs.

the class DaxAsyncClientDemo method main.

public static void main(String[] args) throws Exception {
    ClientConfig daxConfig = new ClientConfig().withCredentialsProvider(new ProfileCredentialsProvider()).withEndpoints("mydaxcluster.2cmrwl.clustercfg.dax.use1.cache.amazonaws.com:8111");
    AmazonDynamoDBAsync client = new ClusterDaxAsyncClient(daxConfig);
    HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put("Artist", new AttributeValue().withS("No One You Know"));
    key.put("SongTitle", new AttributeValue().withS("Scared of My Shadow"));
    GetItemRequest request = new GetItemRequest().withTableName("Music").withKey(key);
    // Java Futures
    Future<GetItemResult> call = client.getItemAsync(request);
    while (!call.isDone()) {
        // Do other processing while you're waiting for the response
        System.out.println("Doing something else for a few seconds...");
        Thread.sleep(3000);
    }
    try {
        call.get();
    } catch (ExecutionException ee) {
        // Futures always wrap errors as an ExecutionException.
        // The *real* exception is stored as the cause of the
        // ExecutionException
        Throwable exception = ee.getCause();
        System.out.println("Error getting item: " + exception.getMessage());
    }
    // Async callbacks
    call = client.getItemAsync(request, new AsyncHandler<GetItemRequest, GetItemResult>() {

        @Override
        public void onSuccess(GetItemRequest request, GetItemResult getItemResult) {
            System.out.println("Result: " + getItemResult);
        }

        @Override
        public void onError(Exception e) {
            System.out.println("Unable to read item");
            System.err.println(e.getMessage());
        // Callers can also test if exception is an instance of
        // AmazonServiceException or AmazonClientException and cast
        // it to get additional information
        }
    });
    call.get();
}
Also used : AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) AsyncHandler(com.amazonaws.handlers.AsyncHandler) HashMap(java.util.HashMap) ClusterDaxAsyncClient(com.amazon.dax.client.dynamodbv2.ClusterDaxAsyncClient) ExecutionException(java.util.concurrent.ExecutionException) GetItemResult(com.amazonaws.services.dynamodbv2.model.GetItemResult) AmazonDynamoDBAsync(com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsync) ProfileCredentialsProvider(com.amazonaws.auth.profile.ProfileCredentialsProvider) ClientConfig(com.amazon.dax.client.dynamodbv2.ClientConfig) ExecutionException(java.util.concurrent.ExecutionException) GetItemRequest(com.amazonaws.services.dynamodbv2.model.GetItemRequest)

Example 3 with AsyncHandler

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

the class AWSPowerService method powerOff.

private void powerOff(AmazonEC2AsyncClient client, ComputePowerRequest pr, DefaultAdapterContext c) {
    OperationContext opContext = OperationContext.getOperationContext();
    StopInstancesRequest request = new StopInstancesRequest();
    request.withInstanceIds(c.child.id);
    client.stopInstancesAsync(request, new AsyncHandler<StopInstancesRequest, StopInstancesResult>() {

        @Override
        public void onSuccess(StopInstancesRequest request, StopInstancesResult result) {
            AWSUtils.waitForTransitionCompletion(getHost(), result.getStoppingInstances(), "stopped", client, (is, e) -> {
                OperationContext.restoreOperationContext(opContext);
                if (e != null) {
                    onError(e);
                    return;
                }
                updateComputeState(pr, c);
            });
        }

        @Override
        public void onError(Exception e) {
            OperationContext.restoreOperationContext(opContext);
            c.taskManager.patchTaskToFailure(e);
        }
    });
}
Also used : OperationContext(com.vmware.xenon.common.OperationContext) ComputePowerRequest(com.vmware.photon.controller.model.adapterapi.ComputePowerRequest) OperationContext(com.vmware.xenon.common.OperationContext) StopInstancesResult(com.amazonaws.services.ec2.model.StopInstancesResult) StatelessService(com.vmware.xenon.common.StatelessService) Operation(com.vmware.xenon.common.Operation) StartInstancesResult(com.amazonaws.services.ec2.model.StartInstancesResult) BaseAdapterStage(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.BaseAdapterStage) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) DefaultAdapterContext(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.DefaultAdapterContext) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) OFF(com.vmware.photon.controller.model.resources.ComputeService.PowerState.OFF) AsyncHandler(com.amazonaws.handlers.AsyncHandler) AWSClientManagerFactory(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory) AWSClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) StopInstancesResult(com.amazonaws.services.ec2.model.StopInstancesResult) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest)

Example 4 with AsyncHandler

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

the class AWSReservedInstancePlanService method getRegionAsyncHandler.

private AsyncHandler<DescribeRegionsRequest, DescribeRegionsResult> getRegionAsyncHandler(AWSReservedInstanceContext context) {
    AWSReservedInstancePlanService service = this;
    return new AsyncHandler<DescribeRegionsRequest, DescribeRegionsResult>() {

        @Override
        public void onError(Exception e) {
            log(Level.WARNING, "Error while fetching the regions for compute " + context.computeDesc.documentSelfLink + " " + Utils.toString(e));
        }

        @Override
        public void onSuccess(DescribeRegionsRequest request, DescribeRegionsResult describeRegionsResult) {
            List<Region> regions = describeRegionsResult.getRegions();
            if (CollectionUtils.isEmpty(regions)) {
                log(Level.INFO, "No regions exist for compute" + context.computeDesc.documentSelfLink);
                return;
            }
            AtomicInteger currentStageTaskCount = new AtomicInteger(regions.size());
            /*
                 * Fetch all the regions from AWS and collect reserved instances plans for
                 * only those regions which are supported by SDK.
                 */
            for (Region region : regions) {
                try {
                    Regions r = Regions.fromName(region.getRegionName());
                    if (r == null) {
                        new AWSReservedInstanceAsyncHandler(service.getHost(), currentStageTaskCount, region, context).checkAndPatchReservedInstancesPlans();
                        continue;
                    }
                } catch (Exception e) {
                    log(Level.WARNING, e.getMessage());
                    new AWSReservedInstanceAsyncHandler(service.getHost(), currentStageTaskCount, region, context).checkAndPatchReservedInstancesPlans();
                    continue;
                }
                service.ec2ClientManager.getOrCreateEC2ClientAsync(context.parentAuth, region.getRegionName(), service).whenComplete((ec2Client, t) -> {
                    if (t != null) {
                        getFailureConsumer(context, "Error while creating EC2 client for").accept(t);
                        new AWSReservedInstanceAsyncHandler(service.getHost(), currentStageTaskCount, region, context).checkAndPatchReservedInstancesPlans();
                        logWarning("client is null for region %s for compute %s", region.getRegionName(), context.computeDesc.documentSelfLink);
                        return;
                    }
                    ec2Client.describeReservedInstancesAsync(new AWSReservedInstanceAsyncHandler(service.getHost(), currentStageTaskCount, region, context));
                });
            }
        }
    };
}
Also used : AsyncHandler(com.amazonaws.handlers.AsyncHandler) DescribeRegionsResult(com.amazonaws.services.ec2.model.DescribeRegionsResult) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Region(com.amazonaws.services.ec2.model.Region) DescribeRegionsRequest(com.amazonaws.services.ec2.model.DescribeRegionsRequest) Regions(com.amazonaws.regions.Regions)

Example 5 with AsyncHandler

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

the class AWSTaskStatusChecker method buildHandler.

private AsyncHandler buildHandler(T type) {
    return new AsyncHandler<AmazonWebServiceRequest, AmazonWebServiceResult>() {

        @Override
        public void onError(Exception exception) {
            // particular instanceId.
            if (exception instanceof AmazonServiceException && ((AmazonServiceException) exception).getErrorCode().equalsIgnoreCase(AWS_INVALID_INSTANCE_ID_ERROR_CODE)) {
                AWSTaskStatusChecker.this.service.logWarning("Could not retrieve status for instance %s. Retrying... Exception on AWS is %s", AWSTaskStatusChecker.this.instanceId, exception);
                AWSTaskStatusChecker.create(AWSTaskStatusChecker.this.amazonEC2Client, AWSTaskStatusChecker.this.instanceId, AWSTaskStatusChecker.this.desiredState, AWSTaskStatusChecker.this.failureStates, AWSTaskStatusChecker.this.consumer, AWSTaskStatusChecker.this.taskManager, AWSTaskStatusChecker.this.service, AWSTaskStatusChecker.this.expirationTimeMicros).start(type);
                return;
            } else if (exception instanceof AmazonEC2Exception && ((AmazonEC2Exception) exception).getErrorCode().equalsIgnoreCase(AWS_INVALID_VOLUME_ID_ERROR_CODE)) {
                AWSTaskStatusChecker.this.consumer.accept(null);
                return;
            }
            AWSTaskStatusChecker.this.taskManager.patchTaskToFailure(exception);
            return;
        }

        @Override
        public void onSuccess(AmazonWebServiceRequest request, AmazonWebServiceResult result) {
            String status;
            Object instance;
            String failureMessage = null;
            String stateReason = null;
            if (result instanceof DescribeInstancesResult) {
                instance = ((DescribeInstancesResult) result).getReservations().get(0).getInstances().get(0);
                Instance vm = (Instance) instance;
                status = vm.getState().getName();
                stateReason = vm.getStateReason() != null ? vm.getStateReason().getMessage() : null;
            } else if (result instanceof DescribeNatGatewaysResult) {
                instance = ((DescribeNatGatewaysResult) result).getNatGateways().get(0);
                status = ((NatGateway) instance).getState();
                // if NAT gateway creation fails, the status is still "pending";
                // rather than keep checking for status and eventually time out, get the
                // failure message and fail the task
                failureMessage = ((NatGateway) instance).getFailureMessage();
            } else if (result instanceof DescribeVolumesResult) {
                instance = ((DescribeVolumesResult) result).getVolumes().get(0);
                status = ((Volume) instance).getState().toLowerCase();
            } else {
                AWSTaskStatusChecker.this.taskManager.patchTaskToFailure(new IllegalArgumentException("Invalid type " + result));
                return;
            }
            if (failureMessage != null) {
                // operation failed; no need to keep checking for desired status
                AWSTaskStatusChecker.this.taskManager.patchTaskToFailure(new IllegalStateException(failureMessage));
                return;
            } else if (AWSTaskStatusChecker.this.failureStates.contains(status)) {
                // operation failed; no need to keep checking for desired status
                AWSTaskStatusChecker.this.taskManager.patchTaskToFailure(new IllegalStateException("Resource is state:[" + status + "]," + "reason:" + stateReason));
                return;
            } else if (!status.equals(AWSTaskStatusChecker.this.desiredState)) {
                AWSTaskStatusChecker.this.service.logInfo("Instance %s not yet in desired state %s. Current state %s, failure states %s, waiting 5s", AWSTaskStatusChecker.this.instanceId, AWSTaskStatusChecker.this.desiredState, status, AWSTaskStatusChecker.this.failureStates);
                // if the instance is not in the desired state, schedule thread
                // to run again in 5 seconds
                AWSTaskStatusChecker.this.service.getHost().schedule(() -> {
                    AWSTaskStatusChecker.create(AWSTaskStatusChecker.this.amazonEC2Client, AWSTaskStatusChecker.this.instanceId, AWSTaskStatusChecker.this.desiredState, AWSTaskStatusChecker.this.failureStates, AWSTaskStatusChecker.this.consumer, AWSTaskStatusChecker.this.taskManager, AWSTaskStatusChecker.this.service, AWSTaskStatusChecker.this.expirationTimeMicros).start(type);
                }, 5, TimeUnit.SECONDS);
                return;
            }
            AWSTaskStatusChecker.this.consumer.accept(instance);
            return;
        }
    };
}
Also used : AsyncHandler(com.amazonaws.handlers.AsyncHandler) Instance(com.amazonaws.services.ec2.model.Instance) DescribeNatGatewaysResult(com.amazonaws.services.ec2.model.DescribeNatGatewaysResult) NatGateway(com.amazonaws.services.ec2.model.NatGateway) AmazonWebServiceRequest(com.amazonaws.AmazonWebServiceRequest) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) AmazonWebServiceResult(com.amazonaws.AmazonWebServiceResult) Volume(com.amazonaws.services.ec2.model.Volume) AmazonServiceException(com.amazonaws.AmazonServiceException) DescribeVolumesResult(com.amazonaws.services.ec2.model.DescribeVolumesResult) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception)

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