private RunInstancesResult runInstance(String GROUP_NAME, String clustertype) { RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId(ami) .withInstanceType(type) .withMinCount(1) .withMaxCount(1) .withKeyName(MY_KEY) .withSecurityGroups(GROUP_NAME); RunInstancesResult result = ec2.runInstances(runInstancesRequest); System.out.println(clustertype+" node reservation:"+result.getReservation().getInstances().get(0).getInstanceId()); tagInstance(result.getReservation().getInstances().get(0).getInstanceId(),"Name",name+"-"+clustertype,ec2); return result; }
public static String provisionAWSVMWithEC2Client(VerificationHost host, AmazonEC2Client client, String ami, String subnetId, String securityGroupId) { RunInstancesRequest runInstancesRequest = new RunInstancesRequest() .withSubnetId(subnetId) .withImageId(ami) .withInstanceType(instanceType) .withMinCount(1).withMaxCount(1) .withSecurityGroupIds(securityGroupId); // handler invoked once the EC2 runInstancesAsync commands completes RunInstancesResult result = null; try { result = client.runInstances(runInstancesRequest); } catch (Exception e) { host.log(Level.SEVERE, "Error encountered in provisioning machine on AWS", Utils.toString(e)); } assertNotNull(result); assertNotNull(result.getReservation()); assertNotNull(result.getReservation().getInstances()); assertEquals(1, result.getReservation().getInstances().size()); return result.getReservation().getInstances().get(0).getInstanceId(); }
public static String provisionAWSEBSVMWithEC2Client(VerificationHost host, AmazonEC2Client client, String ami, String subnetId, String securityGroupId, BlockDeviceMapping blockDeviceMapping) { RunInstancesRequest runInstancesRequest = new RunInstancesRequest() .withSubnetId(subnetId) .withImageId(ami) .withInstanceType(instanceType) .withMinCount(1).withMaxCount(1) .withSecurityGroupIds(securityGroupId) .withBlockDeviceMappings(blockDeviceMapping); // handler invoked once the EC2 runInstancesAsync commands completes RunInstancesResult result = null; try { result = client.runInstances(runInstancesRequest); } catch (Exception e) { host.log(Level.SEVERE, "Error encountered in provisioning machine on AWS", Utils.toString(e)); } assertNotNull(result); assertNotNull(result.getReservation()); assertNotNull(result.getReservation().getInstances()); assertEquals(1, result.getReservation().getInstances().size()); return result.getReservation().getInstances().get(0).getInstanceId(); }
public List<Instance> runInstances(RunInstancesRequest request, Tag... tags) throws Exception { logger.info("create ec2 instance, request={}", request); RunInstancesResult result = new Runner<RunInstancesResult>() .maxAttempts(3) .retryInterval(Duration.ofSeconds(20)) .retryOn(this::retryOnRunInstance) .run(() -> ec2.runInstances(request)); Threads.sleepRoughly(Duration.ofSeconds(5)); // wait little bit to make sure instance is visible to tag service List<String> instanceIds = result.getReservation().getInstances().stream().map(Instance::getInstanceId).collect(Collectors.toList()); CreateTagsRequest tagsRequest = new CreateTagsRequest() .withResources(instanceIds) .withTags(tags); createTags(tagsRequest); waitUntilRunning(instanceIds); return describeInstances(instanceIds); }
@Test // Happy path test flow for launching nodes public void testLaunchNodes() throws NodesCouldNotBeStartedException{ MockAmazonEc2Client client = new MockAmazonEc2Client(null); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="chrome",os="windows"; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; manageEC2.setUserData(userData); List<Instance> instances = manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); RunInstancesRequest request = client.getRunInstancesRequest(); Assert.assertEquals("Min count should match thread count requested", threadCount, request.getMinCount()); Assert.assertEquals("Max count should match thread count requested", threadCount, request.getMaxCount()); Assert.assertEquals("User data should match", userData, request.getUserData()); Assert.assertTrue("No security group should be set", request.getSecurityGroupIds().isEmpty()); Assert.assertNull("No subnet should be set", request.getSubnetId()); Assert.assertNull("No key name should be set", request.getKeyName()); }
@Override public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) throws IOException { final RunInstancesRequest request = createOnDemandInstancesRequest(pool, execution); // TODO allow for more options (e.g. monitoring & termination protection etc.) LOG.info(">> Sending RunInstances request: {}", request); RunInstancesResult result = client.runInstances(request); LOG.info("<< Got RunInstances result: {}", result); // TODO tag instances: managed-by: Apache Provisionr, business-key: ID etc. execution.setVariable(ProcessVariables.RESERVATION_ID, result.getReservation().getReservationId()); execution.setVariable(ProcessVariables.INSTANCE_IDS, collectInstanceIdsAsList(result.getReservation().getInstances())); }
/** * Run some new ec2 instances. * * @param imageId * AMI for running new instances from * @param runCount * count of instances to run * @return a list of started instances */ public static List<Instance> runInstances(final String imageId, final int runCount) { // pass any credentials as aws-mock does not authenticate them at all AWSCredentials credentials = new BasicAWSCredentials("foo", "bar"); AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials); // the mock endpoint for ec2 which runs on your computer String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/"; amazonEC2Client.setEndpoint(ec2Endpoint); // instance type String instanceType = "m1.large"; // run 10 instances RunInstancesRequest request = new RunInstancesRequest(); final int minRunCount = runCount; final int maxRunCount = runCount; request.withImageId(imageId).withInstanceType(instanceType) .withMinCount(minRunCount).withMaxCount(maxRunCount); RunInstancesResult result = amazonEC2Client.runInstances(request); return result.getReservation().getInstances(); }
/** * Run instances with a random AMI ID. * * @param type * instance type * @param minCount * minimum start up instance number * @param maxCount * maximum start up instance number * @return a list of instances started. */ protected final List<Instance> runInstances(final InstanceType type, final int minCount, final int maxCount) { log.info("Run instances: type=" + type + ", minCount=" + minCount + ", maxCount=" + maxCount); RunInstancesRequest request = new RunInstancesRequest(); String imageId = randomAMI(); request.withImageId(imageId).withInstanceType(type.getName()) .withMinCount(minCount).withMaxCount(maxCount); RunInstancesResult result = amazonEC2Client.runInstances(request); return result.getReservation().getInstances(); }
/** * @inheritDoc */ @Override public String launchInstance( CreateInstanceOptions options, Identity identity ) { RunInstancesRequest request = new RunInstancesRequest(); if ( options.getInstanceProfileName() != null ) { request.setIamInstanceProfile( new IamInstanceProfileSpecification().withName( options.getInstanceProfileName() ) ); } request.setSubnetId( options.getWorkerOptions().getSubnetId() ); request.setSecurityGroupIds( options.getWorkerOptions().getSecurityGroupIds() ); if ( options.getUserData() != null ) { request.setUserData( Base64.encodeBase64String( options.getUserData().getBytes() ) ); } request.withMinCount( 1 ).withMaxCount( 1 ).withImageId( config.getAgentAmiId() ).withInstanceType( InstanceType.T1Micro ); request.setKeyName( options.getWorkerOptions().getKeyPairName() ); request.setClientToken( "launch-ec2-worker-" + contextProvider.getActivityExecutionContext().getWorkflowExecution().getWorkflowId() ); AmazonEC2 ec2 = ActivityUtils.createClient( AmazonEC2Client.class, identity ); RunInstancesResult result = ec2.runInstances( request ); return result.getReservation().getInstances().get( 0 ).getInstanceId(); }
public void createRunInstancesResult(String... instanceIds) { Collection<Instance> instances = new ArrayList<Instance>(); for (int i = 0; i < instanceIds.length; i++) { instances.add(new Instance().withInstanceId(instanceIds[i])); } Reservation reservation = new Reservation().withInstances(instances); RunInstancesResult result = new RunInstancesResult() .withReservation(reservation); doReturn(result).when(ec2).runInstances(any(RunInstancesRequest.class)); }
public static InstanceObject startInstance(AmazonEC2 ec2) { RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId("ami-f6ed6785") .withMonitoring(true) .withInstanceType("t2.micro") .withMinCount(1) .withMaxCount(1) .withKeyName("CNV-lab-AWS") .withSecurityGroups("CNV-ssh+http"); RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest); try { Thread.sleep(1000); } catch (InterruptedException e) {} DescribeInstancesResult describeInstancesResult = ec2.describeInstances(); List<Reservation> reservations = describeInstancesResult.getReservations(); ArrayList<Instance> auxListOfInstances = new ArrayList<Instance>(); for (Reservation reservation : reservations) { auxListOfInstances.addAll(reservation.getInstances()); } InstanceObject instanceObject = null; for (Instance instance : auxListOfInstances) { if(instance.getInstanceId().equals(runInstancesResult.getReservation().getInstances().get(0).getInstanceId())) //id do load balancer, nao adicionamos este as instancias instanceObject = new InstanceObject(instance); } //retornamos a instance criada return instanceObject; }
@Override public void onSuccess(RunInstancesRequest request, RunInstancesResult result) { for (Instance i : result.getReservation().getInstances()) { this.instanceIds.add(i.getInstanceId()); this.host.log("Successfully created instances on AWS endpoint %s", i.getInstanceId()); } }
public static void main(String[] args) { final String USAGE = "To run this example, supply an instance name and AMI image id\n" + "Ex: CreateInstance <instance-name> <ami-image-id>\n"; if (args.length != 2) { System.out.println(USAGE); System.exit(1); } String name = args[0]; String ami_id = args[1]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); RunInstancesRequest run_request = new RunInstancesRequest() .withImageId(ami_id) .withInstanceType(InstanceType.T1Micro) .withMaxCount(1) .withMinCount(1); RunInstancesResult run_response = ec2.runInstances(run_request); String instance_id = run_response.getReservation().getReservationId(); Tag tag = new Tag() .withKey("Name") .withValue(name); CreateTagsRequest tag_request = new CreateTagsRequest() .withTags(tag); CreateTagsResult tag_response = ec2.createTags(tag_request); System.out.printf( "Successfully started EC2 instance %s based on AMI %s", instance_id, ami_id); }
/** * Given an AMI start an EC2 Instance. * * @param amiId * to start * @return the id of the running instance. * @throws ServiceBrokerException */ public String startEC2Instance(String amiId) throws ServiceBrokerException { RunInstancesResult instance = ec2Client .runInstances(new RunInstancesRequest().withImageId(amiId) .withInstanceType("m1.small").withMinCount(1) .withMaxCount(1).withSubnetId(subnetId) .withInstanceType(InstanceType.T2Micro)); String instanceId = getInstanceId(instance); addElasticIp(instanceId); log.info("Instance " + instanceId + " started successfully"); return instanceId; }
@Override public List<Instance> call() { RunInstancesRequest request = new RunInstancesRequest(); request.withInstanceType(this.instanceTemplate.getInstanceType()); request.withImageId(this.instanceTemplate.getAmiId()); InstanceNetworkInterfaceSpecification nic = new InstanceNetworkInterfaceSpecification(); nic.withDeviceIndex(0); // select a subnet at random nic.withSubnetId(randomSubnet()); nic.withAssociatePublicIpAddress(this.instanceTemplate.isAssignPublicIp()); nic.withGroups(this.instanceTemplate.getSecurityGroupIds()); request.withNetworkInterfaces(nic); request.withKeyName(this.instanceTemplate.getKeyPair()); request.withIamInstanceProfile( new IamInstanceProfileSpecification().withArn(this.instanceTemplate.getIamInstanceProfileARN())); request.withUserData(this.instanceTemplate.getEncodedUserData()); request.withEbsOptimized(this.instanceTemplate.isEbsOptimized()); request.withMinCount(this.count).withMaxCount(this.count); if (!this.instanceTemplate.getTags().isEmpty()) { TagSpecification tagSpecifications = new TagSpecification().withResourceType(ResourceType.Instance); tagSpecifications.withTags(tags()); request.withTagSpecifications(tagSpecifications); } RunInstancesResult result = getClient().getApi().runInstances(request); List<Instance> launchedInstances = result.getReservation().getInstances(); List<String> instanceIds = launchedInstances.stream().map(Instance::getInstanceId).collect(Collectors.toList()); return awaitInstances(instanceIds); }
@Override public String createMachine( TargetHandlerParameters parameters ) throws TargetException { this.logger.fine( "Creating a new machine on AWS." ); // For IaaS, we only expect root instance names to be passed if( InstanceHelpers.countInstances( parameters.getScopedInstancePath()) > 1 ) throw new TargetException( "Only root instances can be passed in arguments." ); String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath()); // Deal with the creation String instanceId; try { AmazonEC2 ec2 = createEc2Client( parameters.getTargetProperties()); String userData = UserDataHelpers.writeUserDataAsString( parameters.getMessagingProperties(), parameters.getDomain(), parameters.getApplicationName(), rootInstanceName ); RunInstancesRequest runInstancesRequest = prepareEC2RequestNode( parameters.getTargetProperties(), userData ); RunInstancesResult runInstanceResult = ec2.runInstances( runInstancesRequest ); instanceId = runInstanceResult.getReservation().getInstances().get( 0 ).getInstanceId(); } catch( Exception e ) { this.logger.severe( "An error occurred while creating a new machine on EC2. " + e.getMessage()); throw new TargetException( e ); } return instanceId; }
/** * Starts MQ server with specified name. * @param serverName The name of the server to start. Consider it to be unique. * @return OpenStack internal id if server was start up successfully. Otherwise, <b>null</b>. */ public String startNewMessageQeueHost() { String mqImageId = lookupImageId(config.getMqImageName()); if(mqImageId == null) { String message = "Cannot scale up as requested since no valid " + "EC2 image could be found for name " + config.getMqImageName(); log.severe(message); throw new JCloudScaleException(message); } String flavId = config.getMqInstanceTypeName(); RunInstancesRequest runInstancesRequest = new RunInstancesRequest() // instances in EC2 don't have a name .withInstanceType(flavId) .withImageId(mqImageId) .withMinCount(1) .withMaxCount(1) .withKeyName(config.getSshKey()); RunInstancesResult result = null; try { result = ec2Client.runInstances(runInstancesRequest); } catch(Exception e) { throw new JCloudScaleException("Unable to instantiate MQ image using Amazon EC2: "+e.getMessage()); } String instanceId = result.getReservation().getInstances().get(0).getInstanceId(); // TODO how do we associate the correct IP here? return instanceId; }
@Override public List<Instance> createInstances(RunInstancesRequest request, ResultCapture<RunInstancesResult> extractor) { ActionResult result = resource.performAction("CreateInstances", request, extractor); if (result == null) return null; return CodecUtils.transform(result.getResources(), InstanceImpl.CODEC); }
@Override public List<Instance> createInstances(RunInstancesRequest request, ResultCapture<RunInstancesResult> extractor) { ActionResult result = service.performAction("CreateInstances", request, extractor); if (result == null) return null; return CodecUtils.transform(result.getResources(), InstanceImpl.CODEC); }
@Override public List<Instance> createInstances(String imageId, Integer minCount, Integer maxCount) { return createInstances(imageId, minCount, maxCount, (ResultCapture<RunInstancesResult>)null); }
@Override public List<Instance> createInstances(String imageId, Integer minCount, Integer maxCount, ResultCapture<RunInstancesResult> extractor) { RunInstancesRequest request = new RunInstancesRequest() .withImageId(imageId) .withMinCount(minCount) .withMaxCount(maxCount); return createInstances(request, extractor); }
@Override public RunInstancesResult runInstances(RunInstancesRequest runInstancesRequest) throws AmazonServiceException, AmazonClientException { if(throwRunInstancesError != null) { AmazonClientException exceptionToThrow = throwRunInstancesError; if(!throwExceptionsInRunInstancesIndefinitely) { throwRunInstancesError = null; } throw exceptionToThrow; } this.runInstancesRequest = runInstancesRequest; return runInstancesResult; }
@Test // Test the optional fields for launching a node are indeed optional public void testLaunchNodesOptionalFieldsSet() throws NodesCouldNotBeStartedException { MockAmazonEc2Client client = new MockAmazonEc2Client(null); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="chrome",os=null; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; String securityGroup="securityGroup",subnetId="subnetId",keyName="keyName",linuxImage="linuxImage"; properties.setProperty(region + "_security_group",securityGroup); properties.setProperty(region + "_subnet_id",subnetId); properties.setProperty(region + "_key_name", keyName); properties.setProperty(region + "_linux_node_ami", linuxImage); manageEC2.setUserData(userData); manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); RunInstancesRequest request = client.getRunInstancesRequest(); Assert.assertEquals("Min count should match thread count requested",threadCount,request.getMinCount()); Assert.assertEquals("Max count should match thread count requested",threadCount,request.getMaxCount()); Assert.assertEquals("User data should match",userData,request.getUserData()); Assert.assertEquals("Image id should match",linuxImage,request.getImageId()); List<String> securityGroups = request.getSecurityGroupIds(); Assert.assertEquals("Only one security group should be set",1,securityGroups.size()); Assert.assertEquals("Only one security group should be set", securityGroup, securityGroups.get(0)); Assert.assertEquals("Subnet ids should match", subnetId, request.getSubnetId()); Assert.assertEquals("Key names should match", keyName, request.getKeyName()); }
@Test // Test launching an IE node works correctly public void testLaunchNodesIe() throws NodesCouldNotBeStartedException { MockAmazonEc2Client client = new MockAmazonEc2Client(null); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="internet explorer",os=null; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; String securityGroup="securityGroup",subnetId="subnetId",keyName="keyName",windowsImage="windowsImage"; properties.setProperty(region + "_security_group",securityGroup); properties.setProperty(region + "_subnet_id",subnetId); properties.setProperty(region + "_key_name", keyName); properties.setProperty(region + "_windows_node_ami", windowsImage); manageEC2.setUserData(userData); manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); RunInstancesRequest request = client.getRunInstancesRequest(); Assert.assertEquals("Min count should match thread count requested",threadCount,request.getMinCount()); Assert.assertEquals("Max count should match thread count requested",threadCount,request.getMaxCount()); Assert.assertEquals("User data should match",userData,request.getUserData()); Assert.assertEquals("Image id should match",windowsImage,request.getImageId()); List<String> securityGroups = request.getSecurityGroupIds(); Assert.assertEquals("Only one security group should be set",1,securityGroups.size()); Assert.assertEquals("Only one security group should be set", securityGroup, securityGroups.get(0)); Assert.assertEquals("Subnet ids should match", subnetId, request.getSubnetId()); Assert.assertEquals("Key names should match", keyName, request.getKeyName()); }
@Test // Test if a bad OS is specified, it is handled correctly public void testLaunchNodesBadOs() throws NodesCouldNotBeStartedException{ MockAmazonEc2Client client = new MockAmazonEc2Client(null); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="chrome",os="badOs"; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; String securityGroup="securityGroup",subnetId="subnetId",keyName="keyName",windowsImage="windowsImage"; properties.setProperty(region + "_security_group",securityGroup); properties.setProperty(region + "_subnet_id", subnetId); properties.setProperty(region + "_key_name", keyName); properties.setProperty(region + "_windows_node_ami", windowsImage); manageEC2.setUserData(userData); try{ manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); } catch(RuntimeException e) { Assert.assertTrue("Failure message should be correct",e.getMessage().contains(os)); return; } Assert.fail("Call should fail due to invalid OS"); }
@Test // Tests that if no fallback subnets are specified, the correct exception is thrown public void testSubnetNoFallBack() throws NodesCouldNotBeStartedException { MockAmazonEc2Client client = new MockAmazonEc2Client(null); AmazonServiceException exception = new AmazonServiceException("message"); exception.setErrorCode("InsufficientInstanceCapacity"); client.setThrowDescribeInstancesError(exception); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="chrome",os="linux"; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; String securityGroup="securityGroup",subnetId="subnetId",keyName="keyName",windowsImage="windowsImage"; properties.setProperty(region + "_security_group",securityGroup); properties.setProperty(region + "_subnet_id", subnetId); properties.setProperty(region + "_key_name", keyName); properties.setProperty(region + "_windows_node_ami", windowsImage); manageEC2.setUserData(userData); try{ manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); } catch(NodesCouldNotBeStartedException e) { Assert.assertTrue("Failure message should be correct",e.getMessage().contains("Sufficient resources were not available in any of the availability zones")); return; } Assert.fail("Call should fail due to insufficient resources"); }
@Test // Test that if a fallback subnet is specified, that the request for new nodes will fallback successfully and nodes will be spun up public void testSubnetFallsBackSuccessfully() throws NodesCouldNotBeStartedException { MockAmazonEc2Client client = new MockAmazonEc2Client(null); AmazonServiceException exception = new AmazonServiceException("message"); exception.setErrorCode("InsufficientInstanceCapacity"); client.setThrowDescribeInstancesError(exception); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="chrome",os="linux"; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; String securityGroup="securityGroup",subnetId="subnetId",keyName="keyName",windowsImage="windowsImage",fallBackSubnet="fallback"; properties.setProperty(region + "_security_group",securityGroup); properties.setProperty(region + "_subnet_id", subnetId); properties.setProperty(region + "_subnet_fallback_id_1", fallBackSubnet); properties.setProperty(region + "_key_name", keyName); properties.setProperty(region + "_windows_node_ami", windowsImage); manageEC2.setUserData(userData); List<Instance> instances = manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); System.out.print(""); }
@Test // Tests that if the client fails for an error other than insufficient capacity, subnet fallback logic is not performed public void testSubnetFallBackUnknownError() throws NodesCouldNotBeStartedException { MockAmazonEc2Client client = new MockAmazonEc2Client(null); AmazonServiceException exception = new AmazonServiceException("message"); client.setThrowDescribeInstancesError(exception); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="chrome",os="linux"; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; String securityGroup="securityGroup",subnetId="subnetId",keyName="keyName",windowsImage="windowsImage"; properties.setProperty(region + "_security_group",securityGroup); properties.setProperty(region + "_subnet_id", subnetId); properties.setProperty(region + "_key_name", keyName); properties.setProperty(region + "_windows_node_ami", windowsImage); manageEC2.setUserData(userData); try{ manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); } catch(AmazonServiceException e) { Assert.assertEquals("Exception should be the same",exception,e); return; } Assert.fail("Call should fail due to other AWS error"); }
@Test // Tests that the built in guard against an infinite loop in the fallback recursive logic has a working safeguard public void testSubnetInfiniteLoop() throws NodesCouldNotBeStartedException { MockAmazonEc2Client client = new MockAmazonEc2Client(null); client.setThrowExceptionsInRunInstancesIndefinitely(); AmazonServiceException exception = new AmazonServiceException("message"); exception.setErrorCode("InsufficientInstanceCapacity"); client.setThrowDescribeInstancesError(exception); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="chrome",os="linux"; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; String securityGroup="securityGroup",subnetId="subnetId",keyName="keyName",windowsImage="windowsImage"; properties.setProperty(region + "_security_group",securityGroup); properties.setProperty(region + "_subnet_id", subnetId); properties.setProperty(region + "_subnet_fallback_id_1", "foo"); properties.setProperty(region + "_subnet_fallback_id_2", "foo"); properties.setProperty(region + "_subnet_fallback_id_3", "foo"); properties.setProperty(region + "_subnet_fallback_id_4", "foo"); properties.setProperty(region + "_subnet_fallback_id_5", "foo"); properties.setProperty(region + "_subnet_fallback_id_6", "foo"); properties.setProperty(region + "_key_name", keyName); properties.setProperty(region + "_windows_node_ami", windowsImage); manageEC2.setUserData(userData); try{ manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); } catch(NodesCouldNotBeStartedException e) { Assert.assertTrue("Failure message should be correct",e.getMessage().contains("Sufficient resources were not available in any of the availability zones")); return; } Assert.fail("Call should fail due to insufficient resources"); }
/** * Launch a new EC2 instance * * @param AMI_ID * @param type * @param number * @return list of newly launched instances */ public static List<Instance> launchInstance(String AMI_ID, String type, Integer number) { List<Instance> resultList = new ArrayList<Instance>(); RunInstancesRequest request = new RunInstancesRequest(AMI_ID, number, number); request.setInstanceType(type); RunInstancesResult result = getEC2Client().runInstances(request); resultList.addAll(result.getReservation().getInstances()); return resultList; }
/** * Launch a new EC2 instance * * @param AMI_ID * @param type * @param number * @param keyname * @return list of newly launched instances */ public static List<Instance> launchInstance(String AMI_ID, String type, Integer number, String keyname) { List<Instance> resultList = new ArrayList<Instance>(); RunInstancesRequest request = new RunInstancesRequest(AMI_ID, number, number); request.setInstanceType(type); request.setKeyName(keyname); RunInstancesResult result = getEC2Client().runInstances(request); resultList.addAll(result.getReservation().getInstances()); return resultList; }
@Override public RunInstancesResult runInstances(RunInstancesRequest runInstancesRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
private void createAndRunInstance(AmazonEC2Client ec2Client, Exchange exchange) { String ami; InstanceType instanceType; int minCount; int maxCount; boolean monitoring; String kernelId; boolean ebsOptimized; Collection securityGroups; String keyName; String clientToken; Placement placement; RunInstancesRequest request = new RunInstancesRequest(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.IMAGE_ID))) { ami = exchange.getIn().getHeader(EC2Constants.IMAGE_ID, String.class); request.withImageId(ami); } else { throw new IllegalArgumentException("AMI must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_TYPE))) { instanceType = exchange.getIn().getHeader(EC2Constants.INSTANCE_TYPE, InstanceType.class); request.withInstanceType(instanceType.toString()); } else { throw new IllegalArgumentException("Instance Type must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_MIN_COUNT))) { minCount = exchange.getIn().getHeader(EC2Constants.INSTANCE_MIN_COUNT, Integer.class); request.withMinCount(minCount); } else { throw new IllegalArgumentException("Min instances count must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_MAX_COUNT))) { maxCount = exchange.getIn().getHeader(EC2Constants.INSTANCE_MAX_COUNT, Integer.class); request.withMaxCount(maxCount); } else { throw new IllegalArgumentException("Max instances count must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_MONITORING))) { monitoring = exchange.getIn().getHeader(EC2Constants.INSTANCE_MONITORING, Boolean.class); request.withMonitoring(monitoring); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_KERNEL_ID))) { kernelId = exchange.getIn().getHeader(EC2Constants.INSTANCE_KERNEL_ID, String.class); request.withKernelId(kernelId); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_EBS_OPTIMIZED))) { ebsOptimized = exchange.getIn().getHeader(EC2Constants.INSTANCE_EBS_OPTIMIZED, Boolean.class); request.withEbsOptimized(ebsOptimized); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_SECURITY_GROUPS))) { securityGroups = exchange.getIn().getHeader(EC2Constants.INSTANCE_SECURITY_GROUPS, Collection.class); request.withSecurityGroups(securityGroups); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_KEY_PAIR))) { keyName = exchange.getIn().getHeader(EC2Constants.INSTANCES_KEY_PAIR, String.class); request.withKeyName(keyName); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_CLIENT_TOKEN))) { clientToken = exchange.getIn().getHeader(EC2Constants.INSTANCES_CLIENT_TOKEN, String.class); request.withClientToken(clientToken); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_PLACEMENT))) { placement = exchange.getIn().getHeader(EC2Constants.INSTANCES_PLACEMENT, Placement.class); request.withPlacement(placement); } RunInstancesResult result; try { result = ec2Client.runInstances(request); } catch (AmazonServiceException ase) { LOG.trace("Run Instances command returned the error code {}", ase.getErrorCode()); throw ase; } LOG.trace("Creating and running instances with ami [{}] and instance type {}", ami, instanceType.toString()); Message message = getMessageForResponse(exchange); message.setBody(result); }
private String getInstanceId(RunInstancesResult instance) { return instance.getReservation().getInstances().get(0).getInstanceId(); }
public void onDemandRequest() { if (instances <= instancesSet.size()) { logger.info("No more instances will be launched because there are already enough."); return; } com.amazonaws.services.ec2.AmazonEC2 client = AmazonEC2.connect(); RunInstancesRequest request = new RunInstancesRequest(); // request.setMinCount(instances); // request.setMaxCount(instances); request.setMinCount(instances - instancesSet.size()); request.setMaxCount(instances - instancesSet.size()); request.setImageId(ami); request.setInstanceType(size); if (userData != null) request.setUserData(Base64.encodeAsString(userData .getBytes())); BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setDeleteOnTermination(Boolean.TRUE); ebs.setVolumeSize(diskSize); blockDeviceMapping.setEbs(ebs); ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); request.setBlockDeviceMappings(blockList); ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add(Configuration.SECURITY_GROUP_NAME); request.setSecurityGroups(securityGroups); request.setKeyName(keyName); RunInstancesResult requestResult = client.runInstances(request); Reservation reservation = requestResult.getReservation(); reservation.getInstances(); for (com.amazonaws.services.ec2.model.Instance i : reservation.getInstances()) instancesSet.add(new Instance(this, i.getInstanceId(), null)); }
public static String CreateServer(String keys, JSONObject endpointsAPI, String imageId, String typeId, String keypair) { String instanceId = null; String accessKey = keys.split(";")[0]; String secretKey = keys.split(";")[1]; String regionEndpoint = (String) endpointsAPI.get("amazon-regionEndpoint"); try { // EC2 Client for given region and credentials AmazonEC2 ec2 = new AmazonEC2Client(new BasicAWSCredentials(accessKey, secretKey)); ec2.setEndpoint(regionEndpoint); RunInstancesRequest req = new RunInstancesRequest(); req.withInstanceType(typeId); req.withImageId(imageId); req.withMinCount(1).withMaxCount(1); req.withSecurityGroups("securityGroup"); req.withKeyName(keypair); // Execute run instance request and return ID of first (and only) instance RunInstancesResult runInstances = ec2.runInstances(req); instanceId = runInstances.getReservation().getInstances().get(0).getInstanceId(); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); instanceId = "MSG_FAILED"; } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with AWS, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); instanceId = "MSG_FAILED"; } return instanceId; }
/** * Method to create instance at amazon * TODO: alterar o jeito de adicionar a imagem para criar a maquina * @param type * @param nameinstance * @throws IOException */ @Override public void createinstance(String type, String nameinstance) throws IOException { // Acho que tem que mudar isso aqui em this.setup(); try { // CREATE EC2 INSTANCES ami-912db2fd RunInstancesRequest runInstancesRequest = new RunInstancesRequest() .withInstanceType(type) .withImageId("ami-ef741383") .withMinCount(1) .withMaxCount(1) .withSecurityGroupIds("default"); runInstancesRequest.setMonitoring(Boolean.TRUE); RunInstancesResult result = EC2.runInstances(runInstancesRequest); System.out.println("waiting"); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("OK"); List<com.amazonaws.services.ec2.model.Instance> resultInstance = result.getReservation().getInstances(); String createdInstanceId = null; for (com.amazonaws.services.ec2.model.Instance ins : resultInstance) { createdInstanceId = ins.getInstanceId(); // workflowLogger.log(new Log("New instance has been created:" + createdInstanceId, 0, "test", LogSeverity.INFO)); System.out.println("New instance has been created: " + createdInstanceId);//print the instance ID CreateTagsRequest createTagsRequest = new CreateTagsRequest(); createTagsRequest.withResources(createdInstanceId) // .withTags(new Tag("Name", nameinstance)); EC2.createTags(createTagsRequest); DescribeInstancesRequest request = new DescribeInstancesRequest().withInstanceIds(ins.getInstanceId()); DescribeInstancesResult result2 = EC2.describeInstances(request); List<Reservation> list = result2.getReservations(); for (Reservation res : list) { List<com.amazonaws.services.ec2.model.Instance> instanceList = res.getInstances(); for (com.amazonaws.services.ec2.model.Instance instance : instanceList) { System.out.println("Instance Public IP :" + instance.getPublicIpAddress()); setIpInstance(instance.getPublicIpAddress()); } } } } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); System.out.println("Give a valid input"); System.out.println(""); // AmazonAPI.enteroption(); } }