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

The following examples show how to use com.amazonaws.services.ec2.model.Reservation. 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: Ec2LookupServiceTest.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckIfInstancesExistOrTerminatedMixed(){
    mockedResult.setReservations(Arrays.asList(new Reservation[]{
            fakeInstance("i-12345", "1.2.3.4", "TestOne", "TEP","Linux"),
            fakeInstance("i-abcde", "123.2.3.4", "TestOneTwo", "TST", "Linux"),
            fakeInstance("i-456cd", "123.22.3.4", "HelloTwo", "TEP", "Linux"),
    }));

    Mockito.when(amazonEC2Client.describeInstances(any())).thenReturn(mockedResult);

    List<String> instanceIds = Arrays.asList( "i-12345", "i-abcde", "i-456cd", "i-123ab");
    Map<String, Boolean> result = Ec2LookupService.checkIfInstancesExistOrTerminated(awsEnvironment, instanceIds);

    //there should be 3 items in the collection
    Assert.assertEquals("The elements in the instance ID list are in the result map", instanceIds.size(), result.size());

    Assert.assertTrue("The instance i-123ab is 'terminated'", result.get("i-123ab"));
    Assert.assertFalse("The instance i-12345 'exists'", result.get("i-12345"));
    Assert.assertFalse("The instance i-abcde 'exists'", result.get("i-abcde"));
    Assert.assertFalse("The instance i-456cd 'exists'", result.get("i-456cd"));

}
 
Example #2
Source File: AwsTagReporterTest.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@Test
     public void testTagsAssociated() {
    MockAmazonEc2Client client = new MockAmazonEc2Client(null);
    Collection<Instance> instances = Arrays.asList(new Instance());
    DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult();
    Reservation reservation = new Reservation();
    describeInstancesResult.setReservations(Arrays.asList(reservation));
    reservation.setInstances(instances);
    client.setDescribeInstances(describeInstancesResult);
    Properties properties = new Properties();
    properties.setProperty("tagAccounting","key,value");
    properties.setProperty("function_tag","foo2");
    properties.setProperty("product_tag","foo3");
    AwsTagReporter reporter = new AwsTagReporter("testUuid",client,instances,properties);
    reporter.run();
}
 
Example #3
Source File: AwsTagReporterTest.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testExceptionCaught() {
    MockAmazonEc2Client client = new MockAmazonEc2Client(null);
    Collection<Instance> instances = Arrays.asList(new Instance());
    DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult();
    Reservation reservation = new Reservation();
    describeInstancesResult.setReservations(Arrays.asList(reservation));
    reservation.setInstances(instances);
    client.setDescribeInstances(describeInstancesResult);
    Properties properties = new Properties();
    properties.setProperty("tagAccounting","key");
    properties.setProperty("function_tag","foo2");
    properties.setProperty("product_tag","foo3");
    AwsTagReporter reporter = new AwsTagReporter("testUuid",client,instances,properties);
    reporter.run();
}
 
Example #4
Source File: AwsTagReporterTest.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSleepThrowsErrors() {
    MockAmazonEc2Client client = new MockAmazonEc2Client(null);
    client.setDescribeInstancesToThrowError();
    Collection<Instance> instances = Arrays.asList(new Instance());
    DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult();
    Reservation reservation = new Reservation();
    describeInstancesResult.setReservations(Arrays.asList(reservation));
    reservation.setInstances(instances);
    client.setDescribeInstances(describeInstancesResult);
    Properties properties = new Properties();
    properties.setProperty("accounting_tag","foo");
    properties.setProperty("function_tag","foo2");
    properties.setProperty("product_tag","foo3");
    AwsTagReporter reporter = new AwsTagReporter("testUuid",client,instances,properties) {
        @Override
        void sleep() throws InterruptedException {
            throw new InterruptedException();
        }
    };
    reporter.run();
}
 
