SlaveComputer.java 32.2 KB
Newer Older
K
kohsuke 已提交
1 2
/*
 * The MIT License
3
 *
K
kohsuke 已提交
4
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
5
 *
K
kohsuke 已提交
6 7 8 9 10 11
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
12
 *
K
kohsuke 已提交
13 14
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
15
 *
K
kohsuke 已提交
16 17 18 19 20 21 22 23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
24 25
package hudson.slaves;

26 27
import edu.umd.cs.findbugs.annotations.OverrideMustInvoke;
import edu.umd.cs.findbugs.annotations.When;
K
Kohsuke Kawaguchi 已提交
28
import hudson.AbortException;
29
import hudson.FilePath;
K
kohsuke 已提交
30
import hudson.Util;
31
import hudson.console.ConsoleLogFilter;
K
Kohsuke Kawaguchi 已提交
32 33 34 35 36 37 38 39 40
import hudson.model.Computer;
import hudson.model.Executor;
import hudson.model.ExecutorListener;
import hudson.model.Node;
import hudson.model.Queue;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.User;
import hudson.remoting.Channel;
41
import hudson.remoting.ChannelBuilder;
42
import hudson.remoting.Launcher;
K
Kohsuke Kawaguchi 已提交
43
import hudson.remoting.VirtualChannel;
44
import hudson.security.ACL;
45
import hudson.slaves.OfflineCause.ChannelTermination;
K
Kohsuke Kawaguchi 已提交
46
import hudson.util.Futures;
47
import hudson.util.IOUtils;
K
Kohsuke Kawaguchi 已提交
48 49 50
import hudson.util.NullStream;
import hudson.util.RingBufferLogHandler;
import hudson.util.StreamTaskListener;
51
import hudson.util.io.ReopenableFileOutputStream;
K
Kohsuke Kawaguchi 已提交
52
import hudson.util.io.ReopenableRotatingFileOutputStream;
53 54 55
import jenkins.model.Jenkins;
import jenkins.security.ChannelConfigurator;
import jenkins.security.MasterToSlaveCallable;
56
import jenkins.slaves.EncryptedSlaveAgentJnlpFile;
57
import jenkins.slaves.JnlpSlaveAgentProtocol;
58
import jenkins.slaves.systemInfo.SlaveSystemInfo;
59 60
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
61 62 63 64 65
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
Kohsuke Kawaguchi 已提交
66
import org.kohsuke.stapler.WebMethod;
K
Kohsuke Kawaguchi 已提交
67
import org.kohsuke.stapler.interceptor.RequirePOST;
68

69
import javax.annotation.CheckForNull;
K
Kohsuke Kawaguchi 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

87
import static hudson.slaves.SlaveComputer.LogHolder.SLAVE_LOG_HANDLER;
K
Kohsuke Kawaguchi 已提交
88

89

90 91 92 93 94
/**
 * {@link Computer} for {@link Slave}s.
 *
 * @author Kohsuke Kawaguchi
 */
K
kohsuke 已提交
95
public class SlaveComputer extends Computer {
96 97 98 99
    private volatile Channel channel;
    private volatile transient boolean acceptingTasks = true;
    private Charset defaultCharset;
    private Boolean isUnix;
K
kohsuke 已提交
100 101
    /**
     * Effective {@link ComputerLauncher} that hides the details of
102
     * how we launch a agent agent on this computer.
K
kohsuke 已提交
103 104 105
     *
     * <p>
     * This is normally the same as {@link Slave#getLauncher()} but
106
     * can be different. See {@link #grabLauncher(Node)}.
K
kohsuke 已提交
107
     */
108 109
    private ComputerLauncher launcher;

110 111 112 113 114 115 116 117 118 119 120
    /**
     * Perpetually writable log file.
     */
    private final ReopenableFileOutputStream log;

    /**
     * {@link StreamTaskListener} that wraps {@link #log}, hence perpetually writable.
     */
    private final TaskListener taskListener;


121 122 123 124 125 126 127
    /**
     * 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 已提交
128 129 130 131 132 133 134 135
    /**
     * Tracks the status of the last launch operation, which is always asynchronous.
     * This can be used to wait for the completion, or cancel the launch activity.
     */
    private volatile Future<?> lastConnectActivity = null;

