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

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

Introduction

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

Prototype


public void setInstanceIds(java.util.Collection<String> instanceIds) 

Source Link

Document

The IDs of the instances.

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. jav a2s .  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.co m
 * @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:Encoder.java

License:Open Source License

/**
 * Terminates this machine completely in EC2 and there is no return (program will be terminated).
 * /*from ww w  . j  av  a  2  s.c  om*/
 */

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: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);/*w  ww.  j a v  a2  s.  c o m*/
    request.setInstanceIds(idList);
    TerminateInstancesResult result = cleint.terminateInstances(request);

}

From source file:com.eucalyptus.tests.awssdk.CloudCleaner.java

License:Open Source License

@Test
public void clean() throws Exception {
    testInfo(this.getClass().getSimpleName());
    getCloudInfo();//from ww  w.j  a v a2s .  c o  m

    //Terminate All instances
    List<String> instancesToTerminate = new ArrayList<String>();
    DescribeInstancesResult result = ec2.describeInstances();
    List<Reservation> reservations = result.getReservations();
    if (reservations.size() > 0) {
        print("Found instances to terminate");
        for (Reservation reservation : reservations) {
            List<Instance> instances = reservation.getInstances();
            for (Instance instance : instances) {
                print("Terminating: " + instance.getInstanceId());
                instancesToTerminate.add(instance.getInstanceId());
            }
        }
        TerminateInstancesRequest term = new TerminateInstancesRequest();
        term.setInstanceIds(instancesToTerminate);
        ec2.terminateInstances(term);
    } else {
        print("No instances found");
    }

    // delete all keypairs
    if (getKeyPairCount() > 0) {
        print("Found Keypairs to delete");
        DescribeKeyPairsResult describeKeyPairsResult = ec2.describeKeyPairs();
        for (KeyPairInfo keypair : describeKeyPairsResult.getKeyPairs()) {
            deleteKeyPair(keypair.getKeyName());
        }
    } else {
        print("No keypairs found");
    }

    // delete all groups except default group
    List<SecurityGroup> groups = describeSecurityGroups();
    if (groups.size() > 1) {
        print("Found security groups to delete");
        for (SecurityGroup group : groups) {
            if (!group.getGroupName().equals("default")) {
                deleteSecurityGroup(group.getGroupName());
            }
        }
    } else {
        print("No Security Groups found (other than default)");
    }

    // delete all policies
    List<ScalingPolicy> policies = describePolicies();
    if (policies.size() > 0) {
        print("Found Policies to delete");
        for (ScalingPolicy policy : policies) {
            deletePolicy(policy.getPolicyName());
        }
    } else {
        print("No auto scaling policies found");
    }

    // delete launch configs
    List<LaunchConfiguration> lcs = describeLaunchConfigs();
    if (lcs.size() > 0) {
        print("Found Launch Configs to delete");
        for (LaunchConfiguration lc : lcs) {
            deleteLaunchConfig(lc.getLaunchConfigurationName());
        }
    } else {
        print("No launch configs found");
    }

    // delete autoscaling groups
    List<AutoScalingGroup> asGroups = describeAutoScalingGroups();
    if (asGroups.size() > 0) {
        print("Found Auto Scaling Groups to delete");
        for (AutoScalingGroup asg : asGroups) {
            deleteAutoScalingGroup(asg.getAutoScalingGroupName(), true);
        }
    } else {
        print("No auto scaling groups found");
    }

    // delete volumes
    List<Volume> volumes = ec2.describeVolumes().getVolumes();
    if (volumes.size() > 0) {
        print("Found volumes to delete");
        for (Volume vol : volumes) {
            deleteVolume(vol.getVolumeId());
        }
    } else {
        print("No volumes found");
    }

    //delete snapshots
    List<Snapshot> snapshots = ec2.describeSnapshots().getSnapshots();
    if (snapshots.size() > 0) {
        print("Found snapshots to delete");
        for (Snapshot snap : snapshots) {
            deleteSnapshot(snap.getSnapshotId());
        }
    } else {
        print("No volumes found");
    }
}

From source file:com.hpcloud.daas.ec2.AwsConsoleApp.java

License:Open Source License

