Java 类com.amazonaws.services.ec2.model.Reservation 实例源码

项目:oscm    文件:EC2Communication.java   
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;
}
项目:swordfish-service    文件:EC2SyncImpl.java   
private List<Instance> processResponse(DescribeInstancesResult response) {
    List<Instance> returnedInstances = new ArrayList<>();

    for (Reservation reservation : response.getReservations()) {
        for (com.amazonaws.services.ec2.model.Instance instance : reservation.getInstances()) {

            // Don't show dead servers or servers not tagged as belonging to Swordfish
            if (instance.getState().getName().equals("terminated") || !instance.getTags().contains(new Tag().withKey("Swordfish").withValue("true"))) {
                continue;
            }

            Instance instanceDetails = getInstanceDetails(instance);
            returnedInstances.add(instanceDetails);
            instanceRepository.save(instanceDetails);
            refreshClient(instanceDetails);
        }
    }

    return returnedInstances;
}
项目:turbine-ec2    文件:InstanceList.java   
/**
 * Gets the list of ec2 instances of a given cluster.
 * @return List of instances.
 */
public List<Instance> get() {
    final ClusterTag tag = new ClusterTag(this.cluster, this.config);
    final String name = tag.name();
    final String value = tag.value();
    InstanceList.LOGGER.info(
        String.format(
            "Looking for instances for '%s' filtering with '%s'='%s'",
            this.cluster,
            name,
            value
        )
    );
    final EC2ToTurbineInstance converter = new EC2ToTurbineInstance(
        this.cluster
    );
    return this.provider.client()
        .describeInstances(this.request(name, value))
        .getReservations()
        .parallelStream()
        .map(Reservation::getInstances)
        .flatMap(List::stream)
        .map(converter::convert)
        .collect(Collectors.toList());
}
项目:photon-model    文件:AWSEnumerationAndDeletionAdapterService.java   
@Override
public void onSuccess(DescribeInstancesRequest request,
        DescribeInstancesResult result) {
    OperationContext.restoreOperationContext(this.opContext);
    int totalNumberOfInstances = 0;
    // Print the details of the instances discovered on the AWS endpoint
    for (Reservation r : result.getReservations()) {
        for (Instance i : r.getInstances()) {
            ++totalNumberOfInstances;
            final int finalTotal1 = totalNumberOfInstances;
            this.service.logFine(() -> String.format("%d=====Instance details %s =====",
                    finalTotal1, i.getInstanceId()));
            this.aws.remoteInstanceIds.add(i.getInstanceId());
        }
    }
    final int finalTotal2 = totalNumberOfInstances;
    this.service.logFine(() -> String.format("Successfully enumerated %d instances on the"
                    + " AWS host.", finalTotal2));
    this.aws.subStage = this.next;
    ((AWSEnumerationAndDeletionAdapterService) this.service)
            .deleteResourcesInLocalSystem(this.aws);
    return;
}
项目:cerberus-lifecycle-cli    文件:Ec2ServiceTest.java   
@Test
public void testGetInstancesByTagHappy() {

    String tagKey = "tag key";
    String tagValue = "tag value";
    Filter filter = new Filter().withName(INSTANCE_STATE_FILTER_NAME).withValues(INSTANCE_STATE_RUNNING_FILTER_VALUE);
    Instance instance = mock(Instance.class);

    when(ec2Client.describeInstances(new DescribeInstancesRequest()
            .withFilters(
                    filter,
                    new Filter()
                            .withName(String.format(FILTER_NAME_TEMPL_FOR_EC2_TAGS, tagKey))
                            .withValues(tagValue)
            )
    )).thenReturn(
            new DescribeInstancesResult()
                    .withReservations(
                            new Reservation()
                                    .withInstances(instance))
    );

    List<Instance> instances = ec2Service.getInstancesByTag(tagKey, tagValue, filter);

    assertTrue(instances.contains(instance));
}
项目:director-aws-plugin    文件:EC2Provider.java   
/**
 * Iterates through the instances in the specified {@code DescribeInstancesResult}
 * and calls the specified handler on each instance. This method will retrieve the
 * follow-on {@code DescribeInstanceResult}s if the result holds a {@code nextToken}.
 *
 * @param result          the {@code DescribeInstancesResult}
 * @param instanceHandler the instance handler
 */
