Example usage for com.amazonaws.services.ec2.model InstanceStateChange getPreviousState

List of usage examples for com.amazonaws.services.ec2.model InstanceStateChange getPreviousState

Introduction

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

Prototype


public InstanceState getPreviousState() 

Source Link

Document

The previous state of the instance.

Usage

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

License:Open Source License

/**
 * Wait for a instance to complete transitioning (i.e. status not being in
 * INSTANCE_STATE_IN_PROGRESS_SET or the instance no longer existing).
 * //from   w  ww.  j  a  v  a 2 s .  co  m
 * @param stateChangeList
 * @param instancebuilder
 * @param instanceId
 * @param BuildLogger
 * @throws InterruptedException
 * @throws Exception
 */
private final String waitForTransitionCompletion(List<InstanceStateChange> stateChangeList,
        final String desiredState, String instanceId) throws InterruptedException {

    Boolean transitionCompleted = false;
    InstanceStateChange stateChange = stateChangeList.get(0);
    String previousState = stateChange.getPreviousState().getName();
    String currentState = stateChange.getCurrentState().getName();
    String transitionReason = "";

    while (!transitionCompleted) {
        try {
            Instance instance = getSingleEc2InstanceById(instanceId);
            currentState = instance.getState().getName();
            if (previousState.equals(currentState)) {
                log.info("... '" + instanceId + "' is still in state " + currentState + " ...");
            } else {
                log.info("... '" + instanceId + "' entered state " + currentState + " ...");
                transitionReason = instance.getStateTransitionReason();
            }
            previousState = currentState;

            if (currentState.equals(desiredState)) {
                transitionCompleted = true;
            }
        } catch (AmazonServiceException ase) {
            log.error("Failed to describe instance '" + instanceId + "'!", ase);
            throw ase;
        }

        // Sleep for WAIT_FOR_TRANSITION_INTERVAL seconds until transition
        // has completed.
        if (!transitionCompleted) {
            Thread.sleep(WAIT_FOR_TRANSITION_INTERVAL);
        }
    }

    log.info("Transition of instance '" + instanceId + "' completed with state " + currentState + " ("
            + (StringUtils.isEmpty(transitionReason) ? "Unknown transition reason" : transitionReason) + ").");

    return currentState;
}

From source file:com.github.vatbub.awsvpnlauncher.Main.java

License:Apache License

/**
 * Terminates all AWS instances that were started using this app
 *
 * @see #launch()/*  w ww  .  ja  va  2 s.  c o m*/
 */
private static void terminate() {
    String instanceIdsPrefValue = prefs.getPreference("instanceIDs", "");
    if (instanceIdsPrefValue.equals("")) {
        throw new IllegalStateException(
                "No instance was started with this script so no instance can be terminated. Launch a new instance using the launch command prior to terminate it.");
    }

    FOKLogger.info(Main.class.getName(), "Sending the termination request to AWS EC2...");
    List<String> instanceIds = Arrays.asList(instanceIdsPrefValue.split(";"));
    for (String instanceId : instanceIds) {
        try {
            List<String> instanceIdCopy = new ArrayList<>();
            instanceIdCopy.add(instanceId);
            TerminateInstancesRequest request = new TerminateInstancesRequest(instanceIdCopy);
            TerminateInstancesResult result = client.terminateInstances(request);

            for (InstanceStateChange item : result.getTerminatingInstances()) {
                FOKLogger.info(Main.class.getName(),
                        "Terminated instance: " + item.getInstanceId() + ", instance state changed from "
                                + item.getPreviousState() + " to " + item.getCurrentState());
            }
        } catch (AmazonEC2Exception e) {
            FOKLogger.severe(Main.class.getName(),
                    "Could not terminate instance " + instanceId + ": " + e.getMessage());
        }
    }

    try {
        String cloudflareAPIKey = prefs.getPreference(Property.cloudflareAPIKey);
        String cloudflareEmail = prefs.getPreference(Property.cloudflareEmail);
        String targetDomain = prefs.getPreference(Property.cloudflareTargetZoneId);
        String cloudflareRecordID = prefs.getPreference("cloudflareRecordID", "0");

        CloudflareAccess cloudflareAccess = new CloudflareAccess(cloudflareEmail, cloudflareAPIKey);
        DNSDeleteRecord cloudFlareDeleteDNSRecordRequest = new DNSDeleteRecord(cloudflareAccess, targetDomain,
                cloudflareRecordID);

        FOKLogger.info(Main.class.getName(), "Deleting the DNS record on cloudflare...");
        JSONObject cloudflareResult = cloudFlareDeleteDNSRecordRequest.executeBasic();

        if (cloudflareResult == null) {
            FOKLogger.severe(Main.class.getName(),
                    "Something went wrong while deleting the DNS record for the vpn server on Cloudflare.");
        } else {
            prefs.setPreference("cloudflareRecordID", "0");
            FOKLogger.info(Main.class.getName(), "The DNS record for the VPN Server was successfully deleted");
            FOKLogger.fine(Main.class.getName(), "Cloudflare request result:");
            FOKLogger.fine(Main.class.getName(), cloudflareResult.toString());
        }
    } catch (PropertyNotConfiguredException e) {
        FOKLogger.info(Main.class.getName(),
                "Cloudflare config is not defined, not sending the ip to cloudflare");
    } catch (CloudflareError e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE,
                "Something went wrong while deleting the DNS record for the vpn server on Cloudflare.", e);
    }

    // Delete the config value
    prefs.setPreference("instanceIDs", "");
}

