Example usage for com.amazonaws.services.ec2 AmazonEC2Client describeInstances

List of usage examples for com.amazonaws.services.ec2 AmazonEC2Client describeInstances

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2 AmazonEC2Client describeInstances.

Prototype

@Override
    public DescribeInstancesResult describeInstances() 

Source Link

Usage

From source file:Aws.Instances.java

public void DescribeInstances(AmazonEC2Client ec2) {
    DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
    List<Reservation> reservations = describeInstancesRequest.getReservations();
    Set<Instance> instances = new HashSet<>();

    for (Iterator<Reservation> it = reservations.iterator(); it.hasNext();) {
        Reservation reservationId = it.next();
        instances.addAll(reservationId.getInstances());
    }//from   ww w .  ja v  a 2  s  . c o  m

    Set<String> InstancesIds = new HashSet<>();
    for (Iterator<Instance> Iteratore = instances.iterator(); Iteratore.hasNext();) {
        Instance instanceId = Iteratore.next();
        List<Tag> tags = instanceId.getTags();
        InstancesIds.add(instanceId.getInstanceId());
        System.out.println("Instance ID " + instanceId.getInstanceId() + " ; Instance Tags " + tags);
        for (Iterator<Tag> tag = tags.iterator(); tag.hasNext();) {
            Tag tagkey = tag.next();
            System.out.println(tagkey.withKey("Name").getValue());
        }

    }
}

From source file:com.capitalone.dashboard.collector.AWSCloudCollectorTask.java

License:Apache License

/**
 * The collection action. This is the task which will run on a schedule to
 * gather data from the feature content source system and update the
 * repository with retrieved data.//from   w w w. ja v a2 s  . com
 */
public void collect(AWSCloudCollector collector) {
    logger.info("Starting Cloud collection...");

    ClientConfiguration clientConfig = new ClientConfiguration().withProxyHost("proxy.kdc.capitalone.com")
            .withProxyPort(8099).withPreemptiveBasicProxyAuth(true).withProxyUsername("xxx")
            .withProxyPassword("xxxxxxx");

    String accessKey = "xxx";
    String secretKey = "xxx";

    AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey);
    AmazonEC2Client ec2Client = new AmazonEC2Client(creds, clientConfig);
    AmazonCloudWatchClient cwClient = new AmazonCloudWatchClient(creds, clientConfig);
    DescribeInstancesResult result = ec2Client.describeInstances();

    //create list of instances
    List<Instance> instanceList = new ArrayList<Instance>();
    List<Reservation> reservations = result.getReservations();
    for (Reservation currRes : reservations) {
        List<Instance> currInstanceList = currRes.getInstances();
        instanceList.addAll(currInstanceList);
    }

    //purge the repo of old instance data
    if (awsRawDataRepository.count() > 0)
        awsRawDataRepository.deleteAll();

    //for every instance determine all metrics
    logger.info("Collecting Raw Data...");
    for (Instance currInstance : instanceList) {
        CloudRawData object = cloudClient.getMetrics(currInstance, cwClient, accessKey);
        awsRawDataRepository.save(object);
    }

    //purge the repo of old account data
    if (cloudAccountRepository.count() > 0)
        cloudAccountRepository.deleteAll();

    logger.info("Agregating Data...");
    CloudAggregatedData aggregatedData = new CloudAggregatedData();
    aggregatedData.setAgeWarning(awsRawDataRepository.runAgeWarning("cof-sandbox-dev").size());
    aggregatedData.setAgeExpired(awsRawDataRepository.runAgeExpired("cof-sandbox-dev").size());
    aggregatedData.setAgeGood(awsRawDataRepository.runAgeGood("cof-sandbox-dev").size());
    aggregatedData.setCpuHigh(awsRawDataRepository.runCpuUtilizationHigh("cof-sandbox-dev").size());
    aggregatedData.setCpuMid(awsRawDataRepository.runCpuUtilizationMid("cof-sandbox-dev").size());
    aggregatedData.setCpuLow(awsRawDataRepository.runCpuUtilizationLow("cof-sandbox-dev").size());
    aggregatedData.setNonEncryptedCount(awsRawDataRepository.runNonEncrypted("cof-sandbox-dev").size());
    aggregatedData.setNonTaggedCount(awsRawDataRepository.runNonTagged("cof-sandbox-dev").size());
    aggregatedData.setStoppedCount(awsRawDataRepository.runStopped("cof-sandbox-dev").size());
    aggregatedData.setAccountName("cof-sandbox-dev");
    aggregatedData.setTotalInstanceCount(awsRawDataRepository.runAllInstanceCount("cof-sandbox-dev").size());

    cloudAccountRepository.save(aggregatedData);
    logger.info("Finished Cloud collection.");

}

