use of com.vmware.xenon.common.Operation.CompletionHandler in project photon-model by vmware.
the class EndpointAllocationTaskService method invokeAdapter.
private void invokeAdapter(EndpointAllocationTaskState currentState, SubStage next) {
CompletionHandler c = (o, e) -> {
if (e != null) {
sendFailurePatch(this, currentState, e);
return;
}
EndpointConfigRequest req = new EndpointConfigRequest();
req.isMockRequest = currentState.options.contains(TaskOption.IS_MOCK);
req.requestType = RequestType.ENHANCE;
req.tenantLinks = currentState.tenantLinks;
req.resourceReference = createInventoryUri(this.getHost(), currentState.endpointState.documentSelfLink);
ServiceDocument subTask = o.getBody(ServiceDocument.class);
req.taskReference = UriUtils.buildUri(this.getHost(), subTask.documentSelfLink);
req.endpointProperties = currentState.endpointState.endpointProperties;
sendEnhanceRequest(req, currentState);
};
createSubTask(c, next, currentState);
}
use of com.vmware.xenon.common.Operation.CompletionHandler in project photon-model by vmware.
the class ResourceEnumerationTaskService method sendEnumRequest.
private void sendEnumRequest(Operation start, ResourceEnumerationTaskState state) {
ComputeEnumerateResourceRequest req = new ComputeEnumerateResourceRequest();
req.resourcePoolLink = state.resourcePoolLink;
req.adapterManagementReference = state.adapterManagementReference;
req.resourceReference = createInventoryUri(this.getHost(), state.parentComputeLink);
req.endpointLinkReference = createInventoryUri(this.getHost(), state.endpointLink);
req.enumerationAction = state.enumerationAction;
req.taskReference = UriUtils.buildUri(getHost(), state.documentSelfLink);
req.isMockRequest = state.options.contains(TaskOption.IS_MOCK);
req.preserveMissing = state.options.contains(TaskOption.PRESERVE_MISSING_RESOUCES);
req.endpointLink = state.endpointLink;
req.deletedResourceExpirationMicros = getResourceExpirationMicros(state.expirationPolicy == null ? ResourceExpirationPolicy.EXPIRE_AFTER_ONE_MONTH : state.expirationPolicy);
// Patch the enumerate service URI from the CHD
CompletionHandler descriptionCompletion = (o, ex) -> {
if (ex != null) {
TaskUtils.sendFailurePatch(this, state, ex);
start.fail(ex);
return;
}
ComputeStateWithDescription csd = o.getBody(ComputeStateWithDescription.class);
if (csd.description.enumerationAdapterReference == null) {
// no enumeration adapter associated with this resource, just patch completion
sendSelfFinishedPatch(state);
return;
}
sendRequest(Operation.createPatch(csd.description.enumerationAdapterReference).setBody(req));
};
URI computeUri = UriUtils.extendUriWithQuery(UriUtils.buildUri(this.getHost(), state.parentComputeLink), UriUtils.URI_PARAM_ODATA_EXPAND, Boolean.TRUE.toString());
sendRequest(Operation.createGet(computeUri).setCompletion(descriptionCompletion));
}
use of com.vmware.xenon.common.Operation.CompletionHandler 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.Operation.CompletionHandler in project photon-model by vmware.
the class EndpointEnumerationProcess method disassociateLocalResourceStates.
/**
* Disassociate stale local resource states. The logic works by recording a timestamp when
* enumeration starts. This timestamp is used to lookup resources which have not been touched as
* part of current enumeration cycle. Resources not associated with any endpointLink will be
* removed by the groomer task.
* <p>
* Here is the list of criteria used to locate the stale local resources states:
* <ul>
* <li>Add local documents' kind:
* {@code qBuilder.addKindFieldClause(context.localStateClass)}</li>
* <li>Add time stamp older than current enumeration cycle:
* {@code qBuilder.addRangeClause(ServiceDocument.FIELD_NAME_UPDATE_TIME_MICROS, createLessThanRange(context.enumStartTimeInMicros))}</li>
* <li>Add {@code tenantLinks} and {@code endpointLink} criteria as defined by
* {@code QueryTemplate}</li>
* <li>Add descendant specific criteria as defined by
* {@link #customizeLocalStatesQuery(com.vmware.xenon.services.common.QueryTask.Query.Builder)}</li>
* </ul>
*/
protected DeferredResult<T> disassociateLocalResourceStates(T context) {
final String msg = "Disassociate %ss that no longer exist in the endpoint: %s";
context.service.logFine(() -> String.format(msg, context.localStateClass.getSimpleName(), "STARTING"));
Query.Builder qBuilder = Query.Builder.create().addKindFieldClause(context.localStateClass).addRangeClause(ServiceDocument.FIELD_NAME_UPDATE_TIME_MICROS, createLessThanRange(context.enumStartTimeInMicros));
if (getEndpointRegion() != null) {
// Limit documents within end-point region
qBuilder.addFieldClause(ResourceState.FIELD_NAME_REGION_ID, getEndpointRegion());
}
if (!this.enumExternalResourcesIds.isEmpty() && this.enumExternalResourcesIds.size() <= MAX_RESOURCES_TO_QUERY_ON_DELETE) {
// do not load resources from enumExternalResourcesIds
qBuilder.addInClause(ResourceState.FIELD_NAME_ID, this.enumExternalResourcesIds, Occurance.MUST_NOT_OCCUR);
}
// Delegate to descendants to any doc specific criteria
customizeLocalStatesQuery(qBuilder);
QueryByPages<LOCAL_STATE> queryLocalStates = new QueryByPages<>(context.service.getHost(), qBuilder.build(), context.localStateClass, isApplyInfraFields() ? context.endpointState.tenantLinks : null, isApplyEndpointLink() ? context.endpointState.documentSelfLink : null, null).setQueryTaskTenantLinks(context.endpointState.tenantLinks);
queryLocalStates.setClusterType(ServiceTypeCluster.INVENTORY_SERVICE);
List<DeferredResult<Operation>> disassociateDRs = new ArrayList<>();
// Delete stale resources.
return queryLocalStates.queryDocuments(localState -> {
if (!shouldDelete(localState)) {
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(context.service, context.endpointState.documentSelfLink, 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 = context.service.sendWithDeferredResult(disassociateOp).whenComplete(disassociateOpCompletion::handle).whenComplete((o, e) -> {
final String message = "Disassociate stale %s state";
if (e != null) {
context.service.logWarning(message + ": FAILED with %s", localState.documentSelfLink, Utils.toString(e));
} else {
context.service.log(Level.FINEST, message + ": SUCCESS", localState.documentSelfLink);
}
});
disassociateDRs.add(disassociateDR);
}).thenCompose(ignore -> DeferredResult.allOf(disassociateDRs)).thenApply(ignore -> context);
}
use of com.vmware.xenon.common.Operation.CompletionHandler in project photon-model by vmware.
the class AzureStorageEnumerationAdapterService method disassociateIfNotAttachedToCompute.
private DeferredResult<Operation> disassociateIfNotAttachedToCompute(StorageEnumContext context, DiskState diskState) {
Query query = Query.Builder.create().addKindFieldClause(ComputeService.ComputeState.class).addCollectionItemClause(ComputeService.ComputeState.FIELD_NAME_DISK_LINKS, diskState.documentSelfLink).build();
QueryTask queryTask = QueryTask.Builder.createDirectTask().addOption(QueryOption.COUNT).addOption(QueryOption.INDEXED_METADATA).setQuery(query).build();
queryTask.tenantLinks = diskState.tenantLinks;
if (queryTask.documentExpirationTimeMicros == 0) {
queryTask.documentExpirationTimeMicros = Utils.getNowMicrosUtc() + QueryUtils.TEN_MINUTES_IN_MICROS;
}
return QueryUtils.startInventoryQueryTask(this, queryTask).thenCompose(result -> {
if (result.results != null && result.results.documentCount != 0) {
logFine(() -> String.format("Won't disassociate disk state %s, as it is attached to machine", diskState.documentSelfLink));
return DeferredResult.completed(new Operation());
}
logFine(() -> String.format("Disassociating disk state %s", diskState.documentSelfLink));
Operation operation = PhotonModelUtils.createRemoveEndpointLinksOperation(this, context.request.endpointLink, diskState);
if (operation == null) {
return DeferredResult.completed(new Operation());
}
CompletionHandler completion = operation.getCompletion();
return sendWithDeferredResult(operation).whenComplete(completion::handle).whenComplete((o, e) -> {
final String message = "Disassociate disk state stale %s state";
if (e != null) {
logWarning(message + ": ERROR - %s", diskState.documentSelfLink, Utils.toString(e));
} else {
logFine(message + ": SUCCESS", diskState.documentSelfLink);
}
});
});
}
Aggregations