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

3
import hudson.CloseProofOutputStream;
K
kohsuke 已提交
4 5
import hudson.FilePath;
import hudson.Launcher;
6
import hudson.Launcher.LocalLauncher;
K
kohsuke 已提交
7
import hudson.Proc;
K
kohsuke 已提交
8
import hudson.Proc.RemoteProc;
K
kohsuke 已提交
9
import hudson.Util;
K
kohsuke 已提交
10
import hudson.model.Descriptor.FormException;
K
kohsuke 已提交
11 12
import hudson.remoting.Callable;
import hudson.remoting.Channel;
13
import hudson.remoting.Channel.Listener;
K
kohsuke 已提交
14 15 16
import hudson.remoting.RemoteInputStream;
import hudson.remoting.RemoteOutputStream;
import hudson.remoting.VirtualChannel;
17
import hudson.util.NullStream;
K
kohsuke 已提交
18 19
import hudson.util.StreamCopyThread;
import hudson.util.StreamTaskListener;
20 21
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
kohsuke 已提交
22

23 24
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
K
kohsuke 已提交
25
import java.io.File;
26 27
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
K
kohsuke 已提交
28 29 30
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
K
kohsuke 已提交
31
import java.io.Serializable;
32 33
import java.net.URL;
import java.net.URLConnection;
K
kohsuke 已提交
34 35 36
import java.util.logging.Level;
import java.util.logging.Logger;

K
kohsuke 已提交
37 38 39 40 41
/**
 * Information about a Hudson slave node.
 *
 * @author Kohsuke Kawaguchi
 */
K
kohsuke 已提交
42
public final class Slave implements Node, Serializable {
K
kohsuke 已提交
43
    /**
44
     * PluginName of this slave node.
K
kohsuke 已提交
45
     */
K
kohsuke 已提交
46
    protected final String name;
K
kohsuke 已提交
47 48 49 50 51 52 53 54

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

    /**
     * Path to the root of the workspace
K
kohsuke 已提交
55
     * from the view point of this node, such as "/hudson"
K
kohsuke 已提交
56
     */
K
kohsuke 已提交
57
    protected final String remoteFS;
K
kohsuke 已提交
58 59 60 61 62 63 64 65 66 67 68

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

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

K
kohsuke 已提交
69 70 71 72 73 74 75 76 77 78
    /**
     * Command line to launch the agent, like
     * "ssh myslave java -jar /path/to/hudson-remoting.jar"
     */
    private String agentCommand;

    /**
     * @stapler-constructor
     */
    public Slave(String name, String description, String command, String remoteFS, int numExecutors, Mode mode) throws FormException {
K
kohsuke 已提交
79 80 81 82
        this.name = name;
        this.description = description;
        this.numExecutors = numExecutors;
        this.mode = mode;
K
kohsuke 已提交
83 84
        this.agentCommand = command;
        this.remoteFS = remoteFS;
K
kohsuke 已提交
85

K
d'oh!  
kohsuke 已提交
86
        if (name.equals(""))
87
            throw new FormException("Invalid slave configuration. PluginName is empty", null);
K
kohsuke 已提交
88

89 90 91 92 93
        // 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 已提交
94 95
        if (remoteFS.equals(""))
            throw new FormException("Invalid slave configuration for " + name + ". No remote directory given", null);
K
kohsuke 已提交
96 97 98
    }

    public String getCommand() {
K
kohsuke 已提交
99
        return agentCommand;
K
kohsuke 已提交
100 101 102 103 104 105
    }

    public String getRemoteFS() {
        return remoteFS;
    }

K
kohsuke 已提交
106 107
    public String getNodeName() {
        return name;
K
kohsuke 已提交
108 109 110 111 112 113 114
    }

    public String getNodeDescription() {
        return description;
    }

    public FilePath getFilePath() {
K
kohsuke 已提交
115
        return new FilePath(getComputer().getChannel(),remoteFS);
K
kohsuke 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    }

    public int getNumExecutors() {
        return numExecutors;
    }

    public Mode getMode() {
        return mode;
    }

    /**
     * Estimates the clock difference with this slave.
     *
     * @return
     *      difference in milli-seconds.
K
kohsuke 已提交
131
     *      a positive value indicates that the master is ahead of the slave,
K
kohsuke 已提交
132 133 134
     *      and negative value indicates otherwise.
     */
    public long getClockDifference() throws IOException {
K
kohsuke 已提交
135 136
        VirtualChannel channel = getComputer().getChannel();
        if(channel==null)   return 0;   // can't check
K
kohsuke 已提交
137

K
kohsuke 已提交
138 139 140 141 142 143 144 145
        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 已提交
146

K
kohsuke 已提交
147 148 149 150
            return (startTime+endTime)/2 - slaveTime;
        } catch (InterruptedException e) {
            return 0;   // couldn't check
        }
K
kohsuke 已提交
151 152
    }

K
kohsuke 已提交
153

K
kohsuke 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    /**
     * 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 已提交
180 181 182 183
    public Computer createComputer() {
        return new ComputerImpl(this);
    }

184 185 186 187
    public FilePath getWorkspaceFor(TopLevelItem item) {
        return getWorkspaceRoot().child(item.getName());
    }

K
kohsuke 已提交
188 189 190 191 192 193
    /**
     * Root directory on this slave where all the job workspaces are laid out.
     */
    public FilePath getWorkspaceRoot() {
        return getFilePath().child("workspace");
    }
K
kohsuke 已提交
194

