Example usage for com.amazonaws.services.ec2.model Instance getPrivateIpAddress

List of usage examples for com.amazonaws.services.ec2.model Instance getPrivateIpAddress

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model Instance getPrivateIpAddress.

Prototype


public String getPrivateIpAddress() 

Source Link

Document

The private IPv4 address assigned to the instance.

Usage

From source file:AwsSample.java

License:Open Source License

public static void main(String[] args) throws Exception {

    BasicAWSCredentials credentials = new BasicAWSCredentials("", "");

    /*********************************************
     * //from   www  . j av  a2 s.c  o m
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);

    try {

        /*********************************************
         * 
          *  #2 Describe Availability Zones.
          *  
          *********************************************/
        System.out.println("#2 Describe Availability Zones.");
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");

        /*********************************************
         * 
         *  #3 Describe Available Images
         *  
         *********************************************/
        System.out.println("#3 Describe Available Images");
        DescribeImagesResult dir = ec2.describeImages();
        List<Image> images = dir.getImages();
        System.out.println("You have " + images.size() + " Amazon images");

        /*********************************************
         *                 
         *  #4 Describe Key Pair
         *                 
         *********************************************/
        System.out.println("#9 Describe Key Pair");
        DescribeKeyPairsResult dkr = ec2.describeKeyPairs();
        System.out.println(dkr.toString());

        /*********************************************
         * 
         *  #5 Describe Current Instances
         *  
         *********************************************/
        System.out.println("#4 Describe Current Instances");
        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();
        // add all instances to a Set.
        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s).");
        for (Instance ins : instances) {

            // instance id
            String instanceId = ins.getInstanceId();

            // instance state
            InstanceState is = ins.getState();
            System.out.println(instanceId + " " + is.getName());
        }
        ///////////////////////////////////////

        String Temp_Group = "Testgroup1"; //name of the group
        CreateSecurityGroupRequest r1 = new CreateSecurityGroupRequest(Temp_Group, "temporal group");
        ec2.createSecurityGroup(r1);
        AuthorizeSecurityGroupIngressRequest r2 = new AuthorizeSecurityGroupIngressRequest();
        r2.setGroupName(Temp_Group);

        /*************the property of http*****************/
        IpPermission permission = new IpPermission();
        permission.setIpProtocol("tcp");
        permission.setFromPort(80);
        permission.setToPort(80);
        List<String> ipRanges = new ArrayList<String>();
        ipRanges.add("0.0.0.0/0");
        permission.setIpRanges(ipRanges);

        /*************the property of SSH**********************/
        IpPermission permission1 = new IpPermission();
        permission1.setIpProtocol("tcp");
        permission1.setFromPort(22);
        permission1.setToPort(22);
        List<String> ipRanges1 = new ArrayList<String>();
        ipRanges1.add("0.0.0.0/22");
        permission1.setIpRanges(ipRanges1);

        /*************the property of https**********************/
        IpPermission permission2 = new IpPermission();
        permission2.setIpProtocol("tcp");
        permission2.setFromPort(443);
        permission2.setToPort(443);
        List<String> ipRanges2 = new ArrayList<String>();
        ipRanges2.add("0.0.0.0/0");
        permission2.setIpRanges(ipRanges2);

        /*************the property of tcp**********************/
        IpPermission permission3 = new IpPermission();
        permission3.setIpProtocol("tcp");
        permission3.setFromPort(0);
        permission3.setToPort(65535);
        List<String> ipRanges3 = new ArrayList<String>();
        ipRanges3.add("0.0.0.0/0");
        permission3.setIpRanges(ipRanges3);

        /**********************add rules to the group*********************/
        List<IpPermission> permissions = new ArrayList<IpPermission>();
        permissions.add(permission);
        permissions.add(permission1);
        permissions.add(permission2);
        permissions.add(permission3);
        r2.setIpPermissions(permissions);

        ec2.authorizeSecurityGroupIngress(r2);
        List<String> groupName = new ArrayList<String>();
        groupName.add(Temp_Group);//wait to out our instance into this group

        /*********************************************
        *
        *  #6.2 Create a New Key Pair
        * 
        *********************************************/

        CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest();
        newKeyRequest.setKeyName("Test_Key2");
        CreateKeyPairResult keyresult = ec2.createKeyPair(newKeyRequest);

        /************************print the properties of this key*****************/
        KeyPair kp = new KeyPair();

        kp = keyresult.getKeyPair();
        System.out.println("The key we created is = " + kp.getKeyName() + "\nIts fingerprint is="
                + kp.getKeyFingerprint() + "\nIts material is= \n" + kp.getKeyMaterial());

        String fileName = "C:/Users/Akhil/workspace/Test_Key2.pem";
        File distFile = new File(fileName);
        BufferedReader bufferedReader = new BufferedReader(new StringReader(kp.getKeyMaterial()));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile));
        char buf[] = new char[1024];
        int len;
        while ((len = bufferedReader.read(buf)) != -1) {
            bufferedWriter.write(buf, 0, len);
        }
        bufferedWriter.flush();
        bufferedReader.close();
        bufferedWriter.close();
        //String myinstance; 
        /*********************************************
          * 
          *  #6 Create an Instance
          *  
          *********************************************/
        System.out.println("#5 Create an Instance");
        String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI
        int minInstanceCount = 1; // create 1 instance
        int maxInstanceCount = 1;
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.setKeyName("Test_Key2");
        rir.withSecurityGroups("Testgroup1");

        RunInstancesResult result = ec2.runInstances(rir);

        //get instanceId from the result
        List<Instance> resultInstance = result.getReservation().getInstances();
        String createdInstanceId = null;
        String myAvailabilityZone = null;
        for (Instance ins : resultInstance) {
            createdInstanceId = ins.getInstanceId();
            System.out.println("New instance has been created: " + ins.getInstanceId());
            //myinstance = ins.getInstanceId();

        }

        Thread.currentThread().sleep(60000);

        /*********************************************
         * 
         * 
         * Create a New Volume and attach it
         * 
         ***********************************************/

        List<Instance> resultInstance2 = result.getReservation().getInstances();

        createdInstanceId = null;
        for (Instance ins : resultInstance2) {

            createdInstanceId = ins.getInstanceId();
            System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID

            /*********************************************
              * 
              *  #6.4 Create an Instance
              *  
              *********************************************/

            CreateVolumeRequest newVol = new CreateVolumeRequest(1, "us-east-1a");

            CreateVolumeResult volresult = ec2.createVolume(newVol);
            Volume vol1 = volresult.getVolume();
            String volId = vol1.getVolumeId();
            Thread.currentThread().sleep(30000);

            AttachVolumeRequest attachRequest = new AttachVolumeRequest().withInstanceId(createdInstanceId)
                    .withVolumeId(volId);
            attachRequest.withDevice("/dev/sda5");
            ec2.attachVolume(attachRequest);

            System.out.println("EBS volume has been attached and the volume ID is: " + volId);
        }
        /*********************************************
         * 
         *  #7 Create a 'tag' for the new instance.
         *  
         *********************************************/
        System.out.println("#6 Create a 'tag' for the new instance.");
        List<String> resources = new LinkedList<String>();
        List<Tag> tags = new LinkedList<Tag>();
        Tag nameTag = new Tag("Akhil", "MyFirstInstance");

        resources.add(createdInstanceId);
        tags.add(nameTag);

        CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
        ec2.createTags(ctr);

        /*********************************************
         * 
         *  #8 Stop/Start an Instance
         *  
         *********************************************/
        System.out.println("#7 Stop the Instance");
        List<String> instanceIds = new LinkedList<String>();
        instanceIds.add(createdInstanceId);

        //stop
        StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
        ec2.stopInstances(stopIR);

        //start
        StartInstancesRequest startIR = new StartInstancesRequest(instanceIds);
        ec2.startInstances(startIR);

        System.out.println("#8 Getting DNS, IP.");

        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setInstanceIds(instanceIds);

        DescribeInstancesResult result1 = ec2.describeInstances(request);
        List<Reservation> reservations1 = result1.getReservations();

        List<Instance> instances1;
        for (Reservation res : reservations1) {
            instances1 = res.getInstances();
            for (Instance ins1 : instances1) {
                System.out
                        .println("The public DNS is: " + ins1.getPublicDnsName() + "\n" + ins1.getRamdiskId());
                System.out.println("The private IP is: " + ins1.getPrivateIpAddress());
                System.out.println("The public IP is: " + ins1.getPublicIpAddress());

            }

            /*********************************************
                     
                    
              *  #10 Terminate an Instance
              *  
              *********************************************/
            System.out.println("#8 Terminate the Instance");
            TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);
            //ec2.terminateInstances(tir);

            /*********************************************
             *  
             *  #11 shutdown client object
             *  
             *********************************************/
            ec2.shutdown();

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

}

