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

项目:oscm    文件:EC2Communication.java   
public boolean isInstanceReady(String instanceId) {
    LOGGER.debug("isInstanceReady('{}') entered", instanceId);
    DescribeInstanceStatusResult result = getEC2()
            .describeInstanceStatus(
                    new DescribeInstanceStatusRequest()
                            .withInstanceIds(instanceId));
    List<InstanceStatus> statusList = result.getInstanceStatuses();
    boolean instanceStatus = false;
    boolean systemStatus = false;

    for (InstanceStatus status : statusList) {
        LOGGER.debug("  InstanceState:    {}", status.getInstanceState());
        LOGGER.debug("  InstanceStatus:   {}", status.getInstanceStatus()
                .getStatus());
        LOGGER.debug("  SystemStatus:     {}", status.getSystemStatus()
                .getStatus());
        LOGGER.debug("  AvailabilityZone: {}", status.getAvailabilityZone());

        instanceStatus = ("ok".equals(status.getInstanceStatus()
                .getStatus()));
        systemStatus = ("ok".equals(status.getSystemStatus().getStatus()));
    }
    LOGGER.debug("isInstanceReady('{}') left", instanceId);
    return instanceStatus && systemStatus;
}
项目:oscm    文件:EC2Mockup.java   
public void createDescribeInstanceStatusResult(String instanceId,
        String stateName, String instanceStatusName,
        String systemStatusName) {
    InstanceState state = new InstanceState().withName(stateName);
    InstanceStatusSummary instanceSummary = new InstanceStatusSummary()
            .withStatus(instanceStatusName);
    InstanceStatusSummary systemSummary = new InstanceStatusSummary()
            .withStatus(systemStatusName);
    InstanceStatus instanceStatus = new com.amazonaws.services.ec2.model.InstanceStatus()
            .withInstanceId(instanceId).withInstanceState(state)
            .withInstanceStatus(instanceSummary)
            .withSystemStatus(systemSummary);
    DescribeInstanceStatusResult instanceStatusResult = new DescribeInstanceStatusResult()
            .withInstanceStatuses(instanceStatus);
    doReturn(instanceStatusResult).when(ec2).describeInstanceStatus(
            any(DescribeInstanceStatusRequest.class));
}
项目:Camel    文件:EC2Producer.java   
private void describeInstancesStatus(AmazonEC2Client ec2Client, Exchange exchange) {
    Collection instanceIds;
    DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest();
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_IDS))) {
        instanceIds = exchange.getIn().getHeader(EC2Constants.INSTANCES_IDS, Collection.class);
        request.withInstanceIds(instanceIds);
    } 
    DescribeInstanceStatusResult result;
    try {
        result = ec2Client.describeInstanceStatus(request);
    } catch (AmazonServiceException ase) {
        LOG.trace("Describe Instances Status command returned the error code {}", ase.getErrorCode());
        throw ase;
    }
    Message message = getMessageForResponse(exchange);
    message.setBody(result);        
}
项目:development    文件:EC2Communication.java   
public boolean isInstanceReady(String instanceId) {
    LOGGER.debug("isInstanceReady('{}') entered", instanceId);
    DescribeInstanceStatusResult result = getEC2()
            .describeInstanceStatus(
                    new DescribeInstanceStatusRequest()
                            .withInstanceIds(instanceId));
    List<InstanceStatus> statusList = result.getInstanceStatuses();
    boolean instanceStatus = false;
    boolean systemStatus = false;

    for (InstanceStatus status : statusList) {
        LOGGER.debug("  InstanceState:    {}", status.getInstanceState());
        LOGGER.debug("  InstanceStatus:   {}", status.getInstanceStatus()
                .getStatus());
        LOGGER.debug("  SystemStatus:     {}", status.getSystemStatus()
                .getStatus());
        LOGGER.debug("  AvailabilityZone: {}", status.getAvailabilityZone());

        instanceStatus = ("ok".equals(status.getInstanceStatus()
                .getStatus()));
        systemStatus = ("ok".equals(status.getSystemStatus().getStatus()));
    }
    LOGGER.debug("isInstanceReady('{}') left", instanceId);
    return instanceStatus && systemStatus;
}
项目:development    文件:EC2Mockup.java   
public void createDescribeInstanceStatusResult(String instanceId,
        String stateName, String instanceStatusName,
        String systemStatusName) {
    InstanceState state = new InstanceState().withName(stateName);
    InstanceStatusSummary instanceSummary = new InstanceStatusSummary()
            .withStatus(instanceStatusName);
    InstanceStatusSummary systemSummary = new InstanceStatusSummary()
            .withStatus(systemStatusName);
    InstanceStatus instanceStatus = new com.amazonaws.services.ec2.model.InstanceStatus()
            .withInstanceId(instanceId).withInstanceState(state)
            .withInstanceStatus(instanceSummary)
            .withSystemStatus(systemSummary);
    DescribeInstanceStatusResult instanceStatusResult = new DescribeInstanceStatusResult()
            .withInstanceStatuses(instanceStatus);
    doReturn(instanceStatusResult).when(ec2).describeInstanceStatus(
            any(DescribeInstanceStatusRequest.class));
}
项目:data-lifecycle-service-broker    文件:AWSHelper.java   
private boolean waitForInstance(String instanceId) {
    log.info("Waiting for instance to transition to running");
    for (int i = 0; i < 5; ++i) {

        DescribeInstanceStatusResult result = ec2Client
                .describeInstanceStatus(new DescribeInstanceStatusRequest()
                        .withInstanceIds(instanceId));
        if (!result.getInstanceStatuses().isEmpty()) {
            String state = result.getInstanceStatuses().get(0)
                    .getInstanceState().getName();

            log.info("Instance state is " + state);

            if (state.equals("running")) {
                return true;
            }
        }

        sleep();

    }
    return false;
}
项目:cloud-runner    文件:Instance.java   
public InstanceStatus getInstanceStatus() {
    if (id == null) {
        getSpotStatus();
        if (id == null)
            return InstanceStatus.INSTANCE_NOT_FOUND;
    }

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

    DescribeInstanceStatusRequest instanceReq = new DescribeInstanceStatusRequest();
    List<String> instanceIds = new ArrayList<String>();
    instanceIds.add(id);
    instanceReq.setInstanceIds(instanceIds);
    DescribeInstanceStatusResult instanceRes = client
            .describeInstanceStatus(instanceReq);

    List<com.amazonaws.services.ec2.model.InstanceStatus> reqs = instanceRes
            .getInstanceStatuses();
    if (reqs.size() > 0)
        return InstanceStatus.valueFromStatus(reqs.get(0));
    else {
        return InstanceStatus.INSTANCE_NOT_FOUND;
    }
}
项目:aws-ec2-start-stop-tools    文件:AmazonEC2ServiceTest.java   
@Test
public void testStartInstance() {

    final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID);
    final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Stopped)));

    final StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(INSTANCE_ID);
    final StartInstancesResult startInstancesResult = new StartInstancesResult().withStartingInstances(new InstanceStateChange().withCurrentState(new InstanceState().withName(InstanceStateName.Running)));

    Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    Mockito.doReturn(startInstancesResult).when(amazonEC2Client).startInstances(startInstancesRequest);

    amazonEC2Service.startInstance(INSTANCE_ID);

    final InOrder inOrder = Mockito.inOrder(amazonEC2Client);
    inOrder.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    inOrder.verify(amazonEC2Client).startInstances(startInstancesRequest);
}
项目:aws-ec2-start-stop-tools    文件:AmazonEC2ServiceTest.java   
@Test
public void testStopInstanceStopping() {

    final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID);
    final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running)));

    final StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(INSTANCE_ID);
    final StopInstancesResult stopInstancesResult = new StopInstancesResult().withStoppingInstances(new InstanceStateChange().withCurrentState(new InstanceState().withName(InstanceStateName.Stopping)));

    Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    Mockito.doReturn(stopInstancesResult).when(amazonEC2Client).stopInstances(stopInstancesRequest);

    amazonEC2Service.stopInstance(INSTANCE_ID);

    final InOrder inOrder = Mockito.inOrder(amazonEC2Client);
    inOrder.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    inOrder.verify(amazonEC2Client).stopInstances(stopInstancesRequest);
}
项目:aws-ec2-start-stop-tools    文件:AmazonEC2ServiceTest.java   
@Test
public void testStopInstanceStopped() {

    final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID);
    final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running)));

    final StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(INSTANCE_ID);
    final StopInstancesResult stopInstancesResult = new StopInstancesResult().withStoppingInstances(new InstanceStateChange().withCurrentState(new InstanceState().withName(InstanceStateName.Stopped)));

    Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    Mockito.doReturn(stopInstancesResult).when(amazonEC2Client).stopInstances(stopInstancesRequest);

    amazonEC2Service.stopInstance(INSTANCE_ID);

    final InOrder inOrder = Mockito.inOrder(amazonEC2Client);
    inOrder.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    inOrder.verify(amazonEC2Client).stopInstances(stopInstancesRequest);
}
项目:oscm    文件:EC2Mockup.java   
public EC2Mockup() {
    ec2 = mock(AmazonEC2Client.class);

    answerDescribeInstances = new FifoAnswer<DescribeInstancesResult>();
    doAnswer(answerDescribeInstances).when(ec2)
            .describeInstances(any(DescribeInstancesRequest.class));

    answerDescribeInstanceStatus = new FifoAnswer<DescribeInstanceStatusResult>();
    doAnswer(answerDescribeInstanceStatus).when(ec2).describeInstanceStatus(
            any(DescribeInstanceStatusRequest.class));

}
项目:soundwave    文件:Ec2InstanceStore.java   
private List<InstanceStatus> getInstancesStatusByZone(AvailabilityZone zone,
                                                      AmazonEC2Client client) {

  // Create this list to capture paginated async results from aws sdk
  List<InstanceStatus> statusList = new ArrayList<>();

  // Create an initial request object
  DescribeInstanceStatusRequest statusRequest = new DescribeInstanceStatusRequest()
      .withMaxResults(1000)
      .withFilters(new Filter("availability-zone", Arrays.asList(zone.getZoneName())))
      .withSdkClientExecutionTimeout(600 * 1000)
      .withSdkRequestTimeout(300 * 1000);

  // Make the request for instanceStatus
  DescribeInstanceStatusResult result = client.describeInstanceStatus(statusRequest);

  // Until more results are available we loop through this code
  while (result != null) {

    statusList.addAll(result.getInstanceStatuses());

    if (result.getNextToken() != null) {

      statusRequest.setNextToken(result.getNextToken());
      result = client.describeInstanceStatus(statusRequest);

    } else {
      result = null;
    }
  }

  // Return all statuses as a list of InstanceStatus objects
  return statusList;
}
项目:photon-model    文件:TestAWSSetupUtils.java   
/**
 * Get the state of the EC2 instance.
 */
