Search in sources :

Example 1 with DeferredResult

use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.

the class AWSUtils method getArnSessionCredentialsAsync.

/**
 * Authenticates and returns a DeferredResult set of session credentials for a valid ARN that
 * authorizes this system's account ID (validated through
 * {@link #AWS_MASTER_ACCOUNT_ACCESS_KEY_PROPERTY} and
 * {@link #AWS_MASTER_ACCOUNT_SECRET_KEY_PROPERTY}) and the externalId parameter.
 *
 * If the system properties are unset, then this call will automatically fail.
 *
 * @param arn The Amazon Resource Name to validate.
 * @param externalId The external ID this ARN has authorized.
 * @param region The region to validate within.
 * @param executorService The executor service to issue the request.
 */
public static DeferredResult<Credentials> getArnSessionCredentialsAsync(String arn, String externalId, String region, ExecutorService executorService) {
    AWSCredentialsProvider serviceAwsCredentials;
    try {
        serviceAwsCredentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials(AWS_MASTER_ACCOUNT_ACCESS_KEY, AWS_MASTER_ACCOUNT_SECRET_KEY));
    } catch (Throwable t) {
        return DeferredResult.failed(t);
    }
    AWSSecurityTokenServiceAsync awsSecurityTokenServiceAsync = AWSSecurityTokenServiceAsyncClientBuilder.standard().withRegion(region).withCredentials(serviceAwsCredentials).withExecutorFactory(() -> executorService).build();
    AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(arn).withRoleSessionName(UUID.randomUUID().toString()).withDurationSeconds(getArnSessionDurationSeconds()).withExternalId(externalId);
    DeferredResult<AssumeRoleResult> r = new DeferredResult<>();
    OperationContext operationContext = OperationContext.getOperationContext();
    awsSecurityTokenServiceAsync.assumeRoleAsync(assumeRoleRequest, new AsyncHandler<AssumeRoleRequest, AssumeRoleResult>() {

        @Override
        public void onSuccess(AssumeRoleRequest request, AssumeRoleResult result) {
            OperationContext.restoreOperationContext(operationContext);
            r.complete(result);
        }

        @Override
        public void onError(Exception ex) {
            OperationContext.restoreOperationContext(operationContext);
            r.fail(ex);
        }
    });
    return r.thenApply(AssumeRoleResult::getCredentials);
}
Also used : OperationContext(com.vmware.xenon.common.OperationContext) AssumeRoleRequest(com.amazonaws.services.securitytoken.model.AssumeRoleRequest) AWSSecurityTokenServiceAsync(com.amazonaws.services.securitytoken.AWSSecurityTokenServiceAsync) AssumeRoleResult(com.amazonaws.services.securitytoken.model.AssumeRoleResult) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) AWSSecurityTokenServiceException(com.amazonaws.services.securitytoken.model.AWSSecurityTokenServiceException) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonClientException(com.amazonaws.AmazonClientException) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) AWSStaticCredentialsProvider(com.amazonaws.auth.AWSStaticCredentialsProvider) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider) DeferredResult(com.vmware.xenon.common.DeferredResult)

Example 2 with DeferredResult

use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.

the class AWSEndpointAdapterService method validateCredentialsWithRegions.