From source file:com.chimpler.example.hazelcast.AccountClient.java

License:Apache License

public static HazelcastInstance initHazelcastClient() throws Exception {
    ClientConfig hazelCastClientConfig = new ClientConfig();
    hazelCastClientConfig.getGroupConfig().setName("dev").setPassword("dev-pass");

    AWSCredentialsProvider awsCredentialProvider = new ClasspathPropertiesFileCredentialsProvider(
            "aws.properties");
    AmazonEC2Client ec2 = new AmazonEC2Client(awsCredentialProvider);
    DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
    System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
            + " Availability Zones.");

    DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();

    for (Reservation reservation : describeInstancesRequest.getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            for (GroupIdentifier group : instance.getSecurityGroups()) {
                if (group.getGroupName().equals("jclouds#hazelcast")) {
                    System.out.println("EC2 instance " + instance.getPublicIpAddress());
                    hazelCastClientConfig.addAddress(instance.getPublicIpAddress(),
                            instance.getPublicIpAddress() + ":5701");
                }//from   ww  w. j  a  va 2 s. c  o  m
            }
        }
    }
    HazelcastInstance hazelCastClient = HazelcastClient.newHazelcastClient(hazelCastClientConfig);

    return hazelCastClient;
}

From source file:com.optimalbi.AmazonAccount.java

License:Apache License

private void populateEc2() throws AmazonClientException {
    for (Region region : getRegions()) {
        try {// w ww . j  av a2s. c  o  m
            //                services.addAll(Ec2Service.populateServices(region, getCredentials(), getLogger(), pricing));
            AmazonEC2Client ec2 = new AmazonEC2Client(getCredentials().getCredentials());
            ec2.setRegion(region);
            DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
            List<Reservation> reservations = describeInstancesRequest.getReservations();
            Set<Instance> inst = new HashSet<>();
            for (Reservation reservation : reservations) {
                inst.addAll(reservation.getInstances());
            }

            getLogger().info("EC2, Adding " + inst.size() + " instances from " + region.getName());

            for (Instance i : inst) {
                Service temp = new LocalEc2Service(i.getInstanceId(), getCredentials(), region, ec2,
                        getLogger());
                if (servicePricings != null && servicePricings.size() > 0) {
                    temp.attachPricing(servicePricings.get(region).getEc2Pricing());
                }
                services.add(temp);
            }

        } catch (AmazonClientException e) {
            throw new AmazonClientException(region.getName() + " " + e.getMessage());
        }
        completed.set(completed.get() + 1);
    }

}

From source file:com.optimalbi.Controller.AmazonAccount.java

License:Apache License

private void populateEc2() throws AmazonClientException {
    Map<String, Double> pricing = readEc2Pricing();
    for (Region region : getRegions()) {
        try {//from  w  w w .j  a  v  a 2s .c om
            //                services.addAll(Ec2Service.populateServices(region, getCredentials(), getLogger(), pricing));
            AmazonEC2Client ec2 = new AmazonEC2Client(getCredentials().getCredentials());
            ec2.setRegion(region);
            DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
            List<Reservation> reservations = describeInstancesRequest.getReservations();
            Set<Instance> inst = new HashSet<>();
            for (Reservation reservation : reservations) {
                inst.addAll(reservation.getInstances());
            }

            getLogger().info("EC2, Adding " + inst.size() + " instances from " + region.getName());

            for (Instance i : inst) {
                Service temp = new LocalEc2Service(i.getInstanceId(), getCredentials(), region, ec2,
                        getLogger());
                if (pricing != null) {
                    temp.attachPricing(pricing);
                }
                services.add(temp);
            }

        } catch (AmazonClientException e) {
            throw new AmazonClientException(region.getName() + " " + e.getMessage());
        }
        completed.set(completed.get() + 1);
    }

}

From source file:de.fischer.thotti.ec2.clients.EC2ExecutorITHelper.java

License:Apache License

