Search in sources :

Example 26 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project elasticsearch by elastic.

the class AmazonEC2Mock method describeInstances.

@Override
public DescribeInstancesResult describeInstances(DescribeInstancesRequest describeInstancesRequest) throws AmazonServiceException, AmazonClientException {
    Collection<Instance> filteredInstances = new ArrayList<>();
    logger.debug("--> mocking describeInstances");
    for (Instance instance : instances) {
        boolean tagFiltered = false;
        boolean instanceFound = false;
        Map<String, List<String>> expectedTags = new HashMap<>();
        Map<String, List<String>> instanceTags = new HashMap<>();
        for (Tag tag : instance.getTags()) {
            List<String> tags = instanceTags.get(tag.getKey());
            if (tags == null) {
                tags = new ArrayList<>();
                instanceTags.put(tag.getKey(), tags);
            }
            tags.add(tag.getValue());
        }
        for (Filter filter : describeInstancesRequest.getFilters()) {
            // If we have the same tag name and one of the values, we add the instance
            if (filter.getName().startsWith("tag:")) {
                tagFiltered = true;
                String tagName = filter.getName().substring(4);
                // if we have more than one value for the same key, then the key is appended with .x
                Pattern p = Pattern.compile("\\.\\d+", Pattern.DOTALL);
                Matcher m = p.matcher(tagName);
                if (m.find()) {
                    int i = tagName.lastIndexOf(".");
                    tagName = tagName.substring(0, i);
                }
                List<String> tags = expectedTags.get(tagName);
                if (tags == null) {
                    tags = new ArrayList<>();
                    expectedTags.put(tagName, tags);
                }
                tags.addAll(filter.getValues());
            }
        }
        if (tagFiltered) {
            logger.debug("--> expected tags: [{}]", expectedTags);
            logger.debug("--> instance tags: [{}]", instanceTags);
            instanceFound = true;
            for (Map.Entry<String, List<String>> expectedTagsEntry : expectedTags.entrySet()) {
                List<String> instanceTagValues = instanceTags.get(expectedTagsEntry.getKey());
                if (instanceTagValues == null) {
                    instanceFound = false;
                    break;
                }
                for (String expectedValue : expectedTagsEntry.getValue()) {
                    boolean valueFound = false;
                    for (String instanceTagValue : instanceTagValues) {
                        if (instanceTagValue.equals(expectedValue)) {
                            valueFound = true;
                        }
                    }
                    if (valueFound == false) {
                        instanceFound = false;
                    }
                }
            }
        }
        if (tagFiltered == false || instanceFound) {
            logger.debug("--> instance added");
            filteredInstances.add(instance);
        } else {
            logger.debug("--> instance filtered");
        }
    }
    return new DescribeInstancesResult().withReservations(new Reservation().withInstances(filteredInstances));
}
Also used : Pattern(java.util.regex.Pattern) Instance(com.amazonaws.services.ec2.model.Instance) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) Reservation(com.amazonaws.services.ec2.model.Reservation) Filter(com.amazonaws.services.ec2.model.Filter) ArrayList(java.util.ArrayList) List(java.util.List) Tag(com.amazonaws.services.ec2.model.Tag) Map(java.util.Map) HashMap(java.util.HashMap)

Example 27 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project druid by druid-io.

the class EC2AutoScaler method idToIpLookup.

@Override
public List<String> idToIpLookup(List<String> nodeIds) {
    final List<String> retVal = FluentIterable.from(Lists.partition(nodeIds, MAX_AWS_FILTER_VALUES)).transformAndConcat(new Function<List<String>, Iterable<Reservation>>() {

        @Override
        public Iterable<Reservation> apply(List<String> input) {
            return amazonEC2Client.describeInstances(new DescribeInstancesRequest().withFilters(new Filter("instance-id", input))).getReservations();
        }
    }).transformAndConcat(new Function<Reservation, Iterable<Instance>>() {

        @Override
        public Iterable<Instance> apply(Reservation reservation) {
            return reservation.getInstances();
        }
    }).transform(new Function<Instance, String>() {

        @Override
        public String apply(Instance instance) {
            return instance.getPrivateIpAddress();
        }
    }).toList();
    log.debug("Performing lookup: %s --> %s", nodeIds, retVal);
    return retVal;
}
Also used : Function(com.google.common.base.Function) Reservation(com.amazonaws.services.ec2.model.Reservation) FluentIterable(com.google.common.collect.FluentIterable) Filter(com.amazonaws.services.ec2.model.Filter) Instance(com.amazonaws.services.ec2.model.Instance) List(java.util.List) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest)

