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

import hudson.FilePath;
import hudson.Launcher;
5
import hudson.Launcher.RemoteLauncher;
K
kohsuke 已提交
6
import hudson.Util;
7 8
import hudson.tasks.DynamicLabeler;
import hudson.tasks.LabelFinder;
9 10
import hudson.maven.agent.Main;
import hudson.maven.agent.PluginManagerInterceptor;
K
kohsuke 已提交
11
import hudson.model.Descriptor.FormException;
K
kohsuke 已提交
12 13
import hudson.remoting.Callable;
import hudson.remoting.Channel;
14
import hudson.remoting.Channel.Listener;
K
kohsuke 已提交
15
import hudson.remoting.VirtualChannel;
16
import hudson.remoting.Which;
17
import hudson.util.NullStream;
18
import hudson.util.RingBufferLogHandler;
K
kohsuke 已提交
19 20
import hudson.util.StreamCopyThread;
import hudson.util.StreamTaskListener;
21 22
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
kohsuke 已提交
23

24 25
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
K
kohsuke 已提交
26
import java.io.File;
27 28
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
K
kohsuke 已提交
29 30 31
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
32
import java.io.PrintWriter;
33
import java.io.Serializable;
34 35
import java.net.URL;
import java.net.URLConnection;
36 37 38 39 40
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
K
kohsuke 已提交
41
import java.util.logging.Level;
K
kohsuke 已提交
42
import java.util.logging.LogRecord;
43
import java.util.logging.Logger;
K
kohsuke 已提交
44

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

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

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

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

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

K
kohsuke 已提交
77 78 79 80 81 82
    /**
     * Command line to launch the agent, like
     * "ssh myslave java -jar /path/to/hudson-remoting.jar"
     */
    private String agentCommand;

83 84 85 86 87 88 89 90 91 92
    /**
     * Whitespace-separated labels.
     */
    private String label="";

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

93 94 95
    private transient volatile Set<Label> dynamicLabels;
    private transient volatile int dynamicLabelsInstanceHash;

K
kohsuke 已提交
96 97 98
    /**
     * @stapler-constructor
     */
99
    public Slave(String name, String description, String command, String remoteFS, int numExecutors, Mode mode,
100
                 String label) throws FormException {
K
kohsuke 已提交
101 102 103 104
        this.name = name;
        this.description = description;
        this.numExecutors = numExecutors;
        this.mode = mode;
K
kohsuke 已提交
105 106
        this.agentCommand = command;
        this.remoteFS = remoteFS;
107 108
        this.label = Util.fixNull(label).trim();
        getAssignedLabels();    // compute labels now
K
kohsuke 已提交
109

K
d'oh!  
kohsuke 已提交
110
        if (name.equals(""))
K
kohsuke 已提交
111
            throw new FormException("Invalid slave configuration. Name is empty", null);
K
kohsuke 已提交
112

113 114 115 116 117
        // 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 已提交
118 119
        if (remoteFS.equals(""))
            throw new FormException("Invalid slave configuration for " + name + ". No remote directory given", null);
K
kohsuke 已提交
120 121 122
    }

    public String getCommand() {
K
kohsuke 已提交
123
        return agentCommand;
K
kohsuke 已提交
124 125 126 127 128 129
    }

    public String getRemoteFS() {
        return remoteFS;
    }

K
kohsuke 已提交
130 131
    public String getNodeName() {
        return name;
K
kohsuke 已提交
132 133 134 135 136 137
    }

    public String getNodeDescription() {
        return description;
    }

K
kohsuke 已提交
138
    /**
139
     * Gets the root directory of the Hudson workspace on this slave.
K
kohsuke 已提交
140
     */
K
kohsuke 已提交
141
    public FilePath getFilePath() {
K
kohsuke 已提交
142
        return new FilePath(getComputer().getChannel(),remoteFS);
K
kohsuke 已提交
143 144 145 146 147 148 149 150 151 152
    }

    public int getNumExecutors() {
        return numExecutors;
    }

    public Mode getMode() {
        return mode;
    }

153 154 155
    public String getLabelString() {
        return Util.fixNull(label).trim();
    }
156

157
    public Set<Label> getAssignedLabels() {
158 159
        // todo refactor to make dynamic labels a bit less hacky
        if(labels==null || isChangedDynamicLabels()) {
160 161 162 163 164 165 166 167
            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());
168
            r.addAll(getDynamicLabels());
169 170 171 172 173
            this.labels = Collections.unmodifiableSet(r);
        }
        return labels;
    }

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    /**
     * 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
     */
    public Set<Label> getDynamicLabels() {
        if (dynamicLabels == null) {
            synchronized (this) {
                if (dynamicLabels == null) {
                    dynamicLabels = 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)) {
                                dynamicLabels.add(Hudson.getInstance().getLabel(label));
                            }
                        }
                    } else {
                        dynamicLabelsInstanceHash = 0;
                    }
                }
            }
        }
        return dynamicLabels;
    }