    private Object constructed = new Object();

136 137
    private transient volatile String absoluteRemoteFs;

K
kohsuke 已提交
138 139
    public SlaveComputer(Slave slave) {
        super(slave);
140
        this.log = new ReopenableRotatingFileOutputStream(getLogFile(),10);
141
        this.taskListener = new StreamTaskListener(decorate(this.log));
142
        assert slave.getNumExecutors()!=0 : "Computer created with 0 executors";
K
kohsuke 已提交
143
    }
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158
    /**
     * Uses {@link ConsoleLogFilter} to decorate logger.
     */
    private OutputStream decorate(OutputStream os) {
        for (ConsoleLogFilter f : ConsoleLogFilter.all()) {
            try {
                os = f.decorateLogger(this,os);
            } catch (IOException|InterruptedException e) {
                LOGGER.log(Level.WARNING, "Failed to filter log with "+f, e);
            }
        }
        return os;
    }

159 160 161 162
    /**
     * {@inheritDoc}
     */
    @Override
163
    @OverrideMustInvoke(When.ANYTIME)
164
    public boolean isAcceptingTasks() {
165
        // our boolean flag is an override on any additional programmatic reasons why this agent might not be
166 167
        // accepting tasks.
        return acceptingTasks && super.isAcceptingTasks();
168 169
    }

K
Kohsuke Kawaguchi 已提交
170 171 172
    /**
     * @since 1.498
     */
173 174 175 176
    public String getJnlpMac() {
        return JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(getName());
    }

177
    /**
178
     * Allows suspension of tasks being accepted by the agent computer. While this could be called by a
179 180 181 182
     * {@linkplain hudson.slaves.ComputerLauncher} or a {@linkplain hudson.slaves.RetentionStrategy}, such usage
     * can result in fights between multiple actors calling setting differential values. A better approach
     * is to override {@link hudson.slaves.RetentionStrategy#isAcceptingTasks(hudson.model.Computer)} if the
     * {@link hudson.slaves.RetentionStrategy} needs to control availability.
183
     *
184
     * @param acceptingTasks {@code true} if the agent can accept tasks.
185 186 187 188 189
     */
    public void setAcceptingTasks(boolean acceptingTasks) {
        this.acceptingTasks = acceptingTasks;
    }

190
    @Override
191 192 193 194
    public Boolean isUnix() {
        return isUnix;
    }

195
    @CheckForNull
196
    @Override
197
    public Slave getNode() {
J
Jesse Glick 已提交
198 199 200 201 202 203 204
        Node node = super.getNode();
        if (node == null || node instanceof Slave) {
            return (Slave)node;
        } else {
            logger.log(Level.WARNING, "found an unexpected kind of node {0} from {1} with nodeName={2}", new Object[] {node, this, nodeName});
            return null;
        }
205 206
    }

K
kohsuke 已提交
207 208 209 210 211 212 213 214
    @Override
    public String getIcon() {
        Future<?> l = lastConnectActivity;
        if(l!=null && !l.isDone())
            return "computer-flash.gif";
        return super.getIcon();
    }

M
mindless 已提交
215 216 217 218
    /**
     * @deprecated since 2008-05-20.
     */
    @Deprecated @Override
219 220 221 222 223 224 225 226 227 228 229 230 231
    public boolean isJnlpAgent() {
        return launcher instanceof JNLPLauncher;
    }

    @Override
    public boolean isLaunchSupported() {
        return launcher.isLaunchSupported();
    }