Example 28 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project druid by druid-io.

the class EC2AutoScaler method ipToIdLookup.

@Override
public List<String> ipToIdLookup(List<String> ips) {
    final List<String> retVal = FluentIterable.from(Lists.partition(ips, MAX_AWS_FILTER_VALUES)).transformAndConcat(new Function<List<String>, Iterable<Reservation>>() {

        @Override
        public Iterable<Reservation> apply(List<String> input) {
            return amazonEC2Client.describeInstances(new DescribeInstancesRequest().withFilters(new Filter("private-ip-address", input))).getReservations();
        }
    }).transformAndConcat(new Function<Reservation, Iterable<Instance>>() {

        @Override
        public Iterable<Instance> apply(Reservation reservation) {
            return reservation.getInstances();
        }
    }).transform(new Function<Instance, String>() {

        @Override
        public String apply(Instance instance) {
            return instance.getInstanceId();
        }
    }).toList();
    log.debug("Performing lookup: %s --> %s", ips, retVal);
    return retVal;
}
Also used : Function(com.google.common.base.Function) Reservation(com.amazonaws.services.ec2.model.Reservation) FluentIterable(com.google.common.collect.FluentIterable) Filter(com.amazonaws.services.ec2.model.Filter) Instance(com.amazonaws.services.ec2.model.Instance) List(java.util.List) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest)

Example 29 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project GNS by MobilityFirst.

the class AWSEC2 method getInstances.

/**
   * Returns all the instances in this region.
   *
   * @param ec2
   * @return a set of instance instances
   */
public static Set<Instance> getInstances(AmazonEC2 ec2) {
    Set<Instance> instances = new HashSet<>();
    DescribeInstancesResult describeInstancesResult = ec2.describeInstances();
    List<Reservation> reservations = describeInstancesResult.getReservations();
    // add all instances to a Set.
    for (Reservation reservation : reservations) {
        instances.addAll(reservation.getInstances());
    }
    return instances;
}
Also used : DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) Reservation(com.amazonaws.services.ec2.model.Reservation) Instance(com.amazonaws.services.ec2.model.Instance) HashSet(java.util.HashSet)

Example 30 with Reservation

use of software.amazon.awssdk.services.ec2.model.Reservation in project GNS by MobilityFirst.

the class AWSStatusCheck method main.

/**
   *
   * @param args
   * @throws Exception
   */