220 221 222 223 224

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

K
kohsuke 已提交
225 226 227 228 229
    /**
     * Estimates the clock difference with this slave.
     *
     * @return
     *      difference in milli-seconds.
K
kohsuke 已提交
230
     *      a positive value indicates that the master is ahead of the slave,
K
kohsuke 已提交
231 232 233
     *      and negative value indicates otherwise.
     */
    public long getClockDifference() throws IOException {
K
kohsuke 已提交
234 235
        VirtualChannel channel = getComputer().getChannel();
        if(channel==null)   return 0;   // can't check
K
kohsuke 已提交
236

K
kohsuke 已提交
237 238 239 240 241 242 243 244
        try {
            long startTime = System.currentTimeMillis();
            long slaveTime = channel.call(new Callable<Long,RuntimeException>() {
                public Long call() {
                    return System.currentTimeMillis();
                }
            });
            long endTime = System.currentTimeMillis();
K
kohsuke 已提交
245

K
kohsuke 已提交
246 247 248 249
            return (startTime+endTime)/2 - slaveTime;
        } catch (InterruptedException e) {
            return 0;   // couldn't check
        }
K
kohsuke 已提交
250 251
    }

K
kohsuke 已提交
252

K
kohsuke 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    /**
     * Gets the clock difference in HTML string.
     */
    public String getClockDifferenceString() {
        try {
            long diff = getClockDifference();
            if(-1000<diff && diff <1000)
                return "In sync";  // clock is in sync

            long abs = Math.abs(diff);

            String s = Util.getTimeSpanString(abs);
            if(diff<0)
                s += " ahead";
            else
                s += " behind";

            if(abs>100*60) // more than a minute difference
                s = "<span class='error'>"+s+"</span>";

            return s;
        } catch (IOException e) {
            return "<span class='error'>Unable to check</span>";
        }
    }

K
kohsuke 已提交
279 280 281 282
    public Computer createComputer() {
        return new ComputerImpl(this);
    }

283 284 285 286
    public FilePath getWorkspaceFor(TopLevelItem item) {
        return getWorkspaceRoot().child(item.getName());
    }

K
kohsuke 已提交
287 288 289 290 291 292
    /**
     * Root directory on this slave where all the job workspaces are laid out.
     */
    public FilePath getWorkspaceRoot() {
        return getFilePath().child("workspace");
    }
K
kohsuke 已提交
293

K
kohsuke 已提交
294 295
    public static final class ComputerImpl extends Computer {
        private volatile Channel channel;
K
kohsuke 已提交
296

K
kohsuke 已提交
297 298 299 300 301 302
        /**
         * This is where the log from the remote agent goes.
         */
        private File getLogFile() {
            return new File(Hudson.getInstance().getRootDir(),"slave-"+nodeName+".log");
        }
K
kohsuke 已提交
303

K
kohsuke 已提交
304 305 306 307
        private ComputerImpl(Slave slave) {
            super(slave);
        }

308 309 310 311 312 313 314 315 316
        public Slave getNode() {
            return (Slave)super.getNode();
        }

        @Override
        public boolean isJnlpAgent() {
            return getNode().getCommand().length()==0;
        }

K
kohsuke 已提交
317 318 319 320 321 322
        /**
         * Launches a remote agent.
         */
        private void launch(final Slave slave) {
            closeChannel();

K
kohsuke 已提交
323
            final OutputStream launchLog = openLogFile();
K
kohsuke 已提交
324

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
            if(slave.agentCommand.length()>0) {
                // launch the slave agent asynchronously
                threadPoolForRemoting.execute(new Runnable() {
                    // TODO: do this only for nodes that are so configured.
                    // TODO: support passive connection via JNLP
                    public void run() {
                        final StreamTaskListener listener = new StreamTaskListener(launchLog);
                        try {
                            listener.getLogger().println("Launching slave agent");
                            listener.getLogger().println("$ "+slave.agentCommand);
                            final Process proc = Runtime.getRuntime().exec(slave.agentCommand);

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

                            setChannel(proc.getInputStream(),proc.getOutputStream(),launchLog,new Listener() {
                                public void onClosed(Channel channel, IOException cause) {
                                    if(cause!=null)
                                        cause.printStackTrace(listener.error("slave agent was terminated"));
                                    proc.destroy();
                                }
                            });

                            logger.info("slave agent launched for "+slave.getNodeName());

352 353
                        } catch (InterruptedException e) {
                            e.printStackTrace(listener.error("aborted"));
354 355 356 357 358 359 360 361 362 363
                        } catch (IOException e) {
                            Util.displayIOException(e,listener);

                            String msg = Util.getWin32ErrorMessage(e);
                            if(msg==null)   msg="";
                            else            msg=" : "+msg;
                            msg = "Unable to launch the slave agent for " + slave.getNodeName() + msg;
                            logger.log(Level.SEVERE,msg,e);
                            e.printStackTrace(listener.error(msg));
                        }
K
kohsuke 已提交
364
                    }
365 366
                });
            }
K
kohsuke 已提交
367
        }
K
kohsuke 已提交
368

K
kohsuke 已提交
369 370 371 372 373 374 375 376 377 378 379
        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;
        }