From source file:at.ac.tuwien.infosys.jcloudscale.vm.ec2.EC2Wrapper.java

License:Apache License

/**
 * Finds the first instance with the specified IP address.
 * @param ip//from   www  .  j  av a  2  s  .  c  o m
 * @return
 */
public String findEC2Id(String ip) {
    DescribeInstancesResult result = ec2Client.describeInstances();
    for (Reservation r : result.getReservations()) {
        for (Instance i : r.getInstances()) {
            if ((i.getPublicIpAddress() != null && i.getPublicIpAddress().equals(ip))
                    || (i.getPrivateIpAddress() != null && i.getPrivateIpAddress().equals(ip)))
                return i.getInstanceId();
        }
    }
    return null;
}

From source file:com.automata.cloudcore.xmlbindings.RunningInstancesItemType.java

License:Open Source License

public RunningInstancesItemType(Instance instance) {
    this.instanceId = instance.getInstanceId();
    InstanceStateType instanceStateType = new InstanceStateType();
    instanceStateType.setName(instance.getInstanceLifecycle());
    //instanceStateType.setCode();
    this.instanceState = instanceStateType;
    this.privateDnsName = instance.getPrivateDnsName();
    this.imageId = instance.getImageId();
    this.dnsName = instance.getPublicDnsName();
    //this.reason   = instance.get
    this.keyName = instance.getKeyName();
    if (instance.getStateTransitionReason() != null)
        this.reason = instance.getStateTransitionReason().toString();
    this.amiLaunchIndex = instance.getAmiLaunchIndex().toString();
    //this.productCodes = instance.getProductCodes();
    this.instanceType = instance.getInstanceType();
    //this.launchTime = instance.getLaunchTime();
    //this.placement = instance.getPlacement();
    this.kernelId = instance.getKernelId();
    this.ramdiskId = instance.getRamdiskId();
    this.platform = instance.getPlatform();

    InstanceMonitoringStateType instanceMonitoringStateType;
    instanceMonitoringStateType = new InstanceMonitoringStateType();
    instanceMonitoringStateType.setState(instance.getMonitoring().toString());
    this.monitoring = instanceMonitoringStateType;

    this.subnetId = instance.getSubnetId();
    this.vpcId = instance.getVpcId();
    this.privateIpAddress = instance.getPrivateIpAddress();
    this.ipAddress = instance.getPublicIpAddress();
    this.sourceDestCheck = instance.getSourceDestCheck();
    //this.groupSet = 

    if (instance.getStateReason() != null) {
        StateReasonType stateReasonType = new StateReasonType();
        stateReasonType.setMessage(instance.getStateReason().getMessage());
        this.stateReason = stateReasonType;
    }//ww  w  .  j  a  v  a2s  . c  o m
    this.architecture = instance.getArchitecture();
    this.rootDeviceType = instance.getRootDeviceType();
    this.rootDeviceName = instance.getRootDeviceName();

    /*BlockDeviceMappingsType blockDeviceMappingsType = new BlockDeviceMappingsType();
    List<BlockDeviceMapping> blockDeviceMappingList = new ArrayList<BlockDeviceMapping>();
    BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
    for (){
               
    }
            
    blockDeviceMappingsType = 
    this.blockDeviceMapping = instance.getBlockDeviceMappings();*/
    this.instanceLifecycle = instance.getInstanceLifecycle();
    this.spotInstanceRequestId = instance.getSpotInstanceRequestId();

    if (instance.getLicense() != null) {
        InstanceLicenseResponseType instanceLicenseResponseType;
        instanceLicenseResponseType = new InstanceLicenseResponseType();
        instanceLicenseResponseType.setPool(instance.getLicense().getPool());
        this.license = instanceLicenseResponseType;
    }

    this.virtualizationType = instance.getVirtualizationType();
    this.clientToken = instance.getClientToken();

    /*ResourceTagSetType resourceTagSetType;
    ResourceTagSetItemType resourceTagSetItemType;
    List<ResourceTagSetItemType> resourceTagSetItemTypeList;
            
    resourceTagSetItemTypeList = new ArrayList<ResourceTagSetItemType>();
            
    resourceTagSetType = new ResourceTagSetType();
    resourceTagSetType.getItem()
    this.tagSet = instance.getTags();
    this.hypervisor = instance.get*/
}

