List of usage examples for com.amazonaws.services.ec2 AmazonEC2Client runInstances
@Override
public RunInstancesResult runInstances(RunInstancesRequest request)
Launches the specified number of instances using an AMI for which you have permissions.
From source file:au.edu.unsw.cse.soc.federatedcloud.deployers.aws.ec2.redmine.RedmineEC2DeploymentWrapper.java
License:Open Source License
@Override public void deployResource(CloudResourceDescription description) throws Exception { //Reading the credentials Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("/AwsCredentials.properties")); String accessKey = properties.getProperty("accessKey"); String secretKey = properties.getProperty("secretKey-NULL"); AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); AmazonEC2Client cleint = new AmazonEC2Client(credentials); RunInstancesRequest request = new RunInstancesRequest(); request.setImageId("ami-0b420162"); RunInstancesResult response = cleint.runInstances(request); return;/*from w w w. j a v a2 s .c om*/ response.getReservation().getInstances().get(0).getInstanceId(); }
From source file:com.rmn.qa.aws.AwsVmManager.java
License:Open Source License
/** * Attempts to run the {@link com.amazonaws.services.ec2.model.RunInstancesRequest RunInstancesRequest}, falling * back on alternative subnets if capacity is full in the current region. * * @param request/* ww w. j a v a 2 s . c o m*/ * @param requestNumber * * @return * * @throws NodesCouldNotBeStartedException */ private RunInstancesResult getResults(final RunInstancesRequest request, int requestNumber) throws NodesCouldNotBeStartedException { RunInstancesResult runInstancesResult; try { AmazonEC2Client localClient = getClient(); if (localClient == null) { throw new RuntimeException("The client is not initialized"); } runInstancesResult = localClient.runInstances(request); } catch (AmazonServiceException e) { // If there is insufficient capacity in this subnet / availability zone, then we want to try other // configured subnets if ("InsufficientInstanceCapacity".equals(e.getErrorCode()) || "VolumeTypeNotAvailableInZone".equals(e.getErrorCode())) { log.error(String.format("Insufficient capacity in subnet [%s]: %s", request.getSubnetId(), e)); requestNumber = requestNumber + 1; Properties awsProperties = getAwsProperties(); String fallBackSubnetId = awsProperties .getProperty(region + "_subnet_fallback_id_" + requestNumber); // Make sure and only try to recursively loop so as long as we have a valid fallback subnet id. Logic // to also // prevent an accidental infinite loop if (fallBackSubnetId != null && requestNumber < 5) { log.info("Setting fallback subnet: " + fallBackSubnetId); // Modify the original request with the new subnet ID we're trying to fallback on request.withSubnetId(fallBackSubnetId); } else { throw new NodesCouldNotBeStartedException( "Sufficient resources were not available in any of the availability zones"); } return getResults(request, requestNumber); } else { // We got an error other than insufficient capacity, and should just throw it for the caller to handle throw e; } } return runInstancesResult; }
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(); RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); // TODO: figure out how to change storage type String instanceType = ""; switch (type) { case C4_LARGE: instanceType = "c4.large"; break;//from w w w . j ava2s . com 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:eu.stratosphere.nephele.instance.ec2.EC2CloudManager.java
License:Apache License
/** * Requests (allocates) instances (VMs) from Amazon EC2. * /*from www. ja v a2 s.com*/ * @param awsAccessId * the access ID into AWS * @param awsSecretKey * the secret key used to generate signatures for authentication * @param instancesToBeRequested * Map containing desired instances types and count * @param sshKeyPair * Optional parameter to insert an EC2 SSH key/value pair * @return * List containing the instance IDs of the allocated instances. */ private LinkedList<String> allocateCloudInstance(final Configuration conf, final InstanceType type, final int mincount, final int maxcount) { final String awsAccessId = conf.getString(AWS_ACCESS_ID_KEY, null); final String awsSecretKey = conf.getString(AWS_SECRET_KEY_KEY, null); final String imageID = conf.getString(AWS_AMI_KEY, null); LOG.info("Read Amazon Machine Image from job configuration: " + imageID); final String jobManagerIPAddress = GlobalConfiguration.getString("jobmanager.rpc.address", null); if (jobManagerIPAddress == null) { LOG.error("JobManager IP address is not set (jobmanager.rpc.address)"); return null; } final String sshKeyPair = conf.getString("job.ec2.sshkeypair", null); final AmazonEC2Client ec2client = EC2ClientFactory.getEC2Client(awsAccessId, awsSecretKey); final LinkedList<String> instanceIDs = new LinkedList<String>(); // Iterate over instance types.. final RunInstancesRequest request = new RunInstancesRequest(imageID, mincount, maxcount); request.setInstanceType(type.getIdentifier()); // Set availability zone if configured String av = null; if (this.availabilityZone != null) { av = this.availabilityZone; } final String jobAV = conf.getString("job.ec2.availabilityzone", null); if (jobAV != null) { LOG.info("Found " + jobAV + " as job-specific preference for availability zone"); av = jobAV; } if (av != null) { request.setPlacement(new Placement(av)); } // TODO: Make this configurable! final BlockDeviceMapping bdm = new BlockDeviceMapping(); bdm.setVirtualName("ephemeral0"); bdm.setDeviceName("/dev/sdb1"); if (sshKeyPair != null) { request.setKeyName(sshKeyPair); } final LinkedList<BlockDeviceMapping> bdmlist = new LinkedList<BlockDeviceMapping>(); bdmlist.add(bdm); request.setBlockDeviceMappings(bdmlist); // Setting User-Data parameters request.setUserData(EC2Utilities.createTaskManagerUserData(jobManagerIPAddress)); // Request instances! try { final RunInstancesResult result = ec2client.runInstances(request); for (Instance i : result.getReservation().getInstances()) { instanceIDs.add(i.getInstanceId()); } } catch (AmazonClientException e) { // Only log the error here LOG.error(StringUtils.stringifyException(e)); } return instanceIDs; }
From source file:n3phele.factory.ec2.VirtualServerResource.java
License:Open Source License
private int addOnDemandInstance(List<VirtualServer> items) { RunInstancesRequest vs = new RunInstancesRequest(); vs.setMinCount(items.size());//w ww . jav a 2s.c om vs.setMaxCount(items.size()); String token = items.get(0).getIdempotencyKey(); if (token != null && token.length() > 64) { token = token.substring(token.length() - 64); } vs.setClientToken(token); HashMap<String, String> map = items.get(0).getParametersMap(); Injector.inject(vs, map); if (map.containsKey("availabilityZone") || map.containsKey("groupName")) { Placement p = new Placement(); if (map.containsKey("availabilityZone")) { String availabilityZone = map.get("availabilityZone"); if (availabilityZone != null && !availabilityZone.equals("")) { p.setAvailabilityZone(map.get("availabilityZone")); vs.setPlacement(p); } } if (map.containsKey("groupName")) { String groupName = map.get("groupName"); if (groupName != null && !groupName.equals("")) { p.setGroupName(map.get("groupName")); vs.setPlacement(p); } } } if (items.size() == 1 && createWithZombie(items.get(0))) { return 1; } AmazonEC2Client client = getEC2Client(items.get(0).getAccessKey(), items.get(0).getEncryptedKey(), items.get(0).getLocation()); RunInstancesResult result = null; try { result = client.runInstances(vs); } catch (AmazonServiceException e) { log.log(Level.WARNING, "EC2 error " + e.getErrorCode(), e); throw new WebApplicationException(e, Status.BAD_REQUEST); } catch (AmazonClientException e) { log.log(Level.SEVERE, "EC2 AmazonClientException", e); log.severe("Check for orphaned VMs"); try { result = client.runInstances(vs); } catch (Exception e2) { log.log(Level.SEVERE, "EC2 AmazonClientException", e2); throw new WebApplicationException(e, Status.BAD_REQUEST); } } int i = 0; for (Instance ec2Instance : result.getReservation().getInstances()) { log.info("Create VM[" + i + "] has Instance id " + ec2Instance.getInstanceId()); items.get(i).setInstanceId(ec2Instance.getInstanceId()); i++; } return result.getReservation().getInstances().size(); }
From source file:org.apache.airavata.core.gfac.provider.impl.EC2Provider.java
License:Apache License
private List<Instance> startInstances(AmazonEC2Client ec2, String AMI_ID, String INS_TYPE, ExecutionContext executionContext) throws AmazonServiceException { // start only 1 instance RunInstancesRequest request = new RunInstancesRequest(AMI_ID, 1, 1); request.setKeyName(KEY_PAIR_NAME);//ww w . j a v a2 s.c o m request.setInstanceType(INS_TYPE); RunInstancesResult result = ec2.runInstances(request); List<Instance> instances = result.getReservation().getInstances(); while (!allInstancesStateEqual(instances, InstanceStateName.Running)) { // instance status should not be Terminated if (anyInstancesStateEqual(instances, InstanceStateName.Terminated)) { throw new AmazonClientException("Some Instance is terminated before running a job"); } // notify the status for (Instance ins : instances) { // TODO //executionContext.getNotificationService().info("EC2 Instance " +ins.getInstanceId() + " is " + ins.getState().getName().toString()); } try { Thread.sleep(SLEEP_TIME_SECOND * 1000l); } catch (Exception ex) { // no op } DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); describeInstancesRequest.setInstanceIds(getInstanceIDs(instances)); DescribeInstancesResult describeInstancesResult = ec2.describeInstances(describeInstancesRequest); instances = describeInstancesResult.getReservations().get(0).getInstances(); } log.info("All instances is running"); return instances; }
From source file:org.apache.airavata.gfac.ec2.util.AmazonEC2Util.java
License:Apache License
/** * Starts an Amazon instance with the given information. * * @param ec2 Amazon ec2 client/*from www. j a v a2s.c o m*/ * @param amiId Amazon Machine Image (AMI) id * @param insType Instance type * @param jobExecutionContext Job Execution context * @param keyPairName Key pair name * @return list of instances * @throws AmazonServiceException AmazonServiceException */ public static List<Instance> startInstances(AmazonEC2Client ec2, String amiId, String insType, JobExecutionContext jobExecutionContext, String keyPairName) throws AmazonServiceException { // start only 1 instance RunInstancesRequest request = new RunInstancesRequest(amiId, 1, 1); request.setKeyName(keyPairName); request.setInstanceType(insType); RunInstancesResult result = ec2.runInstances(request); List<Instance> instances = result.getReservation().getInstances(); while (!allInstancesStateEqual(instances, InstanceStateName.Running)) { // instance status should not be Terminated if (anyInstancesStateEqual(instances, InstanceStateName.Terminated)) { throw new AmazonClientException("Some Instance is terminated before running a job"); } // notify the status for (Instance ins : instances) { jobExecutionContext.getNotificationService().publish(new EC2ProviderEvent( "EC2 Instance " + ins.getInstanceId() + " is " + ins.getState().getName())); } try { Thread.sleep(SLEEP_TIME_SECOND * 1000l); } catch (Exception ex) { // no op } DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); describeInstancesRequest.setInstanceIds(getInstanceIDs(instances)); DescribeInstancesResult describeInstancesResult = ec2.describeInstances(describeInstancesRequest); instances = describeInstancesResult.getReservations().get(0).getInstances(); } return instances; }
From source file:pl.edu.agh.samm.tadapter.eucalyptus.EucalyptusTransportAdapter.java
License:Open Source License
/** * starts new VM instance, <b>does not add new resource to core</b> * * @param resource/*from w w w. j a va 2s .c om*/ * @param imageId * @param instanceType * @return * @throws Exception */ private Instance startOneInstanceAction(Resource resource, final String imageId, String instanceType, String userData) throws Exception { AmazonEC2Client client = ec2Clients.get(resource); Image image = getImageByImageID(client, imageId); if (!IMAGE_TYPE_MACHINE.equals(image.getImageType())) { throw new RuntimeException("Provided image type is not machine!"); } if (!IMAGE_STATE_AVAILABLE.equals(image.getState())) { throw new RuntimeException("Provided image state is not " + IMAGE_STATE_AVAILABLE); } RunInstancesRequest command = new RunInstancesRequest(); if (userData != null) { command.setUserData(userData); } command.setImageId(image.getImageId()); command.setInstanceType(instanceType); command.setKernelId(image.getKernelId()); command.setMaxCount(1); command.setMinCount(1); command.setRamdiskId(image.getRamdiskId()); command.setKeyName(resource.getProperty(EUCALYPTUS_KEY_NAME).toString()); RunInstancesResult result = client.runInstances(command); List<Instance> instances = result.getReservation().getInstances(); if (instances.size() < 1) { logger.error("Something bad happend while running VM instance"); } Instance instance = instances.get(0); instance = EC2Util.waitForRunningState(client, instance); logger.info("Started new instance of image " + imageId + "! InstanceId = " + instance.getInstanceId()); instance = EC2Util.waitForPublicDNS(client, instance); logger.info("Instance IP address is: " + instance.getPublicDnsName()); return instance; }
From source file:rollsPOC2.util.AWSHelper.java
public static Instance createOrFindEC2Instance(String instanceName) throws Exception { Instance instance = findEC2Instance(instanceName); if (instance == null || instance.getState().getName().equals("terminated") || instance.getState().getName().equals("shutting-down")) { while (instance != null && instance.getState().getName().equals("shutting-down")) { System.out.println("Waiting for previous EC2 instance to terminate"); Thread.sleep(10000l); instance = findEC2Instance(instanceName); }/*from w w w . j a v a2 s .co m*/ String userDataScript = Base64.getUrlEncoder().encodeToString(Files.readAllBytes( Paths.get(instanceName.getClass().getResource("/scripts/postinstall-script.sh").toURI()))); AmazonEC2Client ec2 = AppServices.getEC2Client(); RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withKeyName("bjss") .withImageId("ami-2d39803a").withUserData(userDataScript).withMinCount(1).withMaxCount(1) .withInstanceType("t2.small").withSecurityGroupIds("IPAASDemo"); RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest); String instanceId = runInstancesResult.getReservation().getInstances().get(0).getInstanceId(); CreateTagsRequest createTagsRequest = new CreateTagsRequest().withResources(instanceId) .withTags(new Tag("Name", "IPAASDemo")); ec2.createTags(createTagsRequest); instance = findEC2Instance(instanceName); while (instance != null && instance.getState().getName().equals("pending")) { System.out.println("Waiting for EC2 instance to start"); Thread.sleep(10000l); instance = findEC2Instance(instanceName); } } return findEC2Instance(instanceName); }