Search in sources :

Example 56 with Instance

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

Example 57 with Instance

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

the class AWSEC2 method createInstanceAndWait.

/**
   * Create an Instance
   *
   * @param ec2
   * @param amiRecord
   * @param key
   * @param securityGroup
   * @return the instanceID string
   */
public static String createInstanceAndWait(AmazonEC2 ec2, AMIRecord amiRecord, String key, SecurityGroup securityGroup) {
    RunInstancesRequest runInstancesRequest;
    if (amiRecord.getVpcSubnet() != null) {
        System.out.println("subnet: " + amiRecord.getVpcSubnet() + " securityGroup: " + securityGroup.getGroupName());
        // new VPC
        runInstancesRequest = new RunInstancesRequest().withMinCount(1).withMaxCount(1).withImageId(amiRecord.getName()).withInstanceType(amiRecord.getInstanceType()).withKeyName(key).withSubnetId(amiRecord.getVpcSubnet()).withSecurityGroupIds(Arrays.asList(securityGroup.getGroupId()));
    } else {
        runInstancesRequest = new RunInstancesRequest(amiRecord.getName(), 1, 1);
        runInstancesRequest.setInstanceType(amiRecord.getInstanceType());
        runInstancesRequest.setSecurityGroups(new ArrayList<>(Arrays.asList(securityGroup.getGroupName())));
        runInstancesRequest.setKeyName(key);
    }
    RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);
    Instance instance = runInstancesResult.getReservation().getInstances().get(0);
    String createdInstanceId = instance.getInstanceId();
    System.out.println("Waiting for instance " + amiRecord.getName() + " to start");
    long startTime = System.currentTimeMillis();
    do {
        ThreadUtils.sleep(1000);
        if (System.currentTimeMillis() - startTime > 90000) {
            // give it a minute and a half
            System.out.println(createdInstanceId + " timed out waiting for start.");
            return null;
        }
        // regrab the instance data from the server
        instance = findInstance(ec2, createdInstanceId);
        //System.out.print(instance.getState().getName());
        System.out.print(".");
    } while (instance != null && !instance.getState().getName().equals(InstanceStateRecord.RUNNING.getName()));
    System.out.println();
    return createdInstanceId;
}
Also used : Instance(com.amazonaws.services.ec2.model.Instance) RunInstancesResult(com.amazonaws.services.ec2.model.RunInstancesResult) RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest)

Example 58 with Instance

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

the class AWSEC2 method describeInstanceDNSAndIP.

/**
   * Print public DNS and IP of an instance
   *
   * @param ec2
   * @param createdInstanceId
   */
public static void describeInstanceDNSAndIP(AmazonEC2 ec2, String createdInstanceId) {
    Instance instance = findInstance(ec2, createdInstanceId);
    if (instance != null) {
        StringBuilder output = new StringBuilder();
        output.append("The public DNS is: ").append(instance.getPublicDnsName());
        output.append(NEWLINE);
        output.append("The private IP is: ").append(instance.getPrivateIpAddress());
        output.append(NEWLINE);
        output.append("The public IP is: ").append(instance.getPublicIpAddress());
        GNSConfig.getLogger().info(output.toString());
    }
}
Also used : Instance(com.amazonaws.services.ec2.model.Instance)

Example 59 with Instance

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

the class Amazontool method main.

/**
   * @param args the command line arguments
   * @throws java.io.IOException
   */
public static void main(String[] args) throws IOException {
    AWSCredentials credentials = new PropertiesCredentials(AWSEC2.class.getResourceAsStream("resources/AwsCredentials.properties"));
    //Create Amazon Client object
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    AWSEC2.describeAllEndpoints(ec2);
//    Instance instance = AWSEC2.findInstance(ec2, "i-86983af6");
//    Address elasticIP = AWSEC2.findElasticIP(ec2, "23.21.120.250");
//    System.out.println(instance.getPublicDnsName());
//    System.out.println(elasticIP.getPublicIp());
//AWSEC2.associateAddress(ec2, "23.21.120.250", instance);
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client) PropertiesCredentials(com.amazonaws.auth.PropertiesCredentials) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) AWSCredentials(com.amazonaws.auth.AWSCredentials)

Example 60 with Instance

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

the class AWSEC2 method createAndInitInstance.

/**
   * Creates an EC2 instance in the region given. Timeout in milleseconds can be specified.
   *
   * @param ec2
   * @param region
   * @param amiRecord
   * @param instanceName
   * @param keyName
   * @param securityGroupName
   * @param script
   * @param tags
   * @param elasticIP
   * @param timeout
   * @return a new instance instance
   */
