Search in sources :

Example 31 with DeferredResult

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;
    });
}
Also used : LINK(com.vmware.xenon.common.ServiceDocumentDescription.PropertyUsageOption.LINK) QueryTask(com.vmware.xenon.services.common.QueryTask) ServiceDocument(com.vmware.xenon.common.ServiceDocument) SecurityGroupState(com.vmware.photon.controller.model.resources.SecurityGroupService.SecurityGroupState) Utils(com.vmware.xenon.common.Utils) UriPaths(com.vmware.photon.controller.model.UriPaths) Map(java.util.Map) PropertyUsageOption(com.vmware.xenon.common.ServiceDocumentDescription.PropertyUsageOption) URI(java.net.URI) AssertUtil(com.vmware.photon.controller.model.util.AssertUtil) FIXED_ITEM_NAME(com.vmware.xenon.common.ServiceDocumentDescription.PropertyIndexingOption.FIXED_ITEM_NAME) Operation(com.vmware.xenon.common.Operation) NicSecurityGroupsRequest(com.vmware.photon.controller.model.adapterapi.NicSecurityGroupsRequest) QueryUtils(com.vmware.photon.controller.model.query.QueryUtils) Set(java.util.Set) OperationRequestType(com.vmware.photon.controller.model.adapterapi.NicSecurityGroupsRequest.OperationRequestType) Collectors(java.util.stream.Collectors) OPTIONAL(com.vmware.xenon.common.ServiceDocumentDescription.PropertyUsageOption.OPTIONAL) List(java.util.List) NicSecurityGroupsTaskState(com.vmware.photon.controller.model.tasks.NicSecurityGroupsTaskService.NicSecurityGroupsTaskState) DeferredResult(com.vmware.xenon.common.DeferredResult) UriUtils(com.vmware.xenon.common.UriUtils) TaskState(com.vmware.xenon.common.TaskState) REQUIRED(com.vmware.xenon.common.ServiceDocumentDescription.PropertyUsageOption.REQUIRED) EXPAND(com.vmware.xenon.common.ServiceDocumentDescription.PropertyIndexingOption.EXPAND) TaskService(com.vmware.xenon.services.common.TaskService) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) QueryTask(com.vmware.xenon.services.common.QueryTask) SecurityGroupState(com.vmware.photon.controller.model.resources.SecurityGroupService.SecurityGroupState)

