Example usage for com.amazonaws.services.ec2.model Image getRootDeviceName

List of usage examples for com.amazonaws.services.ec2.model Image getRootDeviceName

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model Image getRootDeviceName.

Prototype


public String getRootDeviceName() 

Source Link

Document

The device name of the root device volume (for example, /dev/sda1).

Usage

From source file:com.cloudera.director.aws.ec2.EC2Provider.java

License:Apache License

/**
 * Creates block device mappings based on the specified instance template.
 *
 * @param template the instance template
 * @return the block device mappings//from  w ww  .j a  v  a 2  s.  co  m
 */
private List<BlockDeviceMapping> getBlockDeviceMappings(EC2InstanceTemplate template) {

    // Query the AMI about the root device name & mapping information
    DescribeImagesResult result = client
            .describeImages(new DescribeImagesRequest().withImageIds(template.getImage()));
    if (result.getImages().isEmpty()) {
        throw new IllegalArgumentException("The description for image " + template.getImage() + " is empty");
    }
    Image templateImage = result.getImages().get(0);
    String rootDeviceType = templateImage.getRootDeviceType();
    if (!DEVICE_TYPE_EBS.equals(rootDeviceType)) {
        throw new IllegalArgumentException("The root device for image " + template.getImage() + " must be \""
                + DEVICE_TYPE_EBS + "\", found: " + rootDeviceType);
    }
    List<BlockDeviceMapping> originalMappings = templateImage.getBlockDeviceMappings();
    LOG.info(">> Original image block device mappings: {}", originalMappings);
    if (originalMappings.isEmpty()) {
        throw new IllegalArgumentException(
                "The image " + template.getImage() + " has no block device mappings");
    }
    BlockDeviceMapping rootDevice = selectRootDevice(originalMappings, templateImage.getRootDeviceName());
    if (rootDevice == null) {
        throw new IllegalArgumentException("Could not determine root device for image " + template.getImage()
                + " based on root device name " + templateImage.getRootDeviceName());
    }

    // The encrypted property was added to the block device mapping in version 1.8 of the SDK.
    // It is a Boolean, but defaults to false instead of being unset, so we set it to null here.
    rootDevice.getEbs().setEncrypted(null);
    rootDevice.getEbs().setVolumeSize(template.getRootVolumeSizeGB());
    rootDevice.getEbs().setVolumeType(template.getRootVolumeType());
    rootDevice.getEbs().setDeleteOnTermination(true);

    List<BlockDeviceMapping> deviceMappings = Lists.newArrayList(rootDevice);

    int ebsVolumeCount = template.getEbsVolumeCount();

    EBSAllocationStrategy ebsAllocationStrategy = EBSAllocationStrategy.get(template);

    switch (ebsAllocationStrategy) {
    case NO_EBS_VOLUMES:
        // The volumes within an instance should be homogeneous. So we only add
        // instance store volumes when additional EBS volumes aren't mounted.
        deviceMappings.addAll(ephemeralDeviceMappings.apply(template.getType()));
        break;
    case AS_INSTANCE_REQUEST:
        LOG.info("EBS volumes will be allocated as part of instance launch request");
        List<BlockDeviceMapping> ebsDeviceMappings = getEbsBlockDeviceMapping(ebsVolumeCount,
                template.getEbsVolumeType(), template.getEbsVolumeSizeGiB(), template.isEnableEbsEncryption());
        deviceMappings.addAll(ebsDeviceMappings);
        break;
    case AS_SEPARATE_REQUESTS:
        LOG.info("EBS volumes will be separately allocated after instance launch request");
        break;
    default:
        throw new IllegalStateException("Invalid EBS allocation strategy " + ebsAllocationStrategy);
    }

    LOG.info(">> Block device mappings: {}", deviceMappings);
    return deviceMappings;
}

From source file:com.zotoh.cloudapi.aws.AMImage.java

License:Open Source License

private MachineImage toMI(Image i) {
    MachineImage m = null;// ww w  . j a  v a2  s  .co  m
    if (i != null) {
        m = new MachineImage();
        m.setProviderRegionId(_svc.getCloud().getContext().getRegionId());
        m.setArchitecture(toArch(i.getArchitecture()));
        m.setCurrentState(toImageState(i.getState()));

        m.setProviderMachineImageId(i.getImageId());
        m.setName(i.getName());
        m.setProviderOwnerId(i.getOwnerId());
        m.setSoftware("");
        m.setType(toImageType(i.getRootDeviceType()));

        m.addTag("manifest-location", nsb(i.getImageLocation()));
        m.addTag("hypervisor", nsb(i.getHypervisor()));
        m.addTag("alias", nsb(i.getImageOwnerAlias()));
        m.addTag("kernel", nsb(i.getKernelId()));
        m.addTag("public", i.getPublic() ? "true" : "false");
        m.addTag("ramdisk", nsb(i.getRamdiskId()));
        m.addTag("root-dev-name", nsb(i.getRootDeviceName()));
        m.addTag("state-reason", nsb(i.getStateReason()));
        m.addTag("virtualization-type", nsb(i.getVirtualizationType()));

        m.setDescription(i.getDescription());
        m.setPlatform(nsb(i.getPlatform()).toLowerCase().indexOf("windows") >= 0 ? Platform.WINDOWS
                : Platform.UBUNTU);
    }

    return m;
}