Example #5
Source File: AwsTagReporterTest.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@Test()
public void testThreadTimesOut() {
    MockAmazonEc2Client client = new MockAmazonEc2Client(null);
    Collection<Instance> instances = Arrays.asList(new Instance());
    DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult();
    Reservation reservation = new Reservation();
    describeInstancesResult.setReservations(Arrays.asList(reservation));
    // Make count mismatch
    reservation.setInstances(Arrays.asList(new Instance(),new Instance()));
    client.setDescribeInstances(describeInstancesResult);
    Properties properties = new Properties();
    properties.setProperty("accounting_tag","foo");
    properties.setProperty("function_tag","foo2");
    properties.setProperty("product_tag","foo3");
    AwsTagReporter reporter = new AwsTagReporter("testUuid",client,instances,properties);
    AwsTagReporter.TIMEOUT_IN_SECONDS = 1;
    try{
        reporter.run();
    } catch(RuntimeException e) {
        Assert.assertEquals("Error waiting for instances to exist to add tags",e.getMessage());
        return;
    }
    Assert.fail("Exception should have been thrown since tags were never filed");
}
 
Example #6
Source File: EC2Utils.java    From amazon-kinesis-connectors with Apache License 2.0 6 votes vote down vote up
/**
 * Return the DNS name of one Amazon EC2 instance with the provided filter name and value.
 * 
 * @param ec2Client
 *        an Amazon EC2 instance
 * @param filterName
 *        the name of the filter
 * @param filterValue
 *        the value of the filter
 * @return the public DNS name of an instance with the filter name and value. Null if none exist.
 */
public static String getEndpointForFirstActiveInstanceWithTag(AmazonEC2 ec2Client,
        String filterName,
        String filterValue) {
    DescribeInstancesRequest describeInstancesRequest =
            new DescribeInstancesRequest().withFilters(new Filter().withName(filterName).withValues(filterValue));
    DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(describeInstancesRequest);

    List<Reservation> reservations = describeInstancesResult.getReservations();
    for (Reservation reservation : reservations) {
        List<Instance> ec2Instances = reservation.getInstances();
        for (Instance ec2Instance : ec2Instances) {
            if (InstanceStateName.Running.toString().equals(ec2Instance.getState().getName())) {
                return ec2Instance.getPublicDnsName();
            }
        }
    }
    return null;
}
 
Example #7
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 #8
Source File: AutomationReaperTask.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void doWork() {
    log.info("Running " + AutomationReaperTask.NAME);
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
    Filter filter = new Filter("tag:LaunchSource");
    filter.withValues("SeleniumGridScalerPlugin");
    describeInstancesRequest.withFilters(filter);
    List<Reservation> reservations = ec2.describeInstances(describeInstancesRequest);
    for(Reservation reservation : reservations) {
        for(Instance instance : reservation.getInstances()) {
            // Look for orphaned nodes
            Date threshold = AutomationUtils.modifyDate(new Date(),-30, Calendar.MINUTE);
            String instanceId = instance.getInstanceId();
            // If we found a node old enough AND we're not internally tracking it, this means this is an orphaned node and we should terminate it
            if(threshold.after(instance.getLaunchTime()) && !AutomationContext.getContext().nodeExists(instanceId)) {
                log.info("Terminating orphaned node: " + instanceId);
                ec2.terminateInstance(instanceId);
            }
        }
    }
}
 
Example #9
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/***
 * Get list of EC2 {@link Instance}s for a auto scaling group
 *
 * @param groupName Auto scaling group name
 * @param status Instance status (eg. running)
 * @return List of EC2 instances found for the input auto scaling group
 */
public List<Instance> getInstancesForGroup(String groupName,
    String status) {

  final AmazonEC2 amazonEC2 = getEc2Client();

  final DescribeInstancesResult instancesResult = amazonEC2.describeInstances(new DescribeInstancesRequest()
      .withFilters(new Filter().withName("tag:aws:autoscaling:groupName").withValues(groupName)));

  final List<Instance> instances = new ArrayList<>();
  for (Reservation reservation : instancesResult.getReservations()) {
    for (Instance instance : reservation.getInstances()) {
      if (null == status|| null == instance.getState()
          || status.equals(instance.getState().getName())) {
        instances.add(instance);
        LOGGER.info("Found instance: " + instance + " which qualified filter: " + status);
      } else {
        LOGGER.info("Found instance: " + instance + " but did not qualify for filter: " + status);
      }
    }
  }

  return instances;
}
 
