Slave.java 24.3 KB
Newer Older
K
kohsuke 已提交
1 2
package hudson.model;

K
kohsuke 已提交
3
import hudson.EnvVars;
K
kohsuke 已提交
4 5
import hudson.FilePath;
import hudson.Launcher;
6
import hudson.Launcher.RemoteLauncher;
K
kohsuke 已提交
7
import hudson.Util;
8 9
import hudson.slaves.SlaveStartMethod;
import hudson.slaves.SlaveAvailabilityStrategy;
10 11
import hudson.maven.agent.Main;
import hudson.maven.agent.PluginManagerInterceptor;
K
kohsuke 已提交
12
import hudson.model.Descriptor.FormException;
K
kohsuke 已提交
13 14
import hudson.remoting.Callable;
import hudson.remoting.Channel;
15
import hudson.remoting.Channel.Listener;
K
kohsuke 已提交
16
import hudson.remoting.VirtualChannel;
17
import hudson.remoting.Which;
18 19
import hudson.tasks.DynamicLabeler;
import hudson.tasks.LabelFinder;
K
kohsuke 已提交
20 21 22 23 24 25
import hudson.util.ClockDifference;
import hudson.util.NullStream;
import hudson.util.ProcessTreeKiller;
import hudson.util.RingBufferLogHandler;
import hudson.util.StreamCopyThread;
import hudson.util.StreamTaskListener;
26 27
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
28
import org.kohsuke.stapler.DataBoundConstructor;
K
kohsuke 已提交
29

30 31
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
K
kohsuke 已提交
32 33 34 35 36 37 38 39
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
40 41
import java.net.URL;
import java.net.URLConnection;
42
import java.util.*;
K
kohsuke 已提交
43
import java.util.logging.Level;
K
kohsuke 已提交
44
import java.util.logging.LogRecord;
45
import java.util.logging.Logger;
K
kohsuke 已提交
46

47 48
import net.sf.json.JSONObject;

K
kohsuke 已提交
49 50 51 52 53
/**
 * Information about a Hudson slave node.
 *
 * @author Kohsuke Kawaguchi
 */
K
kohsuke 已提交
54
public final class Slave implements Node, Serializable {
K
kohsuke 已提交
55
    /**
K
kohsuke 已提交
56
     * Name of this slave node.
K
kohsuke 已提交
57
     */
K
kohsuke 已提交
58
    protected final String name;
K
kohsuke 已提交
59 60 61 62 63 64 65 66

    /**
     * Description of this node.
     */
    private final String description;

    /**
     * Path to the root of the workspace
K
kohsuke 已提交
67
     * from the view point of this node, such as "/hudson"
K
kohsuke 已提交
68
     */
K
kohsuke 已提交
69
    protected final String remoteFS;
K
kohsuke 已提交
70 71 72 73 74 75 76 77 78 79 80

    /**
     * Number of executors of this node.
     */
    private int numExecutors = 2;

    /**
     * Job allocation strategy.
     */
    private Mode mode;

K
kohsuke 已提交
81
    /**
82 83 84 85 86 87
     * Slave availablility strategy.
     */
    private SlaveAvailabilityStrategy availabilityStrategy;

    /**
     * The starter that will startup this slave.
88
     */
89
    private SlaveStartMethod startMethod;
K
kohsuke 已提交
90

91 92 93 94 95 96 97 98 99 100
    /**
     * Whitespace-separated labels.
     */
    private String label="";