From source file:jp.aws.test.ec2.EC2Instance.java

License:Apache License

/**
 * AMI?/*from   w w  w .j  a va 2 s  . co  m*/
 *
 * @param HashMap
 *            <String,String> filterMap : ID: ownerid => self, amazon,
 *            redhat, 00000000  root-device-type => ebs, instance-store
 *            architecture => i386, x86_64 name => amzn-ami*
 * @return
 * @throws Exception
 * @note - ????????
 */
public List<AMIItem> ami_list(HashMap<String, String> filterMap) {

    List<AMIItem> amiItemList = new ArrayList<AMIItem>();

    // 
    this.clientManager.changeRegion();

    // AMI??
    DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest();
    List<String> ownersList = new ArrayList<String>();

    // OwnerID?(self, amazon, redhat, 00000000)
    ownersList.add(filterMap.get("ownerid"));
    describeImagesRequest.setOwners(ownersList);

    // AMI????????Filter?
    ArrayList<Filter> filters = new ArrayList<Filter>();

    Filter filter = new Filter();
    filter.setName("image-type");

    // machine
    List<String> valueList = new ArrayList<String>();
    valueList.add("machine");
    filter.setValues(valueList);

    // Filter
    filters.add(filter);

    // 
    for (Iterator<String> it = filterMap.keySet().iterator(); it.hasNext();) {
        String key = it.next();
        Log.d("ami_list", String.format("key:%s, value:%s", key, filterMap.get(key)));
        if (key.toLowerCase().equals("ownerid"))
            continue;
        filters.add(new Filter().withName(key).withValues(filterMap.get(key)));
    }

    // Filter
    describeImagesRequest.setFilters(filters);

    // ????AMI??
    DescribeImagesResult describeImagesResult = this.clientManager.ec2().describeImages(describeImagesRequest);

    // AMI?List?(Image?com.amazonaws.services.ec2.model?Image???)
    List<Image> amiList = describeImagesResult.getImages();

    // ?AMI??
    for (Image image : amiList) {
        // http://docs.amazonwebservices.com/AWSAndroidSDK/latest/javadoc/com/amazonaws/services/ec2/model/Image.html
        AMIItem amiItem = new AMIItem();

        StringBuilder builder = new StringBuilder();

        amiItem.imageId = image.getImageId();
        amiItem.imageType = image.getImageType();
        amiItem.imageLocation = image.getImageLocation();
        amiItem.name = image.getName();
        amiItem.architecture = image.getArchitecture();
        amiItem.platform = image.getPlatform();
        amiItem.state = image.getState();
        amiItem.ownerId = image.getOwnerId();
        amiItem.rootDeviceType = image.getRootDeviceType();
        amiItem.rootDeviceName = image.getRootDeviceName();
        amiItem.description = image.getDescription();
        builder.setLength(0); // ?
        List<Tag> tags = image.getTags(); // tag
        for (Tag tag : tags) {
            builder.append(tag.getValue());
            builder.append(", ");
        }

        // ?
        amiItemList.add(amiItem);
    }

    return amiItemList;
}

From source file:org.excalibur.service.aws.ec2.EC2.java

License:Open Source License