public static String getVMState(AmazonEC2Client client,String id) {
    DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest();
    request.withInstanceIds(id);
    request.withIncludeAllInstances(Boolean.TRUE);
    DescribeInstanceStatusResult result = client.describeInstanceStatus(request);
    return result.getInstanceStatuses().get(0).getInstanceState().getName();
}
项目:director-aws-plugin    文件:EC2Provider.java   
/**
 * Waits until the instance has entered a running state.
 *
 * @param ec2InstanceId the EC2 instance id
 * @return true if the instance has entered a running state, false if the instance is shutting down/terminated or
 * the function has timed out waiting for the instance to enter one of these two states.
 */
private boolean waitUntilInstanceHasStarted(String ec2InstanceId) throws InterruptedException {
  // TODO: Add a timeout to this loop.
  while (true) {
    try {
      DescribeInstanceStatusResult result = client.describeInstanceStatus(
          new DescribeInstanceStatusRequest()
              .withIncludeAllInstances(true)
              .withInstanceIds(ec2InstanceId)
      );
      for (InstanceStatus status : result.getInstanceStatuses()) {
        InstanceStateName currentState =
            InstanceStateName.fromValue(status.getInstanceState().getName());

        if (ec2InstanceId.equals(status.getInstanceId())) {
          if (currentState.equals(InstanceStateName.Terminated) ||
              currentState.equals(InstanceStateName.ShuttingDown)) {
            LOG.error("Instance {} has unexpectedly terminated", ec2InstanceId);
            return false;
          } else if (!currentState.equals(InstanceStateName.Pending)) {
            return true;
          }
        }
      }
    } catch (AmazonServiceException e) {
      if (!INVALID_INSTANCE_ID_NOT_FOUND.equals(e.getErrorCode())) {
        AWSExceptions.propagate(e);
      }
    }
    TimeUnit.SECONDS.sleep(5);
  }
}
项目:development    文件:EC2Mockup.java   
public EC2Mockup() {
    ec2 = mock(AmazonEC2Client.class);

    answerDescribeInstances = new FifoAnswer<DescribeInstancesResult>();
    doAnswer(answerDescribeInstances).when(ec2)
            .describeInstances(any(DescribeInstancesRequest.class));

    answerDescribeInstanceStatus = new FifoAnswer<DescribeInstanceStatusResult>();
    doAnswer(answerDescribeInstanceStatus).when(ec2).describeInstanceStatus(
            any(DescribeInstanceStatusRequest.class));

}
项目:cloud-runner    文件:Instance.java   
public static InstanceStatus getInstanceStatus(String id) {
    if (id == null) {
        return InstanceStatus.INSTANCE_NOT_FOUND;
    }

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

    DescribeInstanceStatusRequest instanceReq = new DescribeInstanceStatusRequest();
    List<String> instanceIds = new ArrayList<String>();
    instanceIds.add(id);
    instanceReq.setInstanceIds(instanceIds);
    DescribeInstanceStatusResult instanceRes;
    try {
        instanceRes = client
                .describeInstanceStatus(instanceReq);
    } catch (Exception e) {
        return InstanceStatus.INSTANCE_NOT_FOUND;
    }

    List<com.amazonaws.services.ec2.model.InstanceStatus> reqs = instanceRes
            .getInstanceStatuses();
    if (reqs.size() > 0)
        return InstanceStatus.valueFromStatus(reqs.get(0));
    else {
        return InstanceStatus.INSTANCE_NOT_FOUND;
    }
}
项目:cmn-project    文件:EC2.java   
public void waitUntilRunning(List<String> instanceIds) throws InterruptedException {
    int attempts = 0;
    while (true) {
        attempts++;
        Threads.sleepRoughly(Duration.ofSeconds(30));
        List<InstanceStatus> statuses = ec2.describeInstanceStatus(new DescribeInstanceStatusRequest()
            .withInstanceIds(instanceIds)).getInstanceStatuses();

        if (statuses.size() < instanceIds.size()) {
            logger.info("status is not synced, continue to wait");
            continue;
        }

        for (InstanceStatus status : statuses) {
            logger.info("instance status {} => {}, checks => {}, {}",
                status.getInstanceId(),
                status.getInstanceState().getName(),
                status.getSystemStatus().getStatus(),
                status.getInstanceStatus().getStatus());
        }

        boolean allOK = statuses.stream().allMatch(status ->
            "running".equalsIgnoreCase(status.getInstanceState().getName())
                && "ok".equalsIgnoreCase(status.getSystemStatus().getStatus())
                && "ok".equalsIgnoreCase(status.getInstanceStatus().getStatus()));

        if (allOK) {
            break;
        } else if (attempts > 20) { // roughly after 10 mins
            throw new Error("waited too long to get instance status, something is wrong, please check aws console");
        }
    }
}
项目:cmn-project    文件:DeployASGroupTask.java   
private void waitUntilInstanceRunning(List<String> newInstanceIds) throws InterruptedException {
    while (true) {
        Threads.sleepRoughly(Duration.ofSeconds(30));
        List<InstanceStatus> statuses = AWS.ec2.ec2.describeInstanceStatus(new DescribeInstanceStatusRequest()
            .withInstanceIds(newInstanceIds)).getInstanceStatuses();

        for (InstanceStatus status : statuses) {
            logger.info("instance status {} => {}, checks => {}, {}",
                status.getInstanceId(),
                status.getInstanceState().getName(),
                status.getSystemStatus().getStatus(),
                status.getInstanceStatus().getStatus());
        }

        boolean allOK = statuses.stream().allMatch(status ->
                "running".equalsIgnoreCase(status.getInstanceState().getName())
                    && "ok".equalsIgnoreCase(status.getSystemStatus().getStatus())
                    && "ok".equalsIgnoreCase(status.getInstanceStatus().getStatus())
        );

        if (allOK) {
            logger.info("all new instances are running");
            break;
        } else {
            logger.info("continue to wait, not all new instances are running");
        }
    }
}
项目:aws-ec2-start-stop-tools    文件:AmazonEC2ServiceTest.java   
@Test(expected = AmazonClientException.class)
public void testStartInstanceAlreadyRunning() {

    final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID);
    final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running)));

    Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);

    try {
        amazonEC2Service.startInstance(INSTANCE_ID);
    }
    finally {
        Mockito.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    }
}
项目:aws-ec2-start-stop-tools    文件:AmazonEC2ServiceTest.java   
@Test(expected = AmazonClientException.class)
public void testStopInstanceAlreadyStopped() {

    final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID);
    final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Stopped)));
    Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);

    try {
        amazonEC2Service.stopInstance(INSTANCE_ID);
    }
    finally {
        Mockito.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    }
}
项目:aws-ec2-start-stop-tools    文件:AmazonEC2ServiceTest.java   
@Test(expected = AmazonClientException.class)
public void testGetInstanceStatusNull() {

    final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID);
    try {
        amazonEC2Service.getInstanceStatus(INSTANCE_ID);
    }
    finally {
        Mockito.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    }
}
项目:aws-ec2-start-stop-tools    文件:AmazonEC2ServiceTest.java   
@Test(expected = AmazonClientException.class)
public void testGetInstanceStatusEmpty() {

    final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID);
    final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult();

    Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);

    try {
        amazonEC2Service.getInstanceStatus(INSTANCE_ID);
    }
    finally {
        Mockito.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    }
}
项目:aws-ec2-start-stop-tools    文件:AmazonEC2ServiceTest.java   
@Test(expected = AmazonClientException.class)
public void testGetInstanceStatusMultipleInstances() {

    final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID);
    final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running)), new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running)));

    Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);

    try {
        amazonEC2Service.getInstanceStatus(INSTANCE_ID);
    }
    finally {
        Mockito.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
    }
}
项目:s3-bucket-loader    文件:Ec2Util.java   
public InstanceStatus getInstanceStatus(AmazonEC2Client ec2Client, String instanceId) {
    List<String> instanceIds = new ArrayList<String>();
    instanceIds.add(instanceId);
    DescribeInstanceStatusRequest statusReq = new DescribeInstanceStatusRequest();
    statusReq.setInstanceIds(instanceIds);
    DescribeInstanceStatusResult result = ec2Client.describeInstanceStatus(statusReq);
    List<InstanceStatus> statuses = result.getInstanceStatuses();
    if (statuses == null || statuses.size() == 0) {
        return null;
    }
    return statuses.iterator().next();
}
项目:s3-bucket-loader    文件:Ec2Util.java   
public List<String> dumpEc2InstanceStatus(AmazonEC2Client ec2Client, List<Instance> ec2Instances) {
    try {
        List<String> instanceIds = new ArrayList<String>();

        for (Instance ec2node : ec2Instances) {
            instanceIds.add(ec2node.getInstanceId());
        }

        DescribeInstanceStatusRequest statusReq = new DescribeInstanceStatusRequest();
        statusReq.setInstanceIds(instanceIds);
        DescribeInstanceStatusResult result = ec2Client.describeInstanceStatus(statusReq);

        List<InstanceStatus> statuses = result.getInstanceStatuses();

        List<String> impairedInstances = new ArrayList<String>();

        StringBuffer sb = new StringBuffer("EC2 worker instance STATUS:\n");
        for (InstanceStatus status : statuses) {
            sb.append("\tid:"+status.getInstanceId() + 
                    "\taz:" + status.getAvailabilityZone() + 
                    "\tstate:" + status.getInstanceState().getName() + 
                    "\tstatus:" + status.getInstanceStatus().getStatus() + 
                    "\tsystem_status: " + status.getSystemStatus().getStatus() + "\n"); 

            if (status.getInstanceStatus().getStatus().equalsIgnoreCase("impaired")) {
                impairedInstances.add(status.getInstanceId());
            }
        }

        logger.info(sb.toString()+"\n");

        return impairedInstances;

    } catch(Exception e) {
        logger.error("Error getting instance state: " + e.getMessage(),e);
        return null;
    }

}
项目:elasticsearch_my    文件:AmazonEC2Mock.java   
@Override
public DescribeInstanceStatusResult describeInstanceStatus(DescribeInstanceStatusRequest describeInstanceStatusRequest) throws AmazonServiceException, AmazonClientException {
    throw new UnsupportedOperationException("Not supported in mock");
}
项目:director-aws-plugin    文件:EC2Provider.java   
/**
 * Returns a map from virtual instance IDs to instance state for the specified batch of virtual
 * instance IDs.
 *
 * @param virtualInstanceIds batch of virtual instance IDs
 * @return the map from instance IDs to instance state for the specified batch of virtual
 * instance IDs
 */