private void loadInstanceInformation(Map<String, List<String>> instanceMap) {
    AmazonEC2Client awsClient = getAmazonClient();

    // Get all existing instances in all regions
    for (Region region : awsRegions) {
        String regionName = region.getRegionName();

        if (!instanceMap.containsKey(regionName))
            instanceMap.put(regionName, new LinkedList<String>());

        List<String> instanceIDs = instanceMap.get(regionName);

        awsClient.setEndpoint(region.getEndpoint());
        DescribeInstancesResult instancesRes = awsClient.describeInstances();

        List<Reservation> instancesList = instancesRes.getReservations();

        if (instancesList.isEmpty())
            if (logger.isDebugEnabled())
                logger.debug("No existing instances found in region {}", region.getRegionName());

        for (Reservation reservation : instancesList) {
            for (Instance instance : reservation.getInstances()) {
                instanceIDs.add(instance.getInstanceId());

                if (logger.isDebugEnabled()) {
                    logger.debug("Found instance {} in region {}",
                            new Object[] { instance.getInstanceId(), region.getRegionName() });
                }// ww w  .  j ava  2s.  c  om
            }
        }
    }
}

From source file:de.zalando.awsqueen.awqfetch.FetchCLI.java

License:Open Source License

private void fetchEC2(final Region region) {
    Path ec2Path = Paths.get(currentDir, "ec2");
    ec2Path.toFile().mkdir();/*from ww w. ja  v a  2 s . c  o m*/

    AmazonEC2Client amazonEC2Client = new AmazonEC2Client();
    amazonEC2Client.setRegion(region);

    DescribeInstancesResult describeInstancesResult = amazonEC2Client.describeInstances();
    List<Reservation> reservations = describeInstancesResult.getReservations();
    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();
        for (Instance instance : instances) {
            System.out.println("instance id: " + instance.getInstanceId());
        }
    }

}

From source file:org.apache.airavata.gfac.ec2.AmazonInstanceScheduler.java

License:Apache License

/**
 * Load instances associated with the given ec2 client
 *
 * @param ec2client ec2 client//from   w w w .jav  a  2 s . c o  m
 * @return list of instances
 */
public static List<Instance> loadInstances(AmazonEC2Client ec2client) {
    List<Instance> resultList = new ArrayList<Instance>();
    DescribeInstancesResult describeInstancesResult = ec2client.describeInstances();
    List<Reservation> reservations = describeInstancesResult.getReservations();
    for (Reservation reservation : reservations) {
        for (Instance instance : reservation.getInstances()) {
            System.out.println("instance       : " + instance);
            if ("running".equalsIgnoreCase(instance.getState().getName())) {
                resultList.add(instance);
            }
        }
    }
    return resultList;
}

From source file:org.elasticdroid.model.EC2DashboardModel.java

License:Open Source License

/**
 * Gets the data to populate the EC2 Dashboard with in the background thread, and loads it into
 * a Hashtable<String, Integer>. //from  w  ww  .j  av  a  2 s  .c o m
 * 
 * @param This method accepts *ONE* Hashtable<String, String> of LoginDetails arguments. The
 * required keys are as follows (anything else is ignored):
 * <ul>
 * <li> accessKey: The accesskey for the AWS/AWS IAM account used.</li> 
 * <li> secretAccessKey: The secretAccessKey for the AWS/AWS IAM account used.</li> 
 * <li> endpoint: AWS Endpoint for the selected region (@see {@link AWSConstants.EndPoints}</li>
 * </ul>
 * If you're missing any of these keys, AmazonServiceExceptions will be thrown. This shouldn't
 * be visible to the end-user as this is a programmer fault!!! :P
 * 
 * @return This method can return:
 * <ul>
 * <li>{@link IllegalArgumentException}: If there are too many/few arguments, or the keys are  
 * incorrect. Only one Hashtable<String, String> accepted.</li>
 * <li>{@link Hashtable<String, Integer}: data to populate dashboard with.
 *       <ul>
 *       <li><i>runningInstances:</i> The number of running instances for the user in the current 
 *       region</li>
 *       <li><i>stoppedInstances:</i> The number of stopped instances for the user in the current 
 *       region</li>
 *       <li><i>elasticIp:</i> The number of elastic IPs owned by the user (in the current region)
 *      </li>
 *       <li><i>securityGroups:</i> The number of security groups avail 2 the user (in the current
 *       region)</li>
 *       <li><i>keyPairs:</i> The number of keypairs avail 2 the user (in the current
 *       region)</li>
 *       </ul> 
 * </li>
 * </ul>
 */