@VisibleForTesting
void forEachInstance(DescribeInstancesResult result, InstanceHandler instanceHandler) {
  List<Reservation> reservations;
  while (!(reservations = result.getReservations()).isEmpty()) {
    for (Reservation reservation : reservations) {
      for (Instance instance : reservation.getInstances()) {
        LOG.debug("Calling instance handler with instance {}", instance);
        instanceHandler.handle(instance);
      }
    }

    if (result.getNextToken() != null) {
      result = client.describeInstances(
          new DescribeInstancesRequest().withNextToken(result.getNextToken()));
    } else {
      break;
    }
  }
}
项目:development    文件:EC2Communication.java   
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;
}
项目:Tank    文件:AmazonInstance.java   
/**
 * 
 * @{inheritDoc
 */
@Override
public List<VMInformation> describeInstances(String... instanceIds) {
    List<VMInformation> result = new ArrayList<VMInformation>();
    try {

        DescribeInstancesResult results = asynchEc2Client.describeInstances();
        HashSet<String> ids = new HashSet<String>(Arrays.asList(instanceIds));
        for (Reservation reservationDescription : results.getReservations()) {
            for (com.amazonaws.services.ec2.model.Instance instance : reservationDescription.getInstances()) {
                if (ids.contains(instance.getInstanceId())) {
                    result.add(new AmazonDataConverter().instanceToVmInformation(reservationDescription, instance, vmRegion));
                }
            }
            // result.addAll(TypicaDataConverter.processReservationDescription(reservationDescription));
        }
    } catch (Exception e) {
        LOG.error("Failed to retrieve instance from Amazon: " + e.getMessage());
        throw new RuntimeException(e);
    }

    return result;
}
项目:Tank    文件:AmazonInstance.java   
/**
 * @{inheritDoc
 */
@Override
public List<VMInformation> findInstancesOfType(VMRegion region, VMImageType type) {
    List<VMInformation> ret = new ArrayList<VMInformation>();
    try {
        DescribeInstancesResult instances = asynchEc2Client.describeInstances();
        InstanceDescription instanceForRegionAndType = new TankConfig().getVmManagerConfig().getInstanceForRegionAndType(region, type);
        for (Reservation res : instances.getReservations()) {
            if (res.getInstances() != null) {
                for (com.amazonaws.services.ec2.model.Instance inst : res.getInstances()) {
                    if ((inst.getState().getName().equalsIgnoreCase("running") || inst.getState().getName().equalsIgnoreCase("pending"))
                            && inst.getImageId().equals(instanceForRegionAndType.getAmi())) {
                        ret.add(new AmazonDataConverter().instanceToVmInformation(res, inst, region));
                    }
                }
            }
        }
    } catch (Exception e) {
        LOG.error("Error getting instances: " + e.toString(), e);
        throw new RuntimeException(e);
    }
    return ret;
}
项目:Tank    文件:AmazonInstance.java   
/**
 * @{inheritDoc
 */
private List<VMInformation> findAllInstancesOfType(VMRegion region, VMImageType type) {
    List<VMInformation> ret = new ArrayList<VMInformation>();
    try {
        DescribeInstancesResult instances = asynchEc2Client.describeInstances();
        InstanceDescription instanceForRegionAndType = new TankConfig().getVmManagerConfig().getInstanceForRegionAndType(region, type);
        for (Reservation res : instances.getReservations()) {
            if (res.getInstances() != null) {
                for (com.amazonaws.services.ec2.model.Instance inst : res.getInstances()) {
                    if (inst.getImageId().equals(instanceForRegionAndType.getAmi())) {
                        ret.add(new AmazonDataConverter().instanceToVmInformation(res, inst, region));
                    }
                }
            }
        }
    } catch (Exception e) {
        LOG.error("Error getting instances: " + e.toString(), e);
        throw new RuntimeException(e);
    }
    return ret;
}
项目:Tank    文件:AmazonDataConverter.java   
/**
 * @param data
 * @param instance
 * @param region
 * @return
 */
