Example #1
1
 private Integer startTunnelSSH(Instance instance) throws InterruptedException {
   Instance tunnelInstance = runningInstances(tunnelResourceId).get(0);
   Integer localPort = Double.valueOf(Randoms.number(3000, 10000)).intValue();
   CountDownLatch latch = new CountDownLatch(1);
   Thread tunnelThread =
       new Thread(
           () -> {
             Process process = null;
             try {
               Path keyPath = KeyPair.keyFile(tunnelInstance.getKeyName(), env);
               String userAndHost = "ubuntu@" + hostName(tunnelInstance);
               String portBinding =
                   Strings.format("{}:{}:22", localPort, instance.getPrivateIpAddress());
               List<String> command = tunnelCommand(keyPath, userAndHost, portBinding);
               logger.info("tunnel command => {}", String.join(" ", command));
               process = new ProcessBuilder().command(command).start();
               process.getInputStream().read(); // wait until there is output
               latch.countDown();
               process.waitFor();
             } catch (InterruptedException | IOException e) {
               throw new IllegalStateException(e);
             } finally {
               if (process != null) process.destroy();
             }
           });
   tunnelThread.setDaemon(true);
   tunnelThread.start();
   latch.await();
   return localPort;
 }
Example #2
0
  public static void main(String[] args) throws UnknownHostException {
    AmazonEC2 ec2 = new AmazonEC2Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    ec2.setRegion(usWest2);
    List<String> instanceIds = new ArrayList<>();
    String instanceid = null;
    DescribeInstancesRequest request = new DescribeInstancesRequest();

    List<String> valuesT1 = new ArrayList<String>();
    valuesT1.add("hz-nodes");
    Filter filter = new Filter("tag-value", valuesT1);

    DescribeInstancesResult result = ec2.describeInstances(request.withFilters(filter));

    List<Reservation> reservations = result.getReservations();

    for (Reservation reservation : reservations) {
      List<Instance> instances = reservation.getInstances();
      for (Instance instance : instances) {
        instanceid = instance.getInstanceId();
        PrintManager.PrintMessage(instanceid);
        instanceIds.add(instanceid);
        List<Tag> abc = instance.getTags();
        for (Tag aaa : abc) {
          PrintManager.PrintMessage(aaa.getKey() + " : " + aaa.getValue());
        }
      }
    }
    instanceIds.remove("i-cb45adfc");
    StopInstancesRequest stopReq = new StopInstancesRequest(instanceIds);
    ec2.stopInstances(stopReq);
    RebootInstancesRequest requestRe = new RebootInstancesRequest(instanceIds);
    ec2.rebootInstances(requestRe);
  }
  /*
   * Much of the EC2 data is beyond our direct control, therefore we need to refresh it from time to time to ensure we
   * reflect the reality of the instances.
   */
  protected void fetchLiveInstanceData(boolean force) throws AmazonClientException {
    /*
     * If we've grabbed the data recently, don't bother getting it again unless we are forced
     */
    long now = System.currentTimeMillis();
    if ((lastFetchTime > 0) && (now - lastFetchTime < MIN_FETCH_TIME) && !force) {
      return;
    }

    if (getInstanceId() == null || getInstanceId() == "") {
      /*
       * The getInstanceId() implementation on EC2SpotSlave can return null if the spot request doesn't yet know
       * the instance id that it is starting. What happens is that null is passed to getInstanceId() which
       * searches AWS but without an instanceID the search returns some random box. We then fetch its metadata,
       * including tags, and then later, when the spot request eventually gets the instanceID correctly we push
       * the saved tags from that random box up to the new spot resulting in confusion and delay.
       */
      return;
    }

    Instance i = getInstance(getInstanceId(), getCloud());

    lastFetchTime = now;
    lastFetchInstance = i;
    if (i == null) return;

    publicDNS = i.getPublicDnsName();
    privateDNS = i.getPrivateIpAddress();
    createdTime = i.getLaunchTime().getTime();
    tags = new LinkedList<EC2Tag>();

    for (Tag t : i.getTags()) {
      tags.add(new EC2Tag(t.getKey(), t.getValue()));
    }
  }
  @Override
  public void execute(Context context) throws Exception {
    RunInstancesRequest request =
        new RunInstancesRequest()
            .withKeyName(resource.keyPair.remoteKeyPair.getKeyName())
            .withInstanceType(resource.instanceType)
            .withImageId(resource.ami.imageId())
            .withMinCount(addedCount)
            .withMaxCount(addedCount)
            .withUserData(Base64.encodeBase64String(Strings.bytes(userData(context.env))));

    if (resource.instanceProfile != null)
      request.withIamInstanceProfile(
          new IamInstanceProfileSpecification()
              .withName(resource.instanceProfile.remoteInstanceProfile.getInstanceProfileName()));

    String sgId = resource.securityGroup.remoteSecurityGroup.getGroupId();

    request
        .getNetworkInterfaces()
        .add(
            new InstanceNetworkInterfaceSpecification()
                .withDeviceIndex(0)
                .withSubnetId(resource.subnet.firstRemoteSubnet().getSubnetId())
                .withGroups(sgId)
                .withAssociatePublicIpAddress(resource.subnet.type == SubnetType.PUBLIC));

    if (resource.ebs.rootVolumeSize != null) {
      request
          .getBlockDeviceMappings()
          .add(
              new BlockDeviceMapping()
                  .withDeviceName("/dev/sda1")
                  .withEbs(new EbsBlockDevice().withVolumeSize(resource.ebs.rootVolumeSize)));
    }

    List<com.amazonaws.services.ec2.model.Instance> remoteInstances =
        AWS.ec2.runInstances(request, tags(context.env));
    resource.remoteInstances.addAll(remoteInstances);

    for (com.amazonaws.services.ec2.model.Instance remoteInstance : remoteInstances) {
      String key = String.format("instance/%s/%s", resource.id, remoteInstance.getInstanceId());
      StringBuilder builder = new StringBuilder();
      builder.append("privateIP=").append(remoteInstance.getPrivateIpAddress());
      if (resource.subnet == null || resource.subnet.type == SubnetType.PUBLIC) {
        builder.append(", publicDNS=").append(remoteInstance.getPublicDnsName());
      }
      context.output(key, builder.toString());
    }

    if (resource.elb != null) {
      List<String> instanceIds =
          remoteInstances
              .stream()
              .map(com.amazonaws.services.ec2.model.Instance::getInstanceId)
              .collect(Collectors.toList());
      AWS.elb.attachInstances(
          resource.elb.remoteELB.getLoadBalancerName(), instanceIds, waitUntilInService);
    }
  }