@SuppressWarnings("unchecked")
@Override
protected Object doInBackground(HashMap<?, ?>... params) {
    HashMap<String, String> connectionData;
    HashMap<String, Integer> dashboardData;

    //we accept only one param, but AsyncTask forces us to potentially accept
    //a whole bloody lot of them. :P
    if (params.length != 1) {
        return new IllegalArgumentException(
                "Only one Hashtable<String,String> parameter " + "should be passed.");
    }
    connectionData = (HashMap<String, String>) params[0]; //convenience variable, so that
    //i dont have to keep typing params[0] everywhere in this method.;)

    Log.v(this.getClass().getName(), "Getting EC2 dashboard data...");

    //prepare to get the dashboard data!
    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));
    //create Amazon EC2 Client object, and set tye end point to the region. params[3]
    //contains endpoint
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);
    amazonEC2Client.setEndpoint(connectionData.get("endpoint"));
    //initialise result holder variable
    dashboardData = new HashMap<String, Integer>();

    try {
        //get the number of running and stopped instances
        DescribeInstancesResult instances = amazonEC2Client.describeInstances();

        int numOfRunningInstances = 0;
        int numOfStoppedInstances = 0;
        //get the list of reservations in the results
        for (Reservation reservation : instances.getReservations()) {
            //for each reservation, get the list of instances associated
            for (Instance instance : reservation.getInstances()) {
                if (instance.getState().getCode().byteValue() == InstanceStateConstants.RUNNING) {
                    numOfRunningInstances++;
                } else if (instance.getState().getCode().byteValue() == InstanceStateConstants.STOPPED) {
                    numOfStoppedInstances++;
                }
            }
        }
        dashboardData.put("runningInstances", numOfRunningInstances);
        dashboardData.put("stoppedInstances", numOfStoppedInstances);

        //get the list of elastic Ips.
        dashboardData.put("elasticIp", amazonEC2Client.describeAddresses().getAddresses().size());

        //get the list of security groups
        dashboardData.put("securityGroups",
                amazonEC2Client.describeSecurityGroups().getSecurityGroups().size());

        //get the list of keypairs
        dashboardData.put("keyPairs", amazonEC2Client.describeKeyPairs().getKeyPairs().size());
    } catch (AmazonServiceException amazonServiceException) {
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        return amazonClientException;
    }

    return dashboardData;
}

From source file:pl.edu.agh.samm.tadapter.eucalyptus.EucalyptusTransportAdapter.java

License:Open Source License

/**
 * Find children of cluster controller in fact... Reacts only when in
 * <code>types</code> list the type of VirtualNode appears.
 *
 * @see pl.edu.agh.samm.api.tadapter.ITransportAdapter#discoverChildren(pl.edu.agh.samm.api.core.Resource,
 *      java.util.List)//w  w  w .  j  a  v a  2s.  c  om
 */
@Override
public void discoverChildren(Resource resource, List<String> types) throws Exception {

    if (types.contains(VIRTUAL_NODE_TYPE)) {
        AmazonEC2Client ec2Client = ec2Clients.get(resource);
        if (ec2Client == null) {
            throw new ResourceNotRegisteredException(resource.getUri());
        }

        DescribeInstancesResult result = ec2Client.describeInstances();
        List<Reservation> reservations = result.getReservations();
        Set<Instance> instances = new HashSet<Instance>();

        for (Reservation reservation : reservations) {
            List<Instance> instancesFromReservation = reservation.getInstances();
            for (Instance instance : instancesFromReservation) {
                if (instance.getState().getName().equals(InstanceStateName.Running.toString())) {
                    instances.add(instance);
                }
            }
        }

        Map<String, String> childrenTypes = new HashMap<String, String>();
        Map<String, Map<String, Object>> childrenProperties = new HashMap<String, Map<String, Object>>();

        for (Instance instance : instances) {
            String child = resource.getUri() + "/" + VIRTUAL_NODE_NAME_PREFIX + instance.getInstanceId();
            Map<String, Object> newProperties = new HashMap<String, Object>(resource.getProperties());
            childrenProperties.put(child, newProperties);
            childrenTypes.put(child, VIRTUAL_NODE_TYPE);
        }
        fireNewResourcesEvent(resource.getUri(), childrenTypes, childrenProperties);
    }
}