    /**
     * Lazily computed set of labels from {@link #label}.
     */
    private transient volatile Set<Label> labels;

101 102 103
    private transient volatile Set<Label> dynamicLabels;
    private transient volatile int dynamicLabelsInstanceHash;

K
kohsuke 已提交
104 105 106
    /**
     * @stapler-constructor
     */
107 108
    public Slave(String name, String description, String remoteFS, String numExecutors,
                 Mode mode, String label) throws FormException {
K
kohsuke 已提交
109 110
        this.name = name;
        this.description = description;
111
        this.numExecutors = Util.tryParseNumber(numExecutors, 1).intValue();
K
kohsuke 已提交
112
        this.mode = mode;
K
kohsuke 已提交
113
        this.remoteFS = remoteFS;
114 115
        this.label = Util.fixNull(label).trim();
        getAssignedLabels();    // compute labels now
K
kohsuke 已提交
116

K
d'oh!  
kohsuke 已提交
117
        if (name.equals(""))
K
i18n  
kohsuke 已提交
118
            throw new FormException(Messages.Slave_InvalidConfig_NoName(), null);
K
kohsuke 已提交
119

120 121 122 123 124
        // this prevents the config from being saved when slaves are offline.
        // on a large deployment with a lot of slaves, some slaves are bound to be offline,
        // so this check is harmful.
        //if (!localFS.exists())
        //    throw new FormException("Invalid slave configuration for " + name + ". No such directory exists: " + localFS, null);
K
kohsuke 已提交
125
        if (remoteFS.equals(""))
K
i18n  
kohsuke 已提交
126
            throw new FormException(Messages.Slave_InvalidConfig_NoRemoteDir(name), null);
127

128
        if (this.numExecutors<=0)
K
i18n  
kohsuke 已提交
129
            throw new FormException(Messages.Slave_InvalidConfig_Executors(name), null);
K
kohsuke 已提交
130 131
    }

132 133 134 135 136 137
    public SlaveStartMethod getStartMethod() {
        return startMethod == null ? new JNLPStartMethod() : startMethod;
    }

    public void setStartMethod(SlaveStartMethod startMethod) {
        this.startMethod = startMethod;
K
kohsuke 已提交
138 139 140 141 142 143
    }

    public String getRemoteFS() {
        return remoteFS;
    }

K
kohsuke 已提交
144 145
    public String getNodeName() {
        return name;
K
kohsuke 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159
    }

    public String getNodeDescription() {
        return description;
    }

    public int getNumExecutors() {
        return numExecutors;
    }

    public Mode getMode() {
        return mode;
    }

160 161 162 163 164 165 166 167
    public SlaveAvailabilityStrategy getAvailabilityStrategy() {
        return availabilityStrategy == null ? new SlaveAvailabilityStrategy.Always() : availabilityStrategy;
    }

    public void setAvailabilityStrategy(SlaveAvailabilityStrategy availabilityStrategy) {
        this.availabilityStrategy = availabilityStrategy;
    }

168 169 170
    public String getLabelString() {
        return Util.fixNull(label).trim();
    }
171

172
    public Set<Label> getAssignedLabels() {
173 174
        // todo refactor to make dynamic labels a bit less hacky
        if(labels==null || isChangedDynamicLabels()) {
175 176 177 178 179 180 181 182
            Set<Label> r = new HashSet<Label>();
            String ls = getLabelString();
            if(ls.length()>0) {
                for( String l : ls.split(" +")) {
                    r.add(Hudson.getInstance().getLabel(l));
                }
            }
            r.add(getSelfLabel());
183
            r.addAll(getDynamicLabels());
184 185 186 187 188
            this.labels = Collections.unmodifiableSet(r);
        }
        return labels;
    }

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    /**
     * Check if we should rebuild the list of dynamic labels.
     * @todo make less hacky
     * @return
     */
    private boolean isChangedDynamicLabels() {
        Computer comp = getComputer();
        if (comp == null) {
            return dynamicLabelsInstanceHash != 0;
        } else {
            if (dynamicLabelsInstanceHash == comp.hashCode()) {
                return false;
            }
            dynamicLabels = null; // force a re-calc
            return true;
        }
    }

    /**
     * Returns the possibly empty set of labels that it has been determined as supported by this node.
     *
     * @todo make less hacky
     * @see hudson.tasks.LabelFinder
212 213 214
     *
     * @return
     *      never null.
215 216
     */
    public Set<Label> getDynamicLabels() {
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        // another thread may preempt and set dynamicLabels field to null,
        // so a care needs to be taken to avoid race conditions under all circumstances.
        Set<Label> labels = dynamicLabels;
        if (labels != null)     return labels;

        synchronized (this) {
            labels = dynamicLabels;
            if (labels != null)     return labels;

            dynamicLabels = labels = new HashSet<Label>();
            Computer computer = getComputer();
            VirtualChannel channel;
            if (computer != null && (channel = computer.getChannel()) != null) {
                dynamicLabelsInstanceHash = computer.hashCode();
                for (DynamicLabeler labeler : LabelFinder.LABELERS) {
                    for (String label : labeler.findLabels(channel)) {
                        labels.add(Hudson.getInstance().getLabel(label));
234 235
                    }
                }
236 237
            } else {
                dynamicLabelsInstanceHash = 0;
238
            }
239 240

            return labels;
241 242
        }
    }
243 244 245 246 247

