use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class NicSecurityGroupsTaskService method validateSecurityGroupsEndpoint.
/**
* Validate that all security groups belong to the same endpoint
*/
private DeferredResult<Void> validateSecurityGroupsEndpoint(NicSecurityGroupsTaskState state) {
QueryTask.Query query = QueryTask.Query.Builder.create().addKindFieldClause(SecurityGroupState.class).addInClause(ServiceDocument.FIELD_NAME_SELF_LINK, state.securityGroupLinks).build();
QueryTask queryTask = QueryTask.Builder.createDirectTask().setQuery(query).addSelectTerm(SecurityGroupState.FIELD_NAME_ENDPOINT_LINK).addOption(QueryTask.QuerySpecification.QueryOption.EXPAND_SELECTED_FIELDS).build();
return QueryUtils.startInventoryQueryTask(this, queryTask).thenApply(qrt -> {
AssertUtil.assertTrue(qrt != null && qrt.results.documentCount > 0, String.format("Could not find security groups with links %s", state.securityGroupLinks));
Set<String> endpointLinks = qrt.results.documents.values().stream().map(o -> Utils.fromJson(o, SecurityGroupState.class).endpointLink).collect(Collectors.toSet());
// we only support security groups from the same endpoint for the same request
if (endpointLinks.size() != 1) {
throw new IllegalArgumentException("All security groups must belong to the same endpoint.");
}
if (endpointLinks.iterator().next() == null) {
throw new IllegalArgumentException("All security groups must have endpoint link set.");
}
return null;
});
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AWSUtils method setDeleteOnTerminateAttribute.
public static DeferredResult<DiskService.DiskState> setDeleteOnTerminateAttribute(AmazonEC2AsyncClient client, String instanceId, Map<String, Pair<String, Boolean>> deleteDiskMapByDeviceName, OperationContext opCtx) {
List<InstanceBlockDeviceMappingSpecification> instanceBlockDeviceMappingSpecificationList = deleteDiskMapByDeviceName.entrySet().stream().map(entry -> new InstanceBlockDeviceMappingSpecification().withDeviceName(entry.getKey()).withEbs(new EbsInstanceBlockDeviceSpecification().withDeleteOnTermination(entry.getValue().right).withVolumeId(entry.getValue().left))).collect(Collectors.toList());
DeferredResult<DiskService.DiskState> modifyInstanceAttrDr = new DeferredResult();
ModifyInstanceAttributeRequest modifyInstanceAttrReq = new ModifyInstanceAttributeRequest().withInstanceId(instanceId).withAttribute(InstanceAttributeName.BlockDeviceMapping).withBlockDeviceMappings(instanceBlockDeviceMappingSpecificationList);
AWSAsyncHandler<ModifyInstanceAttributeRequest, ModifyInstanceAttributeResult> modifyInstanceAttrHandler = new AWSAsyncHandler<ModifyInstanceAttributeRequest, ModifyInstanceAttributeResult>() {
@Override
protected void handleError(Exception exception) {
OperationContext.restoreOperationContext(opCtx);
modifyInstanceAttrDr.fail(exception);
}
@Override
protected void handleSuccess(ModifyInstanceAttributeRequest request, ModifyInstanceAttributeResult result) {
OperationContext.restoreOperationContext(opCtx);
modifyInstanceAttrDr.complete(new DiskService.DiskState());
}
};
client.modifyInstanceAttributeAsync(modifyInstanceAttrReq, modifyInstanceAttrHandler);
return modifyInstanceAttrDr;
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AWSComputeDiskDay2Service method startInstance.
/**
* start the instance and on success updates the disk and compute state to reflect the detach information.
*/
private void startInstance(AmazonEC2AsyncClient client, DiskContext c, DeferredResult<DiskContext> dr, OperationContext opCtx) {
StartInstancesRequest startRequest = new StartInstancesRequest();
startRequest.withInstanceIds(c.baseAdapterContext.child.id);
client.startInstancesAsync(startRequest, new AWSAsyncHandler<StartInstancesRequest, StartInstancesResult>() {
@Override
protected void handleError(Exception e) {
service.logSevere(() -> String.format("[AWSComputeDiskDay2Service] Failed to start the instance %s. %s", c.baseAdapterContext.child.id, Utils.toString(e)));
OperationContext.restoreOperationContext(opCtx);
c.error = e;
dr.complete(c);
}
@Override
protected void handleSuccess(StartInstancesRequest request, StartInstancesResult result) {
AWSUtils.waitForTransitionCompletion(getHost(), result.getStartingInstances(), "running", client, (is, e) -> {
if (e != null) {
service.logSevere(() -> String.format("[AWSComputeDiskDay2Service] Instance %s failed to reach " + "running state. %s", c.baseAdapterContext.child.id, Utils.toString(e)));
OperationContext.restoreOperationContext(opCtx);
c.error = e;
dr.complete(c);
return;
}
logInfo(() -> String.format("[AWSComputeDiskDay2Service] Successfully started the " + "instance %s", result.getStartingInstances().get(0).getInstanceId()));
updateComputeAndDiskState(dr, c, opCtx);
});
}
});
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AWSComputeDiskDay2Service method handlePatch.
@Override
public void handlePatch(Operation op) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ResourceOperationRequest request = op.getBody(ResourceOperationRequest.class);
try {
validateRequest(request);
op.complete();
} catch (Exception e) {
op.fail(e);
return;
}
// initialize context with baseAdapterContext and request information
DeferredResult<DiskContext> drDiskContext = new DefaultAdapterContext(this, request).populateBaseContext(BaseAdapterStage.VMDESC).thenApply(c -> {
DiskContext context = new DiskContext();
context.baseAdapterContext = c;
context.request = request;
return context;
});
Function<DiskContext, DeferredResult<DiskContext>> fn;
// handle resource operation
if (request.operation.equals(ResourceOperation.ATTACH_DISK.operation)) {
fn = this::performAttachOperation;
} else if (request.operation.equals(ResourceOperation.DETACH_DISK.operation)) {
fn = this::performDetachOperation;
} else {
drDiskContext.thenApply(c -> {
Throwable err = new IllegalArgumentException(String.format("Unknown Operation %s for a disk", request.operation));
c.baseAdapterContext.taskManager.patchTaskToFailure(err);
return c;
});
return;
}
drDiskContext.thenCompose(this::setComputeState).thenCompose(this::setDiskState).thenCompose(this::setClient).thenCompose(fn).whenComplete((ctx, e) -> {
if (ctx.error == null) {
ctx.baseAdapterContext.taskManager.finishTask();
} else {
ctx.baseAdapterContext.taskManager.patchTaskToFailure(ctx.error);
}
});
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AWSComputeDiskDay2Service method performAttachOperation.
private DeferredResult<DiskContext> performAttachOperation(DiskContext context) {
DeferredResult<DiskContext> dr = new DeferredResult<>();
try {
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");
}
String deviceName = getAvailableDeviceName(context, instanceId);
if (deviceName == null) {
return logAndGetFailedDr(context, "No device name is available for attaching new disk");
}
context.diskState.customProperties.put(DEVICE_NAME, deviceName);
AttachVolumeRequest attachVolumeRequest = new AttachVolumeRequest().withInstanceId(instanceId).withVolumeId(diskId).withDevice(deviceName);
AWSAsyncHandler<AttachVolumeRequest, AttachVolumeResult> attachDiskHandler = new AWSAttachDiskHandler(dr, context);
context.amazonEC2Client.attachVolumeAsync(attachVolumeRequest, attachDiskHandler);
} catch (Exception e) {
context.error = e;
return DeferredResult.completed(context);
}
return dr;
}
Aggregations