Search in sources :

Example 1 with SecurityGroup

use of com.amazonaws.services.ec2.model.SecurityGroup in project h2o-2 by h2oai.

the class EC2 method resize.

//@formatter:on
/**
   * Create or terminate EC2 instances. Uses their Name tag to find existing ones.
   */
public Cloud resize() throws Exception {
    AmazonEC2Client ec2 = new AmazonEC2Client(new PersistS3.H2OAWSCredentialsProviderChain());
    ec2.setEndpoint("ec2." + region + ".amazonaws.com");
    DescribeInstancesResult describeInstancesResult = ec2.describeInstances();
    List<Reservation> reservations = describeInstancesResult.getReservations();
    List<Instance> instances = new ArrayList<Instance>();
    for (Reservation reservation : reservations) {
        for (Instance instance : reservation.getInstances()) {
            String ip = ip(instance);
            if (ip != null) {
                String name = null;
                if (instance.getTags().size() > 0)
                    name = instance.getTags().get(0).getValue();
                if (NAME.equals(name))
                    instances.add(instance);
            }
        }
    }
    System.out.println("Found " + instances.size() + " EC2 instances for user " + USER);
    if (instances.size() > boxes) {
        for (int i = 0; i < instances.size() - boxes; i++) {
        // TODO terminate?
        }
    } else if (instances.size() < boxes) {
        int launchCount = boxes - instances.size();
        System.out.println("Creating " + launchCount + " EC2 instances.");
        if (confirm) {
            System.out.println("Please confirm [y/n]");
            String s = Utils.readConsole();
            if (s == null || !s.equalsIgnoreCase("y"))
                throw new Exception("Aborted");
        }
        CreatePlacementGroupRequest group = new CreatePlacementGroupRequest();
        group.withGroupName(USER);
        group.withStrategy(PlacementStrategy.Cluster);
        try {
            ec2.createPlacementGroup(group);
        } catch (AmazonServiceException ex) {
            if (!"InvalidPlacementGroup.Duplicate".equals(ex.getErrorCode()))
                throw ex;
        }
        RunInstancesRequest run = new RunInstancesRequest();
        run.withInstanceType(type);
        run.withImageId(image);
        run.withMinCount(launchCount).withMaxCount(launchCount);
        run.withSecurityGroupIds(securityGroup);
        Placement placement = new Placement();
        placement.setGroupName(USER);
        run.withPlacement(placement);
        BlockDeviceMapping map = new BlockDeviceMapping();
        map.setDeviceName("/dev/sdb");
        map.setVirtualName("ephemeral0");
        run.withBlockDeviceMappings(map);
        run.withUserData(new String(Base64.encodeBase64(cloudConfig.getBytes())));
        RunInstancesResult runRes = ec2.runInstances(run);
        ArrayList<String> ids = new ArrayList<String>();
        for (Instance instance : runRes.getReservation().getInstances()) ids.add(instance.getInstanceId());
        List<Instance> created = wait(ec2, ids);
        System.out.println("Created " + created.size() + " EC2 instances.");
        instances.addAll(created);
    }
    String[] pub = new String[boxes];
    String[] prv = new String[boxes];
    for (int i = 0; i < boxes; i++) {
        pub[i] = instances.get(i).getPublicIpAddress();
        prv[i] = instances.get(i).getPrivateIpAddress();
    }
    System.out.println("EC2 public IPs: " + Utils.join(' ', pub));
    System.out.println("EC2 private IPs: " + Utils.join(' ', prv));
    Cloud cloud = new Cloud();
    cloud.publicIPs.addAll(Arrays.asList(pub));
    cloud.privateIPs.addAll(Arrays.asList(prv));
    return cloud;
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client) PersistS3(water.persist.PersistS3) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonServiceException(com.amazonaws.AmazonServiceException)

Example 2 with SecurityGroup

use of com.amazonaws.services.ec2.model.SecurityGroup in project GNS by MobilityFirst.

the class AWSEC2 method describeSecurityGroups.

/**
   * Describe Security Groups
   *
   * @param ec2
   */
