Example usage for com.amazonaws.services.ec2.model TerminateInstancesRequest TerminateInstancesRequest

List of usage examples for com.amazonaws.services.ec2.model TerminateInstancesRequest TerminateInstancesRequest

Introduction

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

Prototype

public TerminateInstancesRequest() 

Source Link

Document

Default constructor for TerminateInstancesRequest object.

Usage

From source file:Conductor.java

License:Open Source License

/**
 * Health check method. Health Check Thread. Checks encoding servers health by http ping and remove stopped servers.
 * /*from  w  w w.  java2s  . c  o  m*/
 */
private static void doHealthCheck() throws Exception {

    /*
     * the below query means we have still some not ready instances. 
     * when all of instances are ready we have a query result equals zero.
     */
    String Sqlquery = "select * from " + config.getProperty("TableInstanceServers") + " where ready_to_work=1;";

    ResultSet result = SQL.select(Sqlquery);

    if (!SQL.queryWasSuccess())
        throw new Exception(Constants._ERR_DBAccessError);

    if (result != null) {

        String PrivateIP = "";
        String instanceId = "";
        String HHTP_ProtocoleMode = config.getProperty("HttpOrHttpsPRotocolModeForHealthCheck");
        int i = 0;
        int CriticalError = 0;
        // These variables can be any type of security tokens in the future.
        String[] strNamesToPost = { "" };
        String[] strValsToPost = { "" };

        while (result.next()) {

            PrivateIP = result.getString("private_ip");
            instanceId = result.getString("instance_id");

            i = RestCommands.HTTPCommandsFullResponse(HHTP_ProtocoleMode + PrivateIP, strNamesToPost,
                    strValsToPost, 3000);

            DebugMessage.Debug("Server id " + instanceId + " Machine response->" + i, "doHealthCheck()", true,
                    0);

            if (i != 200) {
                CriticalError++;

                //Remove the server name from instance_servers table
                SQL.query("DELETE FROM " + config.getProperty("TableInstanceServers") + " WHERE instance_id = '"
                        + instanceId + "'");

                if (!SQL.queryWasSuccess())
                    throw new Exception(Constants._ERR_DBAccessError);

                // Update all of related jobs for this instance to serverr state in order to report the service problem to the user.
                SQL.query("UPDATE " + config.getProperty("TableUploadSessions")
                        + " SET current_process=-2,progress_report = 'serverr' WHERE instance_id = '"
                        + instanceId + "' AND (current_process=1 OR current_process=2);");

                if (!SQL.queryWasSuccess())
                    throw new Exception(Constants._ERR_DBAccessError);

                // Shoutdown the Instance in EC2
                List<String> instancesToTerminate = new ArrayList<String>();

                instancesToTerminate.add(instanceId);
                TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest();
                terminateRequest.setInstanceIds(instancesToTerminate);
                ec2.terminateInstances(terminateRequest);
            }

        }

        DebugMessage.Debug("Row numeber " + result.getRow() + ", CriticalError count->" + CriticalError,
                "doHealthCheck()", true, 0);

        // Check if we have all of servers off it means network has outage.
        result.last();

        if (CriticalError == result.getRow() && CriticalError > 0)
            throw new Exception(Constants._ERR_NetworkAccessError);

    }

}

From source file:Conductor.java

License:Open Source License

/**
 * Propagate a command to an encode server.
 * /*from   w  ww  .j  av  a  2 s  .c om*/
 * @param instanceID : The ID of command's target encoder machine 
 * @param optionCommand : The command we want to send to servers. PropagatePauseToAnEncoder, PropagateResumeToAnEncoder, PropagateShutdownToAnEncoder, PropagateForceShutdownToAnEncoder
 * @return JSONObject
 */
public static JSONObject propagateCommandToAnEncodeServer(String instanceID, String optionCommand) {

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

    IPIDs.add(instanceID);

    String[] strNamesToPost = { "restcmd" };
    String[] strValsToPost = new String[1];

    if (optionCommand.equals("PropagatePauseToAnEncoder")) {
        strValsToPost[0] = "100";
    } else if (optionCommand.equals("PropagateResumeToAnEncoder")) {
        strValsToPost[0] = "101";

    } else if (optionCommand.equals("PropagateShutdownToAnEncoder")) {
        strValsToPost[0] = "451";
    } else if (optionCommand.equals("PropagateForceShutdownToAnEncoder")) {
        // Shoutdown the Instance in EC2
        List<String> instancesToTerminate = new ArrayList<String>();

        instancesToTerminate.add(instanceID);
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest();
        terminateRequest.setInstanceIds(instancesToTerminate);
        ec2.terminateInstances(terminateRequest);

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put(instanceID, "force_shutdown");
        } catch (Exception e) {
        }

        return jsonObject;
    } else if (optionCommand.equals("PropagateResetTheLogFileToAnEncoder")) {
        strValsToPost[0] = "reset";
    } else {
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("null", "unrecognized command");
        } catch (Exception e) {
        }

        return jsonobject;
    }

    return postCommands(IPIDs.toArray(new String[IPIDs.size()]), strNamesToPost, strValsToPost);

}

