@Test public void testExecHostname() throws IOException { SshClient client = setupClient(); try { ExecResponse response = client.exec("hostname"); assertEquals(response.getExitStatus(), 0); assertEquals(response.getError(), ""); assertEquals(response.getOutput().trim(), "localhost".equals(sshHost) ? InetAddress.getLocalHost().getHostName() : sshHost); } finally { client.disconnect(); } }
private void helloAndJava(SshClient client) { client.connect(); expect(client.exec("echo hello")).andReturn(new ExecResponse("hello", "", 0)); expect(client.exec("java -version")).andReturn(new ExecResponse("", "OpenJDK", 0)); client.disconnect(); }
private int handleScriptOutput(PrintStream out, PrintStream err, Map<? extends NodeMetadata, ExecResponse> responses) { int exitStatus = 0; for (Map.Entry<? extends NodeMetadata, ExecResponse> entry : responses.entrySet()) { out.printf("** Node %s: %s%n", entry.getKey().getId(), Iterables.concat(entry.getKey().getPrivateAddresses(), entry.getKey().getPublicAddresses())); ExecResponse response = entry.getValue(); if (response.getExitStatus() != 0) { exitStatus = response.getExitStatus(); } out.printf("%s%n", response.getOutput()); err.printf("%s%n", response.getError()); } return exitStatus; }
@Test public void testExecInvalidCommand() throws IOException { SshClient client = setupClient(); try { ExecResponse response = client.exec("thisCommandDoesNotExist"); assertNotEquals(response.getExitStatus(), 0); assertTrue(response.getOutput().contains("not found") || response.getError().contains("not found"), "stdout="+response.getOutput()+"; stderr="+response.getError()); } finally { client.disconnect(); } }
public void simpleRootTestWithSudoPassword() { node = createMock(NodeMetadata.class); expect(node.getCredentials()).andReturn(LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()) .atLeastOnce(); replay(node); RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec("echo $USER\necho $USER"), wrapInInitScript(false).runAsRoot(true)); testMe.init(); sshClient.connect(); expect(sshClient.getUsername()).andReturn("tester"); expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); expect( sshClient.exec("sudo -S sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + "testpassword!\n" + "echo $USER\n" + "echo $USER\n" + "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0)); sshClient.disconnect(); replay(sshClient); testMe.call(); }
public void testExitStatusOfCommandGreaterThanZeroFalseWhen0() { SudoAwareInitManager commandRunner = createMockBuilder(SudoAwareInitManager.class).addMockedMethod("runAction") .createStrictMock(); expect(commandRunner.runAction("status")).andReturn(new ExecResponse("", "", 0)); replay(commandRunner); Predicate<String> pred = new ExitStatusOfCommandGreaterThanZero(commandRunner); assertEquals(pred.apply("status"), false); verify(commandRunner); }
public void simpleTest() { RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec("echo $USER\necho $USER"), wrapInInitScript(false).runAsRoot(false)); testMe.init(); sshClient.connect(); expect(sshClient.getUsername()).andReturn("tester"); expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); expect(sshClient.exec("echo $USER\n" + "echo $USER\n")).andReturn(new ExecResponse("tester\ntester\n", null, 0)); sshClient.disconnect(); replay(sshClient); testMe.call(); }
public void testCancelDontInterruptLeavesCommandRunningAndReturnsLastStatus() throws InterruptedException, ExecutionException { ListeningExecutorService userExecutor = MoreExecutors.sameThreadExecutor(); Predicate<String> notRunningAnymore = Predicates.alwaysTrue(); SudoAwareInitManager commandRunner = createMockBuilder(SudoAwareInitManager.class).addMockedMethod("runAction") .addMockedMethod("getStatement").addMockedMethod("getNode").addMockedMethod("toString") .createStrictMock(); InitScript initScript = createMockBuilder(InitScript.class).addMockedMethod("getInstanceName").createStrictMock(); expect(commandRunner.runAction("stdout")).andReturn(new ExecResponse("stillrunning", "", 0)); expect(commandRunner.runAction("stderr")).andReturn(new ExecResponse("", "", 0)); expect(commandRunner.runAction("exitstatus")).andReturn(new ExecResponse("", "", 1)); toStringAndEventBusExpectations(commandRunner, initScript); replay(commandRunner, initScript); BlockUntilInitScriptStatusIsZeroThenReturnOutput future = new BlockUntilInitScriptStatusIsZeroThenReturnOutput( userExecutor, eventBus, notRunningAnymore, commandRunner); future.cancel(false); // note if this didn't cancel properly, the loop would never end! future.run(); try { future.get(); fail(); } catch (CancellationException e) { } verify(commandRunner, initScript); }
@Override protected void prepareNodeBeforeCreatingImage(NodeMetadata node) { // Don't wrap in the init-script, since the comand will clear the user // config, and jclouds won't be able to execute more than one command // (won't be able to poll for the execution status of the command when // running with the init-script) ExecResponse result = view.getComputeService().runScriptOnNode(node.getId(), "waagent -deprovision+user -force", wrapInInitScript(false)); assertEquals(result.getExitStatus(), 0); }
/** * Runs a script on the target node. */ protected void runScriptOnNode(Exchange exchange) throws CamelException { String script = exchange.getIn().getBody(String.class); String nodeId = getNodeId(exchange); String user = getUser(exchange); LoginCredentials credentials = null; if (ObjectHelper.isNotEmpty(user)) { credentials = LoginCredentials.builder().user(user).build(); } ExecResponse execResponse = null; if (credentials == null) { execResponse = computeService.runScriptOnNode(nodeId, script); } else { execResponse = computeService.runScriptOnNode(nodeId, script, RunScriptOptions.Builder.overrideLoginCredentials(credentials).runAsRoot(false)); } if (execResponse == null) { throw new CamelExchangeException("Failed to receive response for run script operation on node: " + nodeId + " using script: " + script, exchange); } exchange.setProperty(JcloudsConstants.RUN_SCRIPT_ERROR, execResponse.getError()); exchange.setProperty(JcloudsConstants.RUN_SCRIPT_EXIT_CODE, execResponse.getExitStatus()); exchange.getOut().setBody(execResponse.getOutput()); }
LoginCredentials.Builder loginBuilder; if (credentials == null) { loginBuilder = LoginCredentials.builder(); } else { loginBuilder = credentials.toBuilder(); credentials = loginBuilder.user(user).password(password).build(); } else { credentials = loginBuilder.user(user).build(); NodeMetadata node = entry.getKey(); System.out.println(""); if (response.getOutput() != null && !response.getOutput().isEmpty()) { System.out.println("Node:" + node.getId() + " Output:" + response.getOutput()); if (response.getError() != null && !response.getError().isEmpty()) { System.out.println("Node:" + node.getId() + " Error:" + response.getError());
@Override public String apply(ExecResponse input) { return input.getOutput(); } };
ExecResponse runCommand(String command) { String statement = String.format("[%s] as %s@%s", command.replace( node.getCredentials().getOptionalPassword().isPresent() ? node.getCredentials().getOptionalPassword().get() : "XXXXX", "XXXXX"), ssh .getUsername(), ssh.getHostAddress()); if (command.endsWith("status") || command.endsWith("stdout") || command.endsWith("stderr")) logger.trace(">> running %s", statement); else computeLogger.debug(">> running " + statement); ExecResponse returnVal = ssh.exec(command); if (!command.endsWith("status")) checkState(returnVal.getExitStatus() == 0, "error running %s; returnVal !=0: %s", statement, returnVal); return returnVal; }
ExecResponse runCommand(String command) { String statement = String.format("[%s] as %s@%s", command.replace( node.getCredentials().getPassword() != null ? node.getCredentials().getPassword() : "XXXXX", "XXXXX"), ssh .getUsername(), ssh.getHostAddress()); if (command.endsWith("status") || command.endsWith("stdout") || command.endsWith("stderr")) logger.trace(">> running %s", statement); else computeLogger.debug(">> running " + statement); ExecResponse returnVal = ssh.exec(command); if (!command.endsWith("status")) checkState(returnVal.getExitStatus() == 0, "error running %s; returnVal !=0: %s", statement, returnVal); return returnVal; }
@Override public boolean apply(SshClient input) { input.connect(); if (input.exec("id").getExitStatus() == 0) { return true; } return false; } }, getSpawnNodeMaxWait(), 1l, SECONDS).apply(client));
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; }
@Override public boolean apply(CommandUsingClient commandUsingClient) { logger.trace("looking for [%s] state on %s@%s", commandUsingClient.command, commandUsingClient.client .getUsername(), commandUsingClient.client.getHostAddress()); ExecResponse response = refresh(commandUsingClient); while (response.getExitStatus() == -1) response = refresh(commandUsingClient); logger.trace("%s@%s: looking for exit code 0: currently: %s", commandUsingClient.client.getUsername(), commandUsingClient.client.getHostAddress(), response.getExitStatus()); return 0 == response.getExitStatus(); }
@Override public boolean apply(String input) { return commandRunner.runAction(input).getExitStatus() > 0; }
public ExecResponse exec(String command) { if (command.equals("hostname")) { return new ExecResponse(sshHost, "", 0); } throw new RuntimeException("command " + command + " not stubbed"); }
private 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); } } }