Example #10
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Get logs of all the ec2 instances created by this #stackName.
 *
 * @param stackName the stack that created the ec2 instances
 * @param region aws region of the stack
 */
private void getAllEC2InstanceConsoleLogs(String stackName, String region) {
    try {
        final DescribeInstancesResult result = getDescribeInstancesResult(stackName, region);
        final long instanceCount = result.getReservations().stream()
                .map(Reservation::getInstances)
                .mapToLong(Collection::size)
                .sum();

        logger.info("");
        logger.info("Downloading logs of " + instanceCount + " EC2 instances in this AWS Cloudformation stack: {");
        for (Reservation reservation : result.getReservations()) {
            for (Instance instance : reservation.getInstances()) {
                final String logs = getEC2InstanceConsoleLogs(instance, getAmazonEC2(region));
                logger.info(logs);
            }
        }
        logger.info("}");
        logger.info("Further details about this EC2 instance console outputs can be found at: "
                + "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html");
        logger.info("");
    } catch (RuntimeException e) {
        logger.warn("Error while trying to download the instance console output from ec2 instances of {}@{}. "
                + "Error: ", stackName, region, e.getMessage());
    }
}
 
Example #11
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 *
 * Testgrid users may need to access the deployment's instances for debugging purposes.
 * Hence, we need to print the ssh access details by probing the internal details of the
 * cloudformation stack.
 *
 * @param stackName the cloudformation stack name
 * @param inputs properties instance that contain the aws region param
 */
private void logEC2SshAccessDetails(String stackName, Properties inputs) {
    try {
        String region = inputs.getProperty(AWS_REGION_PARAMETER);
        DescribeInstancesResult result = getDescribeInstancesResult(stackName, region);
        final long instanceCount = result.getReservations().stream()
                .map(Reservation::getInstances)
                .mapToLong(Collection::size)
                .sum();

        logger.info("");
        logger.info("Found " + instanceCount + " EC2 instances in this AWS Cloudformation stack: {");
        for (Reservation reservation : result.getReservations()) {
            for (Instance instance : reservation.getInstances()) {
                final String loginCommand = getLoginCommand(instance);
                logger.info(loginCommand);
            }
        }
        logger.info("}");
        logger.info("For information on login user names for Linux, please refer: "
                + "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html");
        logger.info("");
    } catch (RuntimeException e) {
        logger.warn("Error while trying to probe the cloudformation stack to find created ec2 instances.", e);
    }
}
 
Example #12
Source File: Ec2LookupServiceTest.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckIfInstancesExistOrTerminatedAllFalse(){
    mockedResult.setReservations(Arrays.asList(new Reservation[]{
            fakeInstance("i-12345", "1.2.3.4", "TestOne", "TEP","Linux"),
            fakeInstance("i-abcde", "123.2.3.4", "TestOneTwo", "TST", "Linux"),
            fakeInstance("i-123ab", "456.2.3.4", "HelloOne", "TEP", "Linux"),
            fakeInstance("i-456cd", "123.22.3.4", "HelloTwo", "TEP", "Linux"),
    }));

    Mockito.when(amazonEC2Client.describeInstances(any())).thenReturn(mockedResult);

    List<String> instanceIds = Arrays.asList("i-12345", "i-abcde", "i-456cd", "i-123ab");
    Map<String, Boolean> result = Ec2LookupService.checkIfInstancesExistOrTerminated(awsEnvironment, instanceIds);


    //there should be 4 items in the collection
    Assert.assertEquals("There should be 4 elements in the map", instanceIds.size(), result.size());
    //all the entries in the map should be false
    Assert.assertTrue("No entry should be set to true", result.entrySet().stream().noneMatch(Map.Entry::getValue));
}
 