From source file:com.axemblr.provisionr.amazon.activities.PublishListOfMachines.java

License:Apache License

@Override
public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) throws Exception {
    @SuppressWarnings("unchecked")
    List<String> instanceIds = (List<String>) execution.getVariable(ProcessVariables.INSTANCE_IDS);
    checkNotNull(instanceIds, "%s not found as a process variable", ProcessVariables.INSTANCE_IDS);

    LOG.info(">> Describing instances {}", instanceIds);
    DescribeInstancesResult result = client
            .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds));
    checkArgument(result.getReservations().size() == 1, "found more than one reservation");

    Reservation reservation = result.getReservations().get(0);
    LOG.info("<< Got one reservation with {} running instances", reservation.getInstances().size());

    List<Machine> machines = Lists.transform(reservation.getInstances(), new Function<Instance, Machine>() {
        @Override/*from  w w w  . j  av a 2 s . c  om*/
        public Machine apply(Instance instance) {
            return Machine.builder().externalId(instance.getInstanceId())
                    .publicDnsName(instance.getPublicDnsName()).publicIp(instance.getPublicIpAddress())
                    .privateDnsName(instance.getPrivateDnsName()).privateIp(instance.getPrivateIpAddress())
                    .createMachine();
        }
    });

    /* Create a new ArrayList to force evaluation for lazy collections */
    execution.setVariable(CoreProcessVariables.MACHINES, Lists.newArrayList(machines));
}