Example 32 with DeferredResult

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;
}
Also used : AmazonCloudWatchAsyncClientBuilder(com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClientBuilder) PowerState(com.vmware.photon.controller.model.resources.ComputeService.PowerState) AWSStaticCredentialsProvider(com.amazonaws.auth.AWSStaticCredentialsProvider) Arrays(java.util.Arrays) AmazonS3ClientBuilder(com.amazonaws.services.s3.AmazonS3ClientBuilder) PROVISIONED_SSD_MIN_SIZE_IN_MB(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.PROVISIONED_SSD_MIN_SIZE_IN_MB) AWSCsvBillParser(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSCsvBillParser) DEVICE_NAME(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.DEVICE_NAME) ObjectListing(com.amazonaws.services.s3.model.ObjectListing) INSTANCE_STATE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.INSTANCE_STATE) AmazonElasticLoadBalancingAsyncClientBuilder(com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingAsyncClientBuilder) AssumeRoleRequest(com.amazonaws.services.securitytoken.model.AssumeRoleRequest) Utils(com.vmware.xenon.common.Utils) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest) AWSSecurityTokenServiceException(com.amazonaws.services.securitytoken.model.AWSSecurityTokenServiceException) Map(java.util.Map) Credentials(com.amazonaws.services.securitytoken.model.Credentials) EXTERNAL_ID_KEY(com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.EXTERNAL_ID_KEY) TransferManagerBuilder(com.amazonaws.services.s3.transfer.TransferManagerBuilder) AWSClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager) AmazonServiceException(com.amazonaws.AmazonServiceException) AWSAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSAsyncHandler) StatelessService(com.vmware.xenon.common.StatelessService) Set(java.util.Set) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup) AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) AWSSecurityTokenServiceAsyncClientBuilder(com.amazonaws.services.securitytoken.AWSSecurityTokenServiceAsyncClientBuilder) ResourceOperation(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperation) AssumeRoleResult(com.amazonaws.services.securitytoken.model.AssumeRoleResult) BackoffStrategy(com.amazonaws.retry.RetryPolicy.BackoffStrategy) Tag(com.amazonaws.services.ec2.model.Tag) DeferredResult(com.vmware.xenon.common.DeferredResult) STATUS_CODE_UNAUTHORIZED(com.vmware.xenon.common.Operation.STATUS_CODE_UNAUTHORIZED) DescribeTagsRequest(com.amazonaws.services.ec2.model.DescribeTagsRequest) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) VOLUME_TYPE_PROVISIONED_SSD(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.VOLUME_TYPE_PROVISIONED_SSD) AWSDeferredResultAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSDeferredResultAsyncHandler) AmazonClientException(com.amazonaws.AmazonClientException) SESSION_TOKEN_KEY(com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.SESSION_TOKEN_KEY) OperationContext(com.vmware.xenon.common.OperationContext) InstanceAttributeName(com.amazonaws.services.ec2.model.InstanceAttributeName) ComputeDescriptionService(com.vmware.photon.controller.model.resources.ComputeDescriptionService) InstanceBlockDeviceMappingSpecification(com.amazonaws.services.ec2.model.InstanceBlockDeviceMappingSpecification) INSTANCE_STATE_STOPPING(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.INSTANCE_STATE_STOPPING) ArrayList(java.util.ArrayList) Regions(com.amazonaws.regions.Regions) InstanceStateChange(com.amazonaws.services.ec2.model.InstanceStateChange) ServiceStateCollectionUpdateRequest(com.vmware.xenon.common.ServiceStateCollectionUpdateRequest) UriPaths(com.vmware.photon.controller.model.UriPaths) BiConsumer(java.util.function.BiConsumer) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider) Filter(com.amazonaws.services.ec2.model.Filter) InstanceState(com.amazonaws.services.ec2.model.InstanceState) AmazonS3(com.amazonaws.services.s3.AmazonS3) DEVICE_TYPE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.DEVICE_TYPE) ResourceState(com.vmware.photon.controller.model.resources.ResourceState) STATUS_CODE_FORBIDDEN(com.vmware.xenon.common.Operation.STATUS_CODE_FORBIDDEN) INSTANCE_STATE_RUNNING(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.INSTANCE_STATE_RUNNING) DeleteTagsRequest(com.amazonaws.services.ec2.model.DeleteTagsRequest) Bucket(com.amazonaws.services.s3.model.Bucket) ModifyInstanceAttributeResult(com.amazonaws.services.ec2.model.ModifyInstanceAttributeResult) VOLUME_TYPE_GENERAL_PURPOSED_SSD(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.VOLUME_TYPE_GENERAL_PURPOSED_SSD) ClientConfiguration(com.amazonaws.ClientConfiguration) AsyncHandler(com.amazonaws.handlers.AsyncHandler) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) PROVISIONED_SSD_MAX_SIZE_IN_MB(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.PROVISIONED_SSD_MAX_SIZE_IN_MB) ComputeEnumerateAdapterRequest(com.vmware.photon.controller.model.adapters.util.ComputeEnumerateAdapterRequest) AWSNicContext(com.vmware.photon.controller.model.adapters.awsadapter.AWSInstanceContext.AWSNicContext) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) RetryPolicy(com.amazonaws.retry.RetryPolicy) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) Service(com.vmware.xenon.common.Service) AWSSecurityTokenServiceAsync(com.amazonaws.services.securitytoken.AWSSecurityTokenServiceAsync) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) Pair(com.vmware.photon.controller.model.adapters.util.Pair) DEFAULT_BACKOFF_STRATEGY(com.amazonaws.retry.PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY) INSTANCE_STATE_SHUTTING_DOWN(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.INSTANCE_STATE_SHUTTING_DOWN) Date(java.util.Date) AwsClientBuilder(com.amazonaws.client.builder.AwsClientBuilder) AmazonEC2AsyncClientBuilder(com.amazonaws.services.ec2.AmazonEC2AsyncClientBuilder) CreateTagsRequest(com.amazonaws.services.ec2.model.CreateTagsRequest) EbsInstanceBlockDeviceSpecification(com.amazonaws.services.ec2.model.EbsInstanceBlockDeviceSpecification) DescribeAvailabilityZonesRequest(com.amazonaws.services.ec2.model.DescribeAvailabilityZonesRequest) DEFAULT_SECURITY_GROUP_NAME(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSSecurityGroupClient.DEFAULT_SECURITY_GROUP_NAME) Collection(java.util.Collection) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) UUID(java.util.UUID) INSTANCE_STATE_PENDING(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.INSTANCE_STATE_PENDING) Collectors(java.util.stream.Collectors) ServiceHost(com.vmware.xenon.common.ServiceHost) VOLUME_TYPE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.VOLUME_TYPE) DEFAULT_RETRY_CONDITION(com.amazonaws.retry.PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION) Objects(java.util.Objects) AmazonElasticLoadBalancingAsyncClient(com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingAsyncClient) List(java.util.List) Optional(java.util.Optional) AWS_MOCK_HOST_SYSTEM_PROPERTY(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_MOCK_HOST_SYSTEM_PROPERTY) DiskService(com.vmware.photon.controller.model.resources.DiskService) TransferManager(com.amazonaws.services.s3.transfer.TransferManager) DescribeAvailabilityZonesResult(com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult) AmazonCloudWatchAsyncClient(com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClient) HashMap(java.util.HashMap) SESSION_EXPIRATION_TIME_MICROS_KEY(com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.SESSION_EXPIRATION_TIME_MICROS_KEY) DeleteSecurityGroupResult(com.amazonaws.services.ec2.model.DeleteSecurityGroupResult) Level(java.util.logging.Level) BasicSessionCredentials(com.amazonaws.auth.BasicSessionCredentials) Datapoint(com.amazonaws.services.cloudwatch.model.Datapoint) AWSSecurityGroupClient(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSSecurityGroupClient) DescribeVpcsResult(com.amazonaws.services.ec2.model.DescribeVpcsResult) INSTANCE_STATE_STOPPED(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.INSTANCE_STATE_STOPPED) CollectionUtils(org.apache.commons.collections.CollectionUtils) AWS_S3PROXY_SYSTEM_PROPERTY(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_S3PROXY_SYSTEM_PROPERTY) Instance(com.amazonaws.services.ec2.model.Instance) TagDescription(com.amazonaws.services.ec2.model.TagDescription) ExecutorService(java.util.concurrent.ExecutorService) AmazonWebServiceRequest(com.amazonaws.AmazonWebServiceRequest) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) AWS_TAG_NAME(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_TAG_NAME) Vpc(com.amazonaws.services.ec2.model.Vpc) EncryptionUtils(com.vmware.photon.controller.model.security.util.EncryptionUtils) Operation(com.vmware.xenon.common.Operation) DeleteSecurityGroupRequest(com.amazonaws.services.ec2.model.DeleteSecurityGroupRequest) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) DescribeTagsResult(com.amazonaws.services.ec2.model.DescribeTagsResult) ModifyInstanceAttributeRequest(com.amazonaws.services.ec2.model.ModifyInstanceAttributeRequest) ARN_KEY(com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.ARN_KEY) Collections(java.util.Collections) ModifyInstanceAttributeRequest(com.amazonaws.services.ec2.model.ModifyInstanceAttributeRequest) InstanceBlockDeviceMappingSpecification(com.amazonaws.services.ec2.model.InstanceBlockDeviceMappingSpecification) ModifyInstanceAttributeResult(com.amazonaws.services.ec2.model.ModifyInstanceAttributeResult) AWSSecurityTokenServiceException(com.amazonaws.services.securitytoken.model.AWSSecurityTokenServiceException) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonClientException(com.amazonaws.AmazonClientException) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) DiskService(com.vmware.photon.controller.model.resources.DiskService) AWSAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSAsyncHandler) EbsInstanceBlockDeviceSpecification(com.amazonaws.services.ec2.model.EbsInstanceBlockDeviceSpecification) DeferredResult(com.vmware.xenon.common.DeferredResult)

