com.amazonaws.services.ec2.model.RunInstancesResult Java Examples

The following examples show how to use com.amazonaws.services.ec2.model.RunInstancesResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseTest.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example #2
Source File: RunInstancesExample.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example #3
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@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("");
}
 
Example #5
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #6
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public List<Instance> createInstances(String imageId, Integer minCount,
        Integer maxCount) {

    return createInstances(imageId, minCount, maxCount,
            (ResultCapture<RunInstancesResult>)null);
}
 
Example #7
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #8
Source File: SubnetImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #9
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #10
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #11
Source File: CreateInstance.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
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 reservation_id = run_response.getReservation().getInstances().get(0).getInstanceId();

    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",
        reservation_id, ami_id);
}
 
Example #12
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #13
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #14
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example #15
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example #16
Source File: MockAmazonEc2Client.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example #17
Source File: Ec2IaasHandler.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #18
Source File: EC2Mockup.java    From development with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #19
Source File: VmManagerTest.java    From SeleniumGridScaler with GNU General Public License v2.0 4 votes vote down vote up
@Test
// Test if multiple security groups can be passed when launching a node
public void testLaunchNodesMultipleSecurityGroups()  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="securityGroup1,securityGroup2,securityGroup3",subnetId="subnetId",keyName="keyName",linuxImage="linuxImage";
    String[] splitSecurityGroupdIds = securityGroup.split(",");
    List securityGroupIdsAryLst = new ArrayList();

    if (securityGroup != null) {
        for (int i = 0; i < splitSecurityGroupdIds.length; i++) {
            securityGroupIdsAryLst.add(splitSecurityGroupdIds[i]);
        }
    }
    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();
    request.setSecurityGroupIds(securityGroupIdsAryLst);
    List<String> securityGroups = request.getSecurityGroupIds();
    List<String> expectedSecurityGroups = Arrays.asList("securityGroup1,securityGroup2,securityGroup3".split(","));
    Assert.assertTrue("Security groups should match all given security groups", securityGroups.containsAll(expectedSecurityGroups));

    List<String> invalidSecurityGroups = Arrays.asList("securityGroup1,securityGroup2,securityGroup7".split(","));
    Assert.assertFalse("Security groups should match only the set security groups", securityGroups.containsAll(invalidSecurityGroups));

    Assert.assertFalse("Security group should not be empty", request.getSecurityGroupIds().isEmpty());
    Assert.assertEquals("More than 1 security group should be set",3,securityGroups.size());
}
 
Example #20
Source File: MockAmazonEc2Client.java    From SeleniumGridScaler with GNU General Public License v2.0 4 votes vote down vote up
public void setRunInstances(RunInstancesResult runInstancesResult) {
    this.runInstancesResult = runInstancesResult;
}
 
Example #21
Source File: AwsVmManager.java    From SeleniumGridScaler with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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
 * @param   requestNumber
 *
 * @return
 *
 * @throws  NodesCouldNotBeStartedException
 */
