use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AWSComputeDiskDay2Service method performDetachOperation.
private DeferredResult<DiskContext> performDetachOperation(DiskContext context) {
DeferredResult<DiskContext> dr = new DeferredResult<>();
try {
validateDetachInfo(context.diskState);
if (context.request.isMockRequest) {
updateComputeAndDiskState(dr, context, null);
return dr;
}
String instanceId = context.computeState.id;
if (instanceId == null || !instanceId.startsWith(AWS_INSTANCE_ID_PREFIX)) {
return logAndGetFailedDr(context, "compute id cannot be empty");
}
String diskId = context.diskState.id;
if (diskId == null || !diskId.startsWith(AWS_VOLUME_ID_PREFIX)) {
return logAndGetFailedDr(context, "disk id cannot be empty");
}
// stop the instance, detach the disk and then start the instance.
if (context.baseAdapterContext.child.powerState.equals(ComputeService.PowerState.ON)) {
StopInstancesRequest stopRequest = new StopInstancesRequest();
stopRequest.withInstanceIds(context.baseAdapterContext.child.id);
context.amazonEC2Client.stopInstancesAsync(stopRequest, new AWSAsyncHandler<StopInstancesRequest, StopInstancesResult>() {
@Override
protected void handleError(Exception e) {
service.logSevere(() -> String.format("[AWSComputeDiskDay2Service] Failed to start compute. %s", Utils.toString(e)));
OperationContext.restoreOperationContext(this.opContext);
context.error = e;
dr.complete(context);
}
@Override
protected void handleSuccess(StopInstancesRequest request, StopInstancesResult result) {
OperationContext.restoreOperationContext(this.opContext);
AWSUtils.waitForTransitionCompletion(getHost(), result.getStoppingInstances(), "stopped", context.amazonEC2Client, (is, e) -> {
if (e != null) {
service.logSevere(() -> String.format("[AWSComputeDiskDay2Service] Failed to stop " + "the compute. %s", Utils.toString(e)));
context.error = e;
dr.complete(context);
return;
}
logInfo(() -> String.format("[AWSComputeDiskDay2Service] Successfully stopped " + "the instance %s", instanceId));
// detach disk from the instance.
detachVolume(context, dr, instanceId, diskId, true);
});
}
});
} else {
detachVolume(context, dr, instanceId, diskId, false);
}
} catch (Exception e) {
context.error = e;
return DeferredResult.completed(context);
}
return dr;
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AWSSecurityGroupEnumerationAdapterService method createResponse.
/**
* Having the enumerated SecurityGroup Ids, query the States and provide them in the response
*/
private DeferredResult<AWSSecurityGroupEnumerationResponse> createResponse(SecurityGroupEnumContext context) {
AWSSecurityGroupEnumerationResponse response = new AWSSecurityGroupEnumerationResponse();
if (context.enumExternalResourcesIds == null || context.enumExternalResourcesIds.isEmpty()) {
DeferredResult<AWSSecurityGroupEnumerationResponse> deferredResult = new DeferredResult<>();
deferredResult.complete(response);
return deferredResult;
}
Query.Builder findSecurityGroupStates = Builder.create().addKindFieldClause(SecurityGroupState.class).addFieldClause(ResourceState.FIELD_NAME_COMPUTE_HOST_LINK, context.request.parentCompute.documentSelfLink).addInClause(SecurityGroupState.FIELD_NAME_ID, context.enumExternalResourcesIds);
QueryTop<SecurityGroupState> querySecurityGroupStates = new QueryTop<>(context.service.getHost(), findSecurityGroupStates.build(), SecurityGroupState.class, context.request.parentCompute.tenantLinks).setMaxResultsLimit(context.enumExternalResourcesIds.size());
querySecurityGroupStates.setClusterType(ServiceTypeCluster.INVENTORY_SERVICE);
return querySecurityGroupStates.queryDocuments(sgState -> response.securityGroupStates.put(sgState.id, sgState.documentSelfLink)).thenApply(aVoid -> response);
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AWSNetworkStateEnumerationAdapterService method updateTagLinks.
private DeferredResult<AWSNetworkStateCreationContext> updateTagLinks(AWSNetworkStateCreationContext context) {
if ((context.awsVpcs == null || context.awsVpcs.isEmpty()) && (context.awsSubnets == null || context.awsSubnets.isEmpty())) {
logFine(() -> "No local vpcs or subnets to be updated so there are no tags to update.");
return DeferredResult.completed(context);
} else {
List<DeferredResult<Set<String>>> updateNetworkSubnetTagLinksOps = new ArrayList<>();
// update tag links for the existing NetworkStates
for (String vpcId : context.awsVpcs.keySet()) {
if (!context.localNetworkStateMap.containsKey(vpcId)) {
// this is not a network to update
continue;
}
Vpc vpc = context.awsVpcs.get(vpcId);
NetworkState existingNetworkState = context.localNetworkStateMap.get(vpcId);
Map<String, String> remoteTags = new HashMap<>();
for (Tag awsVpcTag : vpc.getTags()) {
if (!awsVpcTag.getKey().equals(AWSConstants.AWS_TAG_NAME)) {
remoteTags.put(awsVpcTag.getKey(), awsVpcTag.getValue());
}
}
updateNetworkSubnetTagLinksOps.add(updateLocalTagStates(this, existingNetworkState, remoteTags, null));
}
// update tag links for the existing SubnetStates
for (String subnetId : context.awsSubnets.keySet()) {
if (!context.localSubnetStateMap.containsKey(subnetId)) {
// this is not a subnet to update
continue;
}
Subnet subnet = context.awsSubnets.get(subnetId);
SubnetState existingSubnetState = context.localSubnetStateMap.get(subnetId);
Map<String, String> remoteTags = new HashMap<>();
for (Tag awsSubnetTag : subnet.getTags()) {
if (!awsSubnetTag.getKey().equals(AWSConstants.AWS_TAG_NAME)) {
remoteTags.put(awsSubnetTag.getKey(), awsSubnetTag.getValue());
}
}
updateNetworkSubnetTagLinksOps.add(updateLocalTagStates(this, existingSubnetState, remoteTags, null));
}
return DeferredResult.allOf(updateNetworkSubnetTagLinksOps).thenApply(ignore -> context);
}
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AWSNetworkStateEnumerationAdapterService method deleteStaleLocalStates.
private DeferredResult<AWSNetworkStateCreationContext> deleteStaleLocalStates(AWSNetworkStateCreationContext context, Class<? extends ResourceState> localStateClass, Set<String> remoteResourcesKeys) {
final String msg = "Delete %ss that no longer exist in the endpoint: %s";
logFine(() -> String.format(msg, localStateClass.getSimpleName(), "STARTING"));
Query.Builder qBuilder = Query.Builder.create().addKindFieldClause(localStateClass).addFieldClause("lifecycleState", LifecycleState.PROVISIONING.toString(), Occurance.MUST_NOT_OCCUR).addRangeClause(ServiceDocument.FIELD_NAME_UPDATE_TIME_MICROS, createLessThanRange(context.enumStartTimeInMicros));
if (context.request.regionId != null) {
// Delete resources only in this End-point region
qBuilder.addFieldClause(ResourceState.FIELD_NAME_REGION_ID, context.request.regionId);
}
if (!remoteResourcesKeys.isEmpty() && remoteResourcesKeys.size() <= MAX_RESOURCES_TO_QUERY_ON_DELETE) {
// do not load resources from enumExternalResourcesIds
qBuilder.addInClause(ResourceState.FIELD_NAME_ID, remoteResourcesKeys, Occurance.MUST_NOT_OCCUR);
}
QueryByPages<? extends ResourceState> queryLocalStates = new QueryByPages<>(getHost(), qBuilder.build(), localStateClass, context.request.tenantLinks, context.request.request.endpointLink);
queryLocalStates.setClusterType(ServiceTypeCluster.INVENTORY_SERVICE);
List<DeferredResult<Operation>> disassociateDRs = new ArrayList<>();
// Delete stale resources.
return queryLocalStates.queryDocuments(localState -> {
if (remoteResourcesKeys.contains(localState.id)) {
return;
}
// Deleting the localResourceState is done by disassociating the
// endpointLink from the localResourceState. If the localResourceState
// isn't associated with any other endpointLink, it should be eventually
// deleted by the groomer task
Operation disassociateOp = PhotonModelUtils.createRemoveEndpointLinksOperation(this, context.request.request.endpointLink, localState);
if (disassociateOp == null) {
return;
}
// NOTE: The original Op is set with completion that must be executed.
// Since sendWithDeferredResult is used we must manually call it, otherwise it's
// just ignored.
CompletionHandler disassociateOpCompletion = disassociateOp.getCompletion();
DeferredResult<Operation> disassociateDR = sendWithDeferredResult(disassociateOp).whenComplete(disassociateOpCompletion::handle).whenComplete((o, e) -> {
final String message = "Disassociate stale %s state";
if (e != null) {
logWarning(message + ": FAILED with %s", localState.documentSelfLink, Utils.toString(e));
} else {
log(Level.FINEST, message + ": SUCCESS", localState.documentSelfLink);
}
});
disassociateDRs.add(disassociateDR);
}).thenCompose(ignore -> DeferredResult.allOf(disassociateDRs)).thenApply(ignore -> context);
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class BaseAdaptersRegistryServiceTest method tearDown.
@After
public void tearDown() {
if (!this.documentsToDelete.isEmpty()) {
List<DeferredResult<Operation>> ops = new ArrayList<>();
this.documentsToDelete.forEach(documentSelfLink -> {
this.logger.info("Going to delete: " + documentSelfLink);
Operation dOp = Operation.createDelete(this.host, documentSelfLink);
DeferredResult<Operation> dr = this.host.sendWithDeferredResult(dOp).whenComplete((o, e) -> {
final String msg = "Delete state: " + documentSelfLink;
if (e != null) {
this.logger.warning(msg + " : ERROR. Cause: " + Utils.toString(e));
} else {
this.logger.info(msg + " : SUCCESS");
}
});
ops.add(dr);
});
join(DeferredResult.allOf(ops));
}
}
Aggregations