Example usage for com.amazonaws.services.ec2.model TerminateInstancesResult getTerminatingInstances

List of usage examples for com.amazonaws.services.ec2.model TerminateInstancesResult getTerminatingInstances

Introduction

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

Prototype


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

Source Link

Document

Information about the terminated instances.

Usage

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

License:Apache License

/**
 * Terminates all AWS instances that were started using this app
 *
 * @see #launch()/*from   w  w  w .  j  a v  a2 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.liferay.amazontools.AMIBuilder.java

License:Open Source License

protected void terminateInstance(String instanceId) {
    TerminateInstancesRequest terminateInstancesRequest = new TerminateInstancesRequest();

    List<String> instanceIds = terminateInstancesRequest.getInstanceIds();

    instanceIds.add(instanceId);// w  w w .j  a  va 2s . co m

    TerminateInstancesResult terminateInstancesResult = amazonEC2Client
            .terminateInstances(terminateInstancesRequest);

    List<InstanceStateChange> instanceStateChanges = terminateInstancesResult.getTerminatingInstances();

    if (!instanceStateChanges.isEmpty()) {
        System.out.println("Terminated instance " + instanceId);
    } else {
        System.out.println("Unable to terminate instance " + instanceId);
    }
}

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 w  w .j a v  a2 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);// w w  w.  j  ava 2s .com
    }
    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.rmn.qa.aws.AwsVmManager.java

License:Open Source License

/**
 * Terminates the specified instance./* w  w w .j  a  v  a 2s.  com*/
 *
 * @param  instanceId  Id of the instance to terminate
 */
public boolean terminateInstance(final String instanceId) {
    TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest();
    terminateRequest.withInstanceIds(instanceId);

    AmazonEC2Client localClient = getClient();
    if (localClient == null) {
        throw new RuntimeException("The client is not initialized");
    }
    TerminateInstancesResult result;
    try {
        result = localClient.terminateInstances(terminateRequest);
    } catch (AmazonServiceException ase) {
        // If the node was terminated outside of this plugin, handle the error appropriately
        if (ase.getErrorCode().equals("InvalidInstanceID.NotFound")) {
            log.error("Node not found when attempting to remove: " + instanceId);
            return false;
        } else {
            throw ase;
        }
    }
    List<InstanceStateChange> stateChanges = result.getTerminatingInstances();
    boolean terminatedInstance = false;
    for (InstanceStateChange stateChange : stateChanges) {
        if (instanceId.equals(stateChange.getInstanceId())) {
            terminatedInstance = true;

            InstanceState currentState = stateChange.getCurrentState();
            if (currentState.getCode() != 32 && currentState.getCode() != 48) {
                log.error(String.format(
                        "Machine state for id %s should be terminated (48) or shutting down (32) but was %s instead",
                        instanceId, currentState.getCode()));
                return false;
            }
        }
    }

    if (!terminatedInstance) {
        log.error("Matching terminated instance was not found for instance " + instanceId);
        return false;
    }

    log.info(String.format("Node [%s] successfully terminated", instanceId));
    return true;
}

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.j a  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<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:edu.brandeis.wisedb.aws.VMCreator.java

License:Open Source License

public void terminateVM(VM vm) throws VirtualMachineException {
    TerminateInstancesResult tir = getEC2()
            .terminateInstances(new TerminateInstancesRequest().withInstanceIds(vm.id));
    if (!tir.getTerminatingInstances().get(0).getInstanceId().equals(vm.id)) {
        throw new VirtualMachineException("termination failed. the VM id was not included in the response");
    }//from  w  ww  .  j  a v  a2s.c  om

    int code = tir.getTerminatingInstances().get(0).getCurrentState().getCode();

    // these constants aren't given anywhere... the first is
    // shutting-down, the second is terminated.
    if (code != 32 && code != 48) {
        throw new VirtualMachineException("termination failed.");
    }

}

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  . j  av  a  2 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:jp.primecloud.auto.process.aws.AwsInstanceProcess.java

License:Open Source License

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

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

    // ?
    TerminateInstancesRequest request = new TerminateInstancesRequest();
    request.withInstanceIds(instanceId);
    TerminateInstancesResult result = awsProcessClient.getEc2Client().terminateInstances(request);
    List<InstanceStateChange> terminatingInstances = result.getTerminatingInstances();

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

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

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

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

From source file:n3phele.factory.ec2.VirtualServerResource.java

License:Open Source License

/**
 * Check if a zombie has expired and clean up if it has
 * /*  ww w.ja va2 s  . co  m*/
 * @param s
 *            virtual server
 * @return TRUE if zombie
 */
private boolean checkForZombieExpiry(VirtualServer s) {
    boolean debugInstance = s.getName().equals("debug");
    boolean zombieInstance = s.getName().equals("zombie");
    if (zombieInstance || debugInstance) {
        refreshVirtualServer(s);
        if (s.getStatus().equals(InstanceStateName.Terminated.toString())) {
            log.info("Found dead " + s.getName() + " with id " + s.getInstanceId() + " created "
                    + s.getCreated());
            manager.delete(s);
            return true;
        }
        long created = s.getCreated().getTime();
        long now = new Date().getTime();
        long age = ((now - created) % (60 * 60 * 1000)) / 60000; // minutes
        // into
        // hourly
        // cycle
        if (age > 55 || s.getName().equals("Zombie") || s.getName().equals("Debug")
                || !s.getStatus().equals(InstanceStateName.Running.toString())) {
            log.info("Killing " + s.getName() + " with id " + s.getInstanceId() + " created " + s.getCreated());
            s.setName(debugInstance ? "Debug" : "Zombie");
            update(s);
            try {
                AmazonEC2 client = null;
                client = getEC2Client(s.getAccessKey(), s.getEncryptedKey(), s.getLocation());
                TerminateInstancesResult result = client.terminateInstances(
                        (new TerminateInstancesRequest()).withInstanceIds(s.getInstanceId()));
                log.info("Terminated " + result.getTerminatingInstances().size());
            } catch (Exception e) {
                log.log(Level.SEVERE, "Failed to delete zombie", e);
            }
            return true;
        }
    }
    return false;
}