From source file:com.bloomreach.bstore.highavailability.zookeeper.ZkClient.java

License:Apache License

/**
 * Fetch the public DNS names for the corresponding private Ips. SolrCloud defaults to private ips for all
 * interactions. If you want to run HAFT locally to copy data across 2 different zookeeper clusters, then we need
 * public IP translations to access the index. This method helps achieve that.
 *
 * @return {@link #getZkClusterData()} with private Ip to Public DNS Mapping based on EC2 api.
 *//*from   w  ww .  j ava 2 s. com*/
public ZkClusterData translatePrivateIpToPublicHostNames() {
    AWSCredentials credentials = new BasicAWSCredentials(AwsConfigReader.fetchAccessKey(),
            AwsConfigReader.fetchSecretyKey());
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);

    Set<String> publicDnsNameHosts = new HashSet<String>();
    Map<String, String> privateIptoPublicHostNames = new HashMap<String, String>();

    if (allSolrNodes.isEmpty()) {
        logger.info("No valid solr hosts are found. Cannot do any mapping");
        return zkClusterData;
    }

    //Describe Filter with private-ips matching all solr nodes
    DescribeInstancesRequest request = new DescribeInstancesRequest()
            .withFilters(new Filter("private-ip-address").withValues(allSolrNodes));
    DescribeInstancesResult describeInstancesResult = ec2.describeInstances(request);
    List<Reservation> reservations = describeInstancesResult.getReservations();
    //Iterate over all instances and map their private Ip to Public Host Name
    logger.info("Fetching Public HostNames....");

    for (Reservation reservation : reservations) {
        List<Instance> instances = reservation.getInstances();
        for (Instance instance : instances) {
            logger.info("Private to Public Name of the Host is " + instance.getPrivateIpAddress() + " => "
                    + instance.getPublicDnsName());
            publicDnsNameHosts.add(instance.getPublicDnsName());
            privateIptoPublicHostNames.put(instance.getPrivateIpAddress(), instance.getPublicDnsName());
        }

    }
    //Point all zk data to point to the public dns names
    zkClusterData.updateSolrNodes(publicDnsNameHosts);
    //Set the data in a map so that it doesn't need to get recomputed by every function needing hostnames
    zkClusterData.setPrivateIpToPublicHostNameMap(privateIptoPublicHostNames);
    return zkClusterData;

}