public VMInformation instanceToVmInformation(Reservation data, Instance instance, VMRegion region) {
    VMInformation info = new VMInformation();
    info.setProvider(VMProvider.Amazon);
    info.setRequestId(data.getRequesterId());
    info.setImageId(instance.getImageId());
    info.setInstanceId(instance.getInstanceId());
    info.setKeyName(instance.getKeyName());
    // info.setLaunchTime();
    info.setRegion(region);
    info.setPlatform(instance.getPlatform());
    info.setPrivateDNS(instance.getPrivateDnsName());
    info.setPublicDNS(instance.getPublicDnsName());
    info.setState(instance.getState().getName());
    info.setSize(instance.getInstanceType());
    return info;
}
项目:distributed-image-classification    文件:NodesMgmt.java   
public List<String> getAllRunningInstances() {
    logger.info("Get running instances request");
    DescribeInstancesRequest request = new DescribeInstancesRequest();

    List<String> valuesT1 = new ArrayList<String>();
    valuesT1.add(_defaultTag);
    Filter filter1 = new Filter("tag:" + _tagKey, valuesT1);
    List<String> valuesT2 = new ArrayList<String>();
    valuesT2.add("running"); 
    valuesT2.add("pending");
    Filter filter2 = new Filter("instance-state-name",valuesT2);

    DescribeInstancesResult result = _ec2.describeInstances(request.withFilters(filter1,filter2));
    List<Reservation> reservations = result.getReservations();

    List<String> instancesID = new ArrayList<String>();
    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();
        for (Instance instance : instances) {
            instancesID.add(instance.getInstanceId());
        }
    }

    return instancesID;
}
项目:ec2-util    文件:AwsEc2Client.java   
/**
 * Search Ec2 Instance by Name tag.
 * 
 * @param ec2
 * @param targetName
 *            Search Keyword for Name tag
 * @return Instance with Name tag equals targetName. If it does't found,
 *         then return null.
 */
