List of usage examples for com.amazonaws.services.ec2.model EbsBlockDevice EbsBlockDevice
EbsBlockDevice
From source file:InlineGettingStartedCodeApp.java
License:Open Source License
/** * @param args//from w ww .j a v a2 s .co m */ public static void main(String[] args) { //============================================================================================// //=============================== Submitting a Request =======================================// //============================================================================================// // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(new ClasspathPropertiesFileCredentialsProvider()); Region usEast1 = Region.getRegion(Regions.US_EAST_1); ec2.setRegion(usEast1); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); //*************************** Required Parameters Settings ************************// // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro) // and the latest Amazon Linux AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-700e4a19"); launchSpecification.setInstanceType("t1.micro"); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("ForAssignment2"); launchSpecification.setSecurityGroups(securityGroups); //*************************** Bid Type Settings ************************// // Set the type of the bid to persistent. requestRequest.setType("persistent"); //*************************** Valid From/To Settings ************************// // Set the valid start time to be two minutes from now. Calendar from = Calendar.getInstance(); from.add(Calendar.MINUTE, 2); requestRequest.setValidFrom(from.getTime()); // Set the valid end time to be two minutes and two hours from now. Calendar until = (Calendar) from.clone(); until.add(Calendar.HOUR, 2); requestRequest.setValidUntil(until.getTime()); //*************************** Launch Group Settings ************************// // Set the launch group. requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP"); //*************************** Availability Zone Group Settings ************************// // Set the availability zone group. requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP"); //*************************** Add the block device mapping ************************// // Goal: Setup block device mappings to ensure that we will not delete // the root partition on termination. // Create the block device mapping to describe the root partition. BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); // Set the delete on termination flag to false. EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setDeleteOnTermination(Boolean.FALSE); blockDeviceMapping.setEbs(ebs); // Add the block device mapping to the block list. ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); // Set the block device mapping configuration in the launch specifications. launchSpecification.setBlockDeviceMappings(blockList); //*************************** Add the availability zone ************************// // Setup the availability zone to use. Note we could retrieve the availability // zones using the ec2.describeAvailabilityZones() API. For this demo we will just use // us-east-1b. SpotPlacement placement = new SpotPlacement("us-east-1b"); launchSpecification.setPlacement(placement); //*************************** Add the placement group ************************// // Setup the placement group to use with whatever name you desire. // For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP". // Note: We have commented this out, because we are not leveraging cc1.4xlarge or // cg1.4xlarge in this example. /* SpotPlacement pg = new SpotPlacement(); pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP"); launchSpecification.setPlacement(pg); */ //*************************** Add the launch specification ************************// // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); //============================================================================================// //=========================== Getting the Request ID from the Request ========================// //============================================================================================// // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest); List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests(); // Setup an arraylist to collect all of the request ids we want to watch hit the running // state. ArrayList<String> spotInstanceRequestIds = new ArrayList<String>(); // Add all of the request ids to the hashset, so we can determine when they hit the // active state. for (SpotInstanceRequest requestResponse : requestResponses) { System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId()); spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId()); } //============================================================================================// //=========================== Determining the State of the Spot Request ======================// //============================================================================================// // Create a variable that will track whether there are any requests still in the open state. boolean anyOpen; // Initialize variables. ArrayList<String> instanceIds = new ArrayList<String>(); do { // Create the describeRequest with tall of the request id to monitor (e.g. that we started). DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest(); describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds); // Initialize the anyOpen variable to false ??? which assumes there are no requests open unless // we find one that is still open. anyOpen = false; try { // Retrieve all of the requests we want to monitor. DescribeSpotInstanceRequestsResult describeResult = ec2 .describeSpotInstanceRequests(describeRequest); List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests(); // Look through each request and determine if they are all in the active state. for (SpotInstanceRequest describeResponse : describeResponses) { // If the state is open, it hasn't changed since we attempted to request it. // There is the potential for it to transition almost immediately to closed or // cancelled so we compare against open instead of active. if (describeResponse.getState().equals("open")) { anyOpen = true; break; } // Add the instance id to the list we will eventually terminate. instanceIds.add(describeResponse.getInstanceId()); } } catch (AmazonServiceException e) { // If we have an exception, ensure we don't break out of the loop. // This prevents the scenario where there was blip on the wire. anyOpen = true; } try { // Sleep for 60 seconds. Thread.sleep(60 * 1000); } catch (Exception e) { // Do nothing because it woke up early. } } while (anyOpen); //============================================================================================// //====================================== Canceling the Request ==============================// //============================================================================================// try { // Cancel requests. CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest( spotInstanceRequestIds); ec2.cancelSpotInstanceRequests(cancelRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error cancelling instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } //============================================================================================// //=================================== Terminating any Instances ==============================// //============================================================================================// try { // Terminate instances. TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds); ec2.terminateInstances(terminateRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } }
From source file:advanced.InlineGettingStartedCodeSampleApp.java
License:Open Source License
/** * @param args//w ww . j a va 2 s . co m */ public static void main(String[] args) { //============================================================================================// //=============================== Submitting a Request =======================================// //============================================================================================// // Retrieves the credentials from an AWSCredentials.properties file. AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( InlineTaggingCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties")); } catch (IOException e1) { System.out.println("Credentials were not properly entered into AwsCredentials.properties."); System.out.println(e1.getMessage()); System.exit(-1); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); //*************************** Required Parameters Settings ************************// // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro) // and the latest Amazon Linux AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-8c1fece5"); launchSpecification.setInstanceType("t1.micro"); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); //*************************** Bid Type Settings ************************// // Set the type of the bid to persistent. requestRequest.setType("persistent"); //*************************** Valid From/To Settings ************************// // Set the valid start time to be two minutes from now. Calendar from = Calendar.getInstance(); from.add(Calendar.MINUTE, 2); requestRequest.setValidFrom(from.getTime()); // Set the valid end time to be two minutes and two hours from now. Calendar until = (Calendar) from.clone(); until.add(Calendar.HOUR, 2); requestRequest.setValidUntil(until.getTime()); //*************************** Launch Group Settings ************************// // Set the launch group. requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP"); //*************************** Availability Zone Group Settings ************************// // Set the availability zone group. requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP"); //*************************** Add the block device mapping ************************// // Goal: Setup block device mappings to ensure that we will not delete // the root partition on termination. // Create the block device mapping to describe the root partition. BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); // Set the delete on termination flag to false. EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setDeleteOnTermination(Boolean.FALSE); blockDeviceMapping.setEbs(ebs); // Add the block device mapping to the block list. ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); // Set the block device mapping configuration in the launch specifications. launchSpecification.setBlockDeviceMappings(blockList); //*************************** Add the availability zone ************************// // Setup the availability zone to use. Note we could retrieve the availability // zones using the ec2.describeAvailabilityZones() API. For this demo we will just use // us-east-1b. SpotPlacement placement = new SpotPlacement("us-east-1b"); launchSpecification.setPlacement(placement); //*************************** Add the placement group ************************// // Setup the placement group to use with whatever name you desire. // For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP". // Note: We have commented this out, because we are not leveraging cc1.4xlarge or // cg1.4xlarge in this example. /* SpotPlacement pg = new SpotPlacement(); pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP"); launchSpecification.setPlacement(pg); */ //*************************** Add the launch specification ************************// // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); //============================================================================================// //=========================== Getting the Request ID from the Request ========================// //============================================================================================// // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest); List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests(); // Setup an arraylist to collect all of the request ids we want to watch hit the running // state. ArrayList<String> spotInstanceRequestIds = new ArrayList<String>(); // Add all of the request ids to the hashset, so we can determine when they hit the // active state. for (SpotInstanceRequest requestResponse : requestResponses) { System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId()); spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId()); } //============================================================================================// //=========================== Determining the State of the Spot Request ======================// //============================================================================================// // Create a variable that will track whether there are any requests still in the open state. boolean anyOpen; // Initialize variables. ArrayList<String> instanceIds = new ArrayList<String>(); do { // Create the describeRequest with tall of the request id to monitor (e.g. that we started). DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest(); describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds); // Initialize the anyOpen variable to false which assumes there are no requests open unless // we find one that is still open. anyOpen = false; try { // Retrieve all of the requests we want to monitor. DescribeSpotInstanceRequestsResult describeResult = ec2 .describeSpotInstanceRequests(describeRequest); List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests(); // Look through each request and determine if they are all in the active state. for (SpotInstanceRequest describeResponse : describeResponses) { // If the state is open, it hasn't changed since we attempted to request it. // There is the potential for it to transition almost immediately to closed or // cancelled so we compare against open instead of active. if (describeResponse.getState().equals("open")) { anyOpen = true; break; } // Add the instance id to the list we will eventually terminate. instanceIds.add(describeResponse.getInstanceId()); } } catch (AmazonServiceException e) { // If we have an exception, ensure we don't break out of the loop. // This prevents the scenario where there was blip on the wire. anyOpen = true; } try { // Sleep for 60 seconds. Thread.sleep(60 * 1000); } catch (Exception e) { // Do nothing because it woke up early. } } while (anyOpen); //============================================================================================// //====================================== Canceling the Request ==============================// //============================================================================================// try { // Cancel requests. CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest( spotInstanceRequestIds); ec2.cancelSpotInstanceRequests(cancelRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error cancelling instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } //============================================================================================// //=================================== Terminating any Instances ==============================// //============================================================================================// try { // Terminate instances. TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds); ec2.terminateInstances(terminateRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } }
From source file:advanced.Requests.java
License:Open Source License
/** * The submit method will create 1 x one-time t1.micro request with a maximum bid * price of $0.03 using the Amazon Linux AMI. * // w w w .j av a2 s. c o m * Note the AMI id may change after the release of this code sample, and it is important * to use the latest. You can find the latest version by logging into the AWS Management * console, and attempting to perform a launch. You will be presented with AMI options, * one of which will be Amazon Linux. Simply use that AMI id. */ public void submitRequests() { //==========================================================================// //================= Submit a Spot Instance Request =====================// //==========================================================================// // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice(bidPrice); requestRequest.setInstanceCount(Integer.valueOf(1)); // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro) // and the latest Amazon Linux AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId(amiID); launchSpecification.setInstanceType(instanceType); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add(securityGroup); launchSpecification.setSecurityGroups(securityGroups); // If a placement group has been set, then we will use it in the request. if (placementGroupName != null && !placementGroupName.equals("")) { // Setup the placement group to use with whatever name you desire. SpotPlacement placement = new SpotPlacement(); placement.setGroupName(placementGroupName); launchSpecification.setPlacement(placement); } // Check to see if we need to set the availability zone name. if (availabilityZoneName != null && !availabilityZoneName.equals("")) { // Setup the availability zone to use. Note we could retrieve the availability // zones using the ec2.describeAvailabilityZones() API. SpotPlacement placement = new SpotPlacement(availabilityZoneName); launchSpecification.setPlacement(placement); } if (availabilityZoneGroupName != null && !availabilityZoneGroupName.equals("")) { // Set the availability zone group. requestRequest.setAvailabilityZoneGroup(availabilityZoneGroupName); } // Check to see if we need to set the launch group. if (launchGroupName != null && !launchGroupName.equals("")) { // Set the availability launch group. requestRequest.setLaunchGroup(launchGroupName); } // Check to see if we need to set the valid from option. if (validFrom != null) { requestRequest.setValidFrom(validFrom); } // Check to see if we need to set the valid until option. if (validTo != null) { requestRequest.setValidUntil(validFrom); } // Check to see if we need to set the request type. if (requestType != null && !requestType.equals("")) { // Set the type of the bid. requestRequest.setType(requestType); } // If we should delete the EBS boot partition on termination. if (!deleteOnTermination) { // Create the block device mapping to describe the root partition. BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); // Set the delete on termination flag to false. EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setDeleteOnTermination(Boolean.FALSE); blockDeviceMapping.setEbs(ebs); // Add the block device mapping to the block list. ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); // Set the block device mapping configuration in the launch specifications. launchSpecification.setBlockDeviceMappings(blockList); } // Add the launch specifications to the request. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest); List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests(); // Setup an arraylist to collect all of the request ids we want to watch hit the running // state. spotInstanceRequestIds = new ArrayList<String>(); // Add all of the request ids to the hashset, so we can determine when they hit the // active state. for (SpotInstanceRequest requestResponse : requestResponses) { System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId()); spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId()); } }
From source file:com.cloudera.director.aws.ec2.EC2Provider.java
License:Apache License
private List<BlockDeviceMapping> getEbsBlockDeviceMapping(int count, String volumeType, int volumeSizeGib, boolean enableEncryption) { List<String> deviceNames = ebsAllocator.getEbsDeviceNames(count); List<BlockDeviceMapping> mappings = Lists.newArrayList(); for (String deviceName : deviceNames) { EbsBlockDevice ebs = new EbsBlockDevice().withVolumeType(volumeType).withVolumeSize(volumeSizeGib) .withEncrypted(enableEncryption).withDeleteOnTermination(true); BlockDeviceMapping mapping = new BlockDeviceMapping().withDeviceName(deviceName).withEbs(ebs); mappings.add(mapping);/*from w ww.j ava 2 s. c o m*/ } return mappings; }
From source file:com.dowdandassociates.gentoo.bootstrap.DefaultTestImageProvider.java
License:Apache License
public Optional<Image> get() { if (!testSnapshot.isPresent()) { log.info("test snapshot not present"); return Optional.absent(); }// w w w.j a va 2 s .c o m StringBuilder name = new StringBuilder(); name.append(prefix.get()); if (StringUtils.isNotBlank(dateFormat.get())) { name.append(DateFormatUtils.formatUTC(System.currentTimeMillis(), dateFormat.get())); } String architecture = imageInformation.getArchitecture(); String virtualizationType = imageInformation.getVirtualizationType(); RegisterImageRequest registerImageRequest = new RegisterImageRequest().withArchitecture(architecture) .withVirtualizationType(virtualizationType).withDescription(description.get()) .withName(name.toString()).withRootDeviceName(rootDeviceName.get()); if ("paravirtual".equals(virtualizationType)) { if (!kernelImage.isPresent()) { log.info("kernel image not present"); return Optional.absent(); } registerImageRequest = registerImageRequest.withKernelId(kernelImage.get().getImageId()); } if ("i386".equals(architecture)) { registerImageRequest = registerImageRequest.withBlockDeviceMappings( new BlockDeviceMapping().withDeviceName(rootDeviceName.get()) .withEbs(new EbsBlockDevice().withSnapshotId(testSnapshot.get().getSnapshotId())), new BlockDeviceMapping().withDeviceName("/dev/sda2").withVirtualName("ephemeral0"), new BlockDeviceMapping().withDeviceName("/dev/sda3").withVirtualName("ephemeral1")); } else { registerImageRequest = registerImageRequest.withBlockDeviceMappings( new BlockDeviceMapping().withDeviceName(rootDeviceName.get()) .withEbs(new EbsBlockDevice().withSnapshotId(testSnapshot.get().getSnapshotId())), new BlockDeviceMapping().withDeviceName("/dev/sdb").withVirtualName("ephemeral0"), new BlockDeviceMapping().withDeviceName("/dev/sdc").withVirtualName("ephemeral1"), new BlockDeviceMapping().withDeviceName("/dev/sdd").withVirtualName("ephemeral2"), new BlockDeviceMapping().withDeviceName("/dev/sde").withVirtualName("ephemeral3")); } RegisterImageResult registerImageResult = ec2Client.registerImage(registerImageRequest); String imageId = registerImageResult.getImageId(); DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest().withImageIds(imageId); try { while (true) { log.info("Sleeping for " + sleep.get() + " ms"); Thread.sleep(sleep.get()); DescribeImagesResult describeImagesResult = ec2Client.describeImages(describeImagesRequest); if (describeImagesResult.getImages().isEmpty()) { return Optional.absent(); } Image image = describeImagesResult.getImages().get(0); String state = image.getState(); log.info("Image state = " + state); if ("pending".equals(state)) { continue; } if (!"available".equals(state)) { return Optional.absent(); } return Optional.fromNullable(image); } } catch (InterruptedException e) { return Optional.absent(); } }
From source file:com.urbancode.terraform.tasks.aws.EbsTask.java
License:Apache License
/** * Creates the EBS volume on instance launch. Only the data structures are required as we send * then with the RunInstancesRequest./* ww w . j a v a 2 s. c o m*/ */ private void createOnLaunch() { // These AWS data structures are needed when launching an ami/running an instance. // this will need to be handled differently if creating/attaching an EBS volume // to an already existing instance. // PROBLEM: we don't have the volumeId for this new ebs volume EbsBlockDevice block = new EbsBlockDevice().withDeleteOnTermination(persist).withSnapshotId(snapshotId) .withVolumeSize(volumeSize); blockMap = new BlockDeviceMapping().withDeviceName(deviceName).withEbs(block).withVirtualName(name); }
From source file:de.unibi.cebitec.bibigrid.meta.aws.CreateClusterAWS.java
private List<BlockDeviceMapping> createBlockDeviceMappings(DeviceMapper deviceMapper) { List<BlockDeviceMapping> mappings = new ArrayList<>(); Map<String, String> snapshotToMountPointMap = deviceMapper.getSnapshotIdToMountPoint(); for (Map.Entry<String, String> snapshotIdMountPoint : snapshotToMountPointMap.entrySet()) { try {/* w ww .j a va 2 s . com*/ BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setEbs(new EbsBlockDevice() .withSnapshotId(DeviceMapper.stripSnapshotId(snapshotIdMountPoint.getKey()))); blockDeviceMapping .setDeviceName(deviceMapper.getDeviceNameForSnapshotId(snapshotIdMountPoint.getKey())); mappings.add(blockDeviceMapping); } catch (AmazonServiceException ex) { log.debug("{}", ex.getMessage()); } } return mappings; }
From source file:edu.brandeis.wisedb.aws.VMCreator.java
License:Open Source License
public VM createInstance(VMType type, VMDiskConfiguration disk, boolean waitForRunning) throws VirtualMachineException { AmazonEC2Client ec2 = getEC2();//from www . j a va2s.co m RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); // TODO: figure out how to change storage type String instanceType = ""; switch (type) { case C4_LARGE: instanceType = "c4.large"; break; case C4_XLARGE: instanceType = "c4.xlarge"; break; case M3_LARGE: instanceType = "m3.large"; break; case M3_MEDIUM: instanceType = "m3.medium"; break; case T2_MEDIUM: instanceType = "t2.medium"; break; case T2_SMALL: instanceType = "t2.small"; break; default: break; } BlockDeviceMapping bdm = null; switch (disk) { case HD100: bdm = new BlockDeviceMapping().withDeviceName("/dev/sda1") .withEbs(new EbsBlockDevice().withVolumeSize(100).withVolumeType(VolumeType.Standard) .withDeleteOnTermination(true).withSnapshotId(config.getSnapshotID())); case SSD10: bdm = new BlockDeviceMapping().withDeviceName("/dev/sda1") .withEbs(new EbsBlockDevice().withVolumeSize(10).withVolumeType(VolumeType.Gp2) .withDeleteOnTermination(true).withSnapshotId(config.getSnapshotID())); case SSD30: bdm = new BlockDeviceMapping().withDeviceName("/dev/sda1") .withEbs(new EbsBlockDevice().withVolumeSize(30).withVolumeType(VolumeType.Gp2) .withDeleteOnTermination(true).withSnapshotId(config.getSnapshotID())); default: break; } System.out.println(instanceType); runInstancesRequest = runInstancesRequest.withImageId(config.getAMIID()).withInstanceType(instanceType) .withMinCount(1).withMaxCount(1).withKeyName(config.getKeyPairName()) .withSubnetId(config.getSubnet()).withBlockDeviceMappings(bdm); RunInstancesResult rir = ec2.runInstances(runInstancesRequest); String instanceID = rir.getReservation().getInstances().get(0).getInstanceId(); String ip; if (waitForRunning) { int maxTry = 60; while (true) { try { DescribeInstancesResult dir = ec2 .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceID)); InstanceState is = dir.getReservations().get(0).getInstances().get(0).getState(); //System.out.println("Got state: " + is); // apparently this constant isn't stored anywhere... *sigh* if (is.getCode() == 16) { ip = dir.getReservations().get(0).getInstances().get(0).getPublicIpAddress(); break; } } catch (AmazonServiceException e) { //System.err.println("Trouble with AWS: " + e.getMessage()); } maxTry--; if (maxTry == 0) { throw new VirtualMachineException("machine never entered running state"); } try { Thread.sleep(2000); } catch (InterruptedException e) { } } VM toR = new VM(instanceID, ip, this); return toR; } VM toR = new VM(instanceID, null, this); return toR; }
From source file:hudson.plugins.ec2.util.DeviceMappingParser.java
License:Open Source License
private static EbsBlockDevice parseEbs(String blockDevice) { String[] parts = blockDevice.split(":"); EbsBlockDevice ebs = new EbsBlockDevice(); if (StringUtils.isNotBlank(getOrEmpty(parts, 0))) { ebs.setSnapshotId(parts[0]);// ww w. j av a 2s.c om } if (StringUtils.isNotBlank(getOrEmpty(parts, 1))) { ebs.setVolumeSize(Integer.valueOf(parts[1])); } if (StringUtils.isNotBlank(getOrEmpty(parts, 2))) { ebs.setDeleteOnTermination(Boolean.valueOf(parts[2])); } if (StringUtils.isNotBlank(getOrEmpty(parts, 3))) { ebs.setVolumeType(parts[3]); } if (StringUtils.isNotBlank(getOrEmpty(parts, 4))) { ebs.setIops(Integer.valueOf(parts[4])); } if (StringUtils.isNotBlank(getOrEmpty(parts, 5))) { ebs.setEncrypted(parts[5].equals("encrypted")); } return ebs; }
From source file:org.apache.provisionr.amazon.activities.RunInstances.java
License:Apache License
private AmazonWebServiceRequest createRequest(Pool pool, DelegateExecution execution, boolean spot) throws IOException { final String businessKey = execution.getProcessBusinessKey(); final String securityGroupName = SecurityGroups.formatNameFromBusinessKey(businessKey); final String keyPairName = KeyPairs.formatNameFromBusinessKey(businessKey); final String instanceType = pool.getHardware().getType(); final String imageId = getImageIdFromPoolConfigurationOrQueryImageTable(pool, pool.getProvider(), instanceType);//from w w w. j a v a2s .co m final String userData = Resources.toString( Resources.getResource(RunInstances.class, "/org/apache/provisionr/amazon/userdata.sh"), Charsets.UTF_8); List<BlockDevice> blockDevices = pool.getHardware().getBlockDevices(); List<BlockDeviceMapping> blockDeviceMappings = Lists.newArrayList(); if (blockDevices != null && blockDevices.size() > 0) { for (BlockDevice device : blockDevices) { blockDeviceMappings.add(new BlockDeviceMapping().withDeviceName(device.getName()).withEbs( new EbsBlockDevice().withVolumeSize(device.getSize()).withDeleteOnTermination(true))); } } if (spot) { Calendar validUntil = Calendar.getInstance(); validUntil.add(Calendar.MINUTE, 10); final String spotPrice = checkNotNull(pool.getProvider().getOption(ProviderOptions.SPOT_BID), "The bid for spot instances was not specified"); LaunchSpecification ls = new LaunchSpecification().withInstanceType(instanceType) .withKeyName(keyPairName).withImageId(imageId).withBlockDeviceMappings(blockDeviceMappings) .withSecurityGroups(Lists.newArrayList(securityGroupName)) .withUserData(Base64.encodeBytes(userData.getBytes(Charsets.UTF_8))); return new RequestSpotInstancesRequest().withSpotPrice(spotPrice).withLaunchSpecification(ls) .withLaunchGroup(businessKey).withInstanceCount(pool.getExpectedSize()) .withType(SpotInstanceType.OneTime).withValidUntil(validUntil.getTime()); } else { return new RunInstancesRequest().withClientToken(businessKey).withSecurityGroups(securityGroupName) .withKeyName(keyPairName).withInstanceType(instanceType).withImageId(imageId) .withBlockDeviceMappings(blockDeviceMappings).withMinCount(pool.getMinSize()) .withMaxCount(pool.getExpectedSize()) .withUserData(Base64.encodeBytes(userData.getBytes(Charsets.UTF_8))); } }