Search in sources :

Example 1 with DescribeImagesResult

use of com.amazonaws.services.ec2.model.DescribeImagesResult in project SimianArmy by Netflix.

the class AWSClient method describeImages.

/**
 * Describe a set of specific images.
 *
 * @param imageIds the image ids
 * @return the images
 */
public List<Image> describeImages(String... imageIds) {
    if (imageIds == null || imageIds.length == 0) {
        LOGGER.info(String.format("Getting all AMIs in region %s.", region));
    } else {
        LOGGER.info(String.format("Getting AMIs for %d ids in region %s.", imageIds.length, region));
    }
    AmazonEC2 ec2Client = ec2Client();
    DescribeImagesRequest request = new DescribeImagesRequest();
    if (imageIds != null) {
        request.setImageIds(Arrays.asList(imageIds));
    }
    DescribeImagesResult result = ec2Client.describeImages(request);
    List<Image> images = result.getImages();
    LOGGER.info(String.format("Got %d AMIs in region %s.", images.size(), region));
    return images;
}
Also used : AmazonEC2(com.amazonaws.services.ec2.AmazonEC2)

Example 2 with DescribeImagesResult

use of com.amazonaws.services.ec2.model.DescribeImagesResult in project TOSCAna by StuPro-TOSCAna.

the class CapabilityMapper method mapOsCapabilityToImageId.

/**
 *     This method requests the AWS server for ImageIds with filters which are filled based on
 *     the values of the OsCapability. The image with the latest creation date is picked and its imageId returned.
 *
 *     @param osCapability The OsCapability to map.
 *     @return A String that contains a valid ImageId that can be added to the properties of an ec2.
 */
public String mapOsCapabilityToImageId(OsCapability osCapability) throws SdkClientException, ParseException, IllegalArgumentException {
    AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).withRegion(awsRegion).build();
    // need to set these
    DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest().withFilters(new Filter("virtualization-type").withValues("hvm"), new Filter("root-device-type").withValues("ebs")).withOwners(// this is the ownerId of amazon itself
    "099720109477");
    if (osCapability.getType().isPresent() && osCapability.getType().get().equals(OsCapability.Type.WINDOWS)) {
        describeImagesRequest.withFilters(new Filter("platform").withValues("windows"));
    }
    if (osCapability.getDistribution().isPresent()) {
        if (osCapability.getDistribution().get().equals(OsCapability.Distribution.UBUNTU)) {
            // */ubuntu/images/* gets better results than plain *ubuntu*
            describeImagesRequest.withFilters(new Filter("name").withValues("*ubuntu/images/*"));
        } else {
            // just search for the string
            describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getDistribution().toString() + "*"));
        }
    }
    if (osCapability.getVersion().isPresent()) {
        describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getVersion().get() + "*"));
    }
    if (osCapability.getArchitecture().isPresent()) {
        if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_64)) {
            describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64));
        } else if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_32)) {
            describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_32));
        } else {
            throw new UnsupportedOperationException("This architecture is not supported " + osCapability.getArchitecture());
        }
    } else {
        // defaulting to 64 bit architecture
        describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64));
    }
    try {
        DescribeImagesResult describeImagesResult = ec2.describeImages(describeImagesRequest);
        String imageId = processResult(describeImagesResult);
        logger.debug("ImageId is: '{}'", imageId);
        return imageId;
    } catch (SdkClientException se) {
        logger.error("Cannot connect to AWS to request image Ids");
        throw se;
    } catch (ParseException pe) {
        logger.error("Error parsing date format of image creation dates");
        throw pe;
    } catch (IllegalArgumentException ie) {
        logger.error("With the filters created from the OsCapability there are no valid images received");
        throw ie;
    }
}
Also used : AWSStaticCredentialsProvider(com.amazonaws.auth.AWSStaticCredentialsProvider) SdkClientException(com.amazonaws.SdkClientException) Filter(com.amazonaws.services.ec2.model.Filter) DescribeImagesResult(com.amazonaws.services.ec2.model.DescribeImagesResult) DescribeImagesRequest(com.amazonaws.services.ec2.model.DescribeImagesRequest) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) ParseException(java.text.ParseException)

Example 3 with DescribeImagesResult

use of com.amazonaws.services.ec2.model.DescribeImagesResult in project TOSCAna by StuPro-TOSCAna.

the class CapabilityMapper method processResult.

/**
 *     Process the result of an DescribeImagesRequest and return the imageId of the latest image.
 *
 *     @param describeImagesResult The result received from aws.
 *     @return The latest imageId.
 */
