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

项目: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;
}
项目:elasticsearch_my    文件:AwsEc2UnicastHostsProvider.java   
private DescribeInstancesRequest buildDescribeInstancesRequest() {
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
        .withFilters(
            new Filter("instance-state-name").withValues("running", "pending")
        );

    for (Map.Entry<String, String> tagFilter : tags.entrySet()) {
        // for a given tag key, OR relationship for multiple different values
        describeInstancesRequest.withFilters(
            new Filter("tag:" + tagFilter.getKey()).withValues(tagFilter.getValue())
        );
    }

    if (!availabilityZones.isEmpty()) {
        // OR relationship amongst multiple values of the availability-zone filter
        describeInstancesRequest.withFilters(
            new Filter("availability-zone").withValues(availabilityZones)
        );
    }

    return describeInstancesRequest;
}
项目:oscm    文件:EC2ProcessorTest.java   
@Test
public void process_STOPING() throws Exception {
    // given
    ec2mock.createDescribeInstancesResult("instance1", "stopped", "1.2.3.4");
    ec2mock.createDescribeInstanceStatusResult("instance1", "ok", "ok",
            "ok");
    ph.setOperation(Operation.EC2_OPERATION);
    ph.setState(FlowState.STOPPING);

    // when
    InstanceStatus result = ec2proc.process();

    // then
    assertTrue(result.isReady());
    assertEquals(FlowState.FINISHED, ph.getState());

    verify(ec2).describeInstances(any(DescribeInstancesRequest.class));
}
项目:swordfish-service    文件:EC2WaiterImpl.java   
@Override
public WaiterHandler<DescribeInstancesRequest> describeInstancesRequestWaiterHandler() {
    return new WaiterHandler<DescribeInstancesRequest>() {
        @Override
        public void onWaitSuccess(DescribeInstancesRequest request) {
            List<String> instanceIds = request.getInstanceIds();

            for (String instanceId : instanceIds) {
                ec2Sync.syncByInstanceId(instanceId);
            }
        }

        @Override
        public void onWaitFailure(Exception e) {
            log.warn("something went wrong waiting for AWS {}", e.getLocalizedMessage());
        }
    };
}
项目:turbine-ec2    文件:InstanceListTest.java   
/**
 * InstanceList can list instances.
 */
@Test
public void listsInstances() {
    Mockito.when(
        this.client.describeInstances(
            Mockito.any(DescribeInstancesRequest.class)
        )
    ).thenReturn(
        new DescribeInstancesResult()
            .withReservations(
                Collections.singletonList(this.fakeReservation())
            )
    );

    final List<Instance> instances = new InstanceList(
        "blah",
        this.fakeConfig(),
        this.provider
    ).get();
    Assertions.assertThat(instances).hasSize(1);
}
项目:turbine-ec2    文件:InstanceListTest.java   
/**
 * InstanceList can list instances.
 */
@Test
public void listsInstancesFromMultipleReservartions() {
    Mockito.when(
        this.client.describeInstances(
            Mockito.any(DescribeInstancesRequest.class)
        )
    ).thenReturn(
        new DescribeInstancesResult()
            .withReservations(
                Arrays.asList(
                    this.fakeReservation(),
                    this.fakeReservation(),
                    this.fakeReservation(),
                    this.fakeReservation()
                )
            )
    );

    final List<Instance> instances = new InstanceList(
        "blah",
        this.fakeConfig(),
        this.provider
    ).get();
    Assertions.assertThat(instances).hasSize(4);
}
项目:aws-auto-operations-using-lambda    文件:InstanceOperation.java   
public String getInstanceStateName(InstanceRequest instanceRequest, Context context) {

        AmazonEC2Async client = createEC2Client();
        try {
            DescribeInstancesResult result = client
                    .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceRequest.getInstanceId()));
            List<Instance> instances = result.getReservations().get(0).getInstances();
            if (instances.size() != 1) {
                throw new RuntimeException("instance can not be found.");
            }
            return instances.get(0).getState().getName();

        } finally {
            client.shutdown();
        }
    }