    public ComputerLauncher getLauncher() {
        return launcher;
    }

232
    protected Future<?> _connect(boolean forceReconnect) {
K
kohsuke 已提交
233
        if(channel!=null)   return Futures.precomputed(null);
234
        if(!forceReconnect && isConnecting())
K
kohsuke 已提交
235
            return lastConnectActivity;
236
        if(forceReconnect && isConnecting())
K
kohsuke 已提交
237
            logger.fine("Forcing a reconnect on "+getName());
238 239

        closeChannel();
K
kohsuke 已提交
240 241
        return lastConnectActivity = Computer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<Object>() {
            public Object call() throws Exception {
242 243
                // do this on another thread so that the lengthy launch operation
                // (which is typical) won't block UI thread.
K
Kohsuke Kawaguchi 已提交
244 245 246

                ACL.impersonate(ACL.SYSTEM);    // background activity should run like a super user

K
kohsuke 已提交
247
                try {
248
                    log.rewind();
249
                    try {
T
Tom Rini 已提交
250
                        for (ComputerListener cl : ComputerListener.all())
251
                            cl.preLaunch(SlaveComputer.this, taskListener);
252
                        offlineCause = null;
253
                        launcher.launch(SlaveComputer.this, taskListener);
254
                    } catch (AbortException e) {
255
                        taskListener.error(e.getMessage());
256 257
                        throw e;
                    } catch (IOException e) {
258 259
                        Util.displayIOException(e,taskListener);
                        e.printStackTrace(taskListener.error(Messages.ComputerLauncher_unexpectedError()));
260 261
                        throw e;
                    } catch (InterruptedException e) {
262
                        e.printStackTrace(taskListener.error(Messages.ComputerLauncher_abortedLaunch()));
263
                        throw e;
264 265 266
                    } catch (Exception e) {
                        e.printStackTrace(taskListener.error(Messages.ComputerLauncher_unexpectedError()));
                        throw e;
267
                    }
268
                } finally {
269
                    if (channel==null && offlineCause == null) {
270
                        offlineCause = new OfflineCause.LaunchFailed();
271 272 273
                        for (ComputerListener cl : ComputerListener.all())
                            cl.onLaunchFailure(SlaveComputer.this, taskListener);
                    }
K
kohsuke 已提交
274
                }
275 276

                if (channel==null)
277
                    throw new IOException("Agent failed to connect, even though the launcher didn't report it. See the log output for details.");
278
                return null;
279 280 281 282 283 284 285 286 287 288 289 290 291
            }
        });
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void taskAccepted(Executor executor, Queue.Task task) {
        super.taskAccepted(executor, task);
        if (launcher instanceof ExecutorListener) {
            ((ExecutorListener)launcher).taskAccepted(executor, task);
        }
292

293 294 295 296
        //getNode() can return null at indeterminate times when nodes go offline
        Slave node = getNode();
        if (node != null && node.getRetentionStrategy() instanceof ExecutorListener) {
            ((ExecutorListener)node.getRetentionStrategy()).taskAccepted(executor, task);
297 298 299 300 301 302 303 304 305 306 307 308
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void taskCompleted(Executor executor, Queue.Task task, long durationMS) {
        super.taskCompleted(executor, task, durationMS);
        if (launcher instanceof ExecutorListener) {
            ((ExecutorListener)launcher).taskCompleted(executor, task, durationMS);
        }
309
        RetentionStrategy r = getRetentionStrategy();
K
kohsuke 已提交
310 311
        if (r instanceof ExecutorListener) {
            ((ExecutorListener) r).taskCompleted(executor, task, durationMS);
312 313 314 315 316 317 318 319 320 321 322 323
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) {
        super.taskCompletedWithProblems(executor, task, durationMS, problems);
        if (launcher instanceof ExecutorListener) {
            ((ExecutorListener)launcher).taskCompletedWithProblems(executor, task, durationMS, problems);
        }
324 325 326
        RetentionStrategy r = getRetentionStrategy();
        if (r instanceof ExecutorListener) {
            ((ExecutorListener) r).taskCompletedWithProblems(executor, task, durationMS, problems);
327 328 329
        }
    }

K
kohsuke 已提交
330 331 332 333 334 335
    @Override
    public boolean isConnecting() {
        Future<?> l = lastConnectActivity;
        return isOffline() && l!=null && !l.isDone();
    }

336 337
    public OutputStream openLogFile() {
        try {
338 339 340
            log.rewind();
            return log;
        } catch (IOException e) {
341
            logger.log(Level.SEVERE, "Failed to create log file "+getLogFile(),e);
342
            return new NullStream();
343 344 345 346 347
        }
    }

    private final Object channelLock = new Object();

K
kohsuke 已提交
348 349 350 351
    public void setChannel(InputStream in, OutputStream out, TaskListener taskListener, Channel.Listener listener) throws IOException, InterruptedException {
        setChannel(in,out,taskListener.getLogger(),listener);
    }

352
    /**
353
     * Creates a {@link Channel} from the given stream and sets that to this agent.
K
kohsuke 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366
     *
     * @param in
     *      Stream connected to the remote "slave.jar". It's the caller's responsibility to do
     *      buffering on this stream, if that's necessary.
     * @param out
     *      Stream connected to the remote peer. It's the caller's responsibility to do
     *      buffering on this stream, if that's necessary.
     * @param launchLog
     *      If non-null, receive the portion of data in <tt>is</tt> before
     *      the data goes into the "binary mode". This is useful
     *      when the established communication channel might include some data that might
     *      be useful for debugging/trouble-shooting.
     * @param listener
367
     *      Gets a notification when the channel closes, to perform clean up. Can be null.
368 369
     *      By the time this method is called, the cause of the termination is reported to the user,
     *      so the implementation of the listener doesn't need to do that again.
370 371
     */
    public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException {
K
Kohsuke Kawaguchi 已提交
372 373 374 375
        ChannelBuilder cb = new ChannelBuilder(nodeName,threadPoolForRemoting)
            .withMode(Channel.Mode.NEGOTIATE)
            .withHeaderStream(launchLog);

376 377
        for (ChannelConfigurator cc : ChannelConfigurator.all()) {
            cc.onChannelBuilding(cb,this);
K
Kohsuke Kawaguchi 已提交
378 379 380
        }

        Channel channel = cb.build(in,out);
381 382 383
        setChannel(channel,launchLog,listener);
    }

J
Jesse Glick 已提交
384 385 386 387 388 389 390 391
    /**
     * Shows {@link Channel#classLoadingCount}.
     * @since 1.495
     */
    public int getClassLoadingCount() throws IOException, InterruptedException {
        return channel.call(new LoadingCount(false));
    }

392 393 394
    /**
     * Shows {@link Channel#classLoadingPrefetchCacheCount}.
     * @return -1 in case that capability is not supported
J
Jesse Glick 已提交
395
     * @since 1.519
396 397 398 399 400 401 402 403
     */
    public int getClassLoadingPrefetchCacheCount() throws IOException, InterruptedException {
        if (!channel.remoteCapability.supportsPrefetch()) {
            return -1;
        }
        return channel.call(new LoadingPrefetchCacheCount());
    }

J
Jesse Glick 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    /**
     * Shows {@link Channel#resourceLoadingCount}.
     * @since 1.495
     */
    public int getResourceLoadingCount() throws IOException, InterruptedException {
        return channel.call(new LoadingCount(true));
    }

    /**
     * Shows {@link Channel#classLoadingTime}.
     * @since 1.495
     */
    public long getClassLoadingTime() throws IOException, InterruptedException {
        return channel.call(new LoadingTime(false));
    }

    /**
     * Shows {@link Channel#resourceLoadingTime}.
     * @since 1.495
     */
    public long getResourceLoadingTime() throws IOException, InterruptedException {
        return channel.call(new LoadingTime(true));
    }

428
    /**
429
     * Returns the remote FS root absolute path or {@code null} if the agent is off-line. The absolute path may change
430 431 432
     * between connections if the connection method does not provide a consistent working directory and the node's
     * remote FS is specified as a relative path.
     *
433
     * @return the remote FS root absolute path or {@code null} if the agent is off-line.
434
     * @since 1.606
435
     */
436 437 438 439 440
    @CheckForNull
    public String getAbsoluteRemoteFs() {
        return channel == null ? null : absoluteRemoteFs;
    }

441
    static class LoadingCount extends MasterToSlaveCallable<Integer,RuntimeException> {
J
Jesse Glick 已提交
442 443 444 445 446 447 448 449 450 451
        private final boolean resource;
        LoadingCount(boolean resource) {
            this.resource = resource;
        }
        @Override public Integer call() {
            Channel c = Channel.current();
            return resource ? c.resourceLoadingCount.get() : c.classLoadingCount.get();
        }
    }

452
    static class LoadingPrefetchCacheCount extends MasterToSlaveCallable<Integer,RuntimeException> {
453 454 455 456 457
        @Override public Integer call() {
            return Channel.current().classLoadingPrefetchCacheCount.get();
        }
    }

458
    static class LoadingTime extends MasterToSlaveCallable<Long,RuntimeException> {
J
Jesse Glick 已提交
459 460 461 462 463 464 465 466 467 468
        private final boolean resource;
        LoadingTime(boolean resource) {
            this.resource = resource;
        }
        @Override public Long call() {
            Channel c = Channel.current();
            return resource ? c.resourceLoadingTime.get() : c.classLoadingTime.get();
        }
    }

469
    /**
470
     * Sets up the connection through an existing channel.
J
Jesse Glick 已提交
471
     * @param channel the channel to use; <strong>warning:</strong> callers are expected to have called {@link ChannelConfigurator} already
472 473 474
     * @since 1.444
     */
    public void setChannel(Channel channel, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException {
475 476 477
        if(this.channel!=null)
            throw new IllegalStateException("Already connected");

478 479
        final TaskListener taskListener = new StreamTaskListener(launchLog);
        PrintStream log = taskListener.getLogger();
480

481 482
        channel.setProperty(SlaveComputer.class, this);

483
        channel.addListener(new Channel.Listener() {
484
            @Override
485 486
            public void onClosed(Channel c, IOException cause) {
                // Orderly shutdown will have null exception
487 488
                if (cause!=null) {
                    offlineCause = new ChannelTermination(cause);
489
                    cause.printStackTrace(taskListener.error("Connection terminated"));
490 491 492
                } else {
                    taskListener.getLogger().println("Connection terminated");
                }
493
                closeChannel();
494 495 496 497 498 499
                try {
                    launcher.afterDisconnect(SlaveComputer.this, taskListener);
                } catch (Throwable t) {
                    LogRecord lr = new LogRecord(Level.SEVERE,
                            "Launcher {0}'s afterDisconnect method propagated an exception when {1}'s connection was closed: {2}");
                    lr.setThrown(t);
500
                    lr.setParameters(new Object[]{launcher, SlaveComputer.this.getName(), t.getMessage()});
501 502
                    logger.log(lr);
                }
503 504
            }
        });
505 506
        if(listener!=null)
            channel.addListener(listener);
507

508 509 510
        String slaveVersion = channel.call(new SlaveVersion());
        log.println("Slave.jar version: " + slaveVersion);

511 512 513 514 515
        boolean _isUnix = channel.call(new DetectOS());
        log.println(_isUnix? hudson.model.Messages.Slave_UnixSlave():hudson.model.Messages.Slave_WindowsSlave());

        String defaultCharsetName = channel.call(new DetectDefaultCharset());

516 517 518 519
        Slave node = getNode();
        if (node == null) { // Node has been disabled/removed during the connection
            throw new IOException("Node "+nodeName+" has been deleted during the channel setup");
        }
520

521 522 523 524
        String remoteFS = node.getRemoteFS();
        if (Util.isRelativePath(remoteFS)) {
            remoteFS = channel.call(new AbsolutePath(remoteFS));
            log.println("NOTE: Relative remote path resolved to: "+remoteFS);
525
        }
526 527 528 529
        if(_isUnix && !remoteFS.contains("/") && remoteFS.contains("\\"))
            log.println("WARNING: "+remoteFS
                    +" looks suspiciously like Windows path. Maybe you meant "+remoteFS.replace('\\','/')+"?");
        FilePath root = new FilePath(channel,remoteFS);
530

K
Kohsuke Kawaguchi 已提交
531 532 533 534 535
        // reference counting problem is known to happen, such as JENKINS-9017, and so as a preventive measure
        // we pin the base classloader so that it'll never get GCed. When this classloader gets released,
        // it'll have a catastrophic impact on the communication.
        channel.pinClassLoader(getClass().getClassLoader());

536
        channel.call(new SlaveInitializer());
537 538 539 540 541 542 543 544
        SecurityContext old = ACL.impersonate(ACL.SYSTEM);
        try {
            for (ComputerListener cl : ComputerListener.all()) {
                cl.preOnline(this,channel,root,taskListener);
            }
        } finally {
            SecurityContextHolder.setContext(old);
        }
545

546 547
        offlineCause = null;

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
        // update the data structure atomically to prevent others from seeing a channel that's not properly initialized yet
        synchronized(channelLock) {
            if(this.channel!=null) {
                // check again. we used to have this entire method in a big sycnhronization block,
                // but Channel constructor blocks for an external process to do the connection
                // if CommandLauncher is used, and that cannot be interrupted because it blocks at InputStream.
                // so if the process hangs, it hangs the thread in a lock, and since Hudson will try to relaunch,
                // we'll end up queuing the lot of threads in a pseudo deadlock.
                // This implementation prevents that by avoiding a lock. HUDSON-1705 is likely a manifestation of this.
                channel.close();
                throw new IllegalStateException("Already connected");
            }
            isUnix = _isUnix;
            numRetryAttempt = 0;
            this.channel = channel;
563
            this.absoluteRemoteFs = remoteFS;
564
            defaultCharset = Charset.forName(defaultCharsetName);
565 566 567 568

            synchronized (statusChangeLock) {
                statusChangeLock.notifyAll();
            }
569
        }
570 571 572 573 574 575 576 577
        old = ACL.impersonate(ACL.SYSTEM);
        try {
            for (ComputerListener cl : ComputerListener.all()) {
                cl.onOnline(this,taskListener);
            }
        } finally {
            SecurityContextHolder.setContext(old);
        }
578
        log.println("Agent successfully connected and online");
579
        Jenkins.getInstance().getQueue().scheduleMaintenance();
580 581 582
    }

    @Override
583
    public Channel getChannel() {
584 585 586 587 588 589 590 591 592 593 594
        return channel;
    }

    public Charset getDefaultCharset() {
        return defaultCharset;
    }

    public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
        if(channel==null)
            return Collections.emptyList();
        else
595
            return channel.call(new SlaveLogFetcher());
596 597
    }

598
    @RequirePOST
599 600 601
    public HttpResponse doDoDisconnect(@QueryParameter String offlineMessage) throws IOException, ServletException {
        if (channel!=null) {
            //does nothing in case computer is already disconnected
602
            checkPermission(DISCONNECT);
603
            offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
604
            disconnect(new OfflineCause.UserCause(User.current(), offlineMessage));
605 606
        }
        return new HttpRedirect(".");
607 608 609
    }

    @Override
610 611
    public Future<?> disconnect(OfflineCause cause) {
        super.disconnect(cause);
K
kohsuke 已提交
612
        return Computer.threadPoolForRemoting.submit(new Runnable() {
613 614 615
            public void run() {
                // do this on another thread so that any lengthy disconnect operation
                // (which could be typical) won't block UI thread.
616 617 618
                launcher.beforeDisconnect(SlaveComputer.this, taskListener);
                closeChannel();
                launcher.afterDisconnect(SlaveComputer.this, taskListener);
619 620 621 622
            }
        });
    }

623
    @RequirePOST
624 625
    public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        if(channel!=null) {
626
            req.getView(this,"already-launched.jelly").forward(req, rsp);
627 628 629
            return;
        }

K
kohsuke 已提交
630
        connect(true);
631 632 633 634 635 636 637 638 639 640 641

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

    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);
K
kohsuke 已提交
642
            connect(true);
643 644 645 646
        }
    }