public static Instance findInstanceByName(AmazonEC2 ec2, String targetName) {
    DescribeInstancesResult instanceResult = ec2.describeInstances();
    List<Reservation> reservations = instanceResult.getReservations();
    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();
        for (Instance instance : instances) {
            List<Tag> tagList = instance.getTags();
            String name = "";
            for (Tag tag : tagList) {
                String tagKey = tag.getKey();
                String tagValue = tag.getValue();
                if (tagKey.contains("Name")) {
                    name = tagValue;
                    if (targetName.equals(name)) {
                        return instance;
                    }
                    break;
                }
            }
        }
    }
    return null;
}
项目:fullstop    文件:AmiIdProviderImpl.java   
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();
    }
}
项目:jenkins-deployment-dashboard-plugin    文件:EC2Connector.java   
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;
}
项目:jenkins-deployment-dashboard-plugin    文件:EC2Connector.java   
@Override
public boolean tagEnvironmentWithVersion(Region region, DeployJobVariables jobVariables) {
    String searchTag = jobVariables.getEnvironment();
    String version = jobVariables.getVersion();
    LOGGER.info("tagEnvironmentWithVersion " + region + " Tag " + searchTag + " version " + version);

    boolean environmentSuccessfulTagged = false;
    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)) {
                    CreateTagsRequest createTagsRequest = new CreateTagsRequest();
                    createTagsRequest.withResources(instance.getInstanceId()).withTags(new Tag(VERSION_TAG, version));
                    LOGGER.info("Create Tag " + version + " for instance " + instance.getInstanceId());
                    ec2.createTags(createTagsRequest);
                    environmentSuccessfulTagged = true;
                }
            }
        }
    }
    return environmentSuccessfulTagged;
}
项目:dohko    文件:EC2.java   
private Instances describeInstances(DescribeInstancesRequest request)
{
    final Instances instances = new Instances();

    DescribeInstancesResult result = ec2_.describeInstances(request);

    for (Reservation reservation : result.getReservations())
    {
        for (Instance instance : reservation.getInstances())
        {
            instances.addInstance(toExcaliburInstance(instance, null));
        }
    }

    return instances;
}
项目:incubator-gobblin    文件:AWSSdkClient.java   
/***
 * 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;
}
项目:amazon-cloudengine    文件:EC2.java   
public boolean ifInstancePending(List<String> instanceIDs) {
    System.out.println("Checking to determine if a Instance is in Pending state...");
    DescribeInstancesRequest describeInstancesRequest=new DescribeInstancesRequest().withInstanceIds(instanceIDs);
    List<Reservation> reservations = ec2.describeInstances(describeInstancesRequest)
            .getReservations();
    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();
        for (Instance instance : instances) {
            System.out.println(" "
                    + instance.getInstanceId()
                    + " is in the " + instance.getState().getName()
                    + " state.");
            if (instance.getState().getName().equals("pending"))
                return true;
        }
    }
    return false;
}
项目:amazon-cloudengine    文件:EC2.java   
public int getInstanceNumWithTag(Tag t) {
    assert (t != null);
    int num = 0;
    List<Reservation> reservations = ec2.describeInstances()
            .getReservations();
    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();
        for (Instance instance : instances) {
            if (!instance.getState().getName().equals("pending")
                    && !instance.getState().getName().equals("running"))
                continue;
            List<Tag> tags = instance.getTags();
            for (Tag tag : tags) {
                if (tag.getKey().equals(t.getKey())
                        && tag.getValue().equals(t.getValue())) {
                    num++;
                    break;
                }
            }
        }
    }
    return num;
}
项目:SeleniumGridScaler    文件:AutomationReaperTask.java   
@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);
            }
        }
    }
}
项目:SeleniumGridScaler    文件:VmManagerTest.java   
@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());
}
项目:SeleniumGridScaler    文件:AwsTagReporterTest.java   
@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();
}
项目:SeleniumGridScaler    文件:AwsTagReporterTest.java   
@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();
}
项目:SeleniumGridScaler    文件:AwsTagReporterTest.java   
@Test
public void testClientThrowsErrors() {
    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 {
            // do nothing
        }
    };
    reporter.run();
}
项目:SeleniumGridScaler    文件:AwsTagReporterTest.java   
@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();
}
项目:SeleniumGridScaler    文件:AwsTagReporterTest.java   
@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");
}
项目:SeleniumGridScaler    文件:AutomationReaperTaskTest.java   
@Test
// Tests that a node that is being tracked internally is not shut down
public void testNoShutdownNodeTracked() {
    MockVmManager ec2 = new MockVmManager();
    Reservation reservation = new Reservation();
    Instance instance = new Instance();
    String instanceId = "foo";
    AutomationContext.getContext().addNode(new AutomationDynamicNode("faky",instanceId,null,null,new Date(),1));
    instance.setInstanceId(instanceId);
    instance.setLaunchTime(AutomationUtils.modifyDate(new Date(),-5,Calendar.HOUR));
    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 tracked internally", ec2.isTerminated());
}
项目:cloudbreak    文件:AwsInstanceConnector.java   
@Override
public List<CloudVmInstanceStatus> check(AuthenticatedContext ac, List<CloudInstance> vms) {
    List<CloudVmInstanceStatus> cloudVmInstanceStatuses = new ArrayList<>();
    for (CloudInstance vm : vms) {
        DescribeInstancesResult result = awsClient.createAccess(new AwsCredentialView(ac.getCloudCredential()),
                ac.getCloudContext().getLocation().getRegion().value())
                .describeInstances(new DescribeInstancesRequest().withInstanceIds(vm.getInstanceId()));
        for (Reservation reservation : result.getReservations()) {
            for (Instance instance : reservation.getInstances()) {
                if ("Stopped".equalsIgnoreCase(instance.getState().getName())) {
                    LOGGER.info("AWS instance is in Stopped state, polling stack.");
                    cloudVmInstanceStatuses.add(new CloudVmInstanceStatus(vm, InstanceStatus.STOPPED));
                } else if ("Running".equalsIgnoreCase(instance.getState().getName())) {
                    LOGGER.info("AWS instance is in Started state, polling stack.");
                    cloudVmInstanceStatuses.add(new CloudVmInstanceStatus(vm, InstanceStatus.STARTED));
                } else if ("Terminated".equalsIgnoreCase(instance.getState().getName())) {
                    LOGGER.info("AWS instance is in Terminated state, polling stack.");
                    cloudVmInstanceStatuses.add(new CloudVmInstanceStatus(vm, InstanceStatus.TERMINATED));
                } else {
                    cloudVmInstanceStatuses.add(new CloudVmInstanceStatus(vm, InstanceStatus.IN_PROGRESS));
                }
            }
        }
    }
    return cloudVmInstanceStatuses;
}
项目:cloudbreak    文件:TagsUtil.java   
protected static void checkTagsAws(Regions region, List<String> instanceIdList, Map<String, String> tagsToCheckMap) {
    Map<String, String> extractedTagsToCheck = new HashMap<>();
    List<Tag> extractedTags;
    AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(region).build();
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
    describeInstancesRequest.withInstanceIds(instanceIdList);
    DescribeInstancesResult describeInstancesResultAll = ec2.describeInstances(describeInstancesRequest);
    List<Reservation> reservationsAll = describeInstancesResultAll.getReservations();
    for (Reservation reservation : reservationsAll) {
        for (Instance instance : reservation.getInstances()) {
            extractedTags = instance.getTags();
            Assert.assertNotNull(extractedTags);
            for (Tag tag : extractedTags) {
                extractedTagsToCheck.put(tag.getKey(), tag.getValue());
            }
            checkTags(tagsToCheckMap, extractedTagsToCheck);
            extractedTags.clear();
        }
    }
}
项目:aws-connector-extension    文件:AWSConnector.java   
private Instance getEc2Instance(IMachine machine, AmazonEC2 connector) throws ConnectorException {
    DescribeInstancesResult describeInstancesResult = null;
    try {
        DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
        describeInstancesResult = connector.describeInstances(describeInstancesRequest.withInstanceIds(machine.getName()));
        List<Reservation> reservations = describeInstancesResult.getReservations();
        if (reservations.size() == 0) {
            // machine not found MUST have been terminated
            return null;
        }

        // always it will be in the first reservation as the query is on
        // only one machine
        List<Instance> instances = reservations.get(0).getInstances();
        for (Instance instance : instances) {
            if (instance.getInstanceId().equals(machine.getName())) {
                // found the machine
                return instance;
            }
        }
    } catch (Exception e) {
        throw new ConnectorException(e);
    }

    return null;
}
项目:clouck    文件:Ec2Reservation.java   
@Override
@SuppressWarnings("rawtypes")
protected boolean isEqual(AbstractResource newResource) {
    Reservation oldReservation = this.getResource();
    Ec2Reservation newEc2Reservation = (Ec2Reservation) newResource;
    Reservation newReservation = newEc2Reservation.getResource();

    if (notEqual(oldReservation.getRequesterId(), newReservation.getRequesterId())) return false;
    if (notEqual(oldReservation.getOwnerId(), newReservation.getOwnerId())) return false;
    if (notEqual(oldReservation.getRequesterId(), newReservation.getRequesterId())) return false;
    if (notEqualCollection(oldReservation.getGroups(), newReservation.getGroups())) return false;
    if (notEqualCollection(oldReservation.getGroupNames(), newReservation.getGroupNames())) return false;
    if (notEqualInstancess(oldReservation.getInstances(), newReservation.getInstances())) return false;
    if (notEqual(this.getInstanceId2Attributes(), newEc2Reservation.getInstanceId2Attributes())) return false;

    return true;
}
项目:clouck    文件:Ec2WrapperImpl.java   
@Override
public List<AbstractResource<?>> describeReservations(Account account, Region region, DateTime dt, Ec2Filter... filters) {
    AmazonEC2 ec2 = findClient(account, region);

    DescribeInstancesRequest req = new DescribeInstancesRequest();
    for (Ec2Filter filter : filters) {
        Filter f = new Filter().withName(filter.getName()).withValues(filter.getValues());
        req.withFilters(f);
    }

    log.debug("start describing instances for account:{} in region:{} via api", account.getId() + "=>" + account.getName(), region);
    DescribeInstancesResult res = ec2.describeInstances(req);
    List<Map<String, Ec2InstanceAttribute>> attributes = new ArrayList<>();
    for (Reservation r : res.getReservations()) {
        Map<String, Ec2InstanceAttribute> attribute = new HashMap<>();
        for (Instance i : r.getInstances()) {
            Boolean terminationProtection = findTerminationProtection(account, region, i.getInstanceId());
            String shutdownBehavior = findShutdownBehavior(account, region, i.getInstanceId());
            String userData = findUserData(account, region, i.getInstanceId());
            Ec2InstanceAttribute ia = new Ec2InstanceAttribute(terminationProtection, shutdownBehavior, userData);
            attribute.put(i.getInstanceId(), ia);
        }
        attributes.add(attribute);
    }
    return converter.toEc2Reservations(res.getReservations(), attributes, account.getId(), region, dt);
}
项目:aws-mock    文件:BaseTest.java   
/**
 * 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;
}
项目:aws-mock    文件:BaseTest.java   
/**
 * 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;
}
项目:datamung    文件:Ec2ActivitiesImpl.java   
/**
 * @inheritDoc
 */