Example #13
Source File: EC2Communication.java    From development with Apache License 2.0 6 votes vote down vote up
public String getInstanceState(String instanceId) {
    LOGGER.debug("getInstanceState('{}') entered", instanceId);
    DescribeInstancesResult result = getEC2().describeInstances(
            new DescribeInstancesRequest().withInstanceIds(instanceId));
    List<Reservation> reservations = result.getReservations();
    Set<Instance> instances = new HashSet<Instance>();

    for (Reservation reservation : reservations) {
        instances.addAll(reservation.getInstances());
        if (instances.size() > 0) {
            String state = instances.iterator().next().getState().getName();
            LOGGER.debug("  InstanceState: {}", state);
            return state;
        }
    }
    LOGGER.debug("getInstanceState('{}') left", instanceId);
    return null;
}
 
Example #14
Source File: BaseTest.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * Describe instances.
 *
 * @param instanceIds            instances' IDs
 * @param enableLogging            log to standard out
 * @return list of instances
 */
protected final List<Instance> describeInstances(
        final Collection<String> instanceIds, final boolean enableLogging) {
    if (enableLogging) {
        log.info("Describe instances:" + toString(instanceIds));
    }
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceIds);
    DescribeInstancesResult result = amazonEC2Client
            .describeInstances(request);
    Assert.assertTrue(result.getReservations().size() > 0);

    List<Instance> instanceList = new ArrayList<Instance>();

    for (Reservation reservation : result.getReservations()) {
        List<Instance> instances = reservation.getInstances();

        if (null != instances) {
            for (Instance i : instances) {
                instanceList.add(i);
            }
        }
    }

    return instanceList;
}
 
Example #15
Source File: Ec2LookupServiceTest.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
private Reservation fakeInstance(String instanceID, String instanceIP, String instanceName, String instanceApplication, String platform) {
    Reservation container = new Reservation();
    List<Instance> instances = new ArrayList<>();
    Instance i = new Instance();
    List<Tag> tags = new ArrayList<>();
    i.setInstanceId(instanceID);
    i.setPrivateIpAddress(instanceIP);
    Tag nameTag = new Tag();
    nameTag.setKey("Name");
    nameTag.setValue(instanceName);
    Tag applicationTag = new Tag();
    applicationTag.setKey("Application");
    applicationTag.setValue(instanceApplication);
    tags.add(applicationTag);
    tags.add(nameTag);
    i.setTags(tags);
    i.setPlatform(platform);
    instances.add(i);
    container.setInstances(instances);

    return container;
}
 
Example #16
Source File: AmiIdProviderImpl.java    From fullstop with Apache License 2.0 6 votes vote down vote up
private Optional<String> getAmiIdFromEC2Api(final EC2InstanceContext context) {
    final String instanceId = context.getInstanceId();
    try {
        return context.getClient(AmazonEC2Client.class)
                .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceId))
                .getReservations()
                .stream()
                .map(Reservation::getInstances)
                .flatMap(Collection::stream)
                .filter(i -> i.getInstanceId().equals(instanceId))
                .map(Instance::getImageId)
                .findFirst();
    } catch (final AmazonClientException e) {
        log.warn("Could not describe instance " + instanceId, e);
        return empty();
    }
}
 
Example #17
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
   * Gets the instance details for ec 2.
   *
   * @param clientMap the client map
   * @param resourceId the resource id
   * @return the instance details for ec 2
   * @throws Exception the exception
   */
  public static Instance getInstanceDetailsForEc2(Map<String,Object> clientMap,String resourceId) throws Exception {
  	AmazonEC2 ec2Client = (AmazonEC2) clientMap.get("client");
  	DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
describeInstancesRequest.setInstanceIds(Arrays.asList(resourceId));


RetryConfig config = RetryConfig.custom().maxAttempts(MAX_ATTEMPTS).waitDuration(Duration.ofSeconds(WAIT_INTERVAL)).build();
RetryRegistry registry = RetryRegistry.of(config);

Retry retry = registry.retry(describeInstancesRequest.toString());
 		
Function<Integer, Instance> decorated
  =  Retry.decorateFunction(retry, (Integer s) -> {
	  DescribeInstancesResult  describeInstancesResult =  ec2Client.describeInstances(describeInstancesRequest);
	  List<Reservation> reservations = describeInstancesResult.getReservations();
		Reservation reservation = reservations.get(0);
		List<Instance> instances = reservation.getInstances();
		return instances.get(0);
    });
return decorated.apply(1);
	
  }
 