Example #5
0
 protected boolean isEc2ProvisionedAmiSlave(Instance i, String ami, String templateDesc) {
   // Check if the ami matches
   if (ami == null || StringUtils.equals(ami, i.getImageId())) {
     // Check if there is a ec2slave tag...
     for (Tag tag : i.getTags()) {
       if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
         if (ami == null || templateDesc == null) {
           return true;
         } else if (StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_DEMAND)
             || StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_SPOT)) {
           // To handle cases where description is null and also upgrade cases for existing slave
           // nodes.
           return true;
         } else if (StringUtils.equals(
                 tag.getValue(),
                 getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_DEMAND, templateDesc))
             || StringUtils.equals(
                 tag.getValue(),
                 getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_SPOT, templateDesc))) {
           return true;
         } else {
           return false;
         }
       }
     }
     return false;
   }
   return false;
 }
Example #6
0
  // Creates new AMI instances from pre-defined snapshot,
  // and returns launched instance IDs.
  public static List<String> createAmiFromSnapshot(AmazonEC2 ec2, int amount, String userData) {
    logger.info("Launching " + amount + " instances.");

    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add(securityGroup);

    RunInstancesRequest request = new RunInstancesRequest();

    // Send launch request.
    request
        .withImageId(imageId) // Utils.imageId
        .withInstanceType(instanceType)
        .withUserData(userData)
        .withKeyName(keyName)
        .withSecurityGroups(securityGroups)
        .withMinCount(amount)
        .withMaxCount(amount);

    // Build instance id list.
    ArrayList<String> ids = new ArrayList<String>();
    for (Instance instance : ec2.runInstances(request).getReservation().getInstances()) {
      ids.add(instance.getInstanceId());
    }

    return ids;
  }