private DeferredResult<Void> validateCredentialsWithRegions(AuthCredentialsServiceState credentials, String endpointRegion) {
    AtomicInteger index = new AtomicInteger(0);
    Regions[] regions = Regions.values();
    int epRegionIndex = Arrays.stream(regions).map(Regions::getName).collect(Collectors.toList()).indexOf(endpointRegion);
    // if found, swap defaultRegion with the first region to optimize
    if (epRegionIndex != -1) {
        Regions temp = regions[0];
        regions[0] = regions[epRegionIndex];
        regions[epRegionIndex] = temp;
    }
    DeferredResult<Void> deferredResult = new DeferredResult<>();
    validateCredentialsWithRegions(credentials, index, regions, deferredResult);
    return deferredResult;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Regions(com.amazonaws.regions.Regions) DeferredResult(com.vmware.xenon.common.DeferredResult)

Example 3 with DeferredResult

use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.

the class AWSInstanceContext method getInstanceTypeInfo.

private DeferredResult<AWSInstanceContext> getInstanceTypeInfo(AWSInstanceContext context) {
    String instanceType = context.child.description.instanceType;
    if (instanceType == null) {
        instanceType = context.child.description.name;
    }
    if (instanceType == null) {
        String msg = String.format("AWS Instance type not specified for [%s] VM.", context.child.name);
        return DeferredResult.failed(new IllegalStateException(msg));
    }
    URI instanceTypeServiceURI = UriUtils.buildUri(context.service.getHost(), AWSInstanceTypeService.SELF_LINK);
    instanceTypeServiceURI = UriUtils.appendQueryParam(instanceTypeServiceURI, URI_PARAM_ENDPOINT, context.child.endpointLink);
    instanceTypeServiceURI = UriUtils.appendQueryParam(instanceTypeServiceURI, URI_PARAM_INSTANCE_TYPE, instanceType);
    Operation op = Operation.createGet(instanceTypeServiceURI).setReferer(context.service.getHost().getUri());
    DeferredResult<InstanceType> dr = context.service.sendWithDeferredResult(op, InstanceType.class);
    return dr.thenAccept(type -> {
        context.instanceTypeInfo = type;
    }).handle((all, err) -> {
        if (err != null) {
            String msg = String.format("Error getting instance-type info for [%s] VM. Reason [%s]", context.child.name, err.getMessage());
            throw new IllegalStateException(msg, err);
        }
        return context;
    });
}
Also used : InstanceNetworkInterfaceSpecification(com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification) DescribeSubnetsRequest(com.amazonaws.services.ec2.model.DescribeSubnetsRequest) DescribeVpcsRequest(com.amazonaws.services.ec2.model.DescribeVpcsRequest) CREATE_CONTEXT_PROP_NAME(com.vmware.photon.controller.model.ComputeProperties.CREATE_CONTEXT_PROP_NAME) Function(java.util.function.Function) CreateSubnetResult(com.amazonaws.services.ec2.model.CreateSubnetResult) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) DescribeSubnetsResult(com.amazonaws.services.ec2.model.DescribeSubnetsResult) ComputeInstanceRequest(com.vmware.photon.controller.model.adapterapi.ComputeInstanceRequest) SecurityGroupState(com.vmware.photon.controller.model.resources.SecurityGroupService.SecurityGroupState) HashSet(java.util.HashSet) AWSSecurityGroupClient(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSSecurityGroupClient) DescribeVpcsResult(com.amazonaws.services.ec2.model.DescribeVpcsResult) URI_PARAM_INSTANCE_TYPE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.URI_PARAM_INSTANCE_TYPE) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) Filter(com.amazonaws.services.ec2.model.Filter) Collections.singletonMap(java.util.Collections.singletonMap) URI(java.net.URI) Subnet(com.amazonaws.services.ec2.model.Subnet) StatelessService(com.vmware.xenon.common.StatelessService) AWS_TAG_NAME(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_TAG_NAME) Vpc(com.amazonaws.services.ec2.model.Vpc) Collection(java.util.Collection) Operation(com.vmware.xenon.common.Operation) Set(java.util.Set) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) Collectors(java.util.stream.Collectors) AWS_VPC_ID_FILTER(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_VPC_ID_FILTER) URI_PARAM_ENDPOINT(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.URI_PARAM_ENDPOINT) InstanceType(com.vmware.photon.controller.model.support.InstanceTypeList.InstanceType) List(java.util.List) BaseComputeInstanceContext(com.vmware.photon.controller.model.adapters.util.instance.BaseComputeInstanceContext) AWS_SUBNET_ID_FILTER(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_SUBNET_ID_FILTER) Tag(com.amazonaws.services.ec2.model.Tag) DeferredResult(com.vmware.xenon.common.DeferredResult) UriUtils(com.vmware.xenon.common.UriUtils) DiskService(com.vmware.photon.controller.model.resources.DiskService) AWSDeferredResultAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSDeferredResultAsyncHandler) CreateSubnetRequest(com.amazonaws.services.ec2.model.CreateSubnetRequest) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) Operation(com.vmware.xenon.common.Operation) InstanceType(com.vmware.photon.controller.model.support.InstanceTypeList.InstanceType) URI(java.net.URI)

Example 4 with DeferredResult

use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.

the class AWSInstanceContext method getSubnets.

/**
 * For every NIC lookup associated AWS Subnet as specified by
 * {@code AWSNicContext.subnetState.id}. If any of the subnets is not found then
 * {@code AWSNicContext.subnet} is not populated. That's an indicator the subnet should be
 * created.
 */
