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

The following examples show how to use com.amazonaws.services.ec2.model.InstanceStatus. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EC2Communication.java    From development with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: EC2Mockup.java    From development with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example #3
Source File: EC2Mockup.java    From development with Apache License 2.0 6 votes vote down vote up
public void addDescribeInstanceStatusResult(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);
    com.amazonaws.services.ec2.model.InstanceStatus instanceStatus = new com.amazonaws.services.ec2.model.InstanceStatus()
            .withInstanceId(instanceId).withInstanceState(state)
            .withInstanceStatus(instanceSummary)
            .withSystemStatus(systemSummary);
    DescribeInstanceStatusResult instanceStatusResult = new DescribeInstanceStatusResult()
            .withInstanceStatuses(instanceStatus);
    answerDescribeInstanceStatus.add(instanceStatusResult);
}
 
Example #4
Source File: Ec2InstanceStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
/**
 * This function is a wrapper to the ec2 describeInstanceStatus function.
 *
 * @param region
 * @return List of InstanceStatus
 */
public List<InstanceStatus> describeInstancesStatusAsync(Region region) throws Exception {

  Preconditions.checkNotNull(region);
  List<InstanceStatus> statusList = new ArrayList<>();
  List<AvailabilityZone> zones = getAvailabilityZones(region);
  AmazonEC2Client client = getClient(region);
  ExecutorService executor = Executors.newFixedThreadPool(zones.size());
  OperationStats op = new OperationStats("ec2InstanceStore", "describeInstancesStatusAsync");
  try {
    List<Callable<List<InstanceStatus>>> retrieveFunction = new ArrayList<>(zones.size());
    for (AvailabilityZone zone : zones) {
      retrieveFunction.add(new Callable<List<InstanceStatus>>() {
        @Override
        public List<InstanceStatus> call() throws Exception {
          return getInstancesStatusByZone(zone, client);
        }
      });
    }

    List<Future<List<InstanceStatus>>> futures = executor.invokeAll(retrieveFunction);
    for (Future<List<InstanceStatus>> future : futures) {
      statusList.addAll(future.get());
    }
    op.succeed();
  } catch (Exception ex) {
    op.failed();
    throw ex;
  } finally {
    executor.shutdown();
  }

  return statusList;
}
 
Example #5
Source File: Ec2InstanceStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #6
Source File: Ec2Util.java    From s3-bucket-loader with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #7
Source File: Ec2Util.java    From s3-bucket-loader with Apache License 2.0 5 votes vote down vote up
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;
	}
	
}
 
Example #8
Source File: AwsStatus.java    From soundwave with Apache License 2.0 4 votes vote down vote up
public InstanceStatus getRaw() {
  return raw;
}
 
Example #9
Source File: AwsStatus.java    From soundwave with Apache License 2.0 4 votes vote down vote up
public void setRaw(InstanceStatus raw) {
  this.raw = raw;
}
 
Example #10
Source File: Instance.java    From soundwave with Apache License 2.0 4 votes vote down vote up
private Response getAwsInstancesStatus(List<String> instanceIds) throws Exception {

    Map<String, Integer> statuses = new HashMap<>();
    for (String instanceId : instanceIds) {

      int intStatus = 0;
      EsAwsStatus status = cmdbInstanceStore.getAwsStatus(instanceId);

      if (status == null) {

        // Instance Status not found in cmdbStore . Mark status as -1
        logger.info("No status found for instanceId {}", instanceId);
        intStatus = -1;

      } else {

        AwsStatus awsStatus = status.getAwsStatus();
        if (awsStatus != null) {

          List<String> codes = awsStatus.getCodes();
          InstanceStatus raw = awsStatus.getRaw();
          String instanceStatus = raw.getInstanceStatus().getStatus();
          String systemStatus = raw.getSystemStatus().getStatus();

          if (codes != null) {

            if (StringUtils.equalsIgnoreCase(instanceStatus, "initializing")
                    || StringUtils.equalsIgnoreCase(systemStatus, "initializing")) {

              // codes are defined but one of the status is initializing
              logger.info("Aws Status requested. Instance is still initializing...");
              intStatus = 0;

            } else {

              // codes are present and system or instance status is abnormal
              logger.warn("Unhealthy instance was found. {} with status {} and {}",
                  instanceId, instanceStatus, systemStatus);
              intStatus = 1;
            }
          }

        }
      }

      // Add trimmed status of the instance to statuses Map
      statuses.put(instanceId, intStatus);

    }

    return Response.status(Response.Status.OK)
        .type(MediaType.APPLICATION_JSON)
        .entity(statuses)
        .build();
  }
 