    public Label getSelfLabel() {
        return Hudson.getInstance().getLabel(name);
    }

248
    public ClockDifference getClockDifference() throws IOException, InterruptedException {
K
kohsuke 已提交
249
        VirtualChannel channel = getComputer().getChannel();
K
kohsuke 已提交
250 251
        if(channel==null)
            throw new IOException(getNodeName()+" is offline");
K
kohsuke 已提交
252

K
kohsuke 已提交
253 254 255 256 257 258 259
        long startTime = System.currentTimeMillis();
        long slaveTime = channel.call(new Callable<Long,RuntimeException>() {
            public Long call() {
                return System.currentTimeMillis();
            }
        });
        long endTime = System.currentTimeMillis();
K
kohsuke 已提交
260

261
        return new ClockDifference((startTime+endTime)/2 - slaveTime);
K
kohsuke 已提交
262 263
    }

K
kohsuke 已提交
264 265 266 267
    public Computer createComputer() {
        return new ComputerImpl(this);
    }

268
    public FilePath getWorkspaceFor(TopLevelItem item) {
K
kohsuke 已提交
269 270 271
        FilePath r = getWorkspaceRoot();
        if(r==null)     return null;    // offline
        return r.child(item.getName());
272 273
    }

K
kohsuke 已提交
274
    public FilePath getRootPath() {
275 276 277 278
        return createPath(remoteFS);
    }

    public FilePath createPath(String absolutePath) {
K
kohsuke 已提交
279 280
        VirtualChannel ch = getComputer().getChannel();
        if(ch==null)    return null;    // offline
281
        return new FilePath(ch,absolutePath);
K
kohsuke 已提交
282 283
    }

K
kohsuke 已提交
284 285
    /**
     * Root directory on this slave where all the job workspaces are laid out.
K
kohsuke 已提交
286 287
     * @return
     *      null if not connected.
K
kohsuke 已提交
288 289
     */
    public FilePath getWorkspaceRoot() {
K
kohsuke 已提交
290 291 292
        FilePath r = getRootPath();
        if(r==null) return null;
        return r.child("workspace");
K
kohsuke 已提交
293
    }
K
kohsuke 已提交
294

K
kohsuke 已提交
295 296
    public static final class ComputerImpl extends Computer {
        private volatile Channel channel;
297
        private Boolean isUnix;
298 299 300 301 302 303
        /**
         * Number of failed attempts to reconnect to this node
         * (so that if we keep failing to reconnect, we can stop
         * trying.)
         */
        private transient int numRetryAttempt;
K
kohsuke 已提交
304

K
kohsuke 已提交
305 306 307 308 309 310
        /**
         * This is where the log from the remote agent goes.
         */
        private File getLogFile() {
            return new File(Hudson.getInstance().getRootDir(),"slave-"+nodeName+".log");
        }
K
kohsuke 已提交
311

K
kohsuke 已提交
312 313 314 315
        private ComputerImpl(Slave slave) {
            super(slave);
        }

316 317 318 319 320
        public Slave getNode() {
            return (Slave)super.getNode();
        }