public static void TerminateInstance(String instanceId) {
    try {//from w w  w.  java2  s .c  o  m
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest();

        List<String> instanceIds = new ArrayList<String>();
        instanceIds.add(instanceId);
        terminateRequest.setInstanceIds(instanceIds);

        TerminateInstancesResult result = ec2.terminateInstances(terminateRequest);

        System.out.println(result);

    } 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:com.pinterest.arcee.aws.EC2HostInfoDAOImpl.java

License:Apache License

@Override
public void terminateHost(String hostId) throws Exception {
    TerminateInstancesRequest request = new TerminateInstancesRequest();
    request.setInstanceIds(Arrays.asList(hostId));
    try {/*from w w  w .  ja  v a  2 s. com*/
        ec2Client.terminateInstances(request);
    } catch (AmazonClientException ex) {
        LOG.error(String.format("Failed to call aws terminateInstances whem terminating host %s", hostId), ex);
        throw new DeployInternalException(
                String.format("Failed to call aws terminateInstances whem terminating host %s", hostId), ex);
    }
}

From source file:com.pinterest.clusterservice.cm.AwsVmManager.java

License:Apache License

@Override
public void terminateHosts(String clusterName, Collection<String> hostIds, boolean replaceHost)
        throws Exception {
    if (replaceHost) {
        TerminateInstancesRequest termianteRequest = new TerminateInstancesRequest();
        termianteRequest.setInstanceIds(hostIds);
        try {//from   www.ja va 2  s .  c  om
            ec2Client.terminateInstances(termianteRequest);
        } catch (AmazonClientException e) {
            LOG.error(String.format("Failed to termiante hosts %s: %s", hostIds.toString(), e.getMessage()));
            throw new Exception(
                    String.format("Failed to termiante hosts %s: %s", hostIds.toString(), e.getMessage()));
        }
    } else {
        // Do not replace host and decrease the cluster capacity
        AutoScalingGroup group = getAutoScalingGroup(clusterName);
        if (group == null) {
            LOG.error(String.format("Failed to terminate hosts: auto scaling group %s does not exist",
                    clusterName));
            throw new Exception(String.format("Failed to terminate hosts: auto scaling group %s does not exist",
                    clusterName));
        }

        UpdateAutoScalingGroupRequest updateRequest = new UpdateAutoScalingGroupRequest();
        updateRequest.setAutoScalingGroupName(clusterName);
        updateRequest.setMinSize(Math.max(group.getMinSize() - hostIds.size(), 0));

        for (String hostId : hostIds) {
            TerminateInstanceInAutoScalingGroupRequest terminateRequest = new TerminateInstanceInAutoScalingGroupRequest();
            terminateRequest.setShouldDecrementDesiredCapacity(true);
            terminateRequest.setInstanceId(hostId);
            aasClient.terminateInstanceInAutoScalingGroup(terminateRequest);
        }
    }
}

From source file:com.yosanai.java.aws.console.DefaultAWSConnectionProvider.java

License:Open Source License

@Override
public void terminateInstances(String... instanceIds) throws Exception {
    List<String> instanceIdsFiltered = getInstances(STATE_TERMINATED, false, instanceIds);
    if (!instanceIdsFiltered.isEmpty()) {
        TerminateInstancesRequest terminateInstancesRequest = new TerminateInstancesRequest();
        terminateInstancesRequest.setInstanceIds(instanceIdsFiltered);
        getConnection().terminateInstances(terminateInstancesRequest);
    }/*from ww w.  j av  a 2  s .  com*/
}

From source file:eu.stratosphere.nephele.instance.ec2.FloatingInstance.java

License:Apache License

/**
 * This method checks if this floating instance has reached the end of its life cycle and, if so, terminates
 * itself.//  ww  w . j a  v  a  2  s . c  o m
 */
public boolean hasLifeCycleEnded() {

    final long currentTime = System.currentTimeMillis();
    final long msremaining = this.leasePeriod - ((currentTime - this.launchTime) % this.leasePeriod);

    if (msremaining < TIME_THRESHOLD) {
        // Destroy this instance
        final AmazonEC2Client client = EC2ClientFactory.getEC2Client(this.awsAccessKey, this.awsSecretKey);
        final TerminateInstancesRequest tr = new TerminateInstancesRequest();
        final LinkedList<String> instanceIDlist = new LinkedList<String>();
        instanceIDlist.add(this.instanceID);
        tr.setInstanceIds(instanceIDlist);
        client.terminateInstances(tr);
        return true;
    }

    return false;
}