项目:photon-model    文件:AWSTaskStatusChecker.java   
private void runSearch(T type) {
    AmazonWebServiceRequest descRequest = buildRequest(type);
    AsyncHandler describeHandler = buildHandler(type);
    if (type instanceof Instance) {
        this.amazonEC2Client.describeInstancesAsync(
                (DescribeInstancesRequest) descRequest, describeHandler);
    } else if (type instanceof NatGateway) {
        this.amazonEC2Client.describeNatGatewaysAsync(
                (DescribeNatGatewaysRequest) descRequest, describeHandler);
    } else if (type instanceof Volume) {
        this.amazonEC2Client.describeVolumesAsync(
                (DescribeVolumesRequest) descRequest, describeHandler);
    } else {
        AWSTaskStatusChecker.this.taskManager.patchTaskToFailure(
                new IllegalArgumentException("Invalid type " + type));
    }
}
项目:photon-model    文件:AWSEnumerationAndDeletionAdapterService.java   
/**
 * Get the instances from AWS filtered by the instances Ids known to the local system.
 */
public void getRemoteInstances(EnumerationDeletionContext aws,
        AWSEnumerationDeletionSubStage next) {
    if (aws.localInstanceIds == null || aws.localInstanceIds.size() == 0) {
        logFine(() -> "No local records found. No states need to be fetched from the AWS"
                + " endpoint.");
        aws.subStage = next;
        deleteResourcesInLocalSystem(aws);
        return;
    }
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    Filter runningInstanceFilter = getAWSNonTerminatedInstancesFilter();
    request.getFilters().add(runningInstanceFilter);
    // Get only the instances from the remote system for which a compute state exists in the
    // local system.
    logFine(() -> String.format("Fetching instance details for %d instances on the AWS"
                    + " endpoint.", aws.localInstanceIds.keySet().size()));
    request.getInstanceIds().addAll(new ArrayList<>(aws.localInstanceIds.keySet()));
    AsyncHandler<DescribeInstancesRequest, DescribeInstancesResult> resultHandler =
            new AWSEnumerationAsyncHandler(this, aws, next);
    aws.amazonEC2Client.describeInstancesAsync(request,
            resultHandler);
}
项目: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;
}
项目:photon-model    文件:TestAWSSetupUtils.java   
/**
 * Method to get Instance details directly from Amazon
 *
 * @throws Throwable
 */
public static List<Instance> getAwsInstancesByIds(AmazonEC2AsyncClient client,
        VerificationHost host, List<String> instanceIds)
        throws Throwable {
    host.log("Getting instances with ids " + instanceIds
            + " from the AWS endpoint using the EC2 client.");

    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
            .withInstanceIds(instanceIds);

    DescribeInstancesResult describeInstancesResult = client
            .describeInstances(describeInstancesRequest);

    return describeInstancesResult.getReservations().stream()
            .flatMap(r -> r.getInstances().stream()).collect(Collectors.toList());
}
项目:photon-model    文件:TestAWSSetupUtils.java   
/**
 * Gets the instance count of non-terminated instances on the AWS endpoint. This is used to run
 * the asserts and validate the results for the data that is collected during enumeration.This
 * also calculates the compute descriptions that will be used to represent the instances that
 * were discovered on the AWS endpoint. Further factoring in the
 *
 * @throws Throwable
 */
public static BaseLineState getBaseLineInstanceCount(VerificationHost host,
        AmazonEC2AsyncClient client,
        List<String> testComputeDescriptions)
        throws Throwable {
    BaseLineState baseLineState = new BaseLineState();
    AWSEnumerationAsyncHandler enumerationHandler = new AWSEnumerationAsyncHandler(host,
            AWSEnumerationAsyncHandler.MODE.GET_COUNT, null, null, null,
            testComputeDescriptions,
            baseLineState);
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    Filter runningInstanceFilter = getAWSNonTerminatedInstancesFilter();
    request.getFilters().add(runningInstanceFilter);
    client.describeInstancesAsync(request, enumerationHandler);
    host.waitFor("Error waiting to get base line instance count from AWS in test ", () -> {
        return baseLineState.isCountPopulated;
    });
    return baseLineState;
}
项目:photon-model    文件:TestAWSSetupUtils.java   
/**
 * Checks if a newly deleted instance has its status set to terminated.
 *
 * @return
 */
