SlaveComputer.java 29.2 KB
Newer Older
K
kohsuke 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * The MIT License
 * 
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
 * 
 * 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:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * 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 26
package hudson.slaves;

import hudson.model.*;
27
import hudson.util.IOException2;
K
Kohsuke Kawaguchi 已提交
28
import hudson.util.IOUtils;
29
import hudson.util.io.ReopenableRotatingFileOutputStream;
30
import jenkins.model.Jenkins.MasterComputer;
31 32 33 34 35 36
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Callable;
import hudson.util.StreamTaskListener;
import hudson.util.NullStream;
import hudson.util.RingBufferLogHandler;
K
kohsuke 已提交
37
import hudson.util.Futures;
38
import hudson.FilePath;
K
kohsuke 已提交
39
import hudson.Util;
K
kohsuke 已提交
40
import hudson.AbortException;
41
import hudson.remoting.Launcher;
42
import hudson.security.ACL;
43
import static hudson.slaves.SlaveComputer.LogHolder.SLAVE_LOG_HANDLER;
44
import hudson.slaves.OfflineCause.ChannelTermination;
K
Kohsuke Kawaguchi 已提交
45
import hudson.util.Secret;
46 47 48 49 50

import java.io.File;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.IOException;
51
import java.io.PrintStream;
52
import java.security.SecureRandom;
53 54 55
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
56
import java.util.logging.Handler;
57 58 59 60
import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
import java.nio.charset.Charset;
K
kohsuke 已提交
61
import java.util.concurrent.Future;
62
import java.security.Security;
63

64
import hudson.util.io.ReopenableFileOutputStream;
K
Kohsuke Kawaguchi 已提交
65 66 67 68 69
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
70
import javax.crypto.spec.IvParameterSpec;
K
Kohsuke Kawaguchi 已提交
71 72
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.RequestDispatcher;
73
import jenkins.model.Jenkins;
74
import jenkins.slaves.JnlpSlaveAgentProtocol;
75 76
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
77 78 79
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
80 81

import javax.servlet.ServletException;
K
Kohsuke Kawaguchi 已提交
82 83
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponseWrapper;
84 85
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
K
Kohsuke Kawaguchi 已提交
86 87 88
import org.kohsuke.stapler.ResponseImpl;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.compression.FilterServletOutputStream;
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 102 103 104 105 106 107
    /**
     * Effective {@link ComputerLauncher} that hides the details of
     * how we launch a slave agent on this computer.
     *
     * <p>
     * This is normally the same as {@link Slave#getLauncher()} but
     * can be different. See {@link #grabLauncher(Node)}. 
     */
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 136 137
    /**
     * 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();

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

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isAcceptingTasks() {
        return acceptingTasks;
    }

K
Kohsuke Kawaguchi 已提交
151 152 153
    /**
     * @since 1.498
     */
154 155 156 157
    public String getJnlpMac() {
        return JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(getName());
    }

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    /**
     * Allows a {@linkplain hudson.slaves.ComputerLauncher} or a {@linkplain hudson.slaves.RetentionStrategy} to
     * suspend tasks being accepted by the slave computer.
     *
     * @param acceptingTasks {@code true} if the slave can accept tasks.
     */
    public void setAcceptingTasks(boolean acceptingTasks) {
        this.acceptingTasks = acceptingTasks;
    }

    /**
     * True if this computer is a Unix machine (as opposed to Windows machine).
     *
     * @return
     *      null if the computer is disconnected and therefore we don't know whether it is Unix or not.
     */
    public Boolean isUnix() {
        return isUnix;
    }

178
    @Override
179 180 181 182
    public Slave getNode() {
        return (Slave)super.getNode();
    }

K
kohsuke 已提交
183 184 185 186 187 188 189 190
    @Override
    public String getIcon() {
        Future<?> l = lastConnectActivity;
        if(l!=null && !l.isDone())
            return "computer-flash.gif";
        return super.getIcon();
    }

M
mindless 已提交
191 192 193 194
    /**
     * @deprecated since 2008-05-20.
     */
    @Deprecated @Override
195 196 197 198 199 200 201 202 203 204 205 206 207
    public boolean isJnlpAgent() {
        return launcher instanceof JNLPLauncher;
    }

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

    public ComputerLauncher getLauncher() {
        return launcher;
    }