    /**
647
     * Serves jar files for JNLP agents.
648
     *
M
mindless 已提交
649
     * @deprecated since 2008-08-18.
650
     *      This URL binding is no longer used and moved up directly under to {@link jenkins.model.Jenkins},
651
     *      but it's left here for now just in case some old JNLP agents request it.
652
     */
653
    @Deprecated
654 655 656 657
    public Slave.JnlpJar getJnlpJars(String fileName) {
        return new Slave.JnlpJar(fileName);
    }

K
Kohsuke Kawaguchi 已提交
658
    @WebMethod(name="slave-agent.jnlp")
659 660
    public HttpResponse doSlaveAgentJnlp(StaplerRequest req, StaplerResponse res) throws IOException, ServletException {
        return new EncryptedSlaveAgentJnlpFile(this, "slave-agent.jnlp.jelly", getName(), CONNECT);
K
Kohsuke Kawaguchi 已提交
661 662
    }

663 664 665 666
    @Override
    protected void kill() {
        super.kill();
        closeChannel();
K
Kohsuke Kawaguchi 已提交
667
        IOUtils.closeQuietly(log);
668 669

        try {
670
            Util.deleteRecursive(getLogDir());
671
        } catch (IOException ex) {
672
            logger.log(Level.WARNING, "Unable to delete agent logs", ex);
673
        }
674 675 676
    }