        @Override
321
        @Deprecated
322
        public boolean isJnlpAgent() {
323
            return getNode().getStartMethod() instanceof JNLPStartMethod;
324 325
        }

326
        @Override
327 328
        public boolean isLaunchSupported() {
            return getNode().getStartMethod().isLaunchSupported();
329 330
        }

K
kohsuke 已提交
331
        /**
332
         * Launches a remote agent asynchronously.
K
kohsuke 已提交
333 334 335
         */
        private void launch(final Slave slave) {
            closeChannel();
336 337 338 339 340 341 342
            Computer.threadPoolForRemoting.execute(new Runnable() {
                public void run() {
                    // do this on another thread so that the lengthy launch operation
                    // (which is typical) won't block UI thread.
                    slave.startMethod.launch(ComputerImpl.this, new StreamTaskListener(openLogFile()));
                }
            });
K
kohsuke 已提交
343
        }
K
kohsuke 已提交
344

K
kohsuke 已提交
345 346 347 348 349 350 351 352 353 354 355
        public OutputStream openLogFile() {
            OutputStream os;
            try {
                os = new FileOutputStream(getLogFile());
            } catch (FileNotFoundException e) {
                logger.log(Level.SEVERE, "Failed to create log file "+getLogFile(),e);
                os = new NullStream();
            }
            return os;
        }

356 357
        private final Object channelLock = new Object();

K
kohsuke 已提交
358 359 360
        /**
         * Creates a {@link Channel} from the given stream and sets that to this slave.
         */
361
        public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Listener listener) throws IOException, InterruptedException {
362
            synchronized(channelLock) {
K
kohsuke 已提交
363 364 365
                if(this.channel!=null)
                    throw new IllegalStateException("Already connected");

366
                Channel channel = new Channel(nodeName,threadPoolForRemoting, Channel.Mode.NEGOTIATE,
K
kohsuke 已提交
367 368 369 370 371 372 373
                    in,out, launchLog);
                channel.addListener(new Listener() {
                    public void onClosed(Channel c,IOException cause) {
                        ComputerImpl.this.channel = null;
                    }
                });
                channel.addListener(listener);
374

375 376
                PrintWriter log = new PrintWriter(launchLog,true);

377 378 379 380
                {// send jars that we need for our operations
                    // TODO: maybe I should generalize this kind of "post initialization" processing
                    FilePath dst = new FilePath(channel,getNode().getRemoteFS());
                    new FilePath(Which.jarFile(Main.class)).copyTo(dst.child("maven-agent.jar"));
381
                    log.println("Copied maven-agent.jar");
382
                    new FilePath(Which.jarFile(PluginManagerInterceptor.class)).copyTo(dst.child("maven-interceptor.jar"));
383
                    log.println("Copied maven-interceptor.jar");
384 385
                }

K
kohsuke 已提交
386
                isUnix = channel.call(new DetectOS());
K
i18n  
kohsuke 已提交
387
                log.println(isUnix?Messages.Slave_UnixSlave():Messages.Slave_WindowsSlave());
388

K
kohsuke 已提交
389
                // install log handler
K
kohsuke 已提交
390
                channel.call(new LogInstaller());
K
kohsuke 已提交
391

392
                numRetryAttempt = 0;
K
kohsuke 已提交
393

394 395
                // prevent others from seeing a channel that's not properly initialized yet
                this.channel = channel;
K
kohsuke 已提交
396 397 398 399
            }
            Hudson.getInstance().getQueue().scheduleMaintenance();
        }

K
kohsuke 已提交
400 401 402 403 404
        @Override
        public VirtualChannel getChannel() {
            return channel;
        }

K
kohsuke 已提交
405 406 407 408 409 410 411 412 413 414 415
        public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
            if(channel==null)
                return Collections.emptyList();
            else
                return channel.call(new Callable<List<LogRecord>,RuntimeException>() {
                    public List<LogRecord> call() {
                        return new ArrayList<LogRecord>(SLAVE_LOG_HANDLER.getView());
                    }
                });
        }

K
kohsuke 已提交
416
        public void doDoDisconnect(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
417
            Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
K
kohsuke 已提交
418 419 420 421
            closeChannel();
            rsp.sendRedirect(".");
        }

K
kohsuke 已提交
422 423 424 425
        public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            if(channel!=null) {
                rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
K
kohsuke 已提交
426 427
            }

428
            launch();
K
kohsuke 已提交
429 430 431 432 433 434

            // TODO: would be nice to redirect the user to "launching..." wait page,
            // then spend a few seconds there and poll for the completion periodically.
            rsp.sendRedirect("log");
        }

435 436 437 438 439 440 441 442 443
        public void tryReconnect() {
            numRetryAttempt++;
            if(numRetryAttempt<6 || (numRetryAttempt%12)==0) {
                // initially retry several times quickly, and after that, do it infrequently.
                logger.info("Attempting to reconnect "+nodeName);
                launch();
            }
        }

444 445 446 447 448
        public void launch() {
            if(channel==null)
                launch(getNode());
        }

K
kohsuke 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462
        /**
         * Gets the string representation of the slave log.
         */
        public String getLog() throws IOException {
            return Util.loadFile(getLogFile());
        }

        /**
         * Handles incremental log.
         */
        public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
            new LargeText(getLogFile(),false).doProgressText(req,rsp);
        }

463 464 465
        /**
         * Serves jar files for JNLP slave agents.
         */
K
kohsuke 已提交
466 467
        public JnlpJar getJnlpJars(String fileName) {
            return new JnlpJar(fileName);
468 469
        }

K
kohsuke 已提交
470 471 472 473 474 475
        @Override
        protected void kill() {
            super.kill();
            closeChannel();
        }

K
kohsuke 已提交
476 477 478
        /**
         * If still connected, disconnect.
         */