208
    protected Future<?> _connect(boolean forceReconnect) {
K
kohsuke 已提交
209
        if(channel!=null)   return Futures.precomputed(null);
210
        if(!forceReconnect && isConnecting())
K
kohsuke 已提交
211
            return lastConnectActivity;
212
        if(forceReconnect && isConnecting())
K
kohsuke 已提交
213
            logger.fine("Forcing a reconnect on "+getName());
214 215

        closeChannel();
K
kohsuke 已提交
216 217
        return lastConnectActivity = Computer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<Object>() {
            public Object call() throws Exception {
218 219
                // do this on another thread so that the lengthy launch operation
                // (which is typical) won't block UI thread.
K
kohsuke 已提交
220
                try {
221
                    log.rewind();
222
                    try {
T
Tom Rini 已提交
223
                        for (ComputerListener cl : ComputerListener.all())
224
                            cl.preLaunch(SlaveComputer.this, taskListener);
K
Kohsuke Kawaguchi 已提交
225

226
                        launcher.launch(SlaveComputer.this, taskListener);
227
                    } catch (AbortException e) {
228
                        taskListener.error(e.getMessage());
229 230
                        throw e;
                    } catch (IOException e) {
231 232
                        Util.displayIOException(e,taskListener);
                        e.printStackTrace(taskListener.error(Messages.ComputerLauncher_unexpectedError()));
233 234
                        throw e;
                    } catch (InterruptedException e) {
235
                        e.printStackTrace(taskListener.error(Messages.ComputerLauncher_abortedLaunch()));
236 237
                        throw e;
                    }
238
                } finally {
239
                    if (channel==null) {
240
                        offlineCause = new OfflineCause.LaunchFailed();
241 242 243
                        for (ComputerListener cl : ComputerListener.all())
                            cl.onLaunchFailure(SlaveComputer.this, taskListener);
                    }
K
kohsuke 已提交
244
                }
245 246 247 248

                if (channel==null)
                    throw new IOException("Slave failed to connect, even though the launcher didn't report it. See the log output for details.");
                return null;
249 250 251 252 253 254 255 256 257 258 259 260 261
            }
        });
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void taskAccepted(Executor executor, Queue.Task task) {
        super.taskAccepted(executor, task);
        if (launcher instanceof ExecutorListener) {
            ((ExecutorListener)launcher).taskAccepted(executor, task);
        }
262 263 264 265 266
        
        //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);
267 268 269 270 271 272 273 274 275 276 277 278
        }
    }

    /**
     * {@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);
        }
279
        RetentionStrategy r = getRetentionStrategy();
K
kohsuke 已提交
280 281
        if (r instanceof ExecutorListener) {
            ((ExecutorListener) r).taskCompleted(executor, task, durationMS);
282 283 284 285 286 287 288 289 290 291 292 293
        }
    }

    /**
     * {@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);
        }
294 295 296
        RetentionStrategy r = getRetentionStrategy();
        if (r instanceof ExecutorListener) {
            ((ExecutorListener) r).taskCompletedWithProblems(executor, task, durationMS, problems);
297 298 299
        }
    }

K
kohsuke 已提交
300 301 302 303 304 305
    @Override
    public boolean isConnecting() {
        Future<?> l = lastConnectActivity;
        return isOffline() && l!=null && !l.isDone();
    }

306 307
    public OutputStream openLogFile() {
        try {
308 309 310
            log.rewind();
            return log;
        } catch (IOException e) {
311
            logger.log(Level.SEVERE, "Failed to create log file "+getLogFile(),e);
312
            return new NullStream();
313 314 315 316 317
        }
    }

    private final Object channelLock = new Object();

K
kohsuke 已提交
318 319 320 321
    public void setChannel(InputStream in, OutputStream out, TaskListener taskListener, Channel.Listener listener) throws IOException, InterruptedException {
        setChannel(in,out,taskListener.getLogger(),listener);
    }

322 323
    /**
     * Creates a {@link Channel} from the given stream and sets that to this slave.
K
kohsuke 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336
     *
     * @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
337
     *      Gets a notification when the channel closes, to perform clean up. Can be null.
338 339
     *      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.
340 341
     */
    public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException {
342 343 344 345
        Channel channel = new Channel(nodeName,threadPoolForRemoting, Channel.Mode.NEGOTIATE, in,out, launchLog);
        setChannel(channel,launchLog,listener);
    }