public static void checkInstancesDeleted(AmazonEC2AsyncClient client,
        VerificationHost host, List<String> instanceIdsToDelete,
        ArrayList<Boolean> deletionFlags) throws Throwable {
    AWSEnumerationAsyncHandler enumerationHandler = new AWSEnumerationAsyncHandler(host,
            AWSEnumerationAsyncHandler.MODE.CHECK_TERMINATION, null, deletionFlags, null, null,
            null);
    DescribeInstancesRequest request = new DescribeInstancesRequest()
            .withInstanceIds(instanceIdsToDelete);
    client.describeInstancesAsync(request, enumerationHandler);
    // Waiting to get a response from AWS before the state computation is done for the list of
    // VMs.
    host.waitFor("Waiting to get response from AWS ", () -> {
        return enumerationHandler.responseReceived;
    });
}
项目:cerberus-lifecycle-cli    文件:AutoScalingService.java   
/**
 * For a given AutoScaling group logical id, get the public dns names associated with each instance.
 *
 * @param logicalId AutoScaling group logical id
 * @return List of public dns names
 */
public List<String> getPublicDnsForAutoScalingGroup(final String logicalId) {
    final List<String> instanceIds = Lists.newLinkedList();
    final Optional<AutoScalingGroup> autoScalingGroup = describeAutoScalingGroup(logicalId);
    final List<String> publicDnsNames = Lists.newLinkedList();

    if (autoScalingGroup.isPresent()) {
        autoScalingGroup.get()
                .getInstances().stream().forEach(instance -> instanceIds.add(instance.getInstanceId()));

        final DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
                .withInstanceIds(instanceIds);
        final DescribeInstancesResult describeInstancesResult =
                ec2Client.describeInstances(describeInstancesRequest);

        describeInstancesResult.getReservations().forEach(reservation ->
                reservation.getInstances().stream().forEach(instance ->
                        publicDnsNames.add(instance.getPublicDnsName()))
        );
    }

    return publicDnsNames;
}
项目:cerberus-lifecycle-cli    文件:Ec2Service.java   
/**
 * Gets all EC2 instances with the given tag key/value pair
 * @param tagKey - Key of the tag
 * @param tagValue - Value of the tag
 * @param filters - Array of EC2 filters
 * @return - List of instances with the given tag
 */