    public RetentionStrategy getRetentionStrategy() {
677
        Slave n = getNode();
678
        return n==null ? RetentionStrategy.INSTANCE : n.getRetentionStrategy();
679 680 681 682 683 684 685
    }

    /**
     * If still connected, disconnect.
     */
    private void closeChannel() {
        // TODO: race condition between this and the setChannel method.
686 687 688 689 690 691 692
        Channel c;
        synchronized (channelLock) {
            c = channel;
            channel = null;
            absoluteRemoteFs = null;
            isUnix = null;
        }
693 694 695 696 697 698
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                logger.log(Level.SEVERE, "Failed to terminate channel to " + getDisplayName(), e);
            }
699
            for (ComputerListener cl : ComputerListener.all())
700
                cl.onOffline(this, offlineCause);
701 702 703 704
        }
    }

    @Override
705
    protected void setNode(final Node node) {
706
        super.setNode(node);
K
kohsuke 已提交
707
        launcher = grabLauncher(node);
708

709
        // maybe the configuration was changed to relaunch the agent, so try to re-launch now.
K
kohsuke 已提交
710 711
        // "constructed==null" test is an ugly hack to avoid launching before the object is fully
        // constructed.
712
        if(constructed!=null) {
713 714 715 716 717 718 719 720
            if (node instanceof Slave) {
                Queue.withLock(new Runnable() {
                    @Override
                    public void run() {
                        ((Slave)node).getRetentionStrategy().check(SlaveComputer.this);
                    }
                });
            } else {
721
                connect(false);
722
            }
723
        }
K
kohsuke 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    }

    /**
     * Grabs a {@link ComputerLauncher} out of {@link Node} to keep it in this {@link Computer}.
     * The returned launcher will be set to {@link #launcher} and used to carry out the actual launch operation.
     *
     * <p>
     * Subtypes that needs to decorate {@link ComputerLauncher} can do so by overriding this method.
     * This is useful for {@link SlaveComputer}s for clouds for example, where one normally needs
     * additional pre-launch step (such as waiting for the provisioned node to become available)
     * before the user specified launch step (like SSH connection) kicks in.
     *
     * @see ComputerLauncherFilter
     */
    protected ComputerLauncher grabLauncher(Node node) {
        return ((Slave)node).getLauncher();
740 741
    }