J
Jesse Glick 已提交
346 347 348 349 350 351 352 353
    /**
     * Shows {@link Channel#classLoadingCount}.
     * @since 1.495
     */
    public int getClassLoadingCount() throws IOException, InterruptedException {
        return channel.call(new LoadingCount(false));
    }

354 355 356
    /**
     * Shows {@link Channel#classLoadingPrefetchCacheCount}.
     * @return -1 in case that capability is not supported
J
Jesse Glick 已提交
357
     * @since 1.519
358 359 360 361 362 363 364 365
     */
    public int getClassLoadingPrefetchCacheCount() throws IOException, InterruptedException {
        if (!channel.remoteCapability.supportsPrefetch()) {
            return -1;
        }
        return channel.call(new LoadingPrefetchCacheCount());
    }

J
Jesse Glick 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    /**
     * 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));
    }

    static class LoadingCount implements Callable<Integer,RuntimeException> {
        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();
        }
    }

401 402 403 404 405 406
    static class LoadingPrefetchCacheCount implements Callable<Integer,RuntimeException> {
        @Override public Integer call() {
            return Channel.current().classLoadingPrefetchCacheCount.get();
        }
    }

J
Jesse Glick 已提交
407 408 409 410 411 412 413 414 415 416 417
    static class LoadingTime implements Callable<Long,RuntimeException> {
        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();
        }
    }

418 419 420 421 422 423
    /**
     * Sets up the connection through an exsting channel.
     *
     * @since 1.444
     */
    public void setChannel(Channel channel, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException {
424 425 426
        if(this.channel!=null)
            throw new IllegalStateException("Already connected");

427 428
        final TaskListener taskListener = new StreamTaskListener(launchLog);
        PrintStream log = taskListener.getLogger();
429

430
        channel.addListener(new Channel.Listener() {
431
            @Override
432 433
            public void onClosed(Channel c, IOException cause) {
                // Orderly shutdown will have null exception
434 435
                if (cause!=null) {
                    offlineCause = new ChannelTermination(cause);
436
                    cause.printStackTrace(taskListener.error("Connection terminated"));
437 438 439
                } else {
                    taskListener.getLogger().println("Connection terminated");
                }
440
                closeChannel();
441
                launcher.afterDisconnect(SlaveComputer.this, taskListener);
442 443
            }
        });
444 445
        if(listener!=null)
            channel.addListener(listener);
446

447 448 449
        String slaveVersion = channel.call(new SlaveVersion());
        log.println("Slave.jar version: " + slaveVersion);

450 451 452 453 454 455 456 457
        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());

        String remoteFs = getNode().getRemoteFS();
        if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\"))
            log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?");
458
        FilePath root = new FilePath(channel,getNode().getRemoteFS());
459

K
Kohsuke Kawaguchi 已提交
460 461 462 463 464
        // 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());

465
        channel.call(new SlaveInitializer());
466 467 468 469 470 471 472 473
        SecurityContext old = ACL.impersonate(ACL.SYSTEM);
        try {
            for (ComputerListener cl : ComputerListener.all()) {
                cl.preOnline(this,channel,root,taskListener);
            }
        } finally {
            SecurityContextHolder.setContext(old);
        }
474

475 476
        offlineCause = null;

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
        // 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;
            defaultCharset = Charset.forName(defaultCharsetName);
493 494 495 496

            synchronized (statusChangeLock) {
                statusChangeLock.notifyAll();
            }
497
        }
498 499 500 501 502 503 504 505
        old = ACL.impersonate(ACL.SYSTEM);
        try {
            for (ComputerListener cl : ComputerListener.all()) {
                cl.onOnline(this,taskListener);
            }
        } finally {
            SecurityContextHolder.setContext(old);
        }
A
abayer 已提交
506
        log.println("Slave successfully connected and online");
507
        Jenkins.getInstance().getQueue().scheduleMaintenance();
508 509 510
    }

    @Override
511
    public Channel getChannel() {
512 513 514 515 516 517 518 519 520 521 522
        return channel;
    }

    public Charset getDefaultCharset() {
        return defaultCharset;
    }

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