K
kohsuke 已提交
479 480 481
        private void closeChannel() {
            Channel c = channel;
            channel = null;
482
            isUnix=null;
K
kohsuke 已提交
483 484 485 486 487
            if(c!=null)
                try {
                    c.close();
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "Failed to terminate channel to "+getDisplayName(),e);
K
kohsuke 已提交
488
                }
K
kohsuke 已提交
489 490 491 492 493 494 495 496 497 498 499
        }

        @Override
        protected void setNode(Node node) {
            super.setNode(node);
            if(channel==null)
                // maybe the configuration was changed to relaunch the slave, so try it now.
                launch((Slave)node);
        }

        private static final Logger logger = Logger.getLogger(ComputerImpl.class.getName());
K
kohsuke 已提交
500 501 502 503 504 505

        private static final class DetectOS implements Callable<Boolean,IOException> {
            public Boolean call() throws IOException {
                return File.pathSeparatorChar==':';
            }
        }
K
kohsuke 已提交
506 507
    }

508 509 510 511
    /**
     * Web-bound object used to serve jar files for JNLP.
     */
    public static final class JnlpJar {
K
kohsuke 已提交
512
        private final String fileName;
513

K
kohsuke 已提交
514 515
        public JnlpJar(String fileName) {
            this.fileName = fileName;
516 517 518
        }

        public void doIndex( StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
519 520 521 522
            URL res = req.getServletContext().getResource("/WEB-INF/" + fileName);
            if(res==null) {
                // during the development this path doesn't have the files.
                res = new URL(new File(".").getAbsoluteFile().toURL(),"target/generated-resources/WEB-INF/"+fileName);
523 524
            }

K
kohsuke 已提交
525
            URLConnection con = res.openConnection();
526 527 528 529 530 531 532
            InputStream in = con.getInputStream();
            rsp.serveFile(req, in, con.getLastModified(), con.getContentLength(), "*.jar" );
            in.close();
        }

    }

K
kohsuke 已提交
533
    public Launcher createLauncher(TaskListener listener) {
534 535
        ComputerImpl c = getComputer();
        return new RemoteLauncher(listener, c.getChannel(), c.isUnix);
K
kohsuke 已提交
536 537
    }

K
kohsuke 已提交
538
    /**
539
     * Gets the corresponding computer object.
K
kohsuke 已提交
540
     */
541
    public ComputerImpl getComputer() {
542
        return (ComputerImpl)Hudson.getInstance().getComputer(this);
K
kohsuke 已提交
543 544
    }

545 546 547 548
    public Computer toComputer() {
        return getComputer();
    }

K
kohsuke 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final Slave that = (Slave) o;

        return name.equals(that.name);
    }

    public int hashCode() {
        return name.hashCode();
    }

K
kohsuke 已提交
562 563 564 565 566 567 568 569 570
    /**
     * Invoked by XStream when this object is read into memory.
     */
    private Object readResolve() {
        // convert the old format to the new one
        if(command!=null && agentCommand==null) {
            if(command.length()>0)  command += ' ';
            agentCommand = command+"java -jar ~/bin/slave.jar";
        }
571 572 573 574 575
        if (startMethod == null) {
            startMethod = (agentCommand == null || agentCommand.trim().length() == 0)
                    ? new JNLPStartMethod()
                    : new CommandStartMethod(agentCommand);
        }
K
kohsuke 已提交
576 577 578
        return this;
    }

K
kohsuke 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    /**
     * This field is used on each slave node to record log records on the slave.
     */
    private static final RingBufferLogHandler SLAVE_LOG_HANDLER = new RingBufferLogHandler();

    private static class LogInstaller implements Callable<Void,RuntimeException> {
        public Void call() {
            // avoid double installation of the handler
            Logger logger = Logger.getLogger("hudson");
            logger.removeHandler(SLAVE_LOG_HANDLER);
            logger.addHandler(SLAVE_LOG_HANDLER);
            return null;
        }
        private static final long serialVersionUID = 1L;
    }