private String processResult(DescribeImagesResult describeImagesResult) throws ParseException, IllegalArgumentException {
    Integer numReceivedImages = describeImagesResult.getImages().size();
    logger.debug("Got '{}' images from aws", numReceivedImages);
    if (numReceivedImages > 0) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        Map<Date, Image> creationDateMap = new HashMap<>();
        for (Image image : describeImagesResult.getImages()) {
            Date date = dateFormat.parse(image.getCreationDate());
            creationDateMap.put(date, image);
        }
        Image latest = creationDateMap.get(Collections.max(creationDateMap.keySet()));
        logger.debug("Latest image received: '{}'", latest);
        return latest.getImageId();
    } else {
        throw new IllegalArgumentException("No images received");
    }
}
Also used : HashMap(java.util.HashMap) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) Image(com.amazonaws.services.ec2.model.Image) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 4 with DescribeImagesResult

use of com.amazonaws.services.ec2.model.DescribeImagesResult in project photon-model by vmware.

the class TestAWSImageEnumerationTask method lookupAwsImage.

// Kind of overhead cause it loads almost all images just to get the first one.
// Still we need that to make the tests STABLE.
private String lookupAwsImage(AmazonEC2AsyncClient client, String virtualizationType) {
    DescribeImagesRequest request = new DescribeImagesRequest().withFilters(new Filter(AWSConstants.AWS_IMAGE_STATE_FILTER).withValues(AWSConstants.AWS_IMAGE_STATE_AVAILABLE)).withFilters(new Filter(AWSConstants.AWS_IMAGE_IS_PUBLIC_FILTER).withValues(Boolean.TRUE.toString())).withFilters(new Filter("root-device-type").withValues("ebs")).withFilters(new Filter(AWSConstants.AWS_IMAGE_VIRTUALIZATION_TYPE_FILTER).withValues(virtualizationType));
    DescribeImagesResult describeImages = client.describeImages(request);
    Image image = describeImages.getImages().stream().filter(img -> {
        for (BlockDeviceMapping blockDeviceMapping : img.getBlockDeviceMappings()) {
            // blockDeviceMapping can be with noDevice
            EbsBlockDevice ebs = blockDeviceMapping.getEbs();
            if (ebs != null) {
                return true;
            }
        }
        return false;
    }).findFirst().get();
    getHost().log(Level.INFO, "AWS '%s' image loaded (out of %s): %s [%s]", virtualizationType, describeImages.getImages().size(), image.getName(), image);
    return image.getName();
}
Also used : Filter(com.amazonaws.services.ec2.model.Filter) DescribeImagesResult(com.amazonaws.services.ec2.model.DescribeImagesResult) DescribeImagesRequest(com.amazonaws.services.ec2.model.DescribeImagesRequest) EbsBlockDevice(com.amazonaws.services.ec2.model.EbsBlockDevice) BlockDeviceMapping(com.amazonaws.services.ec2.model.BlockDeviceMapping) Image(com.amazonaws.services.ec2.model.Image)

Example 5 with DescribeImagesResult

use of com.amazonaws.services.ec2.model.DescribeImagesResult in project photon-model by vmware.

the class AWSInstanceService method createInstance.