private RunInstancesResult getResults(final RunInstancesRequest request, int requestNumber)
    throws NodesCouldNotBeStartedException {
    RunInstancesResult runInstancesResult;
    try {
        if(client == null){
            throw new RuntimeException("The client is not initialized");
        }
        runInstancesResult = client.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;

            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;
}
 
Example #22
Source File: AwsVmManager.java    From SeleniumGridScaler with GNU General Public License v2.0 4 votes vote down vote up
public List<Instance> launchNodes(final String amiId, final String instanceType, final int numberToStart,
        final String userData, final boolean terminateOnShutdown) throws NodesCouldNotBeStartedException {
    RunInstancesRequest runRequest = new RunInstancesRequest();
    runRequest.withImageId(amiId).withInstanceType(instanceType).withMinCount(numberToStart)
              .withMaxCount(numberToStart).withUserData(userData);
    if (terminateOnShutdown) {
        runRequest.withInstanceInitiatedShutdownBehavior("terminate");
    }

    log.info("Setting image id: " + runRequest.getImageId());
    log.info("Setting instance type: " + runRequest.getInstanceType());

    String subnetKey = awsProperties.getProperty(region + "_subnet_id");
    if (subnetKey != null) {
        log.info("Setting subnet: " + subnetKey);
        runRequest.withSubnetId(subnetKey);
    }

    String securityGroupKey = awsProperties.getProperty(region + "_security_group");
    if (securityGroupKey != null) {

        String[] splitSecurityGroupdIds = securityGroupKey.split(",");

        List securityGroupIdsAryLst = new ArrayList();
        for (int i = 0; i < splitSecurityGroupdIds.length; i++) {

            log.info("Setting security group(s): " + splitSecurityGroupdIds[i]);
            securityGroupIdsAryLst.add(splitSecurityGroupdIds[i]);
        }
        runRequest.setSecurityGroupIds(securityGroupIdsAryLst);
    }

    String keyName = awsProperties.getProperty(region + "_key_name");
    if (keyName != null) {
        log.info("Setting keyname:" + keyName);
        runRequest.withKeyName(keyName);
    }

    log.info("Sending run request to AWS...");

    RunInstancesResult runInstancesResult = getResults(runRequest, 0);
    log.info("Run request result returned.  Adding tags");

    // Tag the instances with the standard RMN AWS data
    List<Instance> instances = runInstancesResult.getReservation().getInstances();
    if (instances.size() == 0) {
        throw new NodesCouldNotBeStartedException(String.format(
                "Error starting up nodes -- count was zero and did not match expected count of %d", numberToStart));
    }

    associateTags(new Date().toString(), instances);
    return instances;
}
 
Example #23
Source File: Ec2Util.java    From s3-bucket-loader with Apache License 2.0 4 votes vote down vote up
public List<Instance> launchEc2Instances(AmazonEC2Client ec2Client, Properties props) throws Exception {
	
	Integer totalExpectedWorkers = Integer.valueOf(props.getProperty("master.workers.total"));
	
	// disk size
	Collection<BlockDeviceMapping> blockDevices = new ArrayList<BlockDeviceMapping>();
	blockDevices.add(
			new BlockDeviceMapping()
				.withDeviceName(props.getProperty("master.workers.ec2.disk.deviceName"))
				.withEbs(new EbsBlockDevice()
						.withVolumeType(VolumeType.valueOf(props.getProperty("master.workers.ec2.disk.volumeType")))
						.withDeleteOnTermination(true)
					    .withVolumeSize(Integer.valueOf(props.getProperty("master.workers.ec2.disk.size.gigabytes")))));
	
	// create our run request for the total workers we expect
	RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
	runInstancesRequest.withImageId(props.getProperty("master.workers.ec2.ami.id"))
				        .withInstanceType(props.getProperty("master.workers.ec2.instanceType"))
				        .withMinCount(totalExpectedWorkers)
				        .withMaxCount(totalExpectedWorkers)
				        .withBlockDeviceMappings(blockDevices)
				        .withKeyName(props.getProperty("master.workers.ec2.keyName"))
				        .withSecurityGroupIds(props.getProperty("master.workers.ec2.securityGroupId"))
				        .withInstanceInitiatedShutdownBehavior(ShutdownBehavior.valueOf(props.getProperty("master.workers.ec2.shutdownBehavior")))
				        .withSubnetId(props.getProperty("master.workers.ec2.subnetId"))
				        .withUserData(Base64.encodeAsString(readFile(props.getProperty("master.workers.ec2.userDataFile")).getBytes()));
	
	// launch
	logger.debug("Launching " + totalExpectedWorkers + " EC2 instances, " +
						"it may take few minutes for workers to come up...: \n" +
						"\tamiId:" + runInstancesRequest.getImageId() +"\n"+
						"\tsecGrpId:" + runInstancesRequest.getSecurityGroupIds().get(0) +"\n"+
						"\tsubnetId:" + runInstancesRequest.getSubnetId() +"\n"+
						"\tinstanceType:" + runInstancesRequest.getInstanceType() +"\n"+
						"\tshutdownBehavior:" + runInstancesRequest.getInstanceInitiatedShutdownBehavior() +"\n"+
						"\tkeyName:" + runInstancesRequest.getKeyName() 
						);


	// as the instances come up, assuming the "userData" above launches the worker we will be good
	// they will auto register w/ us the master 
	RunInstancesResult result = ec2Client.runInstances(runInstancesRequest);
	Reservation reservation = result.getReservation();
	return reservation.getInstances();
}
 
Example #24
Source File: EC2IntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateInstance() throws Exception {

    AmazonEC2Client ec2Client = provider.getClient();
    Assume.assumeNotNull("AWS client not null", ec2Client);

    assertNoStaleInstances(ec2Client, "before");

    try {
        WildFlyCamelContext camelctx = new WildFlyCamelContext();
        camelctx.getNamingContext().bind("ec2Client", ec2Client);
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:createAndRun").to("aws-ec2://TestDomain?amazonEc2Client=#ec2Client&operation=createAndRunInstances");
                from("direct:terminate").to("aws-ec2://TestDomain?amazonEc2Client=#ec2Client&operation=terminateInstances");
            }
        });

        camelctx.start();
        try {

            // Create and run an instance
            Map<String, Object> headers = new HashMap<>();
            headers.put(EC2Constants.IMAGE_ID, "ami-02ace471");
            headers.put(EC2Constants.INSTANCE_TYPE, InstanceType.T2Micro);
            headers.put(EC2Constants.SUBNET_ID, EC2Utils.getSubnetId(ec2Client));
            headers.put(EC2Constants.INSTANCE_MIN_COUNT, 1);
            headers.put(EC2Constants.INSTANCE_MAX_COUNT, 1);
            headers.put(EC2Constants.INSTANCES_TAGS, Arrays.asList(new Tag("Name", "wildfly-camel")));

            ProducerTemplate template = camelctx.createProducerTemplate();
            RunInstancesResult result1 = template.requestBodyAndHeaders("direct:createAndRun", null, headers, RunInstancesResult.class);
            String instanceId = result1.getReservation().getInstances().get(0).getInstanceId();
            System.out.println("InstanceId: " + instanceId);

            // Terminate the instance
            headers = new HashMap<>();
            headers.put(EC2Constants.INSTANCES_IDS, Collections.singleton(instanceId));

            TerminateInstancesResult result2 = template.requestBodyAndHeaders("direct:terminate", null, headers, TerminateInstancesResult.class);
            Assert.assertEquals(instanceId, result2.getTerminatingInstances().get(0).getInstanceId());
        } finally {
            camelctx.close();
        }
    } finally {
        assertNoStaleInstances(ec2Client, "after");
    }
}
 