From source file:com.lunabeat.pooper.commands.AppCommand.java

License:Apache License

private void terminateCluster(String clusterName) {
    HadoopCluster cluster = new HadoopCluster(clusterName, _config);
    TerminateInstancesResult tr = cluster.terminateCluster();
    if (tr == null || tr.getTerminatingInstances().isEmpty()) {
        out.println("no instances terminated.");
        System.exit(0);//w ww  . j  a  v a 2 s .c  o  m
    }
    out.println("Terminating " + tr.getTerminatingInstances().size() + " instances.");
    for (InstanceStateChange i : tr.getTerminatingInstances()) {
        out.println("\t" + i.getInstanceId() + " " + i.getPreviousState().getName() + " -> "
                + i.getCurrentState().getName());
    }
    out.println("Success.");
}

From source file:com.lunabeat.pooper.commands.AppCommand.java

License:Apache License

private void terminateSlaves(String[] args) {
    String clusterName = args[0];
    int nodes = Integer.parseInt(args[1]);
    HadoopCluster cluster = new HadoopCluster(clusterName, _config);
    TerminateInstancesResult tr = cluster.terminateSlaves(nodes);
    if (tr == null || tr.getTerminatingInstances().isEmpty()) {
        out.println("no instances terminated.");
        System.exit(0);/*from w w  w .j  a  va2  s  .  c  om*/
    }
    out.println("Terminating " + tr.getTerminatingInstances().size() + " instances.");
    for (InstanceStateChange i : tr.getTerminatingInstances()) {
        out.println("\t" + i.getInstanceId() + " " + i.getPreviousState().getName() + "-> "
                + i.getCurrentState().getName());
    }
    out.println("Success.");
}

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  ww  w.j  a v a2s .  co  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<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: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  va  2s .  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<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:de.fischer.thotti.ec2.clients.EC2Terminator.java

License:Apache License