526 527 528
    public HttpResponse doDoDisconnect(@QueryParameter String offlineMessage) throws IOException, ServletException {
        if (channel!=null) {
            //does nothing in case computer is already disconnected
529
            checkPermission(DISCONNECT);
530 531
            offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
            disconnect(OfflineCause.create(Messages._SlaveComputer_DisconnectedBy(
532
                    Jenkins.getAuthentication().getName(),
533 534 535 536
                    offlineMessage!=null ? " : " + offlineMessage : "")
            ));
        }
        return new HttpRedirect(".");
537 538 539
    }

    @Override
540 541
    public Future<?> disconnect(OfflineCause cause) {
        super.disconnect(cause);
K
kohsuke 已提交
542
        return Computer.threadPoolForRemoting.submit(new Runnable() {
543 544 545
            public void run() {
                // do this on another thread so that any lengthy disconnect operation
                // (which could be typical) won't block UI thread.
546 547 548
                launcher.beforeDisconnect(SlaveComputer.this, taskListener);
                closeChannel();
                launcher.afterDisconnect(SlaveComputer.this, taskListener);
549 550 551 552 553 554
            }
        });
    }

    public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        if(channel!=null) {
555
            req.getView(this,"already-launched.jelly").forward(req, rsp);
556 557 558
            return;
        }

K
kohsuke 已提交
559
        connect(true);
560 561 562 563 564 565 566 567 568 569 570

        // 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 已提交
571
            connect(true);
572 573 574 575 576 577
        }
    }

    /**
     * Serves jar files for JNLP slave agents.
     *
M
mindless 已提交
578
     * @deprecated since 2008-08-18.
579
     *      This URL binding is no longer used and moved up directly under to {@link jenkins.model.Jenkins},
580 581 582 583 584 585
     *      but it's left here for now just in case some old JNLP slave agents request it.
     */
    public Slave.JnlpJar getJnlpJars(String fileName) {
        return new Slave.JnlpJar(fileName);
    }

K
Kohsuke Kawaguchi 已提交
586 587 588 589 590 591 592 593 594 595 596 597 598 599
    @WebMethod(name="slave-agent.jnlp")
    public void doSlaveAgentJnlp(StaplerRequest req, StaplerResponse res) throws IOException, ServletException {
        RequestDispatcher view = req.getView(this, "slave-agent.jnlp.jelly");
        if ("true".equals(req.getParameter("encrypt"))) {
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            StaplerResponse temp = new ResponseImpl(req.getStapler(), new HttpServletResponseWrapper(res) {
                @Override public ServletOutputStream getOutputStream() throws IOException {
                    return new FilterServletOutputStream(baos);
                }
                @Override public PrintWriter getWriter() throws IOException {
                    throw new IllegalStateException();
                }
            });
            view.forward(req, temp);
600 601 602 603

            byte[] iv = new byte[128/8];
            new SecureRandom().nextBytes(iv);

K
Kohsuke Kawaguchi 已提交
604 605 606 607
            byte[] jnlpMac = JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(getName().getBytes("UTF-8"));
            SecretKey key = new SecretKeySpec(jnlpMac, 0, /* export restrictions */ 128 / 8, "AES");
            byte[] encrypted;
            try {
608 609
                Cipher c = Secret.getCipher("AES/CFB8/NoPadding");
                c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
K
Kohsuke Kawaguchi 已提交
610 611
                encrypted = c.doFinal(baos.toByteArray());
            } catch (GeneralSecurityException x) {
612
                throw new IOException2(x);
K
Kohsuke Kawaguchi 已提交
613 614
            }
            res.setContentType("application/octet-stream");
615
            res.getOutputStream().write(iv);
K
Kohsuke Kawaguchi 已提交
616 617 618 619 620 621 622
            res.getOutputStream().write(encrypted);
        } else {
            checkPermission(CONNECT);
            view.forward(req, res);
        }
    }

623 624 625 626
    @Override
    protected void kill() {
        super.kill();
        closeChannel();
K
Kohsuke Kawaguchi 已提交
627
        IOUtils.closeQuietly(log);
628 629 630
    }

    public RetentionStrategy getRetentionStrategy() {
631
        Slave n = getNode();
632
        return n==null ? RetentionStrategy.INSTANCE : n.getRetentionStrategy();
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
    }

    /**
     * If still connected, disconnect.
     */
    private void closeChannel() {
        // TODO: race condition between this and the setChannel method.
        Channel c = channel;
        channel = null;
        isUnix = null;
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                logger.log(Level.SEVERE, "Failed to terminate channel to " + getDisplayName(), e);
            }