@Override
public Instances createInstances(final InstanceTemplate template, final boolean waitForRunningState) {
    LoginCredentials credentials = template.getLoginCredentials();
    KeyPair keyPair = getKeyPair(checkNotNull(credentials.getCredentialName()));

    checkState(keyPair != null || (!isNullOrEmpty(credentials.getPublicKey())));

    if (keyPair == null) {
        String material = decrypt(credentials.getPublicKey());
        keyPair = new KeyPair().setKeyName(credentials.getCredentialName()).setKeyMaterial(material);
        keyPair.setKeyFingerprint(importKeyPair(keyPair)).setKeyMaterial(null);
    }//ww w .  j a  v  a 2  s  .  c om

    checkState(keyPair != null);

    createSecurityGroupIfDoesNotExist(defaultUserGroupName_);

    final Image image = getImageById(template.getImageId());
    checkNotNull(image, String.format("Image %s does not exist", template.getImageId()));

    StringBuilder sb = new StringBuilder();
    sb.append("#start-data\n").append("#").append(credentials.getPrivateKey());

    if (!isNullOrEmpty(credentials.getPublicKey())) {
        sb.append("\n#").append(credentials.getPublicKey());
    }
    sb.append("\n#end-data");

    String userData = Strings2.nullAsEmpty(template.getUserData())
            .concat(new String(Base64.encodeBase64(sb.toString().getBytes())));

    RunInstancesRequest runInstacesRequest = new RunInstancesRequest()
            .withInstanceType(template.getInstanceType().getName()).withImageId(template.getImageId())
            .withMinCount(template.getMinCount()).withMaxCount(template.getMaxCount())
            .withKeyName(keyPair.getKeyName()).withSecurityGroups(defaultUserGroupName_).withUserData(userData);

    Zone zone = null;

    final Placement placement = new Placement();

    if (template.getGroup() != null && !isNullOrEmpty(template.getGroup().getZone())) {
        zone = this.getZoneByName(template.getGroup().getZone());

        checkState(zone != null, String.format("Invalid zone name [%s] on region [%s]",
                template.getGroup().getZone(), credentials_.getRegion().getName()));

        placement.withAvailabilityZone(zone.getName());

        if (!isNullOrEmpty(template.getGroup().getGroupName())) {
            placement.withGroupName(template.getGroup().getGroupName());
            this.createPlacementGroupsIfDoNotExist(template.getGroup());
        }
    }

    if (zone == null) {
        zone = Lists2.first(listAvailableZonesOfRegion(this.credentials_.getRegion()));
        placement.withAvailabilityZone(zone.getName());
    }

    checkNotNull(zone);
    checkState(!isNullOrEmpty(placement.getAvailabilityZone()));

    runInstacesRequest.withPlacement(placement);

    BlockDeviceMapping blockDeviceMapping = image.getBlockDeviceMappings().get(0);

    Integer diskSize = template.getDiskSize() == null
            ? SystemUtils2.getIntegerProperty("org.excalibur.amazon.default.disk.size", 30)
            : template.getDiskSize();

    EbsBlockDevice disk = new EbsBlockDevice().withSnapshotId(blockDeviceMapping.getEbs().getSnapshotId())
            .withVolumeSize(diskSize).withVolumeType("gp2");

    runInstacesRequest.withBlockDeviceMappings(
            new BlockDeviceMapping().withDeviceName(image.getRootDeviceName()).withEbs(disk));

    RunInstancesResult result = ec2_.runInstances(runInstacesRequest);
    template.setStatus(new InstanceTemplateStatus().setStatus(Status.SUCCESS));

    Iterable<Instance> ec2Instances = waitForRunningState
            ? waitForRunningInstacesState(result.getReservation().getInstances())
            : describeEC2Instances(result.getReservation().getInstances());

    CreateTagsRequest tagsRequest = new CreateTagsRequest();

    String instanceName = isNullOrEmpty(template.getInstanceName()) ? UUID.randomUUID().toString()
            : template.getInstanceName();

    tagsRequest.withTags(new Tag().withKey(DEFAULT_INSTANCE_NAME_TAG).withValue(instanceName));
    tagsRequest.withTags(
            new Tag().withKey(DEFAULT_PLATFORM_INSTANCE_USERNAME_TAG).withValue(DEFAULT_PLATFORM_USER_NAME));
    tagsRequest.withTags(new Tag().withKey("keyname").withValue(keyPair.getKeyName()));

    tagsRequest.withResources(Collections2.transform(newArrayList(ec2Instances), INSTANCE_STRING_FUNCTION));

    for (org.excalibur.core.cloud.api.domain.Tag tag : template.getTags()) {
        if (!isNullOrEmpty(tag.getName()) && !isNullOrEmpty(tag.getValue())) {
            tagsRequest.withTags(new Tag().withKey(tag.getName()).withValue(tag.getValue()));
        }
    }

    ec2_.createTags(tagsRequest);

    if (template.getMaxCount() > 1) {

        for (int i = 0; i < result.getReservation().getInstances().size(); i++) {
            CreateTagsRequest request = new CreateTagsRequest();
            request.withResources(result.getReservation().getInstances().get(i).getInstanceId())
                    .withTags(new Tag().withKey(DEFAULT_INSTANCE_NAME_TAG)
                            .withValue(String.format("%s-%s", instanceName, i + 1)));
            ec2_.createTags(request);
        }
    }

    //        return new Instances(toExcaliburInstances(ec2Instances, keyPair));
    Instances instances = this.describeInstances(ec2Instances);

    //
    LOG.debug("Waiting instances' ready state....");
    ThreadUtils.sleep(30 * 1000);

    LOG.debug("Created [{}] instance(s) from [{}/{}]", instances.size(), template.getMinCount(),
            template.getMaxCount());

    return instances;
}