Example #18
Source File: EC2Connector.java    From jenkins-deployment-dashboard-plugin with MIT License 6 votes vote down vote up
public List<ServerEnvironment> getEnvironmentsByTag(Region region, String searchTag) {
    LOGGER.info("getEnvironmentsByTag " + region + " tag: " + searchTag);
    List<ServerEnvironment> environments = new ArrayList<ServerEnvironment>();

    ec2.setRegion(region);
    DescribeInstancesResult instances = ec2.describeInstances();
    for (Reservation reservation : instances.getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            for (Tag tag : instance.getTags()) {
                if (tag.getValue().equalsIgnoreCase(searchTag)) {
                    environments.add(getEnvironmentFromInstance(instance));
                }
            }
        }
    }
    return environments;
}
 
Example #19
Source File: BaseTest.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * Describe instances.
 *
  * @return list of instances
 */
protected final List<Instance> describeInstances() {

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    DescribeInstancesResult result = amazonEC2Client
            .describeInstances(request);
    List<Instance> instanceList = new ArrayList<Instance>();
    if (result.getReservations().size() > 0) {
     Assert.assertTrue(result.getReservations().size() > 0);

     for (Reservation reservation : result.getReservations()) {
         List<Instance> instances = reservation.getInstances();
	
         if (null != instances) {
             for (Instance i : instances) {
                 instanceList.add(i);
             }
         }
     }
    }
    return instanceList;
}
 
Example #20
Source File: DescribeInstancesExample.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe all mock instances within aws-mock.
 *
 * @return a list of all instances
 */
public static List<Instance> describeAllInstances() {
    // 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);

    DescribeInstancesResult response = amazonEC2Client.describeInstances();
    List<Reservation> reservations = response.getReservations();

    List<Instance> ret = new ArrayList<Instance>();

    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();

        if (null != instances) {

            for (Instance i : instances) {
                ret.add(i);
            }
        }
    }

    return ret;
}
 
Example #21
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private DescribeInstancesResult getDescribeInstancesResult(String state, int code) {
    Instance instances1 = getAwsInstance("i-1", state, code);
    Instance instances2 = getAwsInstance("i-2", state, code);
    Reservation reservation1 = getReservation(instances1, "1");
    Reservation reservation2 = getReservation(instances2, "2");

    return new DescribeInstancesResult().withReservations(reservation1, reservation2);
}
 
Example #22
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private DescribeInstancesResult getDescribeInstancesResultOneRunning(String state, int code) {
    Instance instances1 = getAwsInstance("i-1", state, code);
    Instance instances2 = getAwsInstance("i-2", "running", 16);
    Reservation reservation1 = getReservation(instances1, "1");
    Reservation reservation2 = getReservation(instances2, "2");

    return new DescribeInstancesResult().withReservations(reservation1, reservation2);
}
 
Example #23
Source File: AwsInstanceConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Collection<String> instanceIdsWhichAreNotInCorrectState(List<CloudInstance> vms, AmazonEC2 amazonEC2Client, String state) {
    Set<String> instances = vms.stream().map(CloudInstance::getInstanceId).collect(Collectors.toCollection(HashSet::new));
    DescribeInstancesResult describeInstances = amazonEC2Client.describeInstances(
            new DescribeInstancesRequest().withInstanceIds(instances));
    for (Reservation reservation : describeInstances.getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            if (state.equalsIgnoreCase(instance.getState().getName())) {
                instances.remove(instance.getInstanceId());
            }
        }
    }
    return instances;
}
 
Example #24
Source File: AutomationReaperTaskTest.java    From SeleniumGridScaler with GNU General Public License v2.0 5 votes vote down vote up
@Test
// Tests that a node that is not old enough is not terminated
public void testNoShutdownTooRecent() {
    MockVmManager ec2 = new MockVmManager();
    Reservation reservation = new Reservation();
    Instance instance = new Instance();
    String instanceId = "foo";
    instance.setInstanceId(instanceId);
    instance.setLaunchTime(AutomationUtils.modifyDate(new Date(),-15,Calendar.MINUTE));
    reservation.setInstances(Arrays.asList(instance));
    ec2.setReservations(Arrays.asList(reservation));
    AutomationReaperTask task = new AutomationReaperTask(null,ec2);
    task.run();
    Assert.assertFalse("Node should NOT be terminated as it was not old", ec2.isTerminated());
}
 