private void createInstance(AWSInstanceContext aws) {
    if (aws.computeRequest.isMockRequest) {
        aws.taskManager.finishTask();
        return;
    }
    final DiskState bootDisk = aws.bootDisk;
    if (bootDisk == null) {
        aws.taskManager.patchTaskToFailure(new IllegalStateException("AWS bootDisk not specified"));
        return;
    }
    if (bootDisk.bootConfig != null && bootDisk.bootConfig.files.length > 1) {
        aws.taskManager.patchTaskToFailure(new IllegalStateException("Only 1 configuration file allowed"));
        return;
    }
    // This a single disk state with a bootConfig. There's no expectation
    // that it does exists, but if it does, we only support cloud configs at
    // this point.
    String cloudConfig = null;
    if (bootDisk.bootConfig != null && bootDisk.bootConfig.files.length > CLOUD_CONFIG_DEFAULT_FILE_INDEX) {
        cloudConfig = bootDisk.bootConfig.files[CLOUD_CONFIG_DEFAULT_FILE_INDEX].contents;
    }
    String instanceType = aws.child.description.instanceType;
    if (instanceType == null) {
        // fallback to legacy usage of name
        instanceType = aws.child.description.name;
    }
    if (instanceType == null) {
        aws.error = new IllegalStateException("AWS Instance type not specified");
        aws.stage = AWSInstanceStage.ERROR;
        handleAllocation(aws);
        return;
    }
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId(aws.bootDiskImageNativeId).withInstanceType(instanceType).withMinCount(1).withMaxCount(1).withMonitoring(true).withTagSpecifications(new TagSpecification().withResourceType(ResourceType.Instance).withTags(aws.getAWSTags()));
    if (aws.placement != null) {
        runInstancesRequest.withPlacement(new Placement(aws.placement));
    }
    if (aws.child.customProperties != null && aws.child.customProperties.containsKey(CUSTOM_PROP_SSH_KEY_NAME)) {
        runInstancesRequest = runInstancesRequest.withKeyName(aws.child.customProperties.get(CUSTOM_PROP_SSH_KEY_NAME));
    }
    if (!aws.dataDisks.isEmpty() || bootDisk.capacityMBytes > 0 || bootDisk.customProperties != null) {
        DescribeImagesRequest imagesDescriptionRequest = new DescribeImagesRequest();
        imagesDescriptionRequest.withImageIds(aws.bootDiskImageNativeId);
        DescribeImagesResult imagesDescriptionResult = aws.amazonEC2Client.describeImages(imagesDescriptionRequest);
        if (imagesDescriptionResult.getImages().size() != 1) {
            handleError(aws, new IllegalStateException("AWS ImageId is not available"));
            return;
        }
        Image image = imagesDescriptionResult.getImages().get(0);
        AssertUtil.assertNotNull(aws.instanceTypeInfo, "instanceType cannot be null");
        List<BlockDeviceMapping> blockDeviceMappings = image.getBlockDeviceMappings();
        String rootDeviceType = image.getRootDeviceType();
        String bootDiskType = bootDisk.customProperties.get(DEVICE_TYPE);
        boolean hasHardConstraint = containsHardConstraint(bootDisk);
        BlockDeviceMapping rootDeviceMapping = null;
        try {
            // The number of instance-store disks that will be provisioned is limited by the instance-type.
            suppressExcessInstanceStoreDevices(blockDeviceMappings, aws.instanceTypeInfo);
            for (BlockDeviceMapping blockDeviceMapping : blockDeviceMappings) {
                EbsBlockDevice ebs = blockDeviceMapping.getEbs();
                String diskType = getDeviceType(ebs);
                if (hasHardConstraint) {
                    validateIfDeviceTypesAreMatching(diskType, bootDiskType);
                }
                if (blockDeviceMapping.getNoDevice() != null) {
                    continue;
                }
                if (rootDeviceType.equals(AWSStorageType.EBS.getName()) && blockDeviceMapping.getDeviceName().equals(image.getRootDeviceName())) {
                    rootDeviceMapping = blockDeviceMapping;
                    continue;
                }
                DiskState diskState = new DiskState();
                copyCustomProperties(diskState, bootDisk);
                addMandatoryProperties(diskState, blockDeviceMapping, aws);
                updateDeviceMapping(diskType, bootDiskType, blockDeviceMapping.getDeviceName(), ebs, diskState);
                // update disk state with final volume-type and iops
                if (diskType.equals(AWSStorageType.EBS.getName())) {
                    diskState.customProperties.put(VOLUME_TYPE, ebs.getVolumeType());
                    diskState.customProperties.put(DISK_IOPS, String.valueOf(ebs.getIops()));
                }
                aws.imageDisks.add(diskState);
            }
            customizeBootDiskProperties(bootDisk, rootDeviceType, rootDeviceMapping, hasHardConstraint, aws);
            List<DiskState> ebsDisks = new ArrayList<>();
            List<DiskState> instanceStoreDisks = new ArrayList<>();
            if (!aws.dataDisks.isEmpty()) {
                if (!rootDeviceType.equals(AWSStorageType.EBS.name().toLowerCase())) {
                    instanceStoreDisks = aws.dataDisks;
                    assertAndResetPersistence(instanceStoreDisks);
                    validateSupportForAdditionalInstanceStoreDisks(instanceStoreDisks, blockDeviceMappings, aws.instanceTypeInfo, rootDeviceType);
                } else {
                    splitDataDisks(aws.dataDisks, instanceStoreDisks, ebsDisks);
                    setEbsDefaultsIfNotSpecified(ebsDisks, Boolean.FALSE);
                    if (!instanceStoreDisks.isEmpty()) {
                        assertAndResetPersistence(instanceStoreDisks);
                        validateSupportForAdditionalInstanceStoreDisks(instanceStoreDisks, blockDeviceMappings, aws.instanceTypeInfo, rootDeviceType);
                    }
                }
            }
            // get the available attach paths for new disks and external disks
            List<String> usedDeviceNames = null;
            if (!instanceStoreDisks.isEmpty() || !ebsDisks.isEmpty() || !aws.externalDisks.isEmpty()) {
                usedDeviceNames = getUsedDeviceNames(blockDeviceMappings);
            }
            if (!instanceStoreDisks.isEmpty()) {
                List<String> usedVirtualNames = getUsedVirtualNames(blockDeviceMappings);
                blockDeviceMappings.addAll(createInstanceStoreMappings(instanceStoreDisks, usedDeviceNames, usedVirtualNames, aws.instanceTypeInfo.id, aws.instanceTypeInfo.dataDiskSizeInMB, image.getPlatform(), image.getVirtualizationType()));
            }
            if (!ebsDisks.isEmpty() || !aws.externalDisks.isEmpty()) {
                aws.availableEbsDiskNames = AWSBlockDeviceNameMapper.getAvailableNames(AWSSupportedOS.get(image.getPlatform()), AWSSupportedVirtualizationTypes.get(image.getVirtualizationType()), AWSStorageType.EBS, instanceType, usedDeviceNames);
            }
            if (!ebsDisks.isEmpty()) {
                blockDeviceMappings.addAll(createEbsDeviceMappings(ebsDisks, aws.availableEbsDiskNames));
            }
            runInstancesRequest.withBlockDeviceMappings(blockDeviceMappings);
        } catch (Exception e) {
            aws.error = e;
            aws.stage = AWSInstanceStage.ERROR;
            handleAllocation(aws);
            return;
        }
    }
    AWSNicContext primaryNic = aws.getPrimaryNic();
    if (primaryNic != null && primaryNic.nicSpec != null) {
        runInstancesRequest.withNetworkInterfaces(primaryNic.nicSpec);
    } else {
        runInstancesRequest.withSecurityGroupIds(AWSUtils.getOrCreateSecurityGroups(aws, null));
    }
    if (cloudConfig != null) {
        try {
            runInstancesRequest.setUserData(Base64.getEncoder().encodeToString(cloudConfig.getBytes(Utils.CHARSET)));
        } catch (UnsupportedEncodingException e) {
            handleError(aws, new IllegalStateException("Error encoding user data"));
            return;
        }
    }
    String message = "[AWSInstanceService] Sending run instance request for instance id: " + aws.bootDiskImageNativeId + ", instance type: " + instanceType + ", parent task id: " + aws.computeRequest.taskReference;
    this.logInfo(() -> message);
    // handler invoked once the EC2 runInstancesAsync commands completes
    AsyncHandler<RunInstancesRequest, RunInstancesResult> creationHandler = new AWSCreationHandler(this, aws);
    aws.amazonEC2Client.runInstancesAsync(runInstancesRequest, creationHandler);
}
Also used : DescribeImagesRequest(com.amazonaws.services.ec2.model.DescribeImagesRequest) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TagSpecification(com.amazonaws.services.ec2.model.TagSpecification) Image(com.amazonaws.services.ec2.model.Image) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Placement(com.amazonaws.services.ec2.model.Placement) DescribeImagesResult(com.amazonaws.services.ec2.model.DescribeImagesResult) RunInstancesResult(com.amazonaws.services.ec2.model.RunInstancesResult) EbsBlockDevice(com.amazonaws.services.ec2.model.EbsBlockDevice) BlockDeviceMapping(com.amazonaws.services.ec2.model.BlockDeviceMapping) InstanceBlockDeviceMapping(com.amazonaws.services.ec2.model.InstanceBlockDeviceMapping) RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest) AWSNicContext(com.vmware.photon.controller.model.adapters.awsadapter.AWSInstanceContext.AWSNicContext)