private DeferredResult<AWSInstanceContext> getSubnets(AWSInstanceContext context) {
    if (context.nics.isEmpty()) {
        return DeferredResult.completed(context);
    }
    List<DeferredResult<DescribeSubnetsResult>> getSubnetDRs = new ArrayList<>();
    for (AWSNicContext nicCtx : context.nics) {
        DescribeSubnetsRequest subnetRequest = new DescribeSubnetsRequest().withFilters(new Filter(AWS_VPC_ID_FILTER, singletonList(nicCtx.networkState.id))).withFilters(new Filter(AWS_SUBNET_ID_FILTER, singletonList(nicCtx.subnetState.id)));
        String msg = "Getting AWS Subnet [" + nicCtx.networkState.id + "/" + nicCtx.subnetState.id + "] for [" + nicCtx.nicStateWithDesc.name + "] NIC for [" + context.child.name + "] VM";
        AWSDeferredResultAsyncHandler<DescribeSubnetsRequest, DescribeSubnetsResult> subnetHandler = new AWSDeferredResultAsyncHandler<DescribeSubnetsRequest, DescribeSubnetsResult>(this.service, msg) {

            @Override
            protected DeferredResult<DescribeSubnetsResult> consumeSuccess(DescribeSubnetsRequest request, DescribeSubnetsResult result) {
                // The subnet specified might not exist. It's OK cause it will be created.
                if (!result.getSubnets().isEmpty()) {
                    nicCtx.subnet = result.getSubnets().get(0);
                }
                return DeferredResult.completed(result);
            }
        };
        context.amazonEC2Client.describeSubnetsAsync(subnetRequest, subnetHandler);
        getSubnetDRs.add(subnetHandler.toDeferredResult());
    }
    return DeferredResult.allOf(getSubnetDRs).handle((all, exc) -> {
        if (exc != null) {
            String msg = String.format("Error getting Subnets from AWS for [%s] VM.", context.child.name);
            throw new IllegalStateException(msg, exc);
        }
        return context;
    });
}
Also used : Filter(com.amazonaws.services.ec2.model.Filter) AWSDeferredResultAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSDeferredResultAsyncHandler) ArrayList(java.util.ArrayList) DescribeSubnetsResult(com.amazonaws.services.ec2.model.DescribeSubnetsResult) DeferredResult(com.vmware.xenon.common.DeferredResult) DescribeSubnetsRequest(com.amazonaws.services.ec2.model.DescribeSubnetsRequest)

Example 5 with DeferredResult

use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.

the class AWSInstanceContext method createSubnetsIfNotExist.

/**
 * For every NIC create AWS Subnet (as specified by {@code AWSNicContext.subnetState}) if it
 * does not exist.
 *
 * @see #getSubnets(AWSInstanceContext)
 */