Example #7
0
 /**
  * Counts the number of instances in EC2 currently running that are using the specified image and
  * a template.
  *
  * @param ami If AMI is left null, then all instances are counted and template description is
  *     ignored.
  *     <p>This includes those instances that may be started outside Jenkins.
  * @param templateDesc
  */
 public int countCurrentEC2Slaves(String ami, String templateDesc) throws AmazonClientException {
   int n = 0;
   for (Reservation r : connect().describeInstances().getReservations()) {
     for (Instance i : r.getInstances()) {
       if (isEc2ProvisionedAmiSlave(i, ami, templateDesc)) {
         InstanceStateName stateName = InstanceStateName.fromValue(i.getState().getName());
         if (stateName == InstanceStateName.Pending || stateName == InstanceStateName.Running) {
           EC2AbstractSlave foundSlave = null;
           for (EC2AbstractSlave ec2Node : NodeIterator.nodes(EC2AbstractSlave.class)) {
             if (ec2Node.getInstanceId().equals(i.getInstanceId())) {
               foundSlave = ec2Node;
               break;
             }
           }
           // Don't count disconnected slaves as being used, we will connected them later is
           // required
           if (foundSlave != null && foundSlave.toComputer().isOffline()) continue;
           n++;
         }
       }
     }
   }
   // Count pending spot requests too
   for (SpotInstanceRequest sir :
       connect().describeSpotInstanceRequests().getSpotInstanceRequests()) {
     // Count Spot requests that are open and still have a
     // chance to be active.
     if (sir.getState().equals("open")) {
       n++;
     }
   }
   return n;
 }
Example #8
0
  /**
   * Determines whether the AMI of the given instance matches the AMI of template and has the
   * required label (if requiredLabel is non-null)
   */
  private boolean checkInstance(
      PrintStream logger,
      Instance existingInstance,
      Label requiredLabel,
      EC2AbstractSlave[] returnNode) {
    logProvision(logger, "checkInstance: " + existingInstance);
    if (StringUtils.isNotBlank(getIamInstanceProfile())) {
      if (existingInstance.getIamInstanceProfile() != null) {
        if (!existingInstance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())) {
          logProvision(logger, " false - IAM Instance profile does not match");
          return false;
        }
        // Match, fall through
      } else {
        logProvision(logger, " false - Null IAM Instance profile");
        return false;
      }
    }

    if (existingInstance
            .getState()
            .getName()
            .equalsIgnoreCase(InstanceStateName.Terminated.toString())
        || existingInstance
            .getState()
            .getName()
            .equalsIgnoreCase(InstanceStateName.ShuttingDown.toString())) {
      logProvision(logger, " false - Instance is terminated or shutting down");
      return false;
    }
    // See if we know about this and it has capacity
    for (EC2AbstractSlave node : NodeIterator.nodes(EC2AbstractSlave.class)) {
      if (node.getInstanceId().equals(existingInstance.getInstanceId())) {
        logProvision(logger, "Found existing corresponding Jenkins slave: " + node.getInstanceId());
        if (!node.toComputer().isPartiallyIdle()) {
          logProvision(logger, " false - Node is not partially idle");
          return false;
        }
        // REMOVEME - this was added to force provision to work, but might not allow
        // stopped instances to be found - need to investigate further
        else if (false && node.toComputer().isOffline()) {
          logProvision(logger, " false - Node is offline");
          return false;
        } else if (requiredLabel != null && !requiredLabel.matches(node.getAssignedLabels())) {
          logProvision(logger, " false - we need a Node having label " + requiredLabel);
          return false;
        } else {
          logProvision(logger, " true - Node has capacity - can use it");
          returnNode[0] = node;
          return true;
        }
      }
    }
    logProvision(logger, " true - Instance has no node, but can be used");
    return true;
  }
  public static String getPublicDns(String instanceId) {

    System.out.println("Retreiving public dns.");

    DescribeInstancesResult results = ec2.describeInstances();
    List<Reservation> reservations = results.getReservations();

    for (Reservation reservation : reservations) {
      for (Instance instance : reservation.getInstances()) {
        if (instance.getInstanceId().equals(instanceId)) return instance.getPublicDnsName();
      }
    }
    return "NA";
  }
  /** Query amazon to get ASG name. Currently not available as part of instance info api. */
  private String populateASGName(String region, String instanceId) {
    AmazonEC2 client = new AmazonEC2Client(provider.getCredentials());
    client.setEndpoint("ec2." + region + ".amazonaws.com");
    DescribeInstancesRequest desc = new DescribeInstancesRequest().withInstanceIds(instanceId);
    DescribeInstancesResult res = client.describeInstances(desc);

    for (Reservation resr : res.getReservations()) {
      for (Instance ins : resr.getInstances()) {
        for (com.amazonaws.services.ec2.model.Tag tag : ins.getTags()) {
          if (tag.getKey().equals("aws:autoscaling:groupName")) return tag.getValue();
        }
      }
    }
    return null;
  }
 private void createTag(AmazonEC2Client ec2, Instance instance) {
   // Create Tags
   Tag tag = new Tag("Project", "2.3");
   CreateTagsRequest createTagsRequest = new CreateTagsRequest();
   createTagsRequest.withResources(instance.getInstanceId()).withTags(tag);
   ec2.createTags(createTagsRequest);
 }
