Example usage for com.amazonaws.services.ec2.model StartInstancesResult getStartingInstances

List of usage examples for com.amazonaws.services.ec2.model StartInstancesResult getStartingInstances

Introduction

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

Prototype


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

Source Link

Document

Information about the started instances.

Usage

From source file:ca.roussil.ec2instancestarter.SimpleEc2Service.java

License:Open Source License

@Override
public void startInstance(String ec2InstanceId) throws InterruptedException {

    Instance instance = getSingleEc2InstanceById(ec2InstanceId);
    InstanceState state = instance.getState();

    // different possible states: pending, running, shutting-down,
    // terminated, stopping, stopped
    String stateName = state.getName();
    if (stateName.equalsIgnoreCase("pending")) {
        log.info("startInstance: instance with id= " + ec2InstanceId
                + " state is pending, no action was taken.");
    } else if (stateName.equalsIgnoreCase("running")) {
        log.info("startInstance: instance with id= " + ec2InstanceId
                + " state is running, no action was taken.");
    } else if (stateName.equalsIgnoreCase("shutting-down")) {
        log.info("startInstance: instance with id= " + ec2InstanceId
                + " state is shutting-down, no action was taken.");

        // TODO maybe we should wait for the instance to shutdown before
        // starting it again.. ?
    } else if (stateName.equalsIgnoreCase("terminated")) {
        log.info("startInstance: instance with id= " + ec2InstanceId
                + " state is terminated, no action was taken.");

        // TODO throw error ?
    } else if (stateName.equalsIgnoreCase("stopping")) {
        log.info("startInstance: instance with id= " + ec2InstanceId
                + " state is stopping, no action was taken.");

        // TODO maybe we should wait for the instance to stop before
        // starting it again.. ? what is the difference between
        // shutting-down and stopping ??
    } else if (stateName.equalsIgnoreCase("stopped")) {
        log.info("startInstance: instance with id= " + ec2InstanceId
                + " state is stopped, the instance has been asked to start...");

        StartInstancesRequest startRequest = new StartInstancesRequest().withInstanceIds(ec2InstanceId);
        StartInstancesResult startResult = config.getAmazonEC2Client().startInstances(startRequest);
        List<InstanceStateChange> stateChangeList = startResult.getStartingInstances();

        waitForTransitionCompletion(stateChangeList, "running", ec2InstanceId);
    }/*from w  w w.  jav a2 s. c  o m*/
}

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

License:Apache License

private void executeRequest(EC2RequestData<StartInstancesRequest> 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   www  . j  a  v a2 s  . com

    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<StartInstancesRequest> runRequests = regionRequests.getRequests();

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

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

            StartInstancesResult result = null;

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

            // @todo here we should check, if Amazon started all requested instances, Oliver Fischer, 15. June 2011
            if (logger.isInfoEnabled()) {
                for (InstanceStateChange stateChange : result.getStartingInstances()) {
                    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:jp.primecloud.auto.process.aws.AwsInstanceProcess.java

License:Open Source License

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

    // /*from  www.  j a v  a2s  .  co m*/
    Instance instance = instanceDao.read(instanceNo);
    processLogger.debug(null, instance, "AwsInstanceStart",
            new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId });

    // ?
    StartInstancesRequest request = new StartInstancesRequest();
    request.withInstanceIds(instanceId);
    StartInstancesResult result = awsProcessClient.getEc2Client().startInstances(request);
    List<InstanceStateChange> startingInstances = result.getStartingInstances();

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

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

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

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

From source file:org.elasticdroid.model.ControlInstancesModel.java

License:Open Source License

/**
 * Method that does the actual work of starting or stopping the instances
 * /*from  w w w.ja v  a 2  s .c o m*/
 * This method uses the stop boolean to identify whether the instances should be stopped 
 * (stop = true) or started (stop = false).
 * 
 * @return Returns one of the following:
 * <ul>
 *    <li>newInstanceStates: Returns a list of stateCodes and state names for all of the instances
 *    </li>
 *    <li> AmazonServiceException</li>
 *    <li> AmazonClientException</li>
 * </ul>
 * 
 */
public Object controlInstances(List<String> instances) {

    for (String instance : instances) {
        Log.v(TAG, "Starting instance: " + instance);
    }

    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));
    //create Amazon EC2 Client object, and set tye end point to the region. params[3]
    //contains endpoint
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);
    //override the default connection endpoint if provided.
    if (connectionData.get("endpoint") != null) {
        amazonEC2Client.setEndpoint(connectionData.get("endpoint"));
    }

    //if you want to start an instance
    if (operationType == ControlType.START_INSTANCE) {
        StartInstancesRequest request = new StartInstancesRequest(instances);
        StartInstancesResult result = null;
        try {
            result = amazonEC2Client.startInstances(request);
        } catch (AmazonServiceException amazonServiceException) {
            return amazonServiceException;
        } catch (AmazonClientException amazonClientException) {
            return amazonClientException;
        }
        //redundant check.
        if (result != null) {
            return result.getStartingInstances();
        }
    }
    //stop = true, start the instance.
    else {
        StopInstancesRequest request = new StopInstancesRequest(instances);
        StopInstancesResult result = null;

        try {
            result = amazonEC2Client.stopInstances(request);
        } catch (AmazonServiceException amazonServiceException) {
            return amazonServiceException;
        } catch (AmazonClientException amazonClientException) {
            return amazonClientException;
        }

        if (result != null) {
            return result.getStoppingInstances();
        }
    }

    return null;
}

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

License:GNU General Public License

/**
 * Sends request to Amazon EC2 to start given instances.
 * <p>//  ww w. jav  a 2 s.c om
 * Provided instances should be in {@link #INST_STOPPED_STATE} state
 * in order for command to execute properly.
 *
 * @param instIds Instances IDs to start. Not {@code null} and not empty.
 * @throws GridSpiException  Thrown if any exception occurs.
 */
private void startInstances(Collection<String> instIds) throws GridSpiException {
    assert !F.isEmpty(instIds);

    StartInstancesRequest req = new StartInstancesRequest().withInstanceIds(instIds);

    StartInstancesResult res;

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

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

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

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

License:Apache License

@Override
public String start(String instanceId) {
    if (!_isAws) {
        return LOCAL_HOST;
    }//from   w w  w.ja  va 2 s .co  m

    if (LOCAL_HOST.equalsIgnoreCase(instanceId)) {
        return instanceId;
    }

    List<String> instances = new ArrayList<String>();
    instances.add(instanceId);
    StartInstancesRequest startInstancesRequest = new StartInstancesRequest(instances);
    StartInstancesResult startInstancesResult = _ec2.startInstances(startInstancesRequest);
    InstanceStateChange change = null;
    if (!startInstancesResult.getStartingInstances().isEmpty()) {
        change = startInstancesResult.getStartingInstances().get(0);
        _log.info("from state=" + change.getPreviousState() + " to state=" + change.getCurrentState());
        return change.getInstanceId();
    }
    return null;
}