private Map<String, InstanceState> getBatchInstanceState(Collection<String> virtualInstanceIds) {
  Map<String, InstanceState> instanceStateByVirtualInstanceId =
      Maps.newHashMapWithExpectedSize(virtualInstanceIds.size());

  BiMap<String, String> virtualInstanceIdsByEC2InstanceId =
      getEC2InstanceIdsByVirtualInstanceId(virtualInstanceIds).inverse();

  int page = 0;
  LOG.info(">> Fetching page {}", page);

  if (virtualInstanceIdsByEC2InstanceId.isEmpty()) {
    // No EC2 instances are found, which means these id's are already terminated and gone.
    // In practice, this is possible when no instances were provisioned to begin with.
    // For example, when a deployment fails due to tagging error.
    return instanceStateByVirtualInstanceId;
  }

  DescribeInstanceStatusResult result = client.describeInstanceStatus(
      new DescribeInstanceStatusRequest()
          // Note that sending in an empty set will result in fetching _all_ instance Ids.
          // It requires you to send one or more EC2 Ids
          .withInstanceIds(virtualInstanceIdsByEC2InstanceId.keySet())
          .withIncludeAllInstances(true)
  );
  LOG.info("<< Result: {}", result);

  while (!result.getInstanceStatuses().isEmpty()) {
    for (InstanceStatus status : result.getInstanceStatuses()) {

      InstanceStateName currentState =
          InstanceStateName.fromValue(status.getInstanceState().getName());
      String ec2InstanceId = status.getInstanceId();
      String virtualInstanceId = virtualInstanceIdsByEC2InstanceId.get(ec2InstanceId);
      InstanceState instanceState = EC2InstanceState.fromInstanceStateName(currentState);
      instanceStateByVirtualInstanceId.put(virtualInstanceId, instanceState);
    }

    String nextToken = result.getNextToken();
    if (nextToken != null) {
      page++;
      LOG.info(">> Fetching page {} using token {}", page, nextToken);
      result = client.describeInstanceStatus(new DescribeInstanceStatusRequest()
          .withNextToken(nextToken));
      LOG.info("<< Result: {}", result);
    } else {
      break;
    }
  }

  return instanceStateByVirtualInstanceId;
}
项目:dohko    文件:EC2.java   
@Override
public void stop(final String... instanceIds)
{
    if (instanceIds != null && instanceIds.length > 0)
    {
        final long startTime = System.nanoTime();

        StopInstancesResult stopInstancesResult = ec2_.stopInstances(new StopInstancesRequest().withInstanceIds(instanceIds));
        List<Callable<org.excalibur.service.aws.ConfigurationService.InstanceStateType>> tasks = newArrayList();

        for (final InstanceStateChange state: stopInstancesResult.getStoppingInstances())
        {
            tasks.add(new Callable<org.excalibur.service.aws.ConfigurationService.InstanceStateType>()
            {
                BackoffLimitedRetryHandler backoffLimitedRetryHandler = new BackoffLimitedRetryHandler();

                @Override
                public org.excalibur.service.aws.ConfigurationService.InstanceStateType call() throws Exception
                {
                    InstanceState currentState = state.getCurrentState();
                    org.excalibur.service.aws.ConfigurationService.InstanceStateType finalState = 
                            org.excalibur.service.aws.ConfigurationService.InstanceStateType.STOPPED;

                    int failureCount = 0;

                    do
                    {
                        if ("stopping".equalsIgnoreCase(currentState.getName()))
                        {
                            backoffLimitedRetryHandler.imposeBackoffExponentialDelay(1000, 2, failureCount++, 1000, String.format("waiting instance%:s", state.getInstanceId()));

                            currentState = ec2_
                                    .describeInstanceStatus(new DescribeInstanceStatusRequest().withInstanceIds(state.getInstanceId()))
                                    .getInstanceStatuses().get(0).getInstanceState();
                        }
                    } while (!finalState.getValue().equalsIgnoreCase(currentState.getName()));

                    System.out.println(state.getInstanceId() + "=" + (System.nanoTime() - startTime));

                    return finalState;
                }
            });
        }

        invokeAll(tasks);

        long end = System.nanoTime() - startTime;
        System.out.println(end);
    }
}
项目:cloudbreak    文件:ASGroupStatusCheckerTask.java   
@Override
protected Boolean doCall() {
    LOGGER.info("Checking status of Auto Scaling group '{}'", autoScalingGroupName);
    AmazonEC2Client amazonEC2Client = awsClient.createAccess(new AwsCredentialView(getAuthenticatedContext().getCloudCredential()),
            getAuthenticatedContext().getCloudContext().getLocation().getRegion().value());
    List<String> instanceIds = cloudFormationStackUtil.getInstanceIds(autoScalingClient, autoScalingGroupName);
    if (instanceIds.size() < requiredInstances) {
        LOGGER.debug("Instances in AS group: {}, needed: {}", instanceIds.size(), requiredInstances);
        List<Activity> activities = getAutoScalingActivities();
        if (latestActivity.isPresent()) {
            checkForSpotRequest(latestActivity.get(), amazonEC2Client);
            activities = activities.stream().filter(activity -> activity.getStartTime().after(latestActivity.get().getStartTime()))
                    .collect(Collectors.toList());
        }
        updateLatestActivity(activities);
        checkFailedActivities(activities);
        return false;
    }
    List<DescribeInstanceStatusResult> describeInstanceStatusResultList = new ArrayList<>();

    List<List<String>> partitionedInstanceIdsList = Lists.partition(instanceIds, MAX_INSTANCE_ID_SIZE);

    for (List<String> partitionedInstanceIds : partitionedInstanceIdsList) {
        DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withInstanceIds(partitionedInstanceIds);
        DescribeInstanceStatusResult describeResult = amazonEC2Client.describeInstanceStatus(describeInstanceStatusRequest);
        describeInstanceStatusResultList.add(describeResult);
    }

    List<InstanceStatus> instanceStatusList = describeInstanceStatusResultList.stream()
            .flatMap(describeInstanceStatusResult -> describeInstanceStatusResult.getInstanceStatuses().stream())
            .collect(Collectors.toList());

    if (instanceStatusList.size() < requiredInstances) {
        LOGGER.debug("Instances up: {}, needed: {}", instanceStatusList.size(), requiredInstances);
        return false;
    }

    for (InstanceStatus status : instanceStatusList) {
        if (INSTANCE_RUNNING != status.getInstanceState().getCode()) {
            LOGGER.debug("Instances are up but not all of them are in running state.");
            return false;
        }
    }
    return true;
}
项目:cloudbreak    文件:ASGroupStatusCheckerTaskTest.java   
@Test
public void successTest() throws Exception {
    int requiredInstances = 160;
    AuthenticatedContext authenticatedContext = mock(AuthenticatedContext.class);

    CloudContext cloudContext = mock(CloudContext.class);
    String regionName = "eu-west-1";
    when(cloudContext.getLocation()).thenReturn(Location.location(Region.region(regionName)));

    when(authenticatedContext.getCloudContext()).thenReturn(cloudContext);

    CloudCredential cloudCredential = mock(CloudCredential.class);
    when(authenticatedContext.getCloudCredential()).thenReturn(cloudCredential);

    String asGroupName = "as-group";
    AwsClient awsClient = mock(AwsClient.class);
    AmazonEC2Client amazonEC2Client = mock(AmazonEC2Client.class);
    when(awsClient.createAccess(any(AwsCredentialView.class), eq(regionName))).thenReturn(amazonEC2Client);

    DescribeInstanceStatusResult firstDescribeInstanceStatusResult = new DescribeInstanceStatusResult();
    List<InstanceStatus> firstInstanceStatuses = returnInstanceStatus(0, 100);
    firstDescribeInstanceStatusResult.setInstanceStatuses(firstInstanceStatuses);

    DescribeInstanceStatusResult secondDescribeInstanceStatusResult = new DescribeInstanceStatusResult();
    List<InstanceStatus> secondInstanceStatuses = returnInstanceStatus(100, 160);
    secondDescribeInstanceStatusResult.setInstanceStatuses(secondInstanceStatuses);

    when(amazonEC2Client.describeInstanceStatus(any(DescribeInstanceStatusRequest.class)))
            .thenReturn(firstDescribeInstanceStatusResult)
            .thenReturn(secondDescribeInstanceStatusResult);

    CloudFormationStackUtil cloudFormationStackUtil = mock(CloudFormationStackUtil.class);

    List<String> instancIds = new ArrayList<>();
    for (int i = 0; i < requiredInstances; i++) {
        instancIds.add(Integer.toString(i));
    }

    AmazonAutoScalingClient autoScalingClient = mock(AmazonAutoScalingClient.class);
    when(awsClient.createAutoScalingClient(any(AwsCredentialView.class), anyString())).thenReturn(autoScalingClient);
    when(autoScalingClient.describeScalingActivities(any(DescribeScalingActivitiesRequest.class))).thenReturn(new DescribeScalingActivitiesResult());

    when(cloudFormationStackUtil.getInstanceIds(any(AmazonAutoScalingClient.class), eq(asGroupName))).thenReturn(instancIds);

    ASGroupStatusCheckerTask asGroupStatusCheckerTask = new ASGroupStatusCheckerTask(authenticatedContext, asGroupName, requiredInstances, awsClient,
            cloudFormationStackUtil);
    Boolean taskResult = asGroupStatusCheckerTask.call();

    ArgumentCaptor<DescribeInstanceStatusRequest> instanceStatusRequestArgumentCaptor = ArgumentCaptor.forClass(DescribeInstanceStatusRequest.class);
    verify(amazonEC2Client, times(2)).describeInstanceStatus(instanceStatusRequestArgumentCaptor.capture());

    List<DescribeInstanceStatusRequest> allValues = instanceStatusRequestArgumentCaptor.getAllValues();
    assertEquals(100, allValues.get(0).getInstanceIds().size());
    assertEquals(60, allValues.get(1).getInstanceIds().size());
    assertTrue(taskResult);
}
项目:cloudbreak    文件:ASGroupStatusCheckerTaskTest.java   
@Test
public void failTest() throws Exception {
    int requiredInstances = 160;
    AuthenticatedContext authenticatedContext = mock(AuthenticatedContext.class);

    CloudContext cloudContext = mock(CloudContext.class);
    String regionName = "eu-west-1";
    when(cloudContext.getLocation()).thenReturn(Location.location(Region.region(regionName)));

    when(authenticatedContext.getCloudContext()).thenReturn(cloudContext);

    CloudCredential cloudCredential = mock(CloudCredential.class);
    when(authenticatedContext.getCloudCredential()).thenReturn(cloudCredential);

    String asGroupName = "as-group";
    AwsClient awsClient = mock(AwsClient.class);
    AmazonEC2Client amazonEC2Client = mock(AmazonEC2Client.class);
    when(awsClient.createAccess(any(AwsCredentialView.class), eq(regionName))).thenReturn(amazonEC2Client);

    DescribeInstanceStatusResult firstDescribeInstanceStatusResult = new DescribeInstanceStatusResult();
    List<InstanceStatus> firstInstanceStatuses = returnInstanceStatus(0, 99);
    firstDescribeInstanceStatusResult.setInstanceStatuses(firstInstanceStatuses);

    DescribeInstanceStatusResult secondDescribeInstanceStatusResult = new DescribeInstanceStatusResult();
    List<InstanceStatus> secondInstanceStatuses = returnInstanceStatus(100, 160);
    secondDescribeInstanceStatusResult.setInstanceStatuses(secondInstanceStatuses);

    when(amazonEC2Client.describeInstanceStatus(any(DescribeInstanceStatusRequest.class)))
            .thenReturn(firstDescribeInstanceStatusResult)
            .thenReturn(secondDescribeInstanceStatusResult);

    CloudFormationStackUtil cloudFormationStackUtil = mock(CloudFormationStackUtil.class);

    List<String> instancIds = new ArrayList<>();
    for (int i = 0; i < requiredInstances; i++) {
        instancIds.add(Integer.toString(i));
    }

    AmazonAutoScalingClient autoScalingClient = mock(AmazonAutoScalingClient.class);
    when(awsClient.createAutoScalingClient(any(AwsCredentialView.class), anyString())).thenReturn(autoScalingClient);
    when(autoScalingClient.describeScalingActivities(any(DescribeScalingActivitiesRequest.class))).thenReturn(new DescribeScalingActivitiesResult());

    when(cloudFormationStackUtil.getInstanceIds(any(AmazonAutoScalingClient.class), eq(asGroupName))).thenReturn(instancIds);

    ASGroupStatusCheckerTask asGroupStatusCheckerTask = new ASGroupStatusCheckerTask(authenticatedContext, asGroupName, requiredInstances, awsClient,
            cloudFormationStackUtil);
    Boolean taskResult = asGroupStatusCheckerTask.call();

    ArgumentCaptor<DescribeInstanceStatusRequest> instanceStatusRequestArgumentCaptor = ArgumentCaptor.forClass(DescribeInstanceStatusRequest.class);
    verify(amazonEC2Client, times(2)).describeInstanceStatus(instanceStatusRequestArgumentCaptor.capture());

    List<DescribeInstanceStatusRequest> allValues = instanceStatusRequestArgumentCaptor.getAllValues();
    assertEquals(100, allValues.get(0).getInstanceIds().size());
    assertEquals(60, allValues.get(1).getInstanceIds().size());
    assertFalse(taskResult);
}
项目:aws-ec2-start-stop-tools    文件:AmazonEC2ServiceTest.java   
@Test
public void testGetInstanceStatus() {

    final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID);
    final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running)));

    Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);

    Assertions.assertThat(amazonEC2Service.getInstanceStatus(INSTANCE_ID)).isEqualTo(InstanceStateName.Running);

    Mockito.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest);
}