From source file:com.clouck.model.aws.ec2.Ec2Instance.java

@Override
@SuppressWarnings("rawtypes")
protected boolean isEqual(AbstractResource newResource) {
    Instance oldInstance = this.getResource();
    Ec2Instance newEc2Instance = (Ec2Instance) newResource;
    Instance newInstance = newEc2Instance.getResource();

    if (notEqual(oldInstance.getInstanceId(), newInstance.getInstanceId()))
        return false;
    if (notEqual(oldInstance.getImageId(), newInstance.getImageId()))
        return false;
    if (notEqual(oldInstance.getState(), newInstance.getState()))
        return false;
    if (notEqual(oldInstance.getPrivateDnsName(), newInstance.getPrivateDnsName()))
        return false;
    if (notEqual(oldInstance.getPublicDnsName(), newInstance.getPublicDnsName()))
        return false;
    if (notEqual(oldInstance.getStateTransitionReason(), newInstance.getStateTransitionReason()))
        return false;
    if (notEqual(oldInstance.getKeyName(), newInstance.getKeyName()))
        return false;
    if (notEqual(oldInstance.getAmiLaunchIndex(), newInstance.getAmiLaunchIndex()))
        return false;
    if (notEqualCollection(oldInstance.getProductCodes(), newInstance.getProductCodes()))
        return false;
    if (notEqual(oldInstance.getInstanceType(), newInstance.getInstanceType()))
        return false;
    if (notEqual(oldInstance.getLaunchTime(), newInstance.getLaunchTime()))
        return false;
    if (notEqual(oldInstance.getPlacement(), newInstance.getPlacement()))
        return false;
    if (notEqual(oldInstance.getKernelId(), newInstance.getKernelId()))
        return false;
    if (notEqual(oldInstance.getRamdiskId(), newInstance.getRamdiskId()))
        return false;
    if (notEqual(oldInstance.getPlatform(), newInstance.getPlatform()))
        return false;
    if (notEqual(oldInstance.getMonitoring(), newInstance.getMonitoring()))
        return false;
    if (notEqual(oldInstance.getSubnetId(), newInstance.getSubnetId()))
        return false;
    if (notEqual(oldInstance.getVpcId(), newInstance.getVpcId()))
        return false;
    if (notEqual(oldInstance.getPrivateIpAddress(), newInstance.getPrivateIpAddress()))
        return false;
    if (notEqual(oldInstance.getPublicIpAddress(), newInstance.getPublicIpAddress()))
        return false;
    if (notEqual(oldInstance.getStateReason(), newInstance.getStateReason()))
        return false;
    if (notEqual(oldInstance.getArchitecture(), newInstance.getArchitecture()))
        return false;
    if (notEqual(oldInstance.getRootDeviceType(), newInstance.getRootDeviceType()))
        return false;
    if (notEqual(oldInstance.getRootDeviceName(), newInstance.getRootDeviceName()))
        return false;
    if (notEqualCollection(oldInstance.getBlockDeviceMappings(), newInstance.getBlockDeviceMappings()))
        return false;
    if (notEqual(oldInstance.getVirtualizationType(), newInstance.getVirtualizationType()))
        return false;
    if (notEqual(oldInstance.getInstanceLifecycle(), newInstance.getInstanceLifecycle()))
        return false;
    if (notEqual(oldInstance.getSpotInstanceRequestId(), newInstance.getSpotInstanceRequestId()))
        return false;
    if (notEqual(oldInstance.getLicense(), newInstance.getLicense()))
        return false;
    if (notEqual(oldInstance.getClientToken(), newInstance.getClientToken()))
        return false;
    if (notEqualCollection(oldInstance.getTags(), newInstance.getTags()))
        return false;
    if (notEqualCollection(oldInstance.getSecurityGroups(), newInstance.getSecurityGroups()))
        return false;
    if (notEqual(oldInstance.getSourceDestCheck(), newInstance.getSourceDestCheck()))
        return false;
    if (notEqual(oldInstance.getHypervisor(), newInstance.getHypervisor()))
        return false;
    if (notEqualNetworkInterfaces(oldInstance.getNetworkInterfaces(), newInstance.getNetworkInterfaces()))
        return false;
    if (notEqual(oldInstance.getIamInstanceProfile(), newInstance.getIamInstanceProfile()))
        return false;
    if (notEqual(oldInstance.getEbsOptimized(), newInstance.getEbsOptimized()))
        return false;
    if (notEqual(this.getTerminationProtection(), newEc2Instance.getTerminationProtection()))
        return false;
    if (notEqual(this.getShutdownBehavior(), newEc2Instance.getShutdownBehavior()))
        return false;
    if (notEqual(this.getUserData(), newEc2Instance.getUserData()))
        return false;

    return true;//from   www  .  ja  v  a2  s.co m
}