Example 33 with DeferredResult

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);
            });
        }
    });
}
Also used : Service(com.vmware.xenon.common.Service) Arrays(java.util.Arrays) DetachVolumeRequest(com.amazonaws.services.ec2.model.DetachVolumeRequest) Pair(com.vmware.photon.controller.model.adapters.util.Pair) ResourceOperationUtils.handleAdapterResourceOperationRegistration(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationUtils.handleAdapterResourceOperationRegistration) StopInstancesResult(com.amazonaws.services.ec2.model.StopInstancesResult) AttachVolumeRequest(com.amazonaws.services.ec2.model.AttachVolumeRequest) ResourceOperationSpecService(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationSpecService) ServiceDocument(com.vmware.xenon.common.ServiceDocument) DetachVolumeResult(com.amazonaws.services.ec2.model.DetachVolumeResult) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest) AWS_DISK_OPERATION_TIMEOUT_MINUTES(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_DISK_OPERATION_TIMEOUT_MINUTES) DEVICE_NAME(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.DEVICE_NAME) ResourceOperationRequest(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationRequest) Utils(com.vmware.xenon.common.Utils) AttachVolumeResult(com.amazonaws.services.ec2.model.AttachVolumeResult) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest) AWSBlockDeviceNameMapper(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSBlockDeviceNameMapper) Map(java.util.Map) AWSClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager) Reservation(com.amazonaws.services.ec2.model.Reservation) AWSAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSAsyncHandler) StatelessService(com.vmware.xenon.common.StatelessService) StartInstancesResult(com.amazonaws.services.ec2.model.StartInstancesResult) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) AWS_INSTANCE_ID_PREFIX(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_INSTANCE_ID_PREFIX) List(java.util.List) AWSSupportedOS(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWSSupportedOS) ResourceOperation(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperation) DeferredResult(com.vmware.xenon.common.DeferredResult) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) Optional(java.util.Optional) FactoryService(com.vmware.xenon.common.FactoryService) DiskService(com.vmware.photon.controller.model.resources.DiskService) OperationContext(com.vmware.xenon.common.OperationContext) HashMap(java.util.HashMap) AWS_VOLUME_ID_PREFIX(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_VOLUME_ID_PREFIX) Function(java.util.function.Function) ArrayList(java.util.ArrayList) InstanceBlockDeviceMapping(com.amazonaws.services.ec2.model.InstanceBlockDeviceMapping) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) Volume(com.amazonaws.services.ec2.model.Volume) Instance(com.amazonaws.services.ec2.model.Instance) AWSStorageType(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWSStorageType) Operation(com.vmware.xenon.common.Operation) BaseAdapterStage(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.BaseAdapterStage) AWSSupportedVirtualizationTypes(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWSSupportedVirtualizationTypes) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) DefaultAdapterContext(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.DefaultAdapterContext) PhotonModelConstants(com.vmware.photon.controller.model.constants.PhotonModelConstants) AWSClientManagerFactory(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) StartInstancesResult(com.amazonaws.services.ec2.model.StartInstancesResult) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest)

