@Test(enabled = false)
  public void weCanCancelTasks(NodeMetadata node) throws InterruptedException, ExecutionException {
    ListenableFuture<ExecResponse> future =
        client.submitScriptOnNode(node.getId(), "sleep 300", nameTask("sleeper").runAsRoot(false));
    ExecResponse response = null;
    try {
      response = future.get(1, TimeUnit.MILLISECONDS);
      fail(node.getId() + ": " + response);
    } catch (TimeoutException e) {
      assert !future.isDone();
      response =
          client.runScriptOnNode(
              node.getId(), "/tmp/init-sleeper status", wrapInInitScript(false).runAsRoot(false));
      assert !response.getOutput().trim().equals("") : node.getId() + ": " + response;
      future.cancel(true);
      response =
          client.runScriptOnNode(
              node.getId(), "/tmp/init-sleeper status", wrapInInitScript(false).runAsRoot(false));
      assert response.getOutput().trim().equals("") : node.getId() + ": " + response;
      try {
        future.get();
        fail(future.toString());
      } catch (CancellationException e1) {

      }
    }
  }
  protected void createAndRunAServiceInGroup(String group) throws RunNodesException {
    // note that some cloud providers do not support mixed case tag names
    ImmutableMap<String, String> userMetadata = ImmutableMap.<String, String>of("test", group);

    ImmutableSet<String> tags = ImmutableSet.of(group);
    Stopwatch watch = Stopwatch.createStarted();

    template = buildTemplate(client.templateBuilder());
    template
        .getOptions()
        .inboundPorts(22, 8080)
        .blockOnPort(22, 300)
        .userMetadata(userMetadata)
        .tags(tags);

    NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template));
    long createSeconds = watch.elapsed(TimeUnit.SECONDS);

    final String nodeId = node.getId();

    checkUserMetadataContains(node, userMetadata);
    checkTagsInNodeEquals(node, tags);

    getAnonymousLogger()
        .info(
            format(
                "<< available node(%s) os(%s) in %ss",
                node.getId(), node.getOperatingSystem(), createSeconds));

    watch.reset().start();

    client.runScriptOnNode(nodeId, JettyStatements.install(), nameTask("configure-jetty"));

    long configureSeconds = watch.elapsed(TimeUnit.SECONDS);

    getAnonymousLogger()
        .info(
            format(
                "<< configured node(%s) with %s and jetty %s in %ss",
                nodeId,
                exec(nodeId, "java -fullversion"),
                exec(nodeId, JettyStatements.version()),
                configureSeconds));

    trackAvailabilityOfProcessOnNode(JettyStatements.start(), "start jetty", node);

    client.runScriptOnNode(
        nodeId, JettyStatements.stop(), runAsRoot(false).wrapInInitScript(false));

    trackAvailabilityOfProcessOnNode(JettyStatements.start(), "start jetty", node);
  }
 /** @deprecated since 0.7 */
 @Deprecated
 public static void mapSecurityGroupRuleToIpTables(
     ComputeService computeService,
     NodeMetadata node,
     LoginCredentials credentials,
     String networkInterface,
     Iterable<Integer> ports) {
   for (Integer port : ports) {
     String insertIptableRule =
         IptablesCommands.insertIptablesRule(
             Chain.INPUT, networkInterface, Protocol.TCP, port, Policy.ACCEPT);
     Statement statement = Statements.newStatementList(exec(insertIptableRule));
     ExecResponse response =
         computeService.runScriptOnNode(
             node.getId(), statement, overrideLoginCredentials(credentials).runAsRoot(false));
     if (response.getExitStatus() != 0) {
       String msg =
           String.format(
               "Cannot insert the iptables rule for port %d. Error: %s",
               port, response.getError());
       LOG.error(msg);
       throw new RuntimeException(msg);
     }
   }
 }
  /**
   * If desired, you can disable password authentication for the server because we can use a private
   * key to SSH in.
   *
   * <p>No need to explicitly include the private key with running the script on the node. jclouds
   * is already aware of the private key when the node was created earlier.
   */
  private void disablePasswordAuthentication(NodeMetadata node) throws TimeoutException {
    System.out.format("  Disable Password Authentication%n");

    String script =
        new ScriptBuilder()
            .addStatement(
                exec(
                    "sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config"))
            .addStatement(exec("service ssh restart"))
            .render(OsFamily.UNIX);

    RunScriptOptions options = RunScriptOptions.Builder.blockOnPort(22, 10).blockOnComplete(true);

    computeService.runScriptOnNode(node.getId(), script, options);

    String publicAddress = Iterables.getOnlyElement(node.getPublicAddresses());

    System.out.format("    ssh -i %s root@%s%n", keyPairFile.getAbsolutePath(), publicAddress);
  }
  protected ServiceStats trackAvailabilityOfProcessOnNode(
      Statement process, String processName, NodeMetadata node) {
    ServiceStats stats = new ServiceStats();
    Stopwatch watch = Stopwatch.createStarted();
    ExecResponse exec =
        client.runScriptOnNode(node.getId(), process, runAsRoot(false).wrapInInitScript(false));
    stats.backgroundProcessMilliseconds = watch.elapsed(TimeUnit.MILLISECONDS);
    watch.reset().start();

    HostAndPort socket = null;
    try {
      socket = openSocketFinder.findOpenSocketOnNode(node, 8080, 600, TimeUnit.SECONDS);
    } catch (NoSuchElementException e) {
      throw new NoSuchElementException(
          format("%s%n%s%s", e.getMessage(), exec.getOutput(), exec.getError()));
    }

    stats.socketOpenMilliseconds = watch.elapsed(TimeUnit.MILLISECONDS);

    getAnonymousLogger()
        .info(format("<< %s on node(%s)[%s] %s", processName, node.getId(), socket, stats));
    return stats;
  }
 protected String exec(final String nodeId, Statement command) {
   return client
       .runScriptOnNode(nodeId, command, runAsRoot(false).wrapInInitScript(false))
       .getOutput()
       .trim();
 }
  // 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));
    }
  }