From source file:com.cloudera.director.aws.ec2.EC2Instance.java

License:Apache License

/**
 * Returns the private IP address of the specified EC2 instance.
 *
 * @param instance the instance//  w ww .j a  v  a  2s.c  o  m
 * @return the private IP address of the specified EC2 instance
 * @throws IllegalArgumentException if the instance does not have a valid private IP address
 */
private static InetAddress getPrivateIpAddress(Instance instance) {
    Preconditions.checkNotNull(instance, "instance is null");
    InetAddress privateIpAddress;
    try {
        privateIpAddress = InetAddress.getByName(instance.getPrivateIpAddress());
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("Invalid private IP address", e);
    }
    return privateIpAddress;
}

From source file:com.cloudera.director.aws.ec2.EC2Provider.java

License:Apache License

/**
 * Atomically allocates multiple regular EC2 instances with the specified identifiers based on a
 * single instance template. If not all the instances can be allocated, the number of instances
 * allocated must be at least the specified minimum or the method must fail cleanly with no
 * billing implications./* ww  w  .  ja  v  a  2  s  . c o m*/
 *
 * @param template           the instance template
 * @param virtualInstanceIds the unique identifiers for the instances
 * @param minCount           the minimum number of instances to allocate if not all resources can
 *                           be allocated
 * @return                   the virtual instance ids of the instances that were allocated
 * @throws InterruptedException if the operation is interrupted
 */