Example #25
Source File: EC2.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>CreateInstances</code> action and use a ResultCapture
 * to retrieve the low-level client response.
 *
 * <p>
 *
 * @return A list of <code>Instance</code> resource objects associated with
 *         the result of this action.
 * @see RunInstancesRequest
 */
List<com.amazonaws.resources.ec2.Instance> createInstances(
        RunInstancesRequest request, ResultCapture<RunInstancesResult>
        extractor);
 
Example #26
Source File: EC2.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * The convenient method form for the <code>CreateInstances</code> action.
 *
 * @see #createInstances(RunInstancesRequest, ResultCapture)
 */
List<com.amazonaws.resources.ec2.Instance> createInstances(String imageId,
        Integer minCount, Integer maxCount,
        ResultCapture<RunInstancesResult> extractor);
 
Example #27
Source File: Subnet.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>CreateInstances</code> action and use a ResultCapture
 * to retrieve the low-level client response.
 *
 * <p>
 * The following request parameters will be populated from the data of this
 * <code>Subnet</code> resource, and any conflicting parameter value set in
 * the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>SubnetId</code></b>
 *         - mapped from the <code>Id</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return A list of <code>Instance</code> resource objects associated with
 *         the result of this action.
 * @see RunInstancesRequest
 */
List<Instance> createInstances(RunInstancesRequest request,
        ResultCapture<RunInstancesResult> extractor);