public static Instance createAndInitInstance(AmazonEC2 ec2, RegionRecord region, AMIRecord amiRecord, String instanceName, String keyName, String securityGroupName, String script, Map<String, String> tags, String elasticIP, int timeout) {
    try {
        // set the region (AKA endpoint)
        setRegion(ec2, region);
        // create the instance
        SecurityGroup securityGroup = findOrCreateSecurityGroup(ec2, securityGroupName);
        String keyPair = findOrCreateKeyPair(ec2, keyName);
        String instanceID = createInstanceAndWait(ec2, amiRecord, keyPair, securityGroup);
        if (instanceID == null) {
            return null;
        }
        System.out.println("Instance " + instanceName + " is running in " + region.name());
        // add a name to the instance
        addInstanceTag(ec2, instanceID, "Name", instanceName);
        if (tags != null) {
            addInstanceTags(ec2, instanceID, tags);
        }
        Instance instance = findInstance(ec2, instanceID);
        if (instance == null) {
            return null;
        }
        String hostname = instance.getPublicDnsName();
        System.out.println("Waiting " + timeout / 1000 + " seconds for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable.");
        long startTime = System.currentTimeMillis();
        while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
            ThreadUtils.sleep(1000);
            System.out.print(".");
            if (System.currentTimeMillis() - startTime > timeout) {
                System.out.println(instanceName + " (" + hostname + ")" + " timed out during reachability check.");
                return null;
            }
        }
        System.out.println();
        System.out.println(instanceName + " (" + hostname + ")" + " is reachable.");
        // associate the elasticIP if one is provided
        if (elasticIP != null) {
            System.out.println("Using ElasticIP " + elasticIP + " for instance " + instanceName + " (" + instanceID + ")");
            AWSEC2.associateAddress(ec2, elasticIP, instance);
            // get a new copy cuz things have changed
            instance = findInstance(ec2, instanceID);
            if (instance == null) {
                return null;
            }
            // recheck reachability
            hostname = instance.getPublicDnsName();
            System.out.println("Waiting " + timeout / 1000 + " s for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable after Elastic IP change.");
            startTime = System.currentTimeMillis();
            while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
                ThreadUtils.sleep(1000);
                System.out.print(".");
                if (System.currentTimeMillis() - startTime > timeout) {
                    // give it a minute and ahalf
                    System.out.println(instanceName + " (" + hostname + ")" + " timed out during second (elastic IP) reachability check.");
                    return null;
                }
            }
            System.out.println();
            System.out.println(instanceName + " (" + hostname + ")" + " is still reachable.");
        }
        if (script != null) {
            File keyFile = new File(KEYHOME + FILESEPARATOR + keyName + PRIVATEKEYFILEEXTENSION);
            ExecuteBash.executeBashScript("ec2-user", hostname, keyFile, true, "installScript.sh", script);
        }
        return instance;
    } 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());
    }
    return null;
}
Also used : Instance(com.amazonaws.services.ec2.model.Instance) AmazonServiceException(com.amazonaws.AmazonServiceException) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup) File(java.io.File)

Aggregations

Instance (com.amazonaws.services.ec2.model.Instance)33 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)20 Reservation (com.amazonaws.services.ec2.model.Reservation)16 DescribeInstancesResult (com.amazonaws.services.ec2.model.DescribeInstancesResult)12 RunInstancesResult (com.amazonaws.services.ec2.model.RunInstancesResult)11 Test (org.junit.Test)10 DescribeInstancesRequest (com.amazonaws.services.ec2.model.DescribeInstancesRequest)8 AmazonEC2Client (com.amazonaws.services.ec2.AmazonEC2Client)7 Filter (com.amazonaws.services.ec2.model.Filter)7 Tag (com.amazonaws.services.ec2.model.Tag)7 AWSClient (com.netflix.simianarmy.client.aws.AWSClient)7 ArrayList (java.util.ArrayList)7 Exchange (org.apache.camel.Exchange)7 Processor (org.apache.camel.Processor)7 AmazonServiceException (com.amazonaws.AmazonServiceException)6 LinkedList (java.util.LinkedList)6 AWSCredentials (com.amazonaws.auth.AWSCredentials)5 PropertiesCredentials (com.amazonaws.auth.PropertiesCredentials)5 AutoScalingInstanceDetails (com.amazonaws.services.autoscaling.model.AutoScalingInstanceDetails)5 RunInstancesRequest (com.amazonaws.services.ec2.model.RunInstancesRequest)5