public Collection<String> allocateOnDemandInstances(EC2InstanceTemplate template,
        Collection<String> virtualInstanceIds, int minCount) throws InterruptedException {

    int instanceCount = virtualInstanceIds.size();

    LOG.info(">> Requesting {} instances for {}", instanceCount, template);

    // EC2 client doesn't accept a min count of 0. Readjust the requested
    // value to 1 to allow submitting the request.
    int normalizedMinCount = (minCount == 0) ? 1 : minCount;

    RunInstancesResult runInstancesResult;
    try {
        runInstancesResult = client
                .runInstances(newRunInstancesRequest(template, virtualInstanceIds, normalizedMinCount));
    } catch (AmazonServiceException e) {
        AWSExceptions.propagateIfUnrecoverable(e);

        // As documented at http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-capacity.html

        if ("InsufficientInstanceCapacity".equals(e.getErrorCode())
                || "InstanceLimitExceeded".equals(e.getErrorCode())) {
            if (minCount == 0) {
                LOG.warn("Ignoring insufficient capacity exception due to min count being zero", e);
                return Collections.emptyList();
            } else {
                // fail fast on insufficient instance capacity because we expect it will take
                // a fair amount of time for AWS to bring more capacity online in a zone or it will
                // take some time for customers to request a limit increase
                throw new UnrecoverableProviderException(e.getErrorMessage(), e);
            }
        } else {
            throw AWSExceptions.propagate(e);
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("<< Reservation {} with {}", runInstancesResult.getReservation().getReservationId(),
                summarizeReservationForLogging(runInstancesResult.getReservation()));
    }

    // Tag all the new instances so that we can easily find them later on.
    // Determine which do not yet have a private IP address.

    List<Tag> userDefinedTags = getUserDefinedTags(template);

    Set<String> instancesWithNoPrivateIp = Sets.newHashSet();

    List<Instance> instances = runInstancesResult.getReservation().getInstances();

    // Limit the number of virtual instance id's used for tagging to the
    // number of instances that we managed to reserve.
    List<String> virtualInstanceIdsAllocated = FluentIterable.from(virtualInstanceIds).limit(instances.size())
            .toList();

    List<String> successfulVirtualInstanceIds = Lists.newArrayList();

    for (Map.Entry<String, Instance> entry : zipWith(virtualInstanceIdsAllocated, instances)) {

        String virtualInstanceId = entry.getKey();
        Instance instance = entry.getValue();
        String ec2InstanceId = instance.getInstanceId();

        if (tagInstance(template, userDefinedTags, virtualInstanceId, ec2InstanceId)) {
            successfulVirtualInstanceIds.add(virtualInstanceId);

            if (instance.getPrivateIpAddress() == null) {
                instancesWithNoPrivateIp.add(ec2InstanceId);
            } else {
                LOG.info("<< Instance {} got IP {}", ec2InstanceId, instance.getPrivateIpAddress());
            }
        } else {
            LOG.info("<< Instance {} could not be tagged.", ec2InstanceId);
        }
    }

    int numInstancesTagged = successfulVirtualInstanceIds.size();
    if (numInstancesTagged < minCount) {
        LOG.error(
                "Number of instances tagged ({}) is less than the minimum count ({}). One or more instances may have "
                        + "unexpectedly terminated prior to tagging.",
                numInstancesTagged, minCount);
        delete(template, successfulVirtualInstanceIds);
        throw new UnrecoverableProviderException(
                String.format(COUNT_BELOW_THRESHOLD, numInstancesTagged, minCount));
    }

    // Wait until all of them have a private IP (it should be pretty fast)
    waitForPrivateIpAddresses(instancesWithNoPrivateIp);

    return virtualInstanceIdsAllocated;
}

From source file:com.cloudera.director.aws.ec2.EC2Provider.java

License:Apache License

/**
 * Returns a summary of the specified reservation suitable for logging.
 *
 * @param reservation the reservation/*  w  w  w . j  a  v a 2  s  .  com*/
 * @return a summary of the specified reservation suitable for logging
 */
private String summarizeReservationForLogging(Reservation reservation) {
    StringBuilder builder = new StringBuilder();
    for (Instance instance : reservation.getInstances()) {
        builder.append(String.format("Instance{id=%s privateIp=%s} ", instance.getInstanceId(),
                instance.getPrivateIpAddress()));
    }
    return builder.toString();
}

From source file:com.cloudera.director.aws.ec2.EC2Provider.java

License:Apache License

/**
 * Waits until all of the specified instances have assigned private IP addresses.
 *
 * @param instanceIds the instance IDs//from  ww  w.ja  v  a  2  s  .co  m
 * @throws InterruptedException if the operation is interrupted
 */
private void waitForPrivateIpAddresses(final Collection<String> instanceIds) throws InterruptedException {

    final Set<String> instancesWithNoPrivateIpAddress = Sets.newHashSet(instanceIds);

    while (!instancesWithNoPrivateIpAddress.isEmpty()) {
        LOG.info(">> Waiting for {} instance(s) to get a private IP allocated",
                instancesWithNoPrivateIpAddress.size());

        DescribeInstancesResult result = client.describeInstances(
                new DescribeInstancesRequest().withInstanceIds(instancesWithNoPrivateIpAddress));
        forEachInstance(result, new InstanceHandler() {
            @Override
            public void handle(Instance instance) {
                if (instance.getPrivateIpAddress() != null) {
                    String ec2InstanceId = instance.getInstanceId();

                    LOG.info("<< Instance {} got IP {}", ec2InstanceId, instance.getPrivateIpAddress());

                    instancesWithNoPrivateIpAddress.remove(ec2InstanceId);
                }
            }
        });

        if (!instancesWithNoPrivateIpAddress.isEmpty()) {
            LOG.info("Waiting 5 seconds until next check, {} instance(s) still don't have an IP",
                    instancesWithNoPrivateIpAddress.size());

            TimeUnit.SECONDS.sleep(5);
        }
    }
}