Example #11
Source File: AwsInstanceStatusJob.java    From soundwave with Apache License 2.0 4 votes vote down vote up
private Boolean checkInstancesStatus() {

    try {
      // Type cast cloudInstanceStore to use ec2 functions
      Ec2InstanceStore ec2Store = (Ec2InstanceStore) cloudInstanceStore;

      // Fetch aws status for all instances in the given region
      List<InstanceStatus> statuses = ec2Store.describeInstancesStatusAsync(region);

      if (statuses == null) {
        logger.warn("AWS did not return any InstanceStatus");
        return false;
      }

      // Creates a reverse map of id to Status
      Map<String, InstanceStatus> idToInstanceStatus = new HashMap<>(statuses.size());

      for (InstanceStatus status : statuses) {
        idToInstanceStatus.put(status.getInstanceId(), status);
      }

      // Iterate over all Running CmdbInstances & add status updated ones to list
      Iterator<EsAwsStatus> iterator =
          cmdbInstanceStore.getRunningAndTerminatedAwsStatus(region, 1);

      List<EsAwsStatus> updateInstanceList = getUpdatedInstanceList(iterator, idToInstanceStatus);

      logger.info("Number of instances found to update AwsStatus = {}", updateInstanceList.size());

      // Log the count of healthy instances & unhealthy ones.
      logger.info("Total count: = {} and unhealthy nodes count with status"
          + " not ok = {}", total, badInstanceCount);

      // Update all instances healthy + non healthy in CMDB
      logger.info("Starting a bulk update for awsStatus tag...");
      cmdbInstanceStore.bulkUpdateAwsStatus(updateInstanceList);

      // Reset the counters to 0
      total = 0;
      badInstanceCount = 0;
      logger.info("Re initialized total to {} and badInstanceCount to {}", total, badInstanceCount);

      return true;

    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;

  }
 
Example #12
Source File: Master.java    From s3-bucket-loader with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {

		
		// seed start
		this.masterStartAt = new Date();
		
		/**
		 * START the source for our TOC... if specified
		 */
		if (this.sourceEc2StartStopInstanceId != null) {
			
			// already running?
			InstanceStatus alreadyRunning = ec2util.getInstanceStatus(this.ec2Client, this.sourceEc2StartStopInstanceId);
			if (alreadyRunning == null || !alreadyRunning.getInstanceState().getName().equalsIgnoreCase("running")) {
				this.ec2util.startInstance(this.ec2Client, this.sourceEc2StartStopInstanceId);
			}
			
			// check status
			boolean sourceEc2InstanceStarted = false;
			while(!sourceEc2InstanceStarted) {
				InstanceStatus status = ec2util.getInstanceStatus(this.ec2Client, this.sourceEc2StartStopInstanceId);
				if (status == null || !status.getInstanceState().getName().equalsIgnoreCase("running")) {
					sourceEc2InstanceStarted = false;
					logger.debug("Still waiting for source host instance ["+this.sourceEc2StartStopInstanceId+"] to be running....");
					Thread.currentThread().sleep(2000);
				} else {
					logger.debug("Up and RUNNING! source host instance ["+this.sourceEc2StartStopInstanceId+"]");
					sourceEc2InstanceStarted = true;
					break;
				}
			}

			
			if (this.sourceEc2PostStartCmd != null) {
				
				Thread.currentThread().sleep(30000);
				
				// run the 'master.source.host.post.start.cmd' command
				CmdResult postStartResult = new CommandExecutor().execute(CommandLine.parse(this.sourceEc2PostStartCmd), 3);
				if (postStartResult.getExitCode() > 0) {
					throw new Exception("Source host post start cmd failed: " + this.sourceEc2PostStartCmd);
				}
			}
			
		}

		
		if (props.getProperty("tocGenerator.source.dir") != null && !new File(props.getProperty("tocGenerator.source.dir")).exists()) {
			throw new Exception("'tocGenerator.source.dir' does not exist! " + props.getProperty("tocGenerator.source.dir"));
		}
		
		// initialize workers 
		this.currentMode = CCMode.INITIALIZED;
		this.controlChannel.send(true, CCPayloadType.MASTER_CURRENT_MODE, this.currentMode);
		
		// spawn ec2 cluster if specified
		spawnEC2();
		
		// start our own monitor
		this.masterMonitor = new Thread(this);
		this.masterMonitor.start();
		
		// @see handlePayload(CCPayload) for what happens next as workers come online
		
	}