Example usage for com.amazonaws.services.ec2.model StopInstancesResult getStoppingInstances

List of usage examples for com.amazonaws.services.ec2.model StopInstancesResult getStoppingInstances

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model StopInstancesResult getStoppingInstances.

Prototype


public java.util.List<InstanceStateChange> getStoppingInstances() 

Source Link

Document

Information about the stopped instances.

Usage

From source file:de.fischer.thotti.ec2.clients.EC2Stopper.java

License:Apache License

private void executeRequest(EC2RequestData<StopInstancesRequest> requestData) throws AWSCommunicationException {
    int requestID = 1;
    Map<String, SortedSet<Instance>> instances = new HashMap<String, SortedSet<Instance>>();
    List<Region> awsRegions = getAWSRegions();

    // @todo this should be a separate method
    for (Region region : awsRegions) {
        EC2RunnerContext context = new EC2RunnerContext();

        context.regionName = region.getRegionName();
        context.endPoint = region.getEndpoint();

        getRegionContextCache().put(context.regionName, context);
    }/*from   w w  w  .  ja  v a  2 s  . c o  m*/

    for (String regionName : requestData.getAllRegions()) {
        EC2RunnerContext ctx = getRegionContextCache().get(regionName);
        Comparator comparator = new EC2Executor.InstaceAvailabilityComparator();
        SortedSet<Instance> describedInstances = new TreeSet<Instance>(comparator);

        setRegionContext(ctx);
        switchCommunicationEndPoint();

        RegionRequests regionRequests = requestData.getRegion(regionName);
        List<StopInstancesRequest> runRequests = regionRequests.getRequests();

        for (StopInstancesRequest request : runRequests) {
            if (logger.isInfoEnabled()) {
                List<String> idList = request.getInstanceIds();

                for (String id : idList) {
                    logger.info("Going to stop instance {} in " + "region {} ({}). Internal request ID is #{}.",
                            new Object[] { id, regionName, requestID });
                }
            }

            StopInstancesResult result = null;

            try {
                result = getClient().stopInstances(request);
            } catch (AmazonServiceException ase) {
                handleAmazonServiceException(ase);
            } catch (AmazonClientException ace) {
                handleAmazonClientException(ace);
            }

            // @todo here we should check, if Amazon terminated all requested instances, Oliver Fischer, 15. June 2011
            if (logger.isInfoEnabled()) {
                for (InstanceStateChange stateChange : result.getStoppingInstances()) {

                    logger.info("Amazon AWS changed state of instance {} from {} to {}",
                            new Object[] { stateChange.getInstanceId(), stateChange.getPreviousState(),
                                    stateChange.getCurrentState() });
                }

                requestID++; // For the next request

                instances.put(regionName, describedInstances);
            }
        }
    }
}

From source file:jenkins.plugins.ec2slave.EC2ImageLaunchWrapper.java

License:Open Source License

public void stopInstance(PrintStream logger) {
    logger.println("EC2InstanceComputerLauncher: Stopping EC2 instance [" + instanceId + "] ...");
    if (testMode)
        return;//w  w  w .  j a va 2s .c  o m

    StopInstancesResult result = ec2.stopInstances(new StopInstancesRequest().withInstanceIds(instanceId));
    if (result.getStoppingInstances().size() > 0
            && result.getStoppingInstances().get(0).getCurrentState().equals(InstanceStateName.Stopped)
            && result.getStoppingInstances().get(0).getInstanceId().equals(instanceId)) {
        logger.println("EC2InstanceComputerLauncher: Stopped EC2 instance [" + instanceId + "] ...");
    }
}

From source file:jp.primecloud.auto.process.aws.AwsInstanceProcess.java

License:Open Source License

