@Test
 public void testLaunchCluster() throws RunNodesException {
   int numNodes = 3;
   final String clusterName = "test-launch-cluster";
   Set<? extends NodeMetadata> nodes =
       context
           .getComputeService()
           .createNodesInGroup(
               clusterName,
               numNodes,
               TemplateOptions.Builder.overrideLoginUser("toor")
                   .runScript(AdminAccess.standard()));
   assertEquals(numNodes, nodes.size(), "wrong number of nodes");
   for (NodeMetadata node : nodes) {
     assertEquals("test-launch-cluster", node.getGroup());
     logger.debug("Created Node: %s", node);
     SshClient client = context.utils().sshForNode().apply(node);
     client.connect();
     ExecResponse hello = client.exec("echo hello");
     assertEquals(hello.getOutput().trim(), "hello");
   }
   context
       .getComputeService()
       .destroyNodesMatching(
           new Predicate<NodeMetadata>() {
             @Override
             public boolean apply(NodeMetadata input) {
               return input.getId().contains(clusterName);
             }
           });
 }
 public void refreshSshIfNewAdminCredentialsConfigured(AdminAccess input) {
   if (input.getAdminCredentials() != null && input.shouldGrantSudoToAdminUser()) {
     ssh.disconnect();
     logger.debug(
         ">> reconnecting as %s@%s", input.getAdminCredentials().identity, ssh.getHostAddress());
     ssh =
         sshFactory.apply(
             node =
                 NodeMetadataBuilder.fromNodeMetadata(node)
                     .adminPassword(null)
                     .credentials(input.getAdminCredentials())
                     .build());
     ssh.connect();
     setupLinkToInitFile();
   }
 }
  public void testStartCCInstance() throws Exception {

    Template template =
        view.getComputeService()
            .templateBuilder()
            .fromHardware(EC2HardwareBuilder.cc2_8xlarge().build())
            .osFamily(OsFamily.AMZN_LINUX)
            .build();
    assert template != null : "The returned template was null, but it should have a value.";
    assertEquals(template.getHardware().getProviderId(), InstanceType.CC2_8XLARGE);
    assertEquals(template.getImage().getUserMetadata().get("rootDeviceType"), "ebs");
    assertEquals(template.getImage().getUserMetadata().get("virtualizationType"), "hvm");
    assertEquals(template.getImage().getUserMetadata().get("hypervisor"), "xen");

    template
        .getOptions()
        .runScript(Statements.newStatementList(AdminAccess.standard(), InstallJDK.fromOpenJDK()));

    String group = PREFIX + "cccluster";
    view.getComputeService().destroyNodesMatching(NodePredicates.inGroup(group));
    // TODO make this not lookup an explicit region
    client
        .getPlacementGroupApi()
        .get()
        .deletePlacementGroupInRegion(null, "jclouds#" + group + "#us-east-1");

    try {
      Set<? extends NodeMetadata> nodes =
          view.getComputeService().createNodesInGroup(group, 1, template);
      NodeMetadata node = getOnlyElement(nodes);

      getOnlyElement(
          getOnlyElement(
              client.getInstanceApi().get().describeInstancesInRegion(null, node.getProviderId())));

    } catch (RunNodesException e) {
      System.err.println(e.getNodeErrors().keySet());
      Throwables.propagate(e);
    } finally {
      view.getComputeService().destroyNodesMatching(NodePredicates.inGroup(group));
    }
  }
 protected static Template addRunScriptToTemplate(Template template) {
   template
       .getOptions()
       .runScript(Statements.newStatementList(AdminAccess.standard(), InstallJDK.fromOpenJDK()));
   return template;
 }
  // 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 group = this.group + "r";
    try {
      client.destroyNodesMatching(inGroup(group));
    } catch (Exception e) {

    }
    template = buildTemplate(client.templateBuilder());
    template.getOptions().blockOnPort(22, 120);
    try {
      Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, template);
      NodeMetadata node = get(nodes, 0);
      LoginCredentials good = node.getCredentials();
      assert good.identity != null : nodes;

      for (Entry<? extends NodeMetadata, ExecResponse> response :
          client
              .runScriptOnNodesMatching(
                  runningInGroup(group),
                  "hostname",
                  wrapInInitScript(false).runAsRoot(false).overrideLoginCredentials(good))
              .entrySet()) {
        checkResponseEqualsHostname(response.getValue(), response.getKey());
      }

      // test single-node execution
      ExecResponse response =
          client.runScriptOnNode(
              node.getId(), "hostname", wrapInInitScript(false).runAsRoot(false));
      checkResponseEqualsHostname(response, node);
      OperatingSystem os = node.getOperatingSystem();

      // test bad password
      tryBadPassword(group, good);

      runScriptWithCreds(group, os, good);

      checkNodes(nodes, group, "runScriptWithCreds");

      // test adding AdminAccess later changes the default boot user, in this
      // case to foo, with home dir /over/ridden/foo
      ListenableFuture<ExecResponse> future =
          client.submitScriptOnNode(
              node.getId(),
              AdminAccess.builder().adminUsername("foo").adminHome("/over/ridden/foo").build(),
              nameTask("adminUpdate"));

      response = future.get(3, TimeUnit.MINUTES);

      assert response.getExitStatus() == 0 : node.getId() + ": " + response;

      node = client.getNodeMetadata(node.getId());
      // test that the node updated to the correct admin user!
      assertEquals(node.getCredentials().identity, "foo");
      assert node.getCredentials().credential != null : nodes;

      weCanCancelTasks(node);

      assert response.getExitStatus() == 0 : node.getId() + ": " + response;

      response =
          client.runScriptOnNode(
              node.getId(), "echo $USER", wrapInInitScript(false).runAsRoot(false));

      assert response.getOutput().trim().equals("foo") : node.getId() + ": " + response;

    } finally {
      client.destroyNodesMatching(inGroup(group));
    }
  }
  @Override
  protected Object doExecute() throws Exception {
    ComputeService service = null;
    try {
      service = getComputeService();
    } catch (Throwable t) {
      System.err.println(t.getMessage());
      return null;
    }

    TemplateBuilder builder = service.templateBuilder();
    builder.any();
    if (smallest) {
      builder.smallest();
    }
    if (fastest) {
      builder.fastest();
    }
    if (biggest) {
      builder.biggest();
    }
    if (locationId != null) {
      builder.locationId(locationId);
    }
    if (imageId != null) {
      builder.imageId(imageId);
    }
    if (hardwareId != null) {
      builder.hardwareId(hardwareId);
    }

    if (osFamily != null) {
      builder.osFamily(OsFamily.fromValue(osFamily));
    }

    if (osVersion != null) {
      builder.osVersionMatches(osVersion);
    }

    TemplateOptions options = service.templateOptions();
    List<Statement> statements = Lists.newLinkedList();

    if (adminAccess) {
      statements.add(AdminAccess.standard());
    }
    if (recipes != null) {
      for (String recipe : recipes) {
        statements.add(recipeManager.createStatement(recipe, group));
      }
    }
    if (ec2SecurityGroups != null) {
      options.as(EC2TemplateOptions.class).securityGroups(ec2SecurityGroups);
    }
    if (ec2KeyPair != null) {
      options.as(EC2TemplateOptions.class).keyPair(ec2KeyPair);
    }
    if (ec2NoKeyPair != null) {
      options.as(EC2TemplateOptions.class).noKeyPair();
    }

    Set<? extends NodeMetadata> metadatas = null;

    if (!statements.isEmpty()) {
      options.runScript(new StatementList(statements));
    }

    try {
      metadatas = service.createNodesInGroup(group, number, builder.options(options).build());
    } catch (RunNodesException ex) {
      System.out.println("Failed to create nodes:" + ex.getMessage());
    }

    if (metadatas != null && !metadatas.isEmpty()) {
      System.out.println("Created nodes:");
      printNodes(service, metadatas, System.out);

      for (NodeMetadata node : metadatas) {
        for (String cacheKey : ServiceHelper.findCacheKeysForService(service)) {
          cacheProvider
              .getProviderCacheForType(Constants.ACTIVE_NODE_CACHE)
              .put(cacheKey, node.getId());
          cacheProvider
              .getProviderCacheForType(Constants.INACTIVE_NODE_CACHE)
              .put(cacheKey, node.getId());
          cacheProvider
              .getProviderCacheForType(Constants.SUSPENDED_NODE_CACHE)
              .put(cacheKey, node.getId());
        }
      }
    }

    return null;
  }