742
    /**
743
     * Get the agent version
744 745 746 747 748 749 750 751 752 753 754 755
     */
    public String getSlaveVersion() throws IOException, InterruptedException {
        return channel.call(new SlaveVersion());
    }

    /**
     * Get the OS description.
     */
    public String getOSDescription() throws IOException, InterruptedException {
        return channel.call(new DetectOS()) ? "Unix" : "Windows";
    }

756 757
    private static final Logger logger = Logger.getLogger(SlaveComputer.class.getName());

758
    private static final class SlaveVersion extends MasterToSlaveCallable<String,IOException> {
759 760 761 762 763
        public String call() throws IOException {
            try { return Launcher.VERSION; }
            catch (Throwable ex) { return "< 1.335"; } // Older slave.jar won't have VERSION
        }
    }
764
    private static final class DetectOS extends MasterToSlaveCallable<Boolean,IOException> {
765 766 767 768 769
        public Boolean call() throws IOException {
            return File.pathSeparatorChar==':';
        }
    }

770
    private static final class AbsolutePath extends MasterToSlaveCallable<String,IOException> {
771 772 773

        private static final long serialVersionUID = 1L;

774 775 776 777 778 779 780 781 782 783 784
        private final String relativePath;

        private AbsolutePath(String relativePath) {
            this.relativePath = relativePath;
        }

        public String call() throws IOException {
            return new File(relativePath).getAbsolutePath();
        }
    }