Example #12
0
    @Override
    public String retriableCall() throws IllegalStateException {
      DescribeInstancesRequest desc = new DescribeInstancesRequest().withInstanceIds(instanceId);
      DescribeInstancesResult res = client.describeInstances(desc);

      for (Reservation resr : res.getReservations()) {
        for (Instance ins : resr.getInstances()) {
          for (com.amazonaws.services.ec2.model.Tag tag : ins.getTags()) {
            if (tag.getKey().equals("aws:autoscaling:groupName")) return tag.getValue();
          }
        }
      }

      logger.warn("Couldn't determine ASG name");
      throw new IllegalStateException("Couldn't determine ASG name");
    }
  /*
   * Sets tags on an instance. This will not clear existing tag data, so call clearLiveInstancedata if needed
   */
  protected void pushLiveInstancedata() throws AmazonClientException {
    Instance inst = getInstance(getInstanceId(), getCloud());

    /* Now that we have our instance, we can set tags on it */
    if (inst != null && tags != null && !tags.isEmpty()) {
      HashSet<Tag> inst_tags = new HashSet<Tag>();

      for (EC2Tag t : tags) {
        inst_tags.add(new Tag(t.getName(), t.getValue()));
      }

      CreateTagsRequest tag_request = new CreateTagsRequest();
      tag_request.withResources(inst.getInstanceId()).setTags(inst_tags);
      getCloud().connect().createTags(tag_request);
    }
  }
 protected boolean isAlive(boolean force) {
   fetchLiveInstanceData(force);
   if (lastFetchInstance == null) return false;
   if (lastFetchInstance.getState().getName().equals(InstanceStateName.Terminated.toString()))
     return false;
   return true;
 }
Example #15
0
 private Instance locateInstanceToSSH(List<Instance> instances) {
   for (int i = 0; i < instances.size(); i++) {
     com.amazonaws.services.ec2.model.Instance remoteInstance = instances.get(i);
     logger.info(
         "index={}, instanceId={}, state={}, publicDNS={}, privateDNS={}",
         i,
         remoteInstance.getInstanceId(),
         remoteInstance.getState().getName(),
         remoteInstance.getPublicDnsName(),
         remoteInstance.getPrivateDnsName());
   }
   Asserts.isTrue(
       instances.size() == 1 || instanceIndex != null,
       "more than one remoteInstance, use --{} to specify index",
       Param.INSTANCE_INDEX.key);
   return instances.size() == 1 ? instances.get(0) : instances.get(instanceIndex);
 }
 /** Test of getMaster method, of class HadoopCluster. */
 @Test
 public void testGetMaster() {
   System.out.println("getMaster");
   ClusterInstance result = cluster.getMaster();
   assertNotNull(result);
   assertEquals(cluster.getMasterGroupName(), result.getSecurityGroups().get(0));
   Instance slaveInstance = result.getInstance();
   StringBuilder sb = new StringBuilder("\t");
   sb.append(slaveInstance.getInstanceId());
   sb.append(" ");
   sb.append(slaveInstance.getInstanceType());
   sb.append(" ");
   sb.append(slaveInstance.getLaunchTime().toString());
   sb.append(" ");
   sb.append(slaveInstance.getImageId());
   out.println(sb.toString());
 }
 private List<Instance> listInstance(AmazonEC2Client ec2) {
   List<Instance> testInstances = new ArrayList<Instance>();
   List<Reservation> reservations = ec2.describeInstances().getReservations();
   int reservationCount = reservations.size();
   for (int i = 0; i < reservationCount; i++) {
     List<Instance> instances = reservations.get(i).getInstances();
     int instanceCount = instances.size();
     // Print the instance IDs of every instance in the reservation.
     for (int j = 0; j < instanceCount; j++) {
       Instance instance = instances.get(j);
       if (instance.getState().getName().equals("running")) {
         testInstances.add(instance);
       }
     }
   }
   return testInstances;
 }
 @Override
 public List<Instance> launchNodes(
     String uuid,
     Platform platform,
     String browser,
     String hubHostName,
     int nodeCount,
     int maxSessions) {
   if (throwException) {
     throw new RuntimeException("Can't start nodes");
   }
   this.nodesLaunched = true;
   this.numberLaunched = nodeCount;
   this.browser = browser;
   Instance instance = new Instance();
   instance.setInstanceId("instanceId");
   return Arrays.asList(instance);
 }
