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);
}
});
}
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();
}
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);
}
});
}
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));
});
}
}
};
}
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;
}
};
}
Aggregations