Example #25
Source File: EC2Connector.java    From jenkins-deployment-dashboard-plugin with MIT License 5 votes vote down vote up
public List<ServerEnvironment> getEnvironments(Region region) {
    List<ServerEnvironment> environments = new ArrayList<ServerEnvironment>();

    ec2.setRegion(region);
    DescribeInstancesResult instances = ec2.describeInstances();
    for (Reservation reservation : instances.getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            environments.add(getEnvironmentFromInstance(instance));
        }
    }

    return environments;
}
 
Example #26
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 #27
Source File: AwsTaggingServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void tesTagRootVolumesForSingleInstance() {
    CloudResource instance = CloudResource.builder()
            .type(ResourceType.AWS_INSTANCE).instanceId(INSTANCE_ID).name(INSTANCE_ID).status(CommonStatus.CREATED).build();

    DescribeInstancesResult describeResult = new DescribeInstancesResult()
            .withReservations(new Reservation()
                    .withInstances(new Instance()
                            .withInstanceId(INSTANCE_ID)
                            .withBlockDeviceMappings(new InstanceBlockDeviceMapping()
                                    .withDeviceName("/dev/sda1")
                                    .withEbs(new EbsInstanceBlockDevice().withVolumeId(VOLUME_ID)))
                            .withRootDeviceName("/dev/sda1"))
            );

    AmazonEC2Client ec2Client = mock(AmazonEC2Client.class);
    when(ec2Client.describeInstances(any())).thenReturn(describeResult);
    Map<String, String> userTags = Map.of("key1", "val1", "key2", "val2");

    awsTaggingService.tagRootVolumes(authenticatedContext(), ec2Client, List.of(instance), userTags);

    verify(ec2Client, times(1)).createTags(tagRequestCaptor.capture());
    CreateTagsRequest request = tagRequestCaptor.getValue();
    assertEquals(1, request.getResources().size());
    assertEquals(VOLUME_ID, request.getResources().get(0));
    List<com.amazonaws.services.ec2.model.Tag> tags = request.getTags();
    assertThat(tags, containsInAnyOrder(
            hasProperty("key", Matchers.is("key1")),
            hasProperty("key", Matchers.is("key2"))
    ));
    assertThat(tags, containsInAnyOrder(
            hasProperty("value", Matchers.is("val1")),
            hasProperty("value", Matchers.is("val2"))
    ));
}
 
Example #28
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 #29
Source File: DescribeInstancesExample.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe specified instances within aws-mock.
 *
 * @param instanceIDs
 *            a list of instance IDs to describe
 * @return a list of specified instances
 */
public static List<Instance> describeInstances(final List<String> instanceIDs) {
    // 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);

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.withInstanceIds(instanceIDs);

    DescribeInstancesResult response = amazonEC2Client.describeInstances(request);
    List<Reservation> reservations = response.getReservations();

    List<Instance> ret = new ArrayList<Instance>();

    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();

        if (null != instances) {

            for (Instance i : instances) {
                ret.add(i);
            }
        }
    }

    return ret;
}
 
Example #30
Source File: Ec2TableProviderTest.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUpRead()
{
    when(mockEc2.describeInstances(any(DescribeInstancesRequest.class))).thenAnswer((InvocationOnMock invocation) -> {
        DescribeInstancesRequest request = (DescribeInstancesRequest) invocation.getArguments()[0];

        assertEquals(getIdValue(), request.getInstanceIds().get(0));
        DescribeInstancesResult mockResult = mock(DescribeInstancesResult.class);
        List<Reservation> reservations = new ArrayList<>();
        reservations.add(makeReservation());
        reservations.add(makeReservation());
        when(mockResult.getReservations()).thenReturn(reservations);
        return mockResult;
    });
}