de.fischer.thotti.ec2.clients.EC2Terminator.java Source code

Java tutorial

Introduction

Here is the source code for de.fischer.thotti.ec2.clients.EC2Terminator.java

Source

/*
 * Copyright 2011 Oliver B. Fischer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.fischer.thotti.ec2.clients;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceStateChange;
import com.amazonaws.services.ec2.model.Region;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
import com.amazonaws.services.ec2.model.TerminateInstancesResult;
import de.fischer.thotti.awscommon.AWSAccessCredentials;
import de.fischer.thotti.awscommon.AWSCommunicationException;
import de.fischer.thotti.ec2.EC2Executor;
import de.fischer.thotti.ec2.resources.ec2.InstanceType;
import de.fischer.thotti.ec2.resources.ec2.RegionType;
import de.fischer.thotti.ec2.resources.ec2.ResourcesDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

public class EC2Terminator extends EC2InternalClient {
    private static Logger logger = LoggerFactory.getLogger(EC2Terminator.class);

    public EC2Terminator(AWSAccessCredentials credentials) {
        super(credentials);
    }

    public void terminate(ResourcesDefinition resourcesDefinition) throws AWSCommunicationException {
        EC2RequestData<TerminateInstancesRequest> requestData;

        try {
            requestData = prepareRequests(resourcesDefinition);
            executeRequest(requestData);
        } finally {
            getClient().shutdown();
        }
    }

    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);
        }

        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);
                }
            }
        }
    }

    private EC2RequestData<TerminateInstancesRequest> prepareRequests(ResourcesDefinition definition) {
        EC2RequestData<TerminateInstancesRequest> requestData = new EC2RequestData<TerminateInstancesRequest>();

        for (RegionType region : definition.getRegions()) {
            prepareRequestsPerRegion(requestData, region);
        }

        return requestData;
    }

    private void prepareRequestsPerRegion(EC2RequestData<TerminateInstancesRequest> requestData,
            RegionType region) {
        TerminateInstancesRequest request = new TerminateInstancesRequest();

        for (InstanceType server : region.getInstances()) {
            request.withInstanceIds(server.getInstanceID());
        }

        requestData.getRegion(region.getName()).addRequest(request);
    }
}