public static void describeSecurityGroups(AmazonEC2 ec2) {
    StringBuilder output = new StringBuilder();
    String prefix = currentTab + "Security Groups: ";
    DescribeSecurityGroupsResult describeSecurityGroupsResult = ec2.describeSecurityGroups();
    for (SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) {
        output.append(prefix);
        prefix = ", ";
        output.append(securityGroup.getGroupName());
    }
    System.out.println(output);
}
Also used : DescribeSecurityGroupsResult(com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup)

Example 3 with SecurityGroup

use of com.amazonaws.services.ec2.model.SecurityGroup in project aws-doc-sdk-examples by awsdocs.

the class DescribeSecurityGroups method main.

public static void main(String[] args) {
    final String USAGE = "To run this example, supply a group id\n" + "Ex: DescribeSecurityGroups <group-id>\n";
    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }
    String group_id = args[0];
    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest().withGroupIds(group_id);
    DescribeSecurityGroupsResult response = ec2.describeSecurityGroups(request);
    for (SecurityGroup group : response.getSecurityGroups()) {
        System.out.printf("Found security group with id %s, " + "vpc id %s " + "and description %s", group.getGroupId(), group.getVpcId(), group.getDescription());
    }
}
Also used : DescribeSecurityGroupsRequest(com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) DescribeSecurityGroupsResult(com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup)

Example 4 with SecurityGroup

use of com.amazonaws.services.ec2.model.SecurityGroup in project SimianArmy by Netflix.

the class AWSClient method describeSecurityGroups.

/**
     * Describe a set of security groups.
     *
     * @param groupNames the names of the groups to find
     * @return a list of matching groups
     */
public List<SecurityGroup> describeSecurityGroups(String... groupNames) {
    AmazonEC2 ec2Client = ec2Client();
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
    if (groupNames == null || groupNames.length == 0) {
        LOGGER.info(String.format("Getting all EC2 security groups in region %s.", region));
    } else {
        LOGGER.info(String.format("Getting EC2 security groups for %d names in region %s.", groupNames.length, region));
        request.withGroupNames(groupNames);
    }
    DescribeSecurityGroupsResult result;
    try {
        result = ec2Client.describeSecurityGroups(request);
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidGroup.NotFound")) {
            LOGGER.info("Got InvalidGroup.NotFound error for security groups; returning empty list");
            return Collections.emptyList();
        }
        throw e;
    }
    List<SecurityGroup> securityGroups = result.getSecurityGroups();
    LOGGER.info(String.format("Got %d EC2 security groups in region %s.", securityGroups.size(), region));
    return securityGroups;
}
Also used : AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2)

Example 5 with SecurityGroup

use of com.amazonaws.services.ec2.model.SecurityGroup 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

SecurityGroup (com.amazonaws.services.ec2.model.SecurityGroup)5 AmazonServiceException (com.amazonaws.AmazonServiceException)4 DescribeSecurityGroupsResult (com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult)3 Instance (com.amazonaws.services.ec2.model.Instance)3 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)2 AmazonClientException (com.amazonaws.AmazonClientException)1 AmazonEC2Client (com.amazonaws.services.ec2.AmazonEC2Client)1 AvailabilityZone (com.amazonaws.services.ec2.model.AvailabilityZone)1 DescribeAvailabilityZonesResult (com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult)1 DescribeInstancesResult (com.amazonaws.services.ec2.model.DescribeInstancesResult)1 DescribeSecurityGroupsRequest (com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest)1 Reservation (com.amazonaws.services.ec2.model.Reservation)1 RunInstancesRequest (com.amazonaws.services.ec2.model.RunInstancesRequest)1 RunInstancesResult (com.amazonaws.services.ec2.model.RunInstancesResult)1 Bucket (com.amazonaws.services.s3.model.Bucket)1 ObjectListing (com.amazonaws.services.s3.model.ObjectListing)1 S3ObjectSummary (com.amazonaws.services.s3.model.S3ObjectSummary)1 DomainMetadataRequest (com.amazonaws.services.simpledb.model.DomainMetadataRequest)1 DomainMetadataResult (com.amazonaws.services.simpledb.model.DomainMetadataResult)1 ListDomainsRequest (com.amazonaws.services.simpledb.model.ListDomainsRequest)1