public void stop(AwsProcessClient awsProcessClient, Long instanceNo) {
    AwsInstance awsInstance = awsInstanceDao.read(instanceNo);
    String instanceId = awsInstance.getInstanceId();

    // /*from   w w  w  . j ava  2s  . c  o m*/
    Instance instance = instanceDao.read(instanceNo);
    processLogger.debug(null, instance, "AwsInstanceStop",
            new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId });

    // ??
    StopInstancesRequest request = new StopInstancesRequest();
    request.withInstanceIds(instanceId);
    StopInstancesResult result = awsProcessClient.getEc2Client().stopInstances(request);
    List<InstanceStateChange> stoppingInstances = result.getStoppingInstances();

    // API??
    if (stoppingInstances.size() == 0) {
        // ?
        throw new AutoException("EPROCESS-000128", instanceId);

    } else if (stoppingInstances.size() > 1) {
        // ??????
        AutoException exception = new AutoException("EPROCESS-000130", instanceId);
        exception.addDetailInfo("result=" + stoppingInstances);
        throw exception;
    }

    // 
    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100113", instanceId));
    }

    // 
    awsInstance.setStatus(stoppingInstances.get(0).getCurrentState().getName());
    awsInstanceDao.update(awsInstance);
}

From source file:org.excalibur.service.aws.ec2.EC2.java

License:Open Source License

@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/*from ww w .j  a v  a 2  s.  c  om*/
                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);
    }
}

From source file:org.gridgain.grid.spi.cloud.ec2lite.GridEc2LiteCloudSpi.java

License:GNU General Public License

/**
 * Sends request to Amazon EC2 to stop given instances.
 * <p>/*from  ww w  .  j  a v  a  2 s  .co m*/
 * Provided instances should be in {@link #INST_RUNNING_STATE} state
 * in order for command to execute properly.
 *
 * @param instIds Instances IDs to stop. Not {@code null} and not empty.
 * @param force Pass {@code true} to force instance stop.
 * @throws GridSpiException  Thrown if any exception occurs.
 */
private void stopInstances(Collection<String> instIds, boolean force) throws GridSpiException {
    assert !F.isEmpty(instIds);

    StopInstancesRequest req = new StopInstancesRequest().withInstanceIds(instIds).withForce(force);

    StopInstancesResult res;

    try {
        res = ec2.stopInstances(req);
    } catch (AmazonClientException e) {
        throw new GridSpiException("Failed to perform start instances request.", e);
    }

    Collection<String> stopInstIds = F.transform(res.getStoppingInstances(),
            new C1<InstanceStateChange, String>() {
                @Override
                public String apply(InstanceStateChange ist) {
                    return ist.getInstanceId();
                }
            });

    if (instIds.size() != stopInstIds.size() || !instIds.containsAll(stopInstIds))
        throw new GridSpiException("Instances were not successfully stopped.");
}

From source file:org.gridgain.grid.util.ec2.GridEc2Helper.java

License:GNU General Public License

/**
 * @param instIds Instances' IDs.//from ww w  .  j  av  a2 s .com
 * @return List of stopped instances' IDs.
 * @throws GridException Thrown in case of any exception.
 */
public List<String> stopInstances(Collection<String> instIds) throws GridException {
    StopInstancesRequest req = new StopInstancesRequest();

    req.setInstanceIds(instIds);

    StopInstancesResult res;

    try {
        res = ec2.stopInstances(req);
    } catch (AmazonClientException ex) {
        throw new GridException("Failed to perform EC2 stop instances request: " + ex.getMessage(), ex);
    }

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

    if (res.getStoppingInstances() != null)
        for (InstanceStateChange isc : res.getStoppingInstances())
            stopIds.add(isc.getInstanceId());

    return stopIds;
}

From source file:org.onebusaway.admin.service.server.impl.BundleServerServiceImpl.java

License:Apache License

@Override
public String stop(String instanceId) {
    if (!_isAws) {
        return LOCAL_HOST;
    }/*from w w  w . ja  v  a2s .c  om*/
    if (LOCAL_HOST.equalsIgnoreCase(instanceId)) {
        return instanceId;
    }

    List<String> instances = new ArrayList<String>();
    instances.add(instanceId);
    StopInstancesRequest stopInstancesRequest = new StopInstancesRequest(instances);
    StopInstancesResult stopInstancesResult = _ec2.stopInstances(stopInstancesRequest);
    InstanceStateChange change = null;
    if (!stopInstancesResult.getStoppingInstances().isEmpty()) {
        change = stopInstancesResult.getStoppingInstances().get(0);
        _log.info("from state=" + change.getPreviousState() + " to state=" + change.getCurrentState());
        return change.getInstanceId();
    }
    return null;
}