785
    private static final class DetectDefaultCharset extends MasterToSlaveCallable<String,IOException> {
786 787 788 789 790 791
        public String call() throws IOException {
            return Charset.defaultCharset().name();
        }
    }

    /**
792 793
     * Puts the {@link #SLAVE_LOG_HANDLER} into a separate class so that loading this class
     * in JVM doesn't end up loading tons of additional classes.
794
     */
795 796
    static final class LogHolder {
        /**
797
         * This field is used on each agent to record logs on the agent.
798 799 800
         */
        static final RingBufferLogHandler SLAVE_LOG_HANDLER = new RingBufferLogHandler();
    }
801

802
    private static class SlaveInitializer extends MasterToSlaveCallable<Void,RuntimeException> {
803
        public Void call() {
804 805 806
            // avoid double installation of the handler. JNLP slaves can reconnect to the master multiple times
            // and each connection gets a different RemoteClassLoader, so we need to evict them by class name,
            // not by their identity.
K
Kohsuke Kawaguchi 已提交
807
            for (Handler h : LOGGER.getHandlers()) {
808
                if (h.getClass().getName().equals(SLAVE_LOG_HANDLER.getClass().getName()))
K
Kohsuke Kawaguchi 已提交
809
                    LOGGER.removeHandler(h);
810
            }
K
Kohsuke Kawaguchi 已提交
811
            LOGGER.addHandler(SLAVE_LOG_HANDLER);
812

K
Kohsuke Kawaguchi 已提交
813
            // remove Sun PKCS11 provider if present. See http://wiki.jenkins-ci.org/display/JENKINS/Solaris+Issue+6276483
814 815 816 817 818 819
            try {
                Security.removeProvider("SunPKCS11-Solaris");
            } catch (SecurityException e) {
                // ignore this error.
            }

820
            Channel.current().setProperty("slave",Boolean.TRUE); // indicate that this side of the channel is the slave side.
821

822 823 824
            return null;
        }
        private static final long serialVersionUID = 1L;
825
        private static final Logger LOGGER = Logger.getLogger("");
826
    }