595 596 597
    public static class JNLPStartMethod extends SlaveStartMethod {

        @Override
598
        public boolean isLaunchSupported() {
599 600 601
            return false;
        }

K
kohsuke 已提交
602
        public void launch(ComputerImpl computer, StreamTaskListener listener) {
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
            // do nothing as we cannot self start
        }

        //@DataBoundConstructor
        public JNLPStartMethod() {
        }

        public Descriptor<SlaveStartMethod> getDescriptor() {
            return DESCRIPTOR;
        }

        public static final Descriptor<SlaveStartMethod> DESCRIPTOR = new Descriptor<SlaveStartMethod>(JNLPStartMethod.class) {
            public String getDisplayName() {
                return "Launch slave agents via JNLP";
            }

            public SlaveStartMethod newInstance(StaplerRequest req, JSONObject formData) throws FormException {
                return new JNLPStartMethod();
            }
        };
    }

    public static class CommandStartMethod extends SlaveStartMethod {

        /**
         * Command line to launch the agent, like
         * "ssh myslave java -jar /path/to/hudson-remoting.jar"
         */
        private String agentCommand;

        @DataBoundConstructor
        public CommandStartMethod(String command) {
            this.agentCommand = command;
        }

        public String getCommand() {
            return agentCommand;
        }

        public Descriptor<SlaveStartMethod> getDescriptor() {
            return DESCRIPTOR;
        }

        public static final Descriptor<SlaveStartMethod> DESCRIPTOR = new Descriptor<SlaveStartMethod>(CommandStartMethod.class) {
            public String getDisplayName() {
                return "Launch slave via execution of command on the Master";
            }
        };

        /**
         * Gets the formatted current time stamp.
         */
        private static String getTimestamp() {
            return String.format("[%1$tD %1$tT]", new Date());
        }

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
        public void launch(ComputerImpl computer, final StreamTaskListener listener) {
            try {
                listener.getLogger().println(Messages.Slave_Launching(getTimestamp()));
                listener.getLogger().println("$ " + getCommand());

                ProcessBuilder pb = new ProcessBuilder(Util.tokenize(getCommand()));
                final EnvVars cookie = ProcessTreeKiller.createCookie();
                pb.environment().putAll(cookie);
                final Process proc = pb.start();

                // capture error information from stderr. this will terminate itself
                // when the process is killed.
                new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(),
                        proc.getErrorStream(), listener.getLogger()).start();

                computer.setChannel(proc.getInputStream(), proc.getOutputStream(), listener.getLogger(), new Listener() {
                    public void onClosed(Channel channel, IOException cause) {
                        if (cause != null) {
                            cause.printStackTrace(
                                listener.error(Messages.Slave_Terminated(getTimestamp())));
679
                        }
680
                        ProcessTreeKiller.get().kill(proc, cookie);
681
                    }
682 683 684 685 686 687 688 689 690 691 692 693 694
                });

                LOGGER.info("slave agent launched for " + computer.getDisplayName());
            } catch (InterruptedException e) {
                e.printStackTrace(listener.error("aborted"));
            } catch (IOException e) {
                Util.displayIOException(e, listener);

                String msg = Util.getWin32ErrorMessage(e);
                if (msg == null) {
                    msg = "";
                } else {
                    msg = " : " + msg;
695
                }
696 697 698 699
                msg = Messages.Slave_UnableToLaunch(computer.getDisplayName(), msg);
                LOGGER.log(Level.SEVERE, msg, e);
                e.printStackTrace(listener.error(msg));
            }
700
        }
701 702

        private static final Logger LOGGER = Logger.getLogger(CommandStartMethod.class.getName());
703 704
    }

K
kohsuke 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
//
// backwrad compatibility
//
    /**
     * In Hudson < 1.69 this was used to store the local file path
     * to the remote workspace. No longer in use.
     *
     * @deprecated
     *      ... but still in use during the transition.
     */
    private File localFS;

    /**
     * In Hudson < 1.69 this was used to store the command
     * to connect to the remote machine, like "ssh myslave".
     *
     * @deprecated
     */
    private transient String command;
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    /**
     * Command line to launch the agent, like
     * "ssh myslave java -jar /path/to/hudson-remoting.jar"
     */
    private transient String agentCommand;

    static {
        SlaveStartMethod.LIST.add(Slave.JNLPStartMethod.DESCRIPTOR);
        SlaveStartMethod.LIST.add(Slave.CommandStartMethod.DESCRIPTOR);
    }


//    static {
//        ConvertUtils.register(new Converter(){
//            public Object convert(Class type, Object value) {
//                if (value != null) {
//                System.out.println("CVT: " + type + " from (" + value.getClass() + ") " + value);
//                } else {
//                    System.out.println("CVT: " + type + " from " + value);
//                }
//                return null;  //To change body of implemented methods use File | Settings | File Templates.
//            }
//        }, SlaveStartMethod.class);
//    }
K
kohsuke 已提交
748
}