public List<Instance> getInstancesByTag(final String tagKey, final String tagValue, final Filter... filters) {
    final String filterName = String.format(FILTER_NAME_TEMPL_FOR_EC2_TAGS, tagKey);
    final Filter tagFilter = new Filter().withName(filterName).withValues(tagValue);

    final Set<Filter> filterSet = Sets.newHashSet(filters);
    filterSet.add(tagFilter);
    final DescribeInstancesRequest request = new DescribeInstancesRequest().withFilters(filterSet);

    DescribeInstancesResult result = ec2Client.describeInstances(request);
    List<Instance> instances = Lists.newArrayList();

    result.getReservations().forEach(reservation -> {
        instances.addAll(reservation.getInstances());
    });

    return instances;
}
项目: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));
}
项目:Camel    文件:EC2Producer.java   
private void describeInstances(AmazonEC2Client ec2Client, Exchange exchange) {
    Collection instanceIds;
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_IDS))) {
        instanceIds = exchange.getIn().getHeader(EC2Constants.INSTANCES_IDS, Collection.class);
        request.withInstanceIds(instanceIds);
    } 
    DescribeInstancesResult result;
    try {
        result = ec2Client.describeInstances(request);
    } catch (AmazonServiceException ase) {
        LOG.trace("Describe Instances command returned the error code {}", ase.getErrorCode());
        throw ase;
    }
    Message message = getMessageForResponse(exchange);
    message.setBody(result);        
}
项目: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;
}
项目:development    文件:EC2ProcessorTest.java   
@Test
public void process_STOPING() throws Exception {
    // given
    ec2mock.createDescribeInstancesResult("instance1", "stopped", "1.2.3.4");
    ec2mock.createDescribeInstanceStatusResult("instance1", "ok", "ok",
            "ok");
    ph.setOperation(Operation.EC2_OPERATION);
    ph.setState(FlowState.STOPPING);

    // when
    InstanceStatus result = ec2proc.process();

    // then
    assertTrue(result.isReady());
    assertEquals(FlowState.FINISHED, ph.getState());

    verify(ec2).describeInstances(any(DescribeInstancesRequest.class));
}
项目: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;
}
项目:cloud-runner    文件:Instance.java   
public static String getIp(String id) {
    if (id == null) {
        return null;
    }

    com.amazonaws.services.ec2.AmazonEC2 client = AmazonEC2.connect();

    DescribeInstancesRequest instanceReq = new DescribeInstancesRequest();
    List<String> instanceIds = new ArrayList<String>();
    instanceIds.add(id);
    instanceReq.setInstanceIds(instanceIds);

    DescribeInstancesResult instanceRes = client
            .describeInstances(instanceReq);

    String ip = null;

    try {
        ip = instanceRes.getReservations().get(0).getInstances().get(0)
                .getPublicIpAddress();
    } catch (Exception e) {
        logger.error("Error while getting the IP.", e);
    }

    return ip;
}
项目:fullstop    文件:EC2InstanceProviderImpl.java   
@Override
@Cacheable(cacheNames = "ec2-instance", cacheManager = "twoHoursTTLCacheManager")
public Optional<Instance> getById(final String accountId, final Region region, final String instanceId) {
    try {
        return clientProvider.getClient(AmazonEC2Client.class, accountId, region)
                .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceId))
                .getReservations().stream()
                .flatMap(reservation -> reservation.getInstances().stream())
                .filter(instance -> Objects.equals(instance.getInstanceId(), instanceId))
                .findFirst();
    } catch (AmazonEC2Exception e) {
        if (Objects.equals(e.getErrorCode(), "InvalidInstanceID.NotFound")) {
            return Optional.empty();
        } else {
            throw e;
        }
    }
}
项目: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();
    }
}
项目:fullstop    文件:ExamplePlugin.java   
@Override
// @HystrixCommand(fallback = my coole exception)
// command for account id and client type -> generate new credentials
public void processEvent(final CloudTrailEvent event) {

    final String parameters = event.getEventData().getRequestParameters();
    final String instanceId = getFromParameters(parameters);

    final AmazonEC2Client client = getClientForAccount(
            event.getEventData().getUserIdentity().getAccountId(),
            Region.getRegion(Regions.fromName(event.getEventData().getAwsRegion())));

    final DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(Collections.singleton(instanceId));

    // try
    final DescribeInstancesResult result = client.describeInstances(request);
    // catch credentials are old
    // throw new my coole exception ( account id, CLIENTTYPE.EC2, exception) -> this will trigger hystrix

    LOG.info("SAVING RESULT INTO MAGIC DB", result);
}
项目: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;
}
项目:scale.cloudpool    文件:GetInstances.java   
@Override
public List<Instance> call() {
    List<Instance> instances = new ArrayList<>();
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.withInstanceIds(this.instanceIds);
    request.withFilters(this.filters);
    // paginate through result as long as there is another response token
    boolean moreResults = false;
    do {
        DescribeInstancesResult result = getClient().getApi().describeInstances(request);
        instances.addAll(instances(result));
        moreResults = result.getNextToken() != null && !result.getNextToken().equals("");
        request.setNextToken(result.getNextToken());
    } while (moreResults);

    return instances;
}
项目: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);
            }
        }
    }
}
项目: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    文件: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;
}