Example #19
0
  private static void putCache() throws CacheException {
    if (amazon == null) amazon = JCS.getInstance("Instances");
    synchronized (AmazonService.class) {
      amazon.clear();
      DescribeInstancesResult result = amazonClient.describeInstances();
      for (Reservation r : result.getReservations()) {
        for (Instance i : r.getInstances()) {
          amazon.putInGroup(i.getInstanceId(), "Instances", i);
        }
      }

      DescribeImagesRequest ir = new DescribeImagesRequest().withOwners("self");
      DescribeImagesResult images = amazonClient.describeImages(ir);
      for (Image r : images.getImages()) {
        amazon.putInGroup(r.getImageId(), "AMIs", r);
      }
      log.debug("put cache finished");
    }
  }
  private String getHostName(EC2Computer computer)
      throws AmazonClientException, InterruptedException {
    Instance instance;
    instance = computer.updateInstanceDescription();
    String vpc_id = instance.getVpcId();
    String host;

    if (computer.getNode().usePrivateDnsName) {
      host = instance.getPrivateDnsName();
    } else {
      /* VPC hosts don't have public DNS names, so we need to use an IP address instead */
      if (vpc_id == null || vpc_id.equals("")) {
        host = instance.getPublicDnsName();
      } else {
        host = instance.getPrivateIpAddress();
      }
    }
    return host;
  }
Example #21
0
 private void ssh(Instance instance, Integer tunnelPort) throws IOException, InterruptedException {
   Path keyPath = KeyPair.keyFile(instance.getKeyName(), env);
   String userAndHost;
   if (tunnelPort != null) userAndHost = "ubuntu@localhost";
   else userAndHost = "ubuntu@" + hostName(instance);
   List<String> command = command(keyPath, userAndHost, tunnelPort);
   logger.info("command => {}", String.join(" ", command));
   Process process = new ProcessBuilder().inheritIO().command(command).start();
   process.waitFor();
   logger.info("session disconnected");
 }
 /** Test of getSlaves method, of class HadoopCluster. */
 @Test
 public void testGetSlaves() {
   out.println("getSlaves");
   List<ClusterInstance> result = cluster.getSlaves();
   out.println("found " + result.size() + " slaves for group " + TEST_GROUP);
   assertNotNull(result);
   StringBuilder sb = new StringBuilder("\t");
   for (ClusterInstance slave : result) {
     assertEquals(cluster.getGroupName(), slave.getSecurityGroups().get(0));
     Instance slaveInstance = slave.getInstance();
     if (sb.length() > 1) sb.delete(1, sb.length());
     sb.append(slaveInstance.getInstanceId());
     sb.append(" ");
     sb.append(slaveInstance.getInstanceType());
     sb.append(" ");
     sb.append(slaveInstance.getLaunchTime().toString());
     sb.append(" ");
     sb.append(slaveInstance.getImageId());
     out.println(sb.toString());
   }
 }
Example #23
0
 protected EC2OndemandSlave newOndemandSlave(Instance inst) throws FormException, IOException {
   return new EC2OndemandSlave(
       inst.getInstanceId(),
       description,
       remoteFS,
       getNumExecutors(),
       labels,
       mode,
       initScript,
       tmpDir,
       remoteAdmin,
       jvmopts,
       stopOnTerminate,
       idleTerminationMinutes,
       inst.getPublicDnsName(),
       inst.getPrivateDnsName(),
       EC2Tag.fromAmazonTags(inst.getTags()),
       parent.name,
       usePrivateDnsName,
       useDedicatedTenancy,
       getLaunchTimeout(),
       amiType);
 }