public static void main(String[] args) throws Exception {
    init();
    /*
     * Amazon EC2
     */
    for (String endpoint : endpoints) {
        try {
            ec2.setEndpoint(endpoint);
            System.out.println("**** Endpoint: " + endpoint);
            DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
            System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() + " Availability Zones.");
            for (AvailabilityZone zone : availabilityZonesResult.getAvailabilityZones()) {
                System.out.println(zone.getZoneName());
            }
            DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
            List<Reservation> reservations = describeInstancesRequest.getReservations();
            Set<Instance> instances = new HashSet<Instance>();
            System.out.println("Instances: ");
            for (Reservation reservation : reservations) {
                for (Instance instance : reservation.getInstances()) {
                    instances.add(instance);
                    System.out.println(instance.getPublicDnsName() + " is " + instance.getState().getName());
                }
            }
            System.out.println("Security groups: ");
            DescribeSecurityGroupsResult describeSecurityGroupsResult = ec2.describeSecurityGroups();
            for (SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) {
                System.out.println(securityGroup.getGroupName());
            }
        //System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        } 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());
        }
        /*
       * Amazon SimpleDB
       *
       */
        try {
            ListDomainsRequest sdbRequest = new ListDomainsRequest().withMaxNumberOfDomains(100);
            ListDomainsResult sdbResult = sdb.listDomains(sdbRequest);
            int totalItems = 0;
            for (String domainName : sdbResult.getDomainNames()) {
                DomainMetadataRequest metadataRequest = new DomainMetadataRequest().withDomainName(domainName);
                DomainMetadataResult domainMetadata = sdb.domainMetadata(metadataRequest);
                totalItems += domainMetadata.getItemCount();
            }
            System.out.println("You have " + sdbResult.getDomainNames().size() + " Amazon SimpleDB domain(s)" + "containing a total of " + totalItems + " items.");
        } 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());
        }
        /*
       * Amazon S3
       *.
       */
        try {
            List<Bucket> buckets = s3.listBuckets();
            long totalSize = 0;
            int totalItems = 0;
            for (Bucket bucket : buckets) {
                /*
           * In order to save bandwidth, an S3 object listing does not
           * contain every object in the bucket; after a certain point the
           * S3ObjectListing is truncated, and further pages must be
           * obtained with the AmazonS3Client.listNextBatchOfObjects()
           * method.
           */
                ObjectListing objects = s3.listObjects(bucket.getName());
                do {
                    for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                        totalSize += objectSummary.getSize();
                        totalItems++;
                    }
                    objects = s3.listNextBatchOfObjects(objects);
                } while (objects.isTruncated());
            }
            System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s), " + "containing " + totalItems + " objects with a total size of " + totalSize + " bytes.");
        } catch (AmazonServiceException ase) {
            /*
         * AmazonServiceExceptions represent an error response from an AWS
         * services, i.e. your request made it to AWS, but the AWS service
         * either found it invalid or encountered an error trying to execute
         * it.
         */
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            /*
         * AmazonClientExceptions represent an error that occurred inside
         * the client on the local host, either while trying to send the
         * request to AWS or interpret the response. For example, if no
         * network connection is available, the client won't be able to
         * connect to AWS to execute a request and will throw an
         * AmazonClientException.
         */
            System.out.println("Error Message: " + ace.getMessage());
        }
    }
}
Also used : ListDomainsResult(com.amazonaws.services.simpledb.model.ListDomainsResult) Instance(com.amazonaws.services.ec2.model.Instance) DomainMetadataResult(com.amazonaws.services.simpledb.model.DomainMetadataResult) AmazonClientException(com.amazonaws.AmazonClientException) AvailabilityZone(com.amazonaws.services.ec2.model.AvailabilityZone) ObjectListing(com.amazonaws.services.s3.model.ObjectListing) S3ObjectSummary(com.amazonaws.services.s3.model.S3ObjectSummary) DescribeAvailabilityZonesResult(com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) DomainMetadataRequest(com.amazonaws.services.simpledb.model.DomainMetadataRequest) Reservation(com.amazonaws.services.ec2.model.Reservation) Bucket(com.amazonaws.services.s3.model.Bucket) ListDomainsRequest(com.amazonaws.services.simpledb.model.ListDomainsRequest) AmazonServiceException(com.amazonaws.AmazonServiceException) DescribeSecurityGroupsResult(com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult) HashSet(java.util.HashSet)

Aggregations

Reservation (com.amazonaws.services.ec2.model.Reservation)39 Instance (com.amazonaws.services.ec2.model.Instance)35 DescribeInstancesResult (com.amazonaws.services.ec2.model.DescribeInstancesResult)23 ArrayList (java.util.ArrayList)21 DescribeInstancesRequest (com.amazonaws.services.ec2.model.DescribeInstancesRequest)16 Filter (com.amazonaws.services.ec2.model.Filter)11 CloudInstance (com.sequenceiq.cloudbreak.cloud.model.CloudInstance)8 Test (org.junit.Test)8 Tag (com.amazonaws.services.ec2.model.Tag)7 Function (com.google.common.base.Function)6 AwsCredentialView (com.sequenceiq.cloudbreak.cloud.aws.view.AwsCredentialView)6 CloudVmMetaDataStatus (com.sequenceiq.cloudbreak.cloud.model.CloudVmMetaDataStatus)6 AmazonAutoScalingClient (com.amazonaws.services.autoscaling.AmazonAutoScalingClient)5 AmazonCloudFormationClient (com.amazonaws.services.cloudformation.AmazonCloudFormationClient)5 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)5 CreateTagsRequest (com.amazonaws.services.ec2.model.CreateTagsRequest)5 AuthenticatedContext (com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext)5 InstanceAuthentication (com.sequenceiq.cloudbreak.cloud.model.InstanceAuthentication)5 InstanceTemplate (com.sequenceiq.cloudbreak.cloud.model.InstanceTemplate)5 Volume (com.sequenceiq.cloudbreak.cloud.model.Volume)5