private DeferredResult<AWSInstanceContext> createSubnetsIfNotExist(AWSInstanceContext context) {
    if (context.nics.isEmpty()) {
        return DeferredResult.completed(context);
    }
    List<DeferredResult<Void>> createSubnetDRs = new ArrayList<>();
    for (AWSNicContext nicCtx : context.nics) {
        if (nicCtx.subnet != null) {
            // No need to create
            continue;
        }
        // Create AWS subnet and set it to nicCtx.subnet {{
        CreateSubnetRequest subnetRequest = new CreateSubnetRequest().withVpcId(nicCtx.vpc.getVpcId()).withCidrBlock(nicCtx.subnetState.subnetCIDR);
        if (nicCtx.subnetState.zoneId != null) {
            subnetRequest.withAvailabilityZone(nicCtx.subnetState.zoneId);
        }
        String msg = "Create AWS subnet + [" + nicCtx.subnetState.name + "]";
        AWSDeferredResultAsyncHandler<CreateSubnetRequest, CreateSubnetResult> createAWSSubnet = new AWSDeferredResultAsyncHandler<CreateSubnetRequest, CreateSubnetResult>(this.service, msg) {

            @Override
            protected DeferredResult<CreateSubnetResult> consumeSuccess(CreateSubnetRequest request, CreateSubnetResult result) {
                nicCtx.subnet = result.getSubnet();
                AWSUtils.tagResourcesWithName(context.amazonEC2Client, nicCtx.subnetState.name, nicCtx.subnet.getSubnetId());
                return DeferredResult.completed(result);
            }
        };
        context.amazonEC2Client.createSubnetAsync(subnetRequest, createAWSSubnet);
        // }}
        // Once AWS subnet creation is done PATCH SubnetState.id {{
        Function<CreateSubnetResult, DeferredResult<Void>> patchSubnetState = (ignore) -> {
            SubnetState patchSubnet = new SubnetState();
            patchSubnet.id = nicCtx.subnet.getSubnetId();
            patchSubnet.documentSelfLink = nicCtx.subnetState.documentSelfLink;
            patchSubnet.customProperties = singletonMap(CREATE_CONTEXT_PROP_NAME, context.computeRequest.resourceLink());
            Operation op = Operation.createPatch(context.service.getHost(), patchSubnet.documentSelfLink).setBody(patchSubnet);
            return context.service.sendWithDeferredResult(op, SubnetState.class).thenAccept(patchedSubnet -> nicCtx.subnetState = patchedSubnet);
        };
        // }}
        // Chain AWS subnet creation with SubnetState patching
        createSubnetDRs.add(createAWSSubnet.toDeferredResult().thenCompose(patchSubnetState));
    }
    return DeferredResult.allOf(createSubnetDRs).handle((all, exc) -> {
        if (exc != null) {
            String msg = String.format("Error creating Subnets in AWS for [%s] VM.", context.child.name);
            throw new IllegalStateException(msg, exc);
        }
        return context;
    });
}
Also used : InstanceNetworkInterfaceSpecification(com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification) DescribeSubnetsRequest(com.amazonaws.services.ec2.model.DescribeSubnetsRequest) DescribeVpcsRequest(com.amazonaws.services.ec2.model.DescribeVpcsRequest) CREATE_CONTEXT_PROP_NAME(com.vmware.photon.controller.model.ComputeProperties.CREATE_CONTEXT_PROP_NAME) Function(java.util.function.Function) CreateSubnetResult(com.amazonaws.services.ec2.model.CreateSubnetResult) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) DescribeSubnetsResult(com.amazonaws.services.ec2.model.DescribeSubnetsResult) ComputeInstanceRequest(com.vmware.photon.controller.model.adapterapi.ComputeInstanceRequest) SecurityGroupState(com.vmware.photon.controller.model.resources.SecurityGroupService.SecurityGroupState) HashSet(java.util.HashSet) AWSSecurityGroupClient(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSSecurityGroupClient) DescribeVpcsResult(com.amazonaws.services.ec2.model.DescribeVpcsResult) URI_PARAM_INSTANCE_TYPE(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.URI_PARAM_INSTANCE_TYPE) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) Filter(com.amazonaws.services.ec2.model.Filter) Collections.singletonMap(java.util.Collections.singletonMap) URI(java.net.URI) Subnet(com.amazonaws.services.ec2.model.Subnet) StatelessService(com.vmware.xenon.common.StatelessService) AWS_TAG_NAME(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_TAG_NAME) Vpc(com.amazonaws.services.ec2.model.Vpc) Collection(java.util.Collection) Operation(com.vmware.xenon.common.Operation) Set(java.util.Set) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) Collectors(java.util.stream.Collectors) AWS_VPC_ID_FILTER(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_VPC_ID_FILTER) URI_PARAM_ENDPOINT(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.URI_PARAM_ENDPOINT) InstanceType(com.vmware.photon.controller.model.support.InstanceTypeList.InstanceType) List(java.util.List) BaseComputeInstanceContext(com.vmware.photon.controller.model.adapters.util.instance.BaseComputeInstanceContext) AWS_SUBNET_ID_FILTER(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_SUBNET_ID_FILTER) Tag(com.amazonaws.services.ec2.model.Tag) DeferredResult(com.vmware.xenon.common.DeferredResult) UriUtils(com.vmware.xenon.common.UriUtils) DiskService(com.vmware.photon.controller.model.resources.DiskService) AWSDeferredResultAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSDeferredResultAsyncHandler) CreateSubnetRequest(com.amazonaws.services.ec2.model.CreateSubnetRequest) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) CreateSubnetResult(com.amazonaws.services.ec2.model.CreateSubnetResult) ArrayList(java.util.ArrayList) Operation(com.vmware.xenon.common.Operation) CreateSubnetRequest(com.amazonaws.services.ec2.model.CreateSubnetRequest) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) AWSDeferredResultAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSDeferredResultAsyncHandler) 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