Search in sources :

Example 6 with ExecResponse

use of org.jclouds.compute.domain.ExecResponse in project whirr by apache.

the class RunScriptCommand method handleScriptOutput.

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;
}
Also used : ExecResponse(org.jclouds.compute.domain.ExecResponse) Map(java.util.Map)

Example 7 with ExecResponse

use of org.jclouds.compute.domain.ExecResponse in project whirr by apache.

the class CdhHadoopServiceTest method testVersion.

@Test(timeout = TestConstants.ITEST_TIMEOUT)
public void testVersion() throws Exception {
    Statement checkVersion = Statements.exec("cat /usr/lib/hadoop/cloudera/cdh_version.properties");
    Map<? extends NodeMetadata, ExecResponse> responses = controller.runScriptOnNodesMatching(clusterSpec, ALL, checkVersion);
    printResponses(checkVersion, responses);
    assertResponsesContain(responses, checkVersion, "cdh4");
}
Also used : ExecResponse(org.jclouds.compute.domain.ExecResponse) Statement(org.jclouds.scriptbuilder.domain.Statement) Test(org.junit.Test)

Example 8 with ExecResponse

use of org.jclouds.compute.domain.ExecResponse in project legacy-jclouds-examples by jclouds.

the class MainApp method main.

public static void main(String[] args) {
    if (args.length < PARAMETERS)
        throw new IllegalArgumentException(INVALID_SYNTAX);
    String provider = args[0];
    String identity = args[1];
    String credential = args[2];
    String groupName = args[3];
    Action action = Action.valueOf(args[4].toUpperCase());
    if (action == Action.EXEC && args.length < PARAMETERS + 1)
        throw new IllegalArgumentException("please quote the command to exec as the last parameter");
    String command = (action == Action.EXEC) ? args[5] : "echo hello";
    if (action == Action.RUN && args.length < PARAMETERS + 1)
        throw new IllegalArgumentException("please pass the local file to run as the last parameter");
    File file = null;
    if (action == Action.RUN) {
        file = new File(args[5]);
        if (!file.exists())
            throw new IllegalArgumentException("file must exist! " + file);
    }
    String minRam = System.getProperty("minRam");
    String loginUser = System.getProperty("loginUser", "toor");
    // note that you can check if a provider is present ahead of time
    checkArgument(contains(allKeys, provider), "provider %s not in supported list: %s", provider, allKeys);
    LoginCredentials login = (action != Action.DESTROY) ? getLoginForCommandExecution(action) : null;
    ComputeService compute = initComputeService(provider, identity, credential);
    try {
        switch(action) {
            case ADD:
                System.out.printf(">> adding node to group %s%n", groupName);
                // Default template chooses the smallest size on an operating system
                // that tested to work with java, which tends to be Ubuntu or CentOS
                TemplateBuilder templateBuilder = compute.templateBuilder();
                // just tweak minRam
                if (minRam != null)
                    templateBuilder.minRam(Integer.parseInt(minRam));
                // note this will create a user with the same name as you on the
                // node. ex. you can connect via ssh publicip
                Statement bootInstructions = AdminAccess.standard();
                // to run commands as root, we use the runScript option in the template.
                if (provider.equalsIgnoreCase("virtualbox"))
                    templateBuilder.options(overrideLoginUser(loginUser).runScript(bootInstructions));
                else
                    templateBuilder.options(runScript(bootInstructions));
                NodeMetadata node = getOnlyElement(compute.createNodesInGroup(groupName, 1, templateBuilder.build()));
                System.out.printf("<< node %s: %s%n", node.getId(), concat(node.getPrivateAddresses(), node.getPublicAddresses()));
            case EXEC:
                System.out.printf(">> running [%s] on group %s as %s%n", command, groupName, login.identity);
                // when you run commands, you can pass options to decide whether to
                // run it as root, supply or own credentials vs from cache, and wrap
                // in an init script vs directly invoke
                Map<? extends NodeMetadata, ExecResponse> responses = // 
                compute.runScriptOnNodesMatching(// predicate used to select nodes
                inGroup(groupName), // what you actually intend to run
                exec(command), // use my local user &
                overrideLoginCredentials(login).runAsRoot(// don't attempt to run as root (sudo)
                false).wrapInInitScript(// run command directly
                false));
                for (Entry<? extends NodeMetadata, ExecResponse> response : responses.entrySet()) {
                    System.out.printf("<< node %s: %s%n", response.getKey().getId(), concat(response.getKey().getPrivateAddresses(), response.getKey().getPublicAddresses()));
                    System.out.printf("<<     %s%n", response.getValue());
                }
                break;
            case RUN:
                System.out.printf(">> running [%s] on group %s as %s%n", file, groupName, login.identity);
                // when running a sequence of commands, you probably want to have jclouds use the default behavior,
                // which is to fork a background process.
                responses = // 
                compute.runScriptOnNodesMatching(inGroup(groupName), // passing in a string with the contents of the file
                Files.toString(file, Charsets.UTF_8), overrideLoginCredentials(login).runAsRoot(false).nameTask(// ensuring task name isn't
                "_" + file.getName().replaceAll("\\..*", "")));
                for (Entry<? extends NodeMetadata, ExecResponse> response : responses.entrySet()) {
                    System.out.printf("<< node %s: %s%n", response.getKey().getId(), concat(response.getKey().getPrivateAddresses(), response.getKey().getPublicAddresses()));
                    System.out.printf("<<     %s%n", response.getValue());
                }
                break;
            case DESTROY:
                System.out.printf(">> destroying nodes in group %s%n", groupName);
                // you can use predicates to select which nodes you wish to destroy.
                Set<? extends NodeMetadata> destroyed = // 
                compute.destroyNodesMatching(Predicates.<NodeMetadata>and(not(TERMINATED), inGroup(groupName)));
                System.out.printf("<< destroyed nodes %s%n", destroyed);
                break;
        }
    } catch (RunNodesException e) {
        System.err.println("error adding node to group " + groupName + ": " + e.getMessage());
        error = 1;
    } catch (RunScriptOnNodesException e) {
        System.err.println("error executing " + command + " on group " + groupName + ": " + e.getMessage());
        error = 1;
    } catch (Exception e) {
        System.err.println("error: " + e.getMessage());
        error = 1;
    } finally {
        compute.getContext().close();
        System.exit(error);
    }
}
Also used : ExecResponse(org.jclouds.compute.domain.ExecResponse) Statement(org.jclouds.scriptbuilder.domain.Statement) TemplateBuilder(org.jclouds.compute.domain.TemplateBuilder) ComputeService(org.jclouds.compute.ComputeService) RunScriptOnNodesException(org.jclouds.compute.RunScriptOnNodesException) RunNodesException(org.jclouds.compute.RunNodesException) NodeMetadata(org.jclouds.compute.domain.NodeMetadata) LoginCredentials(org.jclouds.domain.LoginCredentials) Builder.overrideLoginCredentials(org.jclouds.compute.options.TemplateOptions.Builder.overrideLoginCredentials) RunNodesException(org.jclouds.compute.RunNodesException) File(java.io.File) RunScriptOnNodesException(org.jclouds.compute.RunScriptOnNodesException)