Example 34 with DeferredResult

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);
        }
    });
}
Also used : Service(com.vmware.xenon.common.Service) Arrays(java.util.Arrays) DetachVolumeRequest(com.amazonaws.services.ec2.model.DetachVolumeRequest) Pair(com.vmware.photon.controller.model.adapters.util.Pair) ResourceOperationUtils.handleAdapterResourceOperationRegistration(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationUtils.handleAdapterResourceOperationRegistration) StopInstancesResult(com.amazonaws.services.ec2.model.StopInstancesResult) AttachVolumeRequest(com.amazonaws.services.ec2.model.AttachVolumeRequest) ResourceOperationSpecService(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationSpecService) ServiceDocument(com.vmware.xenon.common.ServiceDocument) DetachVolumeResult(com.amazonaws.services.ec2.model.DetachVolumeResult) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest) AWS_DISK_OPERATION_TIMEOUT_MINUTES(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_DISK_OPERATION_TIMEOUT_MINUTES) DEVICE_NAME(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.DEVICE_NAME) ResourceOperationRequest(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationRequest) Utils(com.vmware.xenon.common.Utils) AttachVolumeResult(com.amazonaws.services.ec2.model.AttachVolumeResult) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest) AWSBlockDeviceNameMapper(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSBlockDeviceNameMapper) Map(java.util.Map) AWSClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager) Reservation(com.amazonaws.services.ec2.model.Reservation) AWSAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSAsyncHandler) StatelessService(com.vmware.xenon.common.StatelessService) StartInstancesResult(com.amazonaws.services.ec2.model.StartInstancesResult) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) AWS_INSTANCE_ID_PREFIX(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_INSTANCE_ID_PREFIX) List(java.util.List) AWSSupportedOS(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWSSupportedOS) ResourceOperation(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperation) DeferredResult(com.vmware.xenon.common.DeferredResult) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) Optional(java.util.Optional) FactoryService(com.vmware.xenon.common.FactoryService) DiskService(com.vmware.photon.controller.model.resources.DiskService) OperationContext(com.vmware.xenon.common.OperationContext) HashMap(java.util.HashMap) AWS_VOLUME_ID_PREFIX(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_VOLUME_ID_PREFIX) Function(java.util.function.Function) ArrayList(java.util.ArrayList) InstanceBlockDeviceMapping(com.amazonaws.services.ec2.model.InstanceBlockDeviceMapping) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) Volume(com.amazonaws.services.ec2.model.Volume) Instance(com.amazonaws.services.ec2.model.Instance) AWSStorageType(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWSStorageType) Operation(com.vmware.xenon.common.Operation) BaseAdapterStage(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.BaseAdapterStage) AWSSupportedVirtualizationTypes(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWSSupportedVirtualizationTypes) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) DefaultAdapterContext(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.DefaultAdapterContext) PhotonModelConstants(com.vmware.photon.controller.model.constants.PhotonModelConstants) AWSClientManagerFactory(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) DefaultAdapterContext(com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.DefaultAdapterContext) ResourceOperationRequest(com.vmware.photon.controller.model.adapters.registry.operations.ResourceOperationRequest) DeferredResult(com.vmware.xenon.common.DeferredResult)