K
kohsuke 已提交
195 196
    public static final class ComputerImpl extends Computer {
        private volatile Channel channel;
K
kohsuke 已提交
197

K
kohsuke 已提交
198 199 200 201 202 203
        /**
         * This is where the log from the remote agent goes.
         */
        private File getLogFile() {
            return new File(Hudson.getInstance().getRootDir(),"slave-"+nodeName+".log");
        }
K
kohsuke 已提交
204

K
kohsuke 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        private ComputerImpl(Slave slave) {
            super(slave);
        }

        /**
         * Launches a remote agent.
         */
        private void launch(final Slave slave) {
            closeChannel();

            OutputStream os;
            try {
                os = new FileOutputStream(getLogFile());
            } catch (FileNotFoundException e) {
                logger.log(Level.SEVERE, "Failed to create log file "+getLogFile(),e);
                os = new NullStream();
K
kohsuke 已提交
221
            }
K
kohsuke 已提交
222 223 224 225 226 227 228 229 230 231 232
            final OutputStream launchLog = os;

            // 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);
K
kohsuke 已提交
233
                        final Process proc = Runtime.getRuntime().exec(slave.agentCommand);
K
kohsuke 已提交
234 235 236 237 238 239

                        // 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();

K
kohsuke 已提交
240 241
                        setChannel(proc.getInputStream(),proc.getOutputStream(),launchLog,new Listener() {
                            public void onClosed(Channel channel, IOException cause) {
K
kohsuke 已提交
242 243
                                if(cause!=null)
                                    cause.printStackTrace(listener.error("slave agent was terminated"));
K
kohsuke 已提交
244
                                proc.destroy();
K
kohsuke 已提交
245 246 247 248
                            }
                        });

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

K
kohsuke 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262
                    } 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 已提交
263

264 265
        private final Object channelLock = new Object();

K
kohsuke 已提交
266 267 268 269
        /**
         * Creates a {@link Channel} from the given stream and sets that to this slave.
         */
        public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Listener listener) throws IOException {
270
            synchronized(channelLock) {
K
kohsuke 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
                if(this.channel!=null)
                    throw new IllegalStateException("Already connected");

                channel = new Channel(nodeName,threadPoolForRemoting,
                    in,out, launchLog);
                channel.addListener(new Listener() {
                    public void onClosed(Channel c,IOException cause) {
                        ComputerImpl.this.channel = null;
                    }
                });
                channel.addListener(listener);
            }
            Hudson.getInstance().getQueue().scheduleMaintenance();
        }

K
kohsuke 已提交
286 287 288 289 290 291 292 293 294
        @Override
        public VirtualChannel getChannel() {
            return channel;
        }

        public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            if(channel!=null) {
                rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
K
kohsuke 已提交
295 296
            }

K
kohsuke 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
            launch((Slave) getNode());

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

318 319 320
        /**
         * Serves jar files for JNLP slave agents.
         */
321 322
        public JnlpJar getJnlpJars(String fileNamePlusJar) {
            return new JnlpJar(fileNamePlusJar.substring(0,fileNamePlusJar.length()-4)); // remove .jar
323 324
        }

K
kohsuke 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338
        @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 已提交
339
                }
K
kohsuke 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352
        }

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

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    /**
     * Web-bound object used to serve jar files for JNLP.
     */
    public static final class JnlpJar {
        private final String className;

        public JnlpJar(String className) {
            this.className = className;
        }

        public void doIndex( StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            // where is the jar file?
            // we can't use ServletContext.getResourcePaths() because
            // during debugging there's no WEB-INF/lib.
            URL classFile = getClass().getClassLoader().getResource(className.replace('.', '/') + ".class");
            if(classFile==null) {
                rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            String loc = classFile.toExternalForm().substring(4);// cut off jar:
            loc = loc.substring(0,loc.lastIndexOf('!'));


            URLConnection con = new URL(loc).openConnection();
            InputStream in = con.getInputStream();
            rsp.serveFile(req, in, con.getLastModified(), con.getContentLength(), "*.jar" );
            in.close();
        }

    }

K
kohsuke 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    public Launcher createLauncher(TaskListener listener) {
        return new Launcher(listener, getComputer().getChannel()) {
            public Proc launch(final String[] cmd, final String[] env, InputStream _in, OutputStream _out, FilePath _workDir) throws IOException {
                printCommandLine(cmd,_workDir);

                final OutputStream out = new RemoteOutputStream(new CloseProofOutputStream(_out));
                final InputStream  in  = _in==null ? null : new RemoteInputStream(_in);
                final String workDir = _workDir==null ? null : _workDir.getRemote();

                return new RemoteProc(getChannel().callAsync(new RemoteLaunchCallable(cmd, env, in, out, workDir)));
            }

            @Override
            public boolean isUnix() {
                // Windows can handle '/' as a path separator but Unix can't,
                // so err on Unix side
                return remoteFS.indexOf("\\")==-1;
K
kohsuke 已提交
402 403 404 405
            }
        };
    }

K
kohsuke 已提交
406 407 408 409 410
    /**
     * Gets th ecorresponding computer object.
     */
    public Computer getComputer() {
        return Hudson.getInstance().getComputer(getNodeName());
K
kohsuke 已提交
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    }

    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 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    /**
     * 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;
    }

//
// 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;

    private static class RemoteLaunchCallable implements Callable<Integer,IOException> {
        private final String[] cmd;
        private final String[] env;
        private final InputStream in;
        private final OutputStream out;
        private final String workDir;

        public RemoteLaunchCallable(String[] cmd, String[] env, InputStream in, OutputStream out, String workDir) {
            this.cmd = cmd;
            this.env = env;
            this.in = in;
            this.out = out;
            this.workDir = workDir;
        }

        public Integer call() throws IOException {
            Proc p = new LocalLauncher(TaskListener.NULL).launch(cmd, env, in, out,
                workDir ==null ? null : new FilePath(new File(workDir)));
            return p.join();
        }

        private static final long serialVersionUID = 1L;
    }
K
kohsuke 已提交
481
}