From source file:EC2LaunchWaitTerminate.java

License:Open Source License

public static void main(String[] args) throws Exception {

    System.out.println("===========================================");
    System.out.println("Welcome to the AWS Java SDK!");
    System.out.println("===========================================");

    init();/*from  w ww .j  a v a2  s .  c o  m*/

    /*
     * Amazon EC2
     *
     * The AWS EC2 client allows you to create, delete, and administer
     * instances programmatically.
     *
     * In this sample, we use an EC2 client to get a list of all the
     * availability zones, and all instances sorted by reservation id, then 
     * create an instance, list existing instances again, wait a minute and 
     * the terminate the started instance.
     */
    try {
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");
        /* using AWS Ireland. 
         * TODO: Pick the zone where you have your AMI, sec group and keys */
        ec2.setEndpoint("ec2.us-west-2.amazonaws.com");
        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();

        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        System.out.println("Starting a new instance.");
        RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

        /* TODO: configure to use your AMI, key and security group */
        runInstancesRequest.withImageId("ami-ede6128d").withInstanceType("t2.micro").withMinCount(1)
                .withMaxCount(1).withKeyName("CNV-lab-AWS").withSecurityGroups("CNV-ssh+http");
        RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);
        String newInstanceId = runInstancesResult.getReservation().getInstances().get(0).getInstanceId();
        describeInstancesRequest = ec2.describeInstances();
        reservations = describeInstancesRequest.getReservations();
        instances = new HashSet<Instance>();

        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        System.out.println("Waiting 4 minutes. See your instance in the AWS console...");
        Thread.sleep(60000 * 4);
        System.out.println("Terminating the instance.");
        TerminateInstancesRequest termInstanceReq = new TerminateInstancesRequest();
        termInstanceReq.withInstanceIds(newInstanceId);
        ec2.terminateInstances(termInstanceReq);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }
}

From source file:Encoder.java

License:Open Source License

/**
 * Terminates this machine completely in EC2 and there is no return (program will be terminated).
 * /*from   w w  w.j  ava  2 s.  c o m*/
 */

public static void killThisMachine() {

    try {

        DebugMessage.ShowInfo("Killed!", true);

        // Config setting for allowing machine to be shutdown. If false we can't shutdown (it is good just for debugging).
        if (Boolean.parseBoolean(config.getProperty("AllowToKillItSelf"))) {
            /*https://ec2.amazonaws.com/
                 ?Action=ModifyInstanceAttribute
                 &InstanceId=i-87ad5eec
                 &DisableApiTermination.Value=false
                 &AUTHPARAMS*/
            //wget -q -O - http://169.254.169.254/lateta/instance-id

            String instanceId = "";

            String wget = "sudo wget -q -O - " + config.getProperty("MetaInfoServerIP") + "/instance-id";

            Process p = Runtime.getRuntime().exec(wget);
            p.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

            instanceId = br.readLine();

            if (instanceId.equals(""))
                throw new Exception(Constants._ERR_ServiceIsNotAvailable);

            List<String> instancesToTerminate = new ArrayList<String>();
            instancesToTerminate.add(instanceId);
            TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest();
            terminateRequest.setInstanceIds(instancesToTerminate);
            ec2.terminateInstances(terminateRequest);
        }
    } catch (Exception e) {
        DebugMessage.ShowErrors("killThisMachine()", e.getMessage(), "", true);
        System.exit(1);
    }
}

From source file:agentcoordinator.AgentCoordinator.java

private void terminateInstance(String instanceID) {
    TerminateInstancesRequest terminateInstanceRequest = new TerminateInstancesRequest()
            .withInstanceIds(instanceID);
    TerminateInstancesResult terminateInstanceResult = amazonEC2Client
            .terminateInstances(terminateInstanceRequest);
}

From source file:at.ac.tuwien.infosys.jcloudscale.vm.ec2.EC2Wrapper.java

License:Apache License

void shutdownHostViaEC2Id(String ec2Id) {
    // now destroy the server with this EC2 id
    TerminateInstancesRequest req = new TerminateInstancesRequest().withInstanceIds(ec2Id);
    ec2Client.terminateInstances(req);//  w w w. j  a  v  a2  s.c  o  m

    // waiting for server to actually start shutting down.
    try {
        final int SLEEP_TIME = 100;
        int timeout = 100;//10 sec should be enough.
        do {
            Thread.sleep(SLEEP_TIME);
        } while (timeout-- > 0 && isHostRunningViaId(ec2Id));

        if (timeout <= 0)
            log.warning("While Shutting down host with EC2 Id=" + ec2Id
                    + " waited for timeout and server is still active.");
    } catch (InterruptedException e) {
    }
}

