List of usage examples for com.amazonaws.services.ec2.model BlockDeviceMapping getEbs
public EbsBlockDevice getEbs()
Parameters used to automatically set up EBS volumes when the instance is launched.
From source file:com.carrotgarden.maven.aws.ecc.CarrotElasticCompute.java
License:BSD License
/** delete AMI image and related EBS snapshots */ public void imageDelete(final String imageId) throws Exception { final Image image = findImage(imageId); if (image == null) { logger.info("missing imageId = " + imageId); return;//from w w w .j a va 2 s . c o m } else { logger.info("present imageId = " + imageId); } imageUnregister(imageId); for (final BlockDeviceMapping blockDevice : image.getBlockDeviceMappings()) { final EbsBlockDevice elasticDevice = blockDevice.getEbs(); if (elasticDevice == null) { continue; } final String snapshotId = elasticDevice.getSnapshotId(); if (snapshotId == null) { continue; } snapshotDelete(snapshotId); } logger.info("removed imageId = " + imageId); }
From source file:com.carrotgarden.maven.aws.ecc.ElastiCompImageCreate.java
License:BSD License
@Override public void execute() throws MojoFailureException { try {/*w ww .j a va2 s . c o m*/ getLog().info("image create init [" + imageName() + "]"); final CarrotElasticCompute compute = newElasticCompute(); final Image image = compute.imageCreate( // imageInstanceId(), // imageName(), // imageDescription // ); final ImageState state = ImageState.fromValue(image.getState()); switch (state) { case AVAILABLE: break; default: throw new IllegalStateException("image create failed : \n" + image); } final String imageId = image.getImageId(); /** publish result */ project().getProperties().put(imageResultProperty, image); project().getProperties().put(imageIdResultProperty, imageId); /** tag image */ compute.tagCreate(imageId, amazonTagName(), imageName()); /** tag image devices */ for (final BlockDeviceMapping blockDevice : image.getBlockDeviceMappings()) { final EbsBlockDevice elasticDevice = blockDevice.getEbs(); if (elasticDevice == null) { continue; } final String snapshotId = elasticDevice.getSnapshotId(); if (snapshotId == null) { continue; } compute.tagCreate(snapshotId, amazonTagName(), imageName()); } getLog().info("image create image=\n" + image); getLog().info("image create done [" + imageName() + "]"); } catch (final Exception e) { throw new MojoFailureException("bada-boom", e); } }
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 . jav a2 s . c o 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.cloudera.director.aws.ec2.EC2Provider.java
License:Apache License
/** * Selects the root device from a list of block device mappings based on the * root device name for the mappings' image. * * @param mappings list of block device mappings * @param rootDeviceName image root device name * @return root device mapping, or null if it could not be determined *//* w ww. java 2s . c o m*/ @VisibleForTesting static BlockDeviceMapping selectRootDevice(List<BlockDeviceMapping> mappings, String rootDeviceName) { /* * Heuristic to find the root device: * - The best match is the EBS device that matches the root device name for the image, but * this may not happen (/dev/sda1 vs. /dev/sda). See: * http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html * - If there isn't a best match, then a device whose name is a prefix for the image's root * device name is selected. * - If all else fails, it's the first EBS volume in the list. */ BlockDeviceMapping bestMatch = null; BlockDeviceMapping firstEbs = null; for (BlockDeviceMapping mapping : mappings) { if (mapping.getEbs() == null) { continue; } if (firstEbs == null) { firstEbs = mapping; } if (mapping.getDeviceName() == null) { continue; } if (rootDeviceName.equals(mapping.getDeviceName())) { return mapping; } if (rootDeviceName.startsWith(mapping.getDeviceName())) { bestMatch = mapping; } } if (bestMatch != null) { return bestMatch; } else if (firstEbs != null) { return firstEbs; } else { return null; } }
From source file:com.netflix.simianarmy.aws.janitor.crawler.EBSSnapshotJanitorCrawler.java
License:Apache License
private void refreshSnapshotToAMIs() { snapshotToAMIs.clear();/* w w w . j a v a 2 s. c o m*/ for (Image image : getAWSClient().describeImages()) { for (BlockDeviceMapping bdm : image.getBlockDeviceMappings()) { EbsBlockDevice ebd = bdm.getEbs(); if (ebd != null && ebd.getSnapshotId() != null) { LOGGER.debug(String.format("Snapshot %s is used to generate AMI %s", ebd.getSnapshotId(), image.getImageId())); Collection<String> amis = snapshotToAMIs.get(ebd.getSnapshotId()); if (amis == null) { amis = new ArrayList<String>(); snapshotToAMIs.put(ebd.getSnapshotId(), amis); } amis.add(image.getImageId()); } } } }
From source file:jp.primecloud.auto.process.aws.AwsInstanceProcess.java
License:Open Source License
protected List<BlockDeviceMapping> createImageBlockDeviceMappings(AwsProcessClient awsProcessClient, ImageAws imageAws, AwsInstance awsInstance, com.amazonaws.services.ec2.model.Image image) { // ?BlockDeviceMapping? List<BlockDeviceMapping> mappings = new ArrayList<BlockDeviceMapping>(); for (BlockDeviceMapping originalMapping : image.getBlockDeviceMappings()) { BlockDeviceMapping mapping = originalMapping.clone(); if (originalMapping.getEbs() != null) { mapping.withEbs(originalMapping.getEbs().clone()); }//from w w w . jav a 2 s . co m mappings.add(mapping); } for (BlockDeviceMapping mapping : mappings) { if (mapping.getEbs() == null) { continue; } // ?EBS????? mapping.getEbs().withDeleteOnTermination(true); // ???Encrypted?????? if (StringUtils.isNotEmpty(mapping.getEbs().getSnapshotId())) { mapping.getEbs().withEncrypted(null); } // ? String volumeType = Config.getProperty("aws.volumeType"); if (StringUtils.isNotEmpty(volumeType)) { mapping.getEbs().setVolumeType(volumeType); } } // ??? if (awsInstance.getRootSize() != null) { for (BlockDeviceMapping mapping : mappings) { if (image.getRootDeviceName().equals(mapping.getDeviceName())) { mapping.getEbs().setVolumeSize(awsInstance.getRootSize()); break; } } } return mappings; }
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); }/*from w w w . j a v a2 s . c o m*/ 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; }
From source file:org.xmlsh.aws.util.AWSEC2Command.java
License:BSD License
private void writeBlockDeviceMapping(BlockDeviceMapping device) throws XMLStreamException { startElement("device"); attribute("name", device.getDeviceName()); EbsBlockDevice ebs = device.getEbs(); if (ebs != null) { attribute("shapshot-id", ebs.getSnapshotId()); attribute("delete-on-termination", ebs.getDeleteOnTermination()); attribute("volume-size", ebs.getVolumeSize()); attribute("volume-type", ebs.getVolumeType()); attribute("encrypted", ebs.getEncrypted()); attribute("iops", ebs.getIops()); }// ww w . j a v a 2s. co m endElement(); }