649 650
            for (ComputerListener cl : ComputerListener.all())
                cl.onOffline(this);
651 652 653 654 655 656
        }
    }

    @Override
    protected void setNode(Node node) {
        super.setNode(node);
K
kohsuke 已提交
657
        launcher = grabLauncher(node);
658 659

        // maybe the configuration was changed to relaunch the slave, so try to re-launch now.
K
kohsuke 已提交
660 661
        // "constructed==null" test is an ugly hack to avoid launching before the object is fully
        // constructed.
662 663 664 665 666 667
        if(constructed!=null) {
            if (node instanceof Slave)
                ((Slave)node).getRetentionStrategy().check(this);
            else
                connect(false);
        }
K
kohsuke 已提交
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    }

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

686 687 688 689 690 691 692 693 694 695 696 697 698 699
    /**
     * Get the slave version
     */
    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";
    }

700 701
    private static final Logger logger = Logger.getLogger(SlaveComputer.class.getName());

702 703 704 705 706 707
    private static final class SlaveVersion implements Callable<String,IOException> {
        public String call() throws IOException {
            try { return Launcher.VERSION; }
            catch (Throwable ex) { return "< 1.335"; } // Older slave.jar won't have VERSION
        }
    }
708 709 710 711 712 713 714 715 716 717 718 719 720
    private static final class DetectOS implements Callable<Boolean,IOException> {
        public Boolean call() throws IOException {
            return File.pathSeparatorChar==':';
        }
    }

    private static final class DetectDefaultCharset implements Callable<String,IOException> {
        public String call() throws IOException {
            return Charset.defaultCharset().name();
        }
    }

    /**
721 722
     * 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.
723
     */
724 725 726 727 728 729
    static final class LogHolder {
        /**
         * This field is used on each slave node to record log records on the slave.
         */
        static final RingBufferLogHandler SLAVE_LOG_HANDLER = new RingBufferLogHandler();
    }
730

731
    private static class SlaveInitializer implements Callable<Void,RuntimeException> {
732
        public Void call() {
733 734 735
            // 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 已提交
736
            for (Handler h : LOGGER.getHandlers()) {
737
                if (h.getClass().getName().equals(SLAVE_LOG_HANDLER.getClass().getName()))
K
Kohsuke Kawaguchi 已提交
738
                    LOGGER.removeHandler(h);
739
            }
K
Kohsuke Kawaguchi 已提交
740
            LOGGER.addHandler(SLAVE_LOG_HANDLER);
741

K
Kohsuke Kawaguchi 已提交
742
            // remove Sun PKCS11 provider if present. See http://wiki.jenkins-ci.org/display/JENKINS/Solaris+Issue+6276483
743 744 745 746 747 748
            try {
                Security.removeProvider("SunPKCS11-Solaris");
            } catch (SecurityException e) {
                // ignore this error.
            }

749 750
            Channel.current().setProperty("slave",Boolean.TRUE); // indicate that this side of the channel is the slave side.
            
751 752 753
            return null;
        }
        private static final long serialVersionUID = 1L;
754
        private static final Logger LOGGER = Logger.getLogger("");
755
    }
756 757 758 759 760 761 762 763 764 765 766

    /**
     * Obtains a {@link VirtualChannel} that allows some computation to be performed on the master.
     * This method can be called from any thread on the master, or from slave (more precisely,
     * it only works from the remoting request-handling thread in slaves, which means if you've started
     * separate thread on slaves, that'll fail.)
     *
     * @return null if the calling thread doesn't have any trace of where its master is.
     * @since 1.362
     */
    public static VirtualChannel getChannelToMaster() {
767
        if (Jenkins.getInstance()!=null)
768 769 770 771
            return MasterComputer.localChannel;

        // if this method is called from within the slave computation thread, this should work
        Channel c = Channel.current();
772
        if (c!=null && Boolean.TRUE.equals(c.getProperty("slave")))
773 774 775 776
            return c;

        return null;
    }
777 778 779 780 781 782

    private static class SlaveLogFetcher implements Callable<List<LogRecord>,RuntimeException> {
        public List<LogRecord> call() {
            return new ArrayList<LogRecord>(SLAVE_LOG_HANDLER.getView());
        }
    }
783
}