From source file:au.edu.unsw.cse.soc.federatedcloud.deployers.aws.ec2.AWSEC2VMDeploymentWrapper.java

License:Open Source License

@Override
public void undeployResource(String resourceID) throws Exception {
    //Reading the credentials
    Properties properties = new Properties();
    properties.load(this.getClass().getResourceAsStream("/AwsCredentials.properties"));
    String accessKey = properties.getProperty("accessKey");
    String secretKey = properties.getProperty("secretKey-NULL");
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    AmazonEC2Client cleint = new AmazonEC2Client(credentials);

    TerminateInstancesRequest request = new TerminateInstancesRequest();
    List<String> idList = new ArrayList<String>();
    idList.add(resourceID);//www  .j  av a2  s.c o  m
    request.setInstanceIds(idList);
    TerminateInstancesResult result = cleint.terminateInstances(request);

}

From source file:com.axemblr.provisionr.amazon.activities.TerminateInstances.java

License:Apache License

@Override
public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) {
    @SuppressWarnings("unchecked")
    List<String> instanceIds = (List<String>) execution.getVariable(ProcessVariables.INSTANCE_IDS);
    checkNotNull(instanceIds, "process variable '{}' not found", ProcessVariables.INSTANCE_IDS);

    LOG.info(">> Terminating instances: {}", instanceIds);
    client.terminateInstances(new TerminateInstancesRequest().withInstanceIds(instanceIds));
}

From source file:com.cloudera.director.aws.ec2.EC2Provider.java

License:Apache License

@Override
@SuppressWarnings("PMD.UnusedFormalParameter")
public void delete(EC2InstanceTemplate template, Collection<String> virtualInstanceIds)
        throws InterruptedException {

    if (virtualInstanceIds.isEmpty()) {
        return;/*from  w  w w. jav  a  2s .co  m*/
    }

    Map<String, String> ec2InstanceIdsByVirtualInstanceId = getEC2InstanceIdsByVirtualInstanceId(
            virtualInstanceIds);
    Collection<String> ec2InstanceIds = ec2InstanceIdsByVirtualInstanceId.values();
    if (ec2InstanceIds.isEmpty()) {
        LOG.info("Unable to terminate instances, all unknown {}", virtualInstanceIds);
        return;
    }

    LOG.info(">> Terminating {}", ec2InstanceIds);
    TerminateInstancesResult terminateResult = null;
    try {
        terminateResult = client
                .terminateInstances(new TerminateInstancesRequest().withInstanceIds(ec2InstanceIds));
    } catch (AmazonClientException e) {
        throw AWSExceptions.propagate(e);
    }

    LOG.info("<< Result {}", terminateResult);

    if (ec2InstanceIdsByVirtualInstanceId.size() != virtualInstanceIds.size()) {
        Set<String> missingVirtualInstanceIds = Sets.newLinkedHashSet();
        for (String virtualInstanceId : virtualInstanceIds) {
            if (!ec2InstanceIdsByVirtualInstanceId.containsKey(virtualInstanceId)) {
                missingVirtualInstanceIds.add(virtualInstanceId);
            }
        }
        LOG.info("Unable to terminate unknown instances {}", missingVirtualInstanceIds);
    }
}

From source file:com.dowdandassociates.gentoo.bootstrap.DefaultGentooImageProvider.java

License:Apache License

public Optional<Image> get() {
    TestInstanceInformation instanceInfo = testResultInformation.getInstanceInfo();
    Optional<Instance> instance = instanceInfo.getInstance();
    Optional<Image> image = instanceInfo.getImage();
    Optional<Integer> exitStatus = testResultInformation.getExitStatus();

    if (!instance.isPresent()) {
        log.info("Instance is absent");
        return Optional.absent();
    }//from  www. j  av a2  s.c  om

    String instanceId = instance.get().getInstanceId();

    TerminateInstancesResult terminateInstancesResult = ec2Client
            .terminateInstances(new TerminateInstancesRequest().withInstanceIds(instanceId));

    if (!exitStatus.isPresent()) {
        log.info("Exit status is absent");
        return Optional.absent();
    }

    log.info("exit status = " + exitStatus.get());

    if (0 != exitStatus.get()) {
        return Optional.absent();
    }

    if (!image.isPresent()) {
        log.info("Image is absent");
    } else {
        log.info("Image is present");
        log.info("Image id is " + image.get().getImageId());
    }

    return image;
}