380 381
        private final Object channelLock = new Object();

K
kohsuke 已提交
382 383 384
        /**
         * Creates a {@link Channel} from the given stream and sets that to this slave.
         */
385
        public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Listener listener) throws IOException, InterruptedException {
386
            synchronized(channelLock) {
K
kohsuke 已提交
387 388 389
                if(this.channel!=null)
                    throw new IllegalStateException("Already connected");

390
                Channel channel = new Channel(nodeName,threadPoolForRemoting,
K
kohsuke 已提交
391 392 393 394 395 396 397
                    in,out, launchLog);
                channel.addListener(new Listener() {
                    public void onClosed(Channel c,IOException cause) {
                        ComputerImpl.this.channel = null;
                    }
                });
                channel.addListener(listener);
398 399 400 401 402 403

                {// send jars that we need for our operations
                    // TODO: maybe I should generalize this kind of "post initialization" processing
                    PrintWriter log = new PrintWriter(launchLog,true);
                    FilePath dst = new FilePath(channel,getNode().getRemoteFS());
                    new FilePath(Which.jarFile(Main.class)).copyTo(dst.child("maven-agent.jar"));
404
                    log.println("Copied maven-agent.jar");
405
                    new FilePath(Which.jarFile(PluginManagerInterceptor.class)).copyTo(dst.child("maven-interceptor.jar"));
406
                    log.println("Copied maven-interceptor.jar");
407 408
                }

K
kohsuke 已提交
409
                // install log handler
K
kohsuke 已提交
410
                channel.call(new LogInstaller());
K
kohsuke 已提交
411 412


413 414
                // prevent others from seeing a channel that's not properly initialized yet
                this.channel = channel;
K
kohsuke 已提交
415 416 417 418
            }
            Hudson.getInstance().getQueue().scheduleMaintenance();
        }

K
kohsuke 已提交
419 420 421 422 423
        @Override
        public VirtualChannel getChannel() {
            return channel;
        }

K
kohsuke 已提交
424 425 426 427 428 429 430 431 432 433 434
        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 已提交
435 436 437 438 439 440 441
        public void doDoDisconnect(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            if(!Hudson.adminCheck(req,rsp))
                return;
            closeChannel();
            rsp.sendRedirect(".");
        }

K
kohsuke 已提交
442 443 444 445
        public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            if(channel!=null) {
                rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
K
kohsuke 已提交
446 447
            }

K
kohsuke 已提交
448
            launch(getNode());
K
kohsuke 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

            // 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");
        }

        /**
         * 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);
        }

469 470 471
        /**
         * Serves jar files for JNLP slave agents.
         */
K
kohsuke 已提交
472 473
        public JnlpJar getJnlpJars(String fileName) {
            return new JnlpJar(fileName);
474 475
        }

K
kohsuke 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489
        @Override
        protected void kill() {
            super.kill();
            closeChannel();
        }

        private void closeChannel() {
            Channel c = channel;
            channel = null;
            if(c!=null)
                try {
                    c.close();
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "Failed to terminate channel to "+getDisplayName(),e);
K
kohsuke 已提交
490
                }
K
kohsuke 已提交
491 492 493 494 495 496 497 498 499 500 501 502 503
        }

        @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());
    }

504 505 506 507
    /**
     * Web-bound object used to serve jar files for JNLP.
     */
    public static final class JnlpJar {
K
kohsuke 已提交
508
        private final String fileName;
509

K
kohsuke 已提交
510 511
        public JnlpJar(String fileName) {
            this.fileName = fileName;
512 513 514
        }

        public void doIndex( StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
515 516 517 518
            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);
519 520
            }

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

    }

K
kohsuke 已提交
529
    public Launcher createLauncher(TaskListener listener) {
530
        // Windows absolute path always include ':', but this is not a valid char in Unix file systems.
531 532
        // Windows can handle '/' as a path separator but Unix can't,
        // so err on Unix side
533
        boolean isUnix = !remoteFS.contains(":") && !remoteFS.contains("\\");
534

535
        return new RemoteLauncher(listener, getComputer().getChannel(),isUnix);
K
kohsuke 已提交
536 537
    }

K
kohsuke 已提交
538 539 540 541 542
    /**
     * Gets th ecorresponding computer object.
     */
    public Computer getComputer() {
        return Hudson.getInstance().getComputer(getNodeName());
K
kohsuke 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
    }

    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 已提交
558 559 560 561 562 563 564 565 566 567 568 569
    /**
     * 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";
        }
        return this;
    }

K
kohsuke 已提交
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    /**
     * 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;
    }

K
kohsuke 已提交
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
//
// 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;
K
kohsuke 已提交
605
}