@Override
public WorkerInstance describeInstance( String instanceId, Identity identity )
{
    AmazonEC2 ec2 =
        ActivityUtils.createClient( AmazonEC2Client.class, identity );
    DescribeInstancesResult result =
        ec2.describeInstances( new DescribeInstancesRequest().withInstanceIds( instanceId ) );
    if ( result.getReservations().isEmpty() )
    {
        return null;
    }
    Reservation resv = result.getReservations().get( 0 );
    if ( resv.getInstances().isEmpty() )
    {
        return null;
    }
    Instance ins = resv.getInstances().get( 0 );
    WorkerInstance wi = new WorkerInstance();
    wi.setInstanceId( ins.getInstanceId() );
    wi.setInstanceStatus( ins.getState().getName() );
    wi.setPublicIpAddress( ins.getPublicIpAddress() );
    return wi;
}
项目:shabdiz    文件:AmazonEC2HostProvider.java   
private List<Instance> getInstances() {

        final List<Instance> all_instances = new ArrayList<>();
        final DescribeInstancesRequest request = new DescribeInstancesRequest();
        final DescribeInstancesResult result = ec2_client.describeInstances(request);
        final List<Reservation> reservations = result.getReservations();

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

        return all_instances;
    }
项目:oscm    文件:EC2Communication.java   
public String getPublicDNS(String 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) {
            return instances.iterator().next().getPublicDnsName();
        }
    }
    return null;
}
项目:oscm    文件:EC2Communication.java   
public List<Instance> getInstance(String instanceId) {
    DescribeInstancesResult result = getEC2().describeInstances(
            new DescribeInstancesRequest().withInstanceIds(instanceId));
    List<Reservation> reservations = result.getReservations();
    List<Instance> instances = new ArrayList<>();

    for (Reservation reservation : reservations) {
        instances.addAll(reservation.getInstances());
    }
    return instances;
}
项目:oscm    文件:EC2CommunicationTest.java   
@Test
public void testGetInstanceStateEmptyReservation() throws Exception {
    DescribeInstancesResult instancesResult = new DescribeInstancesResult()
            .withReservations(new Reservation());
    doReturn(instancesResult).when(ec2).describeInstances(
            Matchers.any(DescribeInstancesRequest.class));
    String state = ec2comm.getInstanceState("instance1");
    assertNull(state);

    String dns = ec2comm.getPublicDNS("instance1");
    assertNull(dns);
}