827 828 829

    /**
     * Obtains a {@link VirtualChannel} that allows some computation to be performed on the master.
830 831 832
     * This method can be called from any thread on the master, or from agent (more precisely,
     * it only works from the remoting request-handling thread in agents, which means if you've started
     * separate thread on agents, that'll fail.)
833 834 835 836 837
     *
     * @return null if the calling thread doesn't have any trace of where its master is.
     * @since 1.362
     */
    public static VirtualChannel getChannelToMaster() {
838
        if (Jenkins.getInstanceOrNull()!=null) // check if calling thread is on master or on slave
K
Kohsuke Kawaguchi 已提交
839
            return FilePath.localChannel;
840

841
        // if this method is called from within the agent computation thread, this should work
842
        Channel c = Channel.current();
843
        if (c!=null && Boolean.TRUE.equals(c.getProperty("slave")))
844 845 846 847
            return c;

        return null;
    }
848

849 850 851 852 853 854 855
    /**
     * Helper method for Jelly.
     */
    public static List<SlaveSystemInfo> getSystemInfoExtensions() {
        return SlaveSystemInfo.all();
    }

856
    private static class SlaveLogFetcher extends MasterToSlaveCallable<List<LogRecord>,RuntimeException> {
857 858 859 860
        public List<LogRecord> call() {
            return new ArrayList<LogRecord>(SLAVE_LOG_HANDLER.getView());
        }
    }
861 862

    private static final Logger LOGGER = Logger.getLogger(SlaveComputer.class.getName());
863
}