Example #24
0
  // Returns pending/running instance ID list.
  public static ArrayList<String> getInstanceIdsByTag(AmazonEC2 ec2, String key, String value) {
    logger.fine("Requesting instances by tag " + key + "=" + value);

    // Create tag request.
    DescribeInstancesRequest instanceReq = new DescribeInstancesRequest();
    Filter managerFilter = new Filter("tag:" + key).withValues(value),
        activeFilter =
            new Filter("instance-state-code").withValues("0", "16"); // 0||16 == pending||running

    // Send request.
    DescribeInstancesResult result =
        ec2.describeInstances(instanceReq.withFilters(managerFilter, activeFilter));

    // Build instance ID list.
    ArrayList<String> ids = new ArrayList<String>();
    for (Reservation reservation : result.getReservations()) {
      for (Instance instance : reservation.getInstances()) {
        ids.add(instance.getInstanceId());
      }
    }

    logger.fine(ids.size() + " instances found with tag " + key + "=" + value);
    return ids;
  }
    @Override
    public void run() {
      // set up new data center
      RunInstancesRequest dataCenterRequest = createDataCenterRequest();
      RunInstancesResult runDataCenterResult = ec2.runInstances(dataCenterRequest);
      Instance dataCenterInstance = runDataCenterResult.getReservation().getInstances().get(0);
      String dataCenterId = dataCenterInstance.getInstanceId();
      createTag(ec2, dataCenterInstance);

      // wait for 1 min for the data center running
      try {
        Thread.sleep(60 * 1000);
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }

      // wait for data center ready for the web server
      String testSentence = null;
      while (testSentence == null) {
        System.out.println("RunInstance Thread: Waiting for data center ready");

        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        List<Instance> allInstances = listInstance(ec2);
        for (Instance inst : allInstances) {
          if (inst.getInstanceId().equals(dataCenterId)) {
            dataCenterInstance = inst;
            break;
          }
        }

        String randomUserUrl = "http://" + dataCenterInstance.getPublicDnsName() + "/lookup/random";
        try {
          testSentence = sendGet(randomUserUrl);
        } catch (Exception e) {
          // Do nothing
        }
      }

      String newDataCenterUrl = "http://" + dataCenterInstance.getPublicDnsName();

      // update the data center to in-service instances
      for (int i = 0; i < 3; i++) {
        if (instances[i].getUrl() == null) {
          instances[i].changeUrl(newDataCenterUrl);
          isHealthy[i] = true;
          updataHealthCount();
        }
      }
      // complete adding instance
      isAddingInstance = false;
    }
  // Gives fresh copy of instance
  public static Instance updatedInstance(Instance ins) {

    int i, j;
    List<Reservation> reserveList = ec2.describeInstances().getReservations();

    for (i = 0; i < reserveList.size(); i++) {
      List<Instance> instanceList = reserveList.get(i).getInstances();
      for (j = 0; j < instanceList.size(); j++) {
        if (instanceList.get(j).getInstanceId().equalsIgnoreCase(ins.getInstanceId())) {
          return instanceList.get(j);
        }
      }
    }
    return null;
  }
Example #27
0
  public String toString() {
    String ret = "\n";
    while (true) {
      if (amazon == null)
        try {
          amazon = JCS.getInstance("Instances");
        } catch (CacheException e) {

          e.printStackTrace();
          continue;
        }
      synchronized (AmazonService.class) {
        for (Object key : amazon.getGroupKeys("Instances")) {
          Instance i = (Instance) amazon.getFromGroup(key, "Instances");
          if (i == null) continue;
          ret +=
              (i.getInstanceId()
                      + " "
                      + i.getImageId()
                      + " "
                      + i.getImageId()
                      + " "
                      + i.getArchitecture()
                      + " "
                      + i.getPrivateDnsName()
                      + " "
                      + i.getState().getName())
                  + "\n";
        }
        for (Object key : amazon.getGroupKeys("AMIs")) {
          Image r = (Image) amazon.getFromGroup(key, "AMIs");
          ;
          if (r == null) continue;
          ret += (r.getImageId() + " " + r.getDescription() + " " + r.getState()) + "\n";
        }
      }
      if (ret.length() > 10) break;
      else {
        try {
          Thread.sleep(1000 * 5);
        } catch (InterruptedException e) {

          e.printStackTrace();
        }
        continue;
      }
    }

    return ret;
  }
  // Allocates new elastic IP addresses.
  public static Instance allocateElasticIP(Instance ins) {
    // allocate
    AllocateAddressResult elasticResult = ec2.allocateAddress();
    String elasticIp = elasticResult.getPublicIp();
    System.out.println("New elastic IP: " + elasticIp);

    // associate
    AssociateAddressRequest aar = new AssociateAddressRequest();
    aar.setInstanceId(ins.getInstanceId());
    aar.setPublicIp(elasticIp);
    ec2.associateAddress(aar);

    ins = updatedInstance(ins);

    return ins;
  }