Example 35 with DeferredResult

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;
}
Also used : AttachVolumeRequest(com.amazonaws.services.ec2.model.AttachVolumeRequest) AttachVolumeResult(com.amazonaws.services.ec2.model.AttachVolumeResult) DeferredResult(com.vmware.xenon.common.DeferredResult)

Aggregations

DeferredResult (com.vmware.xenon.common.DeferredResult)77 ArrayList (java.util.ArrayList)57 Operation (com.vmware.xenon.common.Operation)52 List (java.util.List)49 Collectors (java.util.stream.Collectors)43 StatelessService (com.vmware.xenon.common.StatelessService)42 Utils (com.vmware.xenon.common.Utils)38 Map (java.util.Map)38 HashMap (java.util.HashMap)37 UriUtils (com.vmware.xenon.common.UriUtils)36 DiskService (com.vmware.photon.controller.model.resources.DiskService)33 PhotonModelUriUtils.createInventoryUri (com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri)33 URI (java.net.URI)33 Collection (java.util.Collection)32 Set (java.util.Set)31 HashSet (java.util.HashSet)30 DiskState (com.vmware.photon.controller.model.resources.DiskService.DiskState)29 QueryTask (com.vmware.xenon.services.common.QueryTask)28 Consumer (java.util.function.Consumer)28 OperationJoin (com.vmware.xenon.common.OperationJoin)26