@Test(
      enabled = true,
      dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired")
  public void testGet() throws Exception {
    Map<String, ? extends NodeMetadata> metadataMap =
        newLinkedHashMap(
            uniqueIndex(
                filter(client.listNodesDetailsMatching(all()), and(withTag(tag), not(TERMINATED))),
                new Function<NodeMetadata, String>() {

                  @Override
                  public String apply(NodeMetadata from) {
                    return from.getId();
                  }
                }));
    for (NodeMetadata node : nodes) {
      metadataMap.remove(node.getId());
      NodeMetadata metadata = client.getNodeMetadata(node.getId());
      assertEquals(metadata.getProviderId(), node.getProviderId());
      assertEquals(metadata.getTag(), node.getTag());
      assertLocationSameOrChild(metadata.getLocation(), template.getLocation());
      checkImageIdMatchesTemplate(metadata);
      checkOsMatchesTemplate(metadata);
      assertEquals(metadata.getState(), NodeState.RUNNING);
      // due to DHCP the addresses can actually change in-between runs.
      assertEquals(metadata.getPrivateAddresses().size(), node.getPrivateAddresses().size());
      assertEquals(metadata.getPublicAddresses().size(), node.getPublicAddresses().size());
    }
    assertNodeZero(metadataMap.values());
  }
  // since surefire and eclipse don't otherwise guarantee the order, we are
  // starting this one alphabetically before create2nodes..
  @Test(enabled = true, dependsOnMethods = "testImagesCache")
  public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception {
    String tag = this.tag + "run";
    try {
      client.destroyNodesMatching(NodePredicates.withTag(tag));
    } catch (Exception e) {

    }

    TemplateOptions options = client.templateOptions().blockOnPort(22, 120);
    try {
      Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, options);
      Credentials good = nodes.iterator().next().getCredentials();
      assert good.account != null;
      assert good.key != null;

      Image image = Iterables.get(nodes, 0).getImage();
      try {
        Map<? extends NodeMetadata, ExecResponse> responses =
            runScriptWithCreds(tag, image.getOsFamily(), new Credentials(good.account, "romeo"));
        assert false : "shouldn't pass with a bad password\n" + responses;
      } catch (RunScriptOnNodesException e) {
        assert Throwables.getRootCause(e).getMessage().contains("Auth fail") : e;
      }

      runScriptWithCreds(tag, image.getOsFamily(), good);

      checkNodes(nodes, tag);

    } finally {
      client.destroyNodesMatching(NodePredicates.withTag(tag));
    }
  }
  @Test(enabled = true, dependsOnMethods = "testTemplateMatch")
  public void testCreateTwoNodesWithRunScript() throws Exception {
    try {
      client.destroyNodesMatching(NodePredicates.withTag(tag));
    } catch (HttpResponseException e) {
      // TODO hosting.com throws 400 when we try to delete a vApp
    } catch (NoSuchElementException e) {

    }
    template = buildTemplate(client.templateBuilder());

    template
        .getOptions()
        .installPrivateKey(keyPair.get("private"))
        .authorizePublicKey(keyPair.get("public"))
        .runScript(buildScript(template.getImage().getOsFamily()).getBytes());
    try {
      nodes = Sets.newTreeSet(client.runNodesWithTag(tag, 2, template));
    } catch (RunNodesException e) {
      nodes = Sets.newTreeSet(Iterables.concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));
      throw e;
    }
    assertEquals(nodes.size(), 2);
    checkNodes(nodes, tag);
    NodeMetadata node1 = nodes.first();
    NodeMetadata node2 = nodes.last();
    // credentials aren't always the same
    // assertEquals(node1.getCredentials(), node2.getCredentials());

    assertLocationSameOrChild(node1.getLocation(), template.getLocation());
    assertLocationSameOrChild(node2.getLocation(), template.getLocation());

    assertEquals(node1.getImage(), template.getImage());
    assertEquals(node2.getImage(), template.getImage());
  }
  @Test(enabled = true, dependsOnMethods = "testCompareSizes")
  public void testCreateTwoNodesWithRunScript() throws Exception {
    try {
      client.destroyNodesMatching(withTag(tag));
    } catch (NoSuchElementException e) {

    }
    refreshTemplate();
    try {
      nodes = newTreeSet(client.runNodesWithTag(tag, 2, template));
    } catch (RunNodesException e) {
      nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));
      throw e;
    }
    assertEquals(nodes.size(), 2);
    checkNodes(nodes, tag);
    NodeMetadata node1 = nodes.first();
    NodeMetadata node2 = nodes.last();
    // credentials aren't always the same
    // assertEquals(node1.getCredentials(), node2.getCredentials());

    assertLocationSameOrChild(node1.getLocation(), template.getLocation());
    assertLocationSameOrChild(node2.getLocation(), template.getLocation());
    checkImageIdMatchesTemplate(node1);
    checkImageIdMatchesTemplate(node2);
    checkOsMatchesTemplate(node1);
    checkOsMatchesTemplate(node2);
  }
  @Test(enabled = true)
  public void testCreateAndRunAService() throws Exception {

    String tag = this.tag + "service";
    try {
      client.destroyNodesMatching(withTag(tag));
    } catch (Exception e) {

    }

    template =
        client
            .templateBuilder()
            .options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080))
            .build();
    // note this is a dependency on the template resolution
    template
        .getOptions()
        .runScript(
            RunScriptData.createScriptInstallAndStartJBoss(
                keyPair.get("public"), template.getImage().getOperatingSystem()));
    try {
      NodeMetadata node = getOnlyElement(client.runNodesWithTag(tag, 1, template));

      checkHttpGet(node);
    } finally {
      client.destroyNodesMatching(withTag(tag));
    }
  }
  // since surefire and eclipse don't otherwise guarantee the order, we are
  // starting this one alphabetically before create2nodes..
  @Test(
      enabled = true,
      dependsOnMethods = {"testCompareSizes"})
  public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception {
    String tag = this.tag + "run";
    try {
      client.destroyNodesMatching(withTag(tag));
    } catch (Exception e) {

    }

    TemplateOptions options = client.templateOptions().blockOnPort(22, 120);
    try {
      Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, options);
      Credentials good = nodes.iterator().next().getCredentials();
      assert good.identity != null : nodes;
      assert good.credential != null : nodes;

      OperatingSystem os = get(nodes, 0).getOperatingSystem();
      try {
        Map<? extends NodeMetadata, ExecResponse> responses =
            runScriptWithCreds(tag, os, new Credentials(good.identity, "romeo"));
        assert false : "shouldn't pass with a bad password\n" + responses;
      } catch (RunScriptOnNodesException e) {
        assert getRootCause(e).getMessage().contains("Auth fail") : e;
      }

      runScriptWithCreds(tag, os, good);

      checkNodes(nodes, tag);

    } finally {
      client.destroyNodesMatching(withTag(tag));
    }
  }
 @Test(enabled = true)
 public void testImagesCache() throws Exception {
   client.listImages();
   long time = System.currentTimeMillis();
   client.listImages();
   long duration = System.currentTimeMillis() - time;
   assert duration < 1000 : String.format("%dms to get images", duration);
 }
 @Test(
     enabled = true,
     dependsOnMethods = {"testImagesCache"})
 public void testTemplateMatch() throws Exception {
   template = buildTemplate(client.templateBuilder());
   Template toMatch = client.templateBuilder().imageId(template.getImage().getId()).build();
   assertEquals(toMatch.getImage(), template.getImage());
 }
 @Test(
     enabled = true,
     dependsOnMethods = {"testListNodes", "testGetNodesWithDetails"})
 public void testDestroyNodes() {
   client.destroyNodesMatching(withTag(tag));
   for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), withTag(tag))) {
     assert node.getState() == NodeState.TERMINATED : node;
     assertEquals(context.getCredentialStore().get("node#" + node.getId()), null);
   }
 }
 @AfterTest
 protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException {
   if (nodes != null) {
     client.destroyNodesMatching(NodePredicates.withTag(tag));
     for (NodeMetadata node :
         Iterables.filter(
             client.listNodesDetailsMatching(NodePredicates.all()), NodePredicates.withTag(tag))) {
       assert node.getState() == NodeState.TERMINATED : node;
     }
   }
   context.close();
 }
 @Test(enabled = true /* , dependsOnMethods = "testTemplateMatch" */)
 public void testTemplateOptions() throws Exception {
   TemplateOptions options = new TemplateOptions().withMetadata();
   Template t = client.templateBuilder().smallest().options(options).build();
   assert t.getOptions().isIncludeMetadata()
       : "The metadata option should be 'true' " + "for the created template";
 }
 public void testListNodes() throws Exception {
   for (ComputeMetadata node : client.listNodes()) {
     assert node.getProviderId() != null;
     assert node.getLocation() != null;
     assertEquals(node.getType(), ComputeType.NODE);
   }
 }
 public void testListImages() throws Exception {
   for (Image image : client.listImages()) {
     assert image.getProviderId() != null : image;
     // image.getLocationId() can be null, if it is a location-free image
     assertEquals(image.getType(), ComputeType.IMAGE);
   }
 }
 @Test(groups = {"integration", "live"})
 public void testGetAssignableLocations() throws Exception {
   for (Location location : client.listAssignableLocations()) {
     System.err.printf("location %s%n", location);
     assert location.getId() != null : location;
     assert location != location.getParent() : location;
     assert location.getScope() != null : location;
     switch (location.getScope()) {
       case PROVIDER:
         assertProvider(location);
         break;
       case REGION:
         assertProvider(location.getParent());
         break;
       case ZONE:
         Location provider = location.getParent().getParent();
         // zone can be a direct descendant of provider
         if (provider == null) provider = location.getParent();
         assertProvider(provider);
         break;
       case HOST:
         Location provider2 = location.getParent().getParent().getParent();
         // zone can be a direct descendant of provider
         if (provider2 == null) provider2 = location.getParent().getParent();
         assertProvider(provider2);
         break;
     }
   }
 }
 @Test(enabled = true, dependsOnMethods = "testSuspendResume")
 public void testListNodes() throws Exception {
   for (ComputeMetadata node : client.listNodes()) {
     assert node.getProviderId() != null;
     assert node.getLocation() != null;
     assertEquals(node.getType(), ComputeType.NODE);
   }
 }
  private void refreshTemplate() {
    template = buildTemplate(client.templateBuilder());

    template
        .getOptions()
        .installPrivateKey(keyPair.get("private"))
        .authorizePublicKey(keyPair.get("public"))
        .runScript(buildScript(template.getImage().getOperatingSystem()));
  }
 public void testListSizes() throws Exception {
   for (Size size : client.listSizes()) {
     assert size.getProviderId() != null;
     assert size.getCores() > 0;
     assert size.getDisk() > 0;
     assert size.getRam() > 0;
     assertEquals(size.getType(), ComputeType.SIZE);
   }
 }
 public void testListSizes() throws Exception {
   for (Hardware hardware : client.listHardwareProfiles()) {
     assert hardware.getProviderId() != null;
     assert getCores(hardware) > 0;
     assert hardware.getVolumes().size() >= 0;
     assert hardware.getRam() > 0;
     assertEquals(hardware.getType(), ComputeType.HARDWARE);
   }
 }
  public void testOptionToNotBlock() throws Exception {
    String tag = this.tag + "block";
    try {
      client.destroyNodesMatching(withTag(tag));
    } catch (Exception e) {

    }
    // no inbound ports
    TemplateOptions options = client.templateOptions().blockUntilRunning(false).inboundPorts();
    try {
      long time = System.currentTimeMillis();
      Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, options);
      NodeMetadata node = getOnlyElement(nodes);
      assert node.getState() != NodeState.RUNNING;
      long duration = System.currentTimeMillis() - time;
      assert duration < 30 * 1000 : "duration longer than 30 seconds!:  " + duration / 1000;
    } finally {
      client.destroyNodesMatching(withTag(tag));
    }
  }
 @Test(enabled = true, dependsOnMethods = "testCreateTwoNodesWithRunScript")
 public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception {
   initializeContextAndClient();
   TreeSet<NodeMetadata> nodes = Sets.newTreeSet(client.runNodesWithTag(tag, 1, template));
   checkNodes(nodes, tag);
   NodeMetadata node = nodes.first();
   this.nodes.add(node);
   assertEquals(nodes.size(), 1);
   assertLocationSameOrChild(node.getLocation(), template.getLocation());
   assertEquals(node.getImage(), template.getImage());
 }
 protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(
     final String tag, OperatingSystem os, Credentials creds) throws RunScriptOnNodesException {
   try {
     return client.runScriptOnNodesMatching(
         runningWithTag(tag),
         newStringPayload(buildScript(os).render(OsFamily.UNIX)),
         overrideCredentialsWith(creds).nameTask("runScriptWithCreds"));
   } catch (SshException e) {
     throw e;
   }
 }
  @Test(enabled = true, dependsOnMethods = "testGet")
  public void testOptionToNotBlock() throws Exception {
    String tag = this.tag + "block";
    try {
      client.destroyNodesMatching(NodePredicates.withTag(tag));
    } catch (Exception e) {

    }
    // no inbound ports
    TemplateOptions options = client.templateOptions().blockUntilRunning(false).inboundPorts();
    try {
      long time = System.currentTimeMillis();
      Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, options);
      NodeMetadata node = Iterables.getOnlyElement(nodes);
      assertEquals(node.getState(), NodeState.PENDING);

      long duration = System.currentTimeMillis() - time;
      assert duration < 30 * 1000 : "duration longer than 30 seconds!:  " + duration / 1000;
    } finally {
      client.destroyNodesMatching(NodePredicates.withTag(tag));
    }
  }
 @Test(
     enabled = true,
     dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired")
 public void testGet() throws Exception {
   Set<? extends NodeMetadata> metadataSet =
       Sets.newHashSet(
           Iterables.filter(
               client.listNodesDetailsMatching(NodePredicates.all()),
               Predicates.and(
                   NodePredicates.withTag(tag), Predicates.not(NodePredicates.TERMINATED))));
   for (NodeMetadata node : nodes) {
     metadataSet.remove(node);
     NodeMetadata metadata = client.getNodeMetadata(node.getId());
     assertEquals(metadata.getProviderId(), node.getProviderId());
     assertEquals(metadata.getTag(), node.getTag());
     assertLocationSameOrChild(metadata.getLocation(), template.getLocation());
     assertEquals(metadata.getImage(), template.getImage());
     assertEquals(metadata.getState(), NodeState.RUNNING);
     assertEquals(metadata.getPrivateAddresses(), node.getPrivateAddresses());
     assertEquals(metadata.getPublicAddresses(), node.getPublicAddresses());
   }
   assertNodeZero(metadataSet);
 }
  @Test(enabled = true)
  public void testCompareSizes() throws Exception {
    Hardware defaultSize = client.templateBuilder().build().getHardware();

    Hardware smallest = client.templateBuilder().smallest().build().getHardware();
    Hardware fastest = client.templateBuilder().fastest().build().getHardware();
    Hardware biggest = client.templateBuilder().biggest().build().getHardware();

    System.out.printf("smallest %s%n", smallest);
    System.out.printf("fastest %s%n", fastest);
    System.out.printf("biggest %s%n", biggest);

    assertEquals(defaultSize, smallest);

    assert getCores(smallest) <= getCores(fastest) : String.format("%d ! <= %d", smallest, fastest);
    assert getCores(biggest) <= getCores(fastest) : String.format("%d ! <= %d", biggest, fastest);

    assert biggest.getRam() >= fastest.getRam() : String.format("%d ! >= %d", biggest, fastest);
    assert biggest.getRam() >= smallest.getRam() : String.format("%d ! >= %d", biggest, smallest);

    assert getCores(fastest) >= getCores(biggest) : String.format("%d ! >= %d", fastest, biggest);
    assert getCores(fastest) >= getCores(smallest) : String.format("%d ! >= %d", fastest, smallest);
  }
  @Test(enabled = true, dependsOnMethods = "testReboot")
  public void testSuspendResume() throws Exception {
    client.suspendNodesMatching(withTag(tag));

    Set<? extends NodeMetadata> stoppedNodes = refreshNodes();

    assert Iterables.all(
            stoppedNodes,
            new Predicate<NodeMetadata>() {

              @Override
              public boolean apply(NodeMetadata input) {
                boolean returnVal = input.getState() == NodeState.SUSPENDED;
                if (!returnVal)
                  System.err.printf(
                      "warning: node %s in state %s%n", input.getId(), input.getState());
                return returnVal;
              }
            })
        : stoppedNodes;

    client.resumeNodesMatching(withTag(tag));
    testGet();
  }
 protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(
     final String tag, OsFamily osFamily, Credentials creds) throws RunScriptOnNodesException {
   try {
     return client.runScriptOnNodesMatching(
         NodePredicates.runningWithTag(tag),
         buildScript(osFamily).getBytes(),
         RunScriptOptions.Builder.overrideCredentialsWith(creds));
   } catch (SshException e) {
     if (Throwables.getRootCause(e).getMessage().contains("Auth fail")) {
       // System.err.printf("bad credentials: %s:%s for %s%n",
       // creds.account, creds.key, client
       // .listNodesDetailsMatching(tag));
     }
     throw e;
   }
 }
 public void testGetNodesWithDetails() throws Exception {
   for (NodeMetadata node : client.listNodesDetailsMatching(NodePredicates.all())) {
     assert node.getProviderId() != null : node;
     assert node.getLocation() != null : node;
     assertEquals(node.getType(), ComputeType.NODE);
     assert node instanceof NodeMetadata;
     NodeMetadata nodeMetadata = (NodeMetadata) node;
     assert nodeMetadata.getProviderId() != null : nodeMetadata;
     // nullable
     // assert nodeMetadata.getImage() != null : node;
     // user specified name is not always supported
     // assert nodeMetadata.getName() != null : nodeMetadata;
     if (nodeMetadata.getState() == NodeState.RUNNING) {
       assert nodeMetadata.getPublicAddresses() != null : nodeMetadata;
       assert nodeMetadata.getPublicAddresses().size() > 0
               || nodeMetadata.getPrivateAddresses().size() > 0
           : nodeMetadata;
       assertNotNull(nodeMetadata.getPrivateAddresses());
     }
   }
 }
 private Set<? extends NodeMetadata> refreshNodes() {
   return filter(client.listNodesDetailsMatching(all()), and(withTag(tag), not(TERMINATED)));
 }
 @Test(enabled = true, dependsOnMethods = "testGet")
 public void testReboot() throws Exception {
   client.rebootNodesMatching(NodePredicates.withTag(tag)); // TODO test
   // validation
   testGet();
 }