Example #29
0
 private String hostName(Instance remoteInstance) {
   String publicDNS = remoteInstance.getPublicDnsName();
   return publicDNS != null ? publicDNS : remoteInstance.getPrivateDnsName();
 }
  public Instance unmarshall(StaxUnmarshallerContext context) throws Exception {
    Instance instance = new Instance();
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) targetDepth += 1;

    while (true) {
      XMLEvent xmlEvent = context.nextEvent();
      if (xmlEvent.isEndDocument()) return instance;

      if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

        if (context.testExpression("instanceId", targetDepth)) {
          instance.setInstanceId(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("imageId", targetDepth)) {
          instance.setImageId(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("instanceState", targetDepth)) {
          instance.setState(InstanceStateStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("privateDnsName", targetDepth)) {
          instance.setPrivateDnsName(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("dnsName", targetDepth)) {
          instance.setPublicDnsName(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("reason", targetDepth)) {
          instance.setStateTransitionReason(
              StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("keyName", targetDepth)) {
          instance.setKeyName(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("amiLaunchIndex", targetDepth)) {
          instance.setAmiLaunchIndex(IntegerStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("productCodes/item", targetDepth)) {
          instance.withProductCodes(ProductCodeStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("instanceType", targetDepth)) {
          instance.setInstanceType(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("launchTime", targetDepth)) {
          instance.setLaunchTime(DateStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("placement", targetDepth)) {
          instance.setPlacement(PlacementStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("kernelId", targetDepth)) {
          instance.setKernelId(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("ramdiskId", targetDepth)) {
          instance.setRamdiskId(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("platform", targetDepth)) {
          instance.setPlatform(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("monitoring", targetDepth)) {
          instance.setMonitoring(MonitoringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("subnetId", targetDepth)) {
          instance.setSubnetId(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("vpcId", targetDepth)) {
          instance.setVpcId(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("privateIpAddress", targetDepth)) {
          instance.setPrivateIpAddress(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("ipAddress", targetDepth)) {
          instance.setPublicIpAddress(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("stateReason", targetDepth)) {
          instance.setStateReason(StateReasonStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("architecture", targetDepth)) {
          instance.setArchitecture(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("rootDeviceType", targetDepth)) {
          instance.setRootDeviceType(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("rootDeviceName", targetDepth)) {
          instance.setRootDeviceName(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("blockDeviceMapping/item", targetDepth)) {
          instance.withBlockDeviceMappings(
              InstanceBlockDeviceMappingStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("virtualizationType", targetDepth)) {
          instance.setVirtualizationType(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("instanceLifecycle", targetDepth)) {
          instance.setInstanceLifecycle(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("spotInstanceRequestId", targetDepth)) {
          instance.setSpotInstanceRequestId(
              StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("clientToken", targetDepth)) {
          instance.setClientToken(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("tagSet/item", targetDepth)) {
          instance.withTags(TagStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("groupSet/item", targetDepth)) {
          instance.withSecurityGroups(
              GroupIdentifierStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("sourceDestCheck", targetDepth)) {
          instance.setSourceDestCheck(BooleanStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("hypervisor", targetDepth)) {
          instance.setHypervisor(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("networkInterfaceSet/item", targetDepth)) {
          instance.withNetworkInterfaces(
              InstanceNetworkInterfaceStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("iamInstanceProfile", targetDepth)) {
          instance.setIamInstanceProfile(
              IamInstanceProfileStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("ebsOptimized", targetDepth)) {
          instance.setEbsOptimized(BooleanStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("sriovNetSupport", targetDepth)) {
          instance.setSriovNetSupport(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }
      } else if (xmlEvent.isEndElement()) {
        if (context.getCurrentDepth() < originalDepth) {
          return instance;
        }
      }
    }
  }