How can i send data to the logger from FileCallable back to master in a Jenkins plugin?

758 Views Asked by At

I'm using the following example from here:

 void someMethod(FilePath file) {
     // make 'file' a fresh empty directory.
     file.act(new Freshen());
 }
 // if 'file' is on a different node, this FileCallable will
 // be transferred to that node and executed there.
 private static final class Freshen implements FileCallable<Void> {
     private static final long serialVersionUID = 1;
     @Override public Void invoke(File f, VirtualChannel channel) {
         // f and file represent the same thing
         f.deleteContents();
         f.mkdirs();
         return null;
     }
 }

The Freshen class will be serialized and sent to a slave for execution. How can i get access and log progress to the logger on the master from inside my Freshen class?

2

There are 2 best solutions below

2
Sascha Vetter On

The Freshen class ... and sent to a slave for execution.

No, the execution will be on the slave and FilePath represents a file path on a specific slave or the master. (see documentation)

Try this code to pass the logger to Freshen (untested):

void someMethod(FilePath file, PrintStream logger) {
    // make 'file' a fresh empty directory.
    file.act(new Freshen(logger));
}
// if 'file' is on a different node, this FileCallable will
// be transferred to that node and executed there.
private static final class Freshen implements FileCallable<Void> {
    private static final long serialVersionUID = 1;

    private final PrintStream logger;

    public Freshen(PrintStream logger) {
        this.logger = logger;
    }

    @Override public Void invoke(File f, VirtualChannel channel) {
        // f and file represent the same thing
        logger.println("test");
        f.deleteContents();
        f.mkdirs();
        return null;
    }
}
1
Krassi On

I am a bit late to the party, but I just stumbled upon the same problem and solved it by passing the TaskListener to the FileCallable:

private static final class Freshen implements FileCallable<Void> {
    private static final long serialVersionUID = 1;

    private final TaskListener listener;

    public Freshen(TaskListener listener) {
        this.listener = listener;
    }

    @Override public Void invoke(File f, VirtualChannel channel) {
        RemoteOutputStream ros = new RemoteOutputStream(listener.getLogger());
        ros.write("hello there".getBytes(StandardCharsets.UTF_8));

        return null;
    }
}