Example 9 with ExecResponse

use of org.jclouds.compute.domain.ExecResponse in project camel by apache.

the class JcloudsComputeProducer method runScriptOnNode.

/**
     * 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());
}
Also used : LoginCredentials(org.jclouds.domain.LoginCredentials) CamelExchangeException(org.apache.camel.CamelExchangeException) ExecResponse(org.jclouds.compute.domain.ExecResponse)

Example 10 with ExecResponse

use of org.jclouds.compute.domain.ExecResponse in project fabric8 by jboss-fuse.

the class JcloudsContainerProvider method start.

@Override
public void start(Container container) {
    assertValid();
    CreateContainerMetadata metadata = container.getMetadata();
    if (!(metadata instanceof CreateJCloudsContainerMetadata)) {
        throw new IllegalStateException("Container doesn't have valid create container metadata type");
    } else {
        CreateJCloudsContainerMetadata jCloudsContainerMetadata = (CreateJCloudsContainerMetadata) metadata;
        CreateJCloudsContainerOptions options = jCloudsContainerMetadata.getCreateOptions();
        ComputeService computeService = getOrCreateComputeService(options);
        try {
            String nodeId = jCloudsContainerMetadata.getNodeId();
            Optional<RunScriptOptions> runScriptOptions = ToRunScriptOptions.withComputeService(computeService).apply(jCloudsContainerMetadata);
            String script = buildStartScript(container.getId(), options);
            ExecResponse response;
            if (runScriptOptions.isPresent()) {
                response = computeService.runScriptOnNode(nodeId, script, runScriptOptions.get());
            } else {
                response = computeService.runScriptOnNode(nodeId, script);
            }
            if (response == null) {
                jCloudsContainerMetadata.setFailure(new Exception("No response received for fabric install script."));
            } else if (response.getOutput() != null && response.getOutput().contains(ContainerProviderUtils.FAILURE_PREFIX)) {
                jCloudsContainerMetadata.setFailure(new Exception(ContainerProviderUtils.parseScriptFailure(response.getOutput())));
            }
        } catch (Throwable t) {
            jCloudsContainerMetadata.setFailure(t);
        }
    }
}
Also used : RunScriptOptions(org.jclouds.compute.options.RunScriptOptions) ToRunScriptOptions(io.fabric8.service.jclouds.functions.ToRunScriptOptions) ExecResponse(org.jclouds.compute.domain.ExecResponse) CreateContainerMetadata(io.fabric8.api.CreateContainerMetadata) ComputeService(org.jclouds.compute.ComputeService) URISyntaxException(java.net.URISyntaxException) RunNodesException(org.jclouds.compute.RunNodesException) MalformedURLException(java.net.MalformedURLException)

Aggregations

ExecResponse (org.jclouds.compute.domain.ExecResponse)19 Test (org.junit.Test)8 Statement (org.jclouds.scriptbuilder.domain.Statement)7 RunScriptOptions (org.jclouds.compute.options.RunScriptOptions)6 IOException (java.io.IOException)5 Map (java.util.Map)4 Cluster (org.apache.whirr.Cluster)4 ComputeService (org.jclouds.compute.ComputeService)4 NodeMetadata (org.jclouds.compute.domain.NodeMetadata)4 LoginCredentials (org.jclouds.domain.LoginCredentials)4 ClusterSpec (org.apache.whirr.ClusterSpec)3 RunNodesException (org.jclouds.compute.RunNodesException)3 CreateContainerMetadata (io.fabric8.api.CreateContainerMetadata)2 ToRunScriptOptions (io.fabric8.service.jclouds.functions.ToRunScriptOptions)2 MalformedURLException (java.net.MalformedURLException)2 URISyntaxException (java.net.URISyntaxException)2 URL (java.net.URL)2 ExecutionException (java.util.concurrent.ExecutionException)2 Future (java.util.concurrent.Future)2 Instance (org.apache.whirr.Cluster.Instance)2