Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins plugin, how to execute system command on remote node?

Our company's Jenkins has master and two slave nodes. I am writing plugin for it. One of the things for plugin to do is to checkout some files from svn. This action cannot be extracted from plugin. To do this I execute console command "svn checkout" from java code of my plugin. The problem is that files from svn are checked out to master, rather than to slave nodes. How can I make files be checked out to slave?

like image 452
V. Artyukhov Avatar asked Nov 01 '12 12:11

V. Artyukhov


2 Answers

First you have these objects, usually received as parameters for perform method:

Launcher launcher;
AbstractBuild<?, ?> build;
BuildListener listener;

Then you have created and added arguments to an argumentListBuilder, maybe something like:

ArgumentListBuilder command = new ArgumentListBuilder();
command.addTokenized("xcopy /?");

Then, do something like:

ProcStarter ps = launcher.new ProcStarter();
ps = ps.cmds(command).stdout(listener);
ps = ps.pwd(build.getWorkspace()).envs(build.getEnvironment(listener));
Proc proc = launcher.launch(ps);
int retcode = proc.join();

ProcStarter will run the command at the node specified by the launcher instance. But please at least glance over the javadocs of all above classes before using, above is not direct copy-paste from working code.

like image 56
hyde Avatar answered Nov 14 '22 12:11

hyde


Here is code based on Hyde's answer, suitable for the Groovy script console (at /script)

def static Run(nodeName, runCommand)
{
    def output = new java.io.ByteArrayOutputStream();
    def listener = new hudson.util.StreamTaskListener(output);
    def node = hudson.model.Hudson.instance.getNode(nodeName);
    def launcher = node.createLauncher(listener);

    def command = new hudson.util.ArgumentListBuilder();
    command.addTokenized(runCommand);
    def ps = launcher.launch();
    ps = ps.cmds(command).stdout(listener);
    // ps = ps.pwd(build.getWorkspace()).envs(build.getEnvironment(listener));
    def proc = launcher.launch(ps);
    int retcode = proc.join();
    return [retcode, output.toString()]
}

// for (aSlave in hudson.model.Hudson.instance.slaves) {
(recode, output) = Run("build-slave9", "xcopy /?");
println output;

(Caveats: untested for programs that read stdin. Note the ByteArrayOutputStream, so don't run programs with very long output. Untested for non-ASCII output.)

like image 3
Kevin Smyth Avatar answered Nov 14 '22 10:11

Kevin Smyth