Aggregations

DescribeImagesRequest (com.amazonaws.services.ec2.model.DescribeImagesRequest)4 DescribeImagesResult (com.amazonaws.services.ec2.model.DescribeImagesResult)4 Image (com.amazonaws.services.ec2.model.Image)4 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)2 BlockDeviceMapping (com.amazonaws.services.ec2.model.BlockDeviceMapping)2 EbsBlockDevice (com.amazonaws.services.ec2.model.EbsBlockDevice)2 Filter (com.amazonaws.services.ec2.model.Filter)2 AmazonServiceException (com.amazonaws.AmazonServiceException)1 SdkClientException (com.amazonaws.SdkClientException)1 AWSStaticCredentialsProvider (com.amazonaws.auth.AWSStaticCredentialsProvider)1 AmazonEC2Client (com.amazonaws.services.ec2.AmazonEC2Client)1 AmazonEC2Exception (com.amazonaws.services.ec2.model.AmazonEC2Exception)1 InstanceBlockDeviceMapping (com.amazonaws.services.ec2.model.InstanceBlockDeviceMapping)1 Placement (com.amazonaws.services.ec2.model.Placement)1 RunInstancesRequest (com.amazonaws.services.ec2.model.RunInstancesRequest)1 RunInstancesResult (com.amazonaws.services.ec2.model.RunInstancesResult)1 TagSpecification (com.amazonaws.services.ec2.model.TagSpecification)1 AwsCredentialView (com.sequenceiq.cloudbreak.cloud.aws.view.AwsCredentialView)1 CloudConnectorException (com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException)1 AWSNicContext (com.vmware.photon.controller.model.adapters.awsadapter.AWSInstanceContext.AWSNicContext)1