private void executeRequest(EC2RequestData<TerminateInstancesRequest> 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);
    }// w  w w.ja  v  a  2s.  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<TerminateInstancesRequest> runRequests = regionRequests.getRequests();

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

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

            TerminateInstancesResult result = null;

            try {
                result = getClient().terminateInstances(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.getTerminatingInstances()) {

                    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:hu.mta.sztaki.lpds.cloud.entice.imageoptimizer.iaashandler.amazontarget.EC2VirtualMachine.java

License:Apache License

@Override
protected void terminateInstance() throws VMManagementException {
    try {/* w ww.java2  s .c o m*/
        int requests = reqCounter.decrementAndGet();
        if (requests < 0) {
            Shrinker.myLogger.severe("Terminating shrinking process, too much VM termination requests");
            Thread.dumpStack();
        }

        Shrinker.myLogger.info("Instance " + getInstanceId() + " received a terminate request");
        TerminateInstancesRequest terminateInstancesRequest = new TerminateInstancesRequest();
        terminateInstancesRequest.withInstanceIds(getInstanceIds());
        TerminateInstancesResult res = this.amazonEC2Client.terminateInstances(terminateInstancesRequest);
        Shrinker.myLogger.info("Terminate request dispatched for instance " + getInstanceId());

        List<InstanceStateChange> stateChanges = res.getTerminatingInstances();
        InstanceStateChange state = null;
        for (InstanceStateChange stateChange : stateChanges)
            if (getInstanceId().contains(stateChange.getInstanceId()))
                state = stateChange;
        if (state != null)
            Shrinker.myLogger.info("State of instance " + getInstanceId() + ": "
                    + state.getPreviousState().getName() + " -> " + state.getCurrentState().getName());
        else
            Shrinker.myLogger.info("null state for instance " + getInstanceId());

        // re-send terminate
        if (state == null || !TERMINATED_STATE.equals(state.getCurrentState().getName())) {
            int timeout = 0;
            int counter = 1;
            while (timeout < TERMINATE_TIMEOUT) {
                try {
                    Thread.sleep(5000);
                } catch (Exception x) {
                }
                Shrinker.myLogger.info("Re-sending (" + counter
                        + "x) terminate request dispatched for instance " + getInstanceId());
                try {
                    res = this.amazonEC2Client.terminateInstances(terminateInstancesRequest);
                    stateChanges = res.getTerminatingInstances();
                    for (InstanceStateChange stateChange : stateChanges)
                        if (getInstanceId().contains(stateChange.getInstanceId()))
                            state = stateChange;
                    if (state != null)
                        Shrinker.myLogger.info("State of instance " + getInstanceId() + ": "
                                + state.getPreviousState().getName() + " -> "
                                + state.getCurrentState().getName());
                    else
                        Shrinker.myLogger.info("null state for instance " + getInstanceId());
                } catch (AmazonServiceException x) { // terminated correctly
                    // it can happen that terminate seemingly didn't succeed for the first time (remains running), 
                    // but then the instance id is gone (correctly) so re-sending terminate will cause exception
                    if ("InvalidInstanceID.NotFound".equals(x.getErrorCode()))
                        break;
                    else
                        throw x;
                }
                if (state != null && TERMINATED_STATE.equals(state.getCurrentState().getName()))
                    break;
                timeout += 5000; // repeat every 5 second
                counter++;
            }

            if (timeout >= TERMINATE_TIMEOUT) {
                Shrinker.myLogger.info("ERROR: Cannot terminate instance: " + getInstanceId());
                System.exit(1);
            }
        }

    } catch (AmazonServiceException x) {
        Shrinker.myLogger.info("terminateInstance error: " + x.getMessage());
        throw new VMManagementException("terminateInstance exception", x);
    } catch (AmazonClientException x) {
        Shrinker.myLogger.info("terminateInstance error: " + x.getMessage());
        throw new VMManagementException("terminateInstance exception", x);
    }
    System.out.println("[T" + (Thread.currentThread().getId() % 100) + "] VM terminated: " + getInstanceId()
            + " " + this.ip + " (@" + new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime())
            + ")");
}

From source file:org.elasticdroid.EC2SingleInstanceView.java

License:Open Source License

/**
 * Process the results returned by the ControlInstancesModel
 * /*www.  jav a 2s .c o m*/
 * @param result. Result can be:
 * <ul>
 *    <li>List<InstanceStateChange>: An ArrayList containing the state changes to 
 *    each of the instances stopped/started.</li>
 *    <li>AmazonClientException: Issues with the client.</li>
 *    <li>AmazonServiceException: Issues with the service itself.</li>
 * </ul>
 */
@SuppressWarnings("unchecked")
private void processControlInstancesModelResult(Object result) {
    //set the model to null
    controlInstancesModel = null;

    //if successful it would have returned a ArrayList<InstanceStateChange>.
    if (result instanceof List<?>) {
        int expectedState = -1;
        //there's only going to be one entry in the list, but nevertheless...
        for (InstanceStateChange change : (List<InstanceStateChange>) result) {

            Log.v(TAG, "Instance ID: " + change.getInstanceId() + ", State: " + change.getCurrentState());
            if (change.getInstanceId().equals(instance.getInstanceId())) {
                //set the state code and state name
                instance.setStateCode(change.getCurrentState().getCode());
                instance.setStateName(change.getCurrentState().getName());
                //get the state we should eventually get to
                if (change.getPreviousState().getCode() == InstanceStateConstants.STOPPED) {
                    expectedState = InstanceStateConstants.RUNNING;
                } else {
                    expectedState = InstanceStateConstants.STOPPED;
                }
            }
        }

        //populate the list
        setListAdapter(
                new EC2SingleInstanceAdapter(this, R.layout.ec2singleinstance, instance, isElasticIpAssigned));

        //start refresh until state is not equal to expected state.
        //i.e. running if stopped, stopped if running.
        if (expectedState >= 0) {
            autoRefreshEC2InstanceModel(expectedState);
        }
    } else if (result instanceof Boolean) {
        Log.v(TAG, "Successfully tagged instance.");
    } else if (result instanceof AmazonServiceException) {
        // if a server error
        if (((AmazonServiceException) result).getErrorCode().startsWith("5")) {
            alertDialogMessage = this.getString(R.string.loginview_server_err_dlg);
        } else {
            alertDialogMessage = this.getString(R.string.loginview_invalid_keys_dlg);
        }
        alertDialogDisplayed = true;
        killActivityOnError = false;//do not kill activity on server error
        //allow user to retry.
    } else if (result instanceof AmazonClientException) {
        alertDialogMessage = this.getString(R.string.loginview_no_connxn_dlg);
        alertDialogDisplayed = true;
        killActivityOnError = false;//do not kill activity on connectivity error. allow 
        //client to retry.
    }
}

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

License:Open Source License

public void startInstances(String... instanceIds) {
    LOG.info("Starting up the instances [{}]", Arrays.toString(instanceIds));
    List<InstanceStateChange> startingInstances = ec2_
            .startInstances(new StartInstancesRequest().withInstanceIds(instanceIds)).getStartingInstances();

    for (InstanceStateChange state : startingInstances) {
        LOG.info("The state of the instance [{}] changed from [{}] to [{}]", state.getInstanceId(),
                state.getPreviousState().getName(), state.getCurrentState().getName());
    }// www.  ja  v  a 2  s.  c om
    //        waitForEc2Instance(instanceToWaitRunningState);
}