Slave.java 16.7 KB
Newer Older
K
kohsuke 已提交
1 2 3
/*
 * The MIT License
 * 
4 5
 * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
 * Erik Ramfelt, Martin Eigenbrodt, Stephen Connolly, Tom Huybrechts
K
kohsuke 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * 
 * 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.
 */
K
kohsuke 已提交
25 26 27 28 29
package hudson.model;

import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
30
import hudson.Launcher.RemoteLauncher;
K
kohsuke 已提交
31
import hudson.model.Descriptor.FormException;
K
kohsuke 已提交
32
import hudson.remoting.Callable;
33 34 35 36 37 38 39 40 41
import hudson.slaves.CommandLauncher;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.DumbSlave;
import hudson.slaves.JNLPLauncher;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.RetentionStrategy;
import hudson.slaves.SlaveComputer;
K
kohsuke 已提交
42
import hudson.util.ClockDifference;
43
import hudson.util.DescribableList;
K
kohsuke 已提交
44
import hudson.util.FormValidation;
K
kohsuke 已提交
45

K
kohsuke 已提交
46 47 48 49
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
50
import java.net.MalformedURLException;
51 52
import java.net.URL;
import java.net.URLConnection;
53 54 55 56 57 58
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;

J
Jesse Glick 已提交
59
import javax.annotation.CheckForNull;
J
Jesse Glick 已提交
60
import javax.annotation.Nonnull;
61
import jenkins.model.Jenkins;
62 63
import jenkins.slaves.WorkspaceLocator;

64
import org.apache.commons.io.IOUtils;
65
import org.kohsuke.stapler.HttpResponse;
66 67 68
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
kohsuke 已提交
69

K
kohsuke 已提交
70 71 72
/**
 * Information about a Hudson slave node.
 *
K
noted  
kohsuke 已提交
73 74 75 76
 * <p>
 * Ideally this would have been in the <tt>hudson.slaves</tt> package,
 * but for compatibility reasons, it can't.
 *
K
kohsuke 已提交
77 78 79
 * <p>
 * TODO: move out more stuff to {@link DumbSlave}.
 *
K
kohsuke 已提交
80 81
 * @author Kohsuke Kawaguchi
 */
82
public abstract class Slave extends Node implements Serializable {
K
kohsuke 已提交
83
    /**
K
kohsuke 已提交
84
     * Name of this slave node.
K
kohsuke 已提交
85
     */
K
kohsuke 已提交
86
    protected String name;
K
kohsuke 已提交
87 88 89 90 91 92 93

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

    /**
94
     * Absolute path to the root of the workspace
K
kohsuke 已提交
95
     * from the view point of this node, such as "/hudson"
K
kohsuke 已提交
96
     */
K
kohsuke 已提交
97
    protected final String remoteFS;
K
kohsuke 已提交
98 99 100 101 102 103 104 105 106 107 108

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

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

K
kohsuke 已提交
109
    /**
110 111
     * Slave availablility strategy.
     */
K
kohsuke 已提交
112
    private RetentionStrategy retentionStrategy;
113 114 115

    /**
     * The starter that will startup this slave.
116
     */
117
    private ComputerLauncher launcher;
K
kohsuke 已提交
118

119 120 121 122
    /**
     * Whitespace-separated labels.
     */
    private String label="";
123
    
124
    private /*almost final*/ DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(Jenkins.getInstance());
125 126 127 128 129

    /**
     * Lazily computed set of labels from {@link #label}.
     */
    private transient volatile Set<Label> labels;
130 131 132 133 134
    
    /**
     * Id of user which creates this slave {@link User}.
     */
    private String userId;
135

K
kohsuke 已提交
136
    public Slave(String name, String nodeDescription, String remoteFS, String numExecutors,
K
kohsuke 已提交
137 138
                 Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy, List<? extends NodeProperty<?>> nodeProperties) throws FormException, IOException {
        this(name,nodeDescription,remoteFS,Util.tryParseNumber(numExecutors, 1).intValue(),mode,labelString,launcher,retentionStrategy, nodeProperties);
K
kohsuke 已提交
139 140
    }

M
mindless 已提交
141 142 143
    /**
     * @deprecated since 2009-02-20.
     */
144 145
    @Deprecated
    public Slave(String name, String nodeDescription, String remoteFS, int numExecutors,
K
kohsuke 已提交
146 147
            Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy) throws FormException, IOException {
    	this(name, nodeDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, new ArrayList());
148 149
    }
    
J
Jesse Glick 已提交
150
    public Slave(@Nonnull String name, String nodeDescription, String remoteFS, int numExecutors,
K
kohsuke 已提交
151
                 Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy, List<? extends NodeProperty<?>> nodeProperties) throws FormException, IOException {
K
kohsuke 已提交
152
        this.name = name;
K
kohsuke 已提交
153
        this.description = nodeDescription;
K
kohsuke 已提交
154
        this.numExecutors = numExecutors;
K
kohsuke 已提交
155
        this.mode = mode;
156
        this.remoteFS = Util.fixNull(remoteFS).trim();
K
kohsuke 已提交
157
        this.label = Util.fixNull(labelString).trim();
158 159
        this.launcher = launcher;
        this.retentionStrategy = retentionStrategy;
160
        getAssignedLabels();    // compute labels now
161 162
        
        this.nodeProperties.replaceBy(nodeProperties);
163 164 165 166 167 168 169 170 171
         Slave node = (Slave) Jenkins.getInstance().getNode(name);

       if(node!=null){
            this.userId= node.getUserId(); //slave has already existed
        }
       else{
            User user = User.current();
            userId = user!=null ? user.getId() : "anonymous";     
        }
K
d'oh!  
kohsuke 已提交
172
        if (name.equals(""))
K
i18n  
kohsuke 已提交
173
            throw new FormException(Messages.Slave_InvalidConfig_NoName(), null);
K
kohsuke 已提交
174

K
kohsuke 已提交
175 176
//        if (remoteFS.equals(""))
//            throw new FormException(Messages.Slave_InvalidConfig_NoRemoteDir(name), null);
177

178
        if (this.numExecutors<=0)
K
i18n  
kohsuke 已提交
179
            throw new FormException(Messages.Slave_InvalidConfig_Executors(name), null);
K
kohsuke 已提交
180
    }
181 182 183 184 185 186 187 188 189
    
    /**
     * Return id of user which created this slave
     * 
     * @return id of user
     */
    public String getUserId() {
        return userId;
    }
K
kohsuke 已提交
190

191 192 193 194
    public void setUserId(String userId){
        this.userId = userId;
    }
    
195
    public ComputerLauncher getLauncher() {
196
        return launcher == null ? new JNLPLauncher() : launcher;
197 198
    }

199
    public void setLauncher(ComputerLauncher launcher) {
200
        this.launcher = launcher;
K
kohsuke 已提交
201 202 203 204 205 206
    }

    public String getRemoteFS() {
        return remoteFS;
    }

K
kohsuke 已提交
207 208
    public String getNodeName() {
        return name;
K
kohsuke 已提交
209 210
    }

J
Jesse Glick 已提交
211 212 213 214
    @Override public String toString() {
        return getClass().getName() + "[" + name + "]";
    }

K
kohsuke 已提交
215 216 217 218
    public void setNodeName(String name) {
        this.name = name; 
    }

K
kohsuke 已提交
219 220 221 222 223 224 225 226 227 228 229 230
    public String getNodeDescription() {
        return description;
    }

    public int getNumExecutors() {
        return numExecutors;
    }

    public Mode getMode() {
        return mode;
    }

K
kohsuke 已提交
231 232 233 234
    public void setMode(Mode mode) {
        this.mode = mode;
    }

235
    public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
236
        assert nodeProperties != null;
237 238 239
    	return nodeProperties;
    }
    
K
kohsuke 已提交
240 241
    public RetentionStrategy getRetentionStrategy() {
        return retentionStrategy == null ? RetentionStrategy.Always.INSTANCE : retentionStrategy;
242 243
    }

K
kohsuke 已提交
244 245
    public void setRetentionStrategy(RetentionStrategy availabilityStrategy) {
        this.retentionStrategy = availabilityStrategy;
246 247
    }

248 249 250
    public String getLabelString() {
        return Util.fixNull(label).trim();
    }
251

252 253 254 255 256 257 258
    @Override
    public void setLabelString(String labelString) throws IOException {
        this.label = Util.fixNull(labelString).trim();
        // Compute labels now.
        getAssignedLabels();
    }

K
Kohsuke Kawaguchi 已提交
259 260 261
    @Override
    public Callable<ClockDifference,IOException> getClockDifferenceCallable() {
        return new GetClockDifference1();
K
kohsuke 已提交
262 263
    }

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

268
    public FilePath getWorkspaceFor(TopLevelItem item) {
269 270 271 272 273 274 275
        for (WorkspaceLocator l : WorkspaceLocator.all()) {
            FilePath workspace = l.locate(item, this);
            if (workspace != null) {
                return workspace;
            }
        }
        
K
kohsuke 已提交
276 277
        FilePath r = getWorkspaceRoot();
        if(r==null)     return null;    // offline
278
        return r.child(item.getFullName());
279 280
    }

K
kohsuke 已提交
281
    public FilePath getRootPath() {
282 283 284
        return createPath(remoteFS);
    }

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

296 297 298
    /**
     * Web-bound object used to serve jar files for JNLP.
     */
299
    public static final class JnlpJar implements HttpResponse {
K
kohsuke 已提交
300
        private final String fileName;
301

K
kohsuke 已提交
302 303
        public JnlpJar(String fileName) {
            this.fileName = fileName;
304 305 306
        }

        public void doIndex( StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
307
            URLConnection con = connect();
308 309
            // since we end up redirecting users to jnlpJars/foo.jar/, set the content disposition
            // so that browsers can download them in the right file name.
310 311
            // see http://support.microsoft.com/kb/260519 and http://www.boutell.com/newfaq/creating/forcedownload.html
            rsp.setHeader("Content-Disposition", "attachment; filename=" + fileName);
K
kohsuke 已提交
312 313 314 315 316
            InputStream in = con.getInputStream();
            rsp.serveFile(req, in, con.getLastModified(), con.getContentLength(), "*.jar" );
            in.close();
        }

317 318 319 320
        public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
            doIndex(req,rsp);
        }

K
kohsuke 已提交
321 322 323 324 325 326
        private URLConnection connect() throws IOException {
            URL res = getURL();
            return res.openConnection();
        }

        public URL getURL() throws MalformedURLException {
327 328
            String name = fileName;
            if (name.equals("hudson-cli.jar"))  name="jenkins-cli.jar";
329
            URL res = Jenkins.getInstance().servletContext.getResource("/WEB-INF/" + name);
K
kohsuke 已提交
330 331
            if(res==null) {
                // during the development this path doesn't have the files.
332
                res = new URL(new File(".").getAbsoluteFile().toURI().toURL(),"target/jenkins/WEB-INF/"+name);
333
            }
K
kohsuke 已提交
334 335
            return res;
        }
336

K
kohsuke 已提交
337 338 339 340 341 342 343
        public byte[] readFully() throws IOException {
            InputStream in = connect().getInputStream();
            try {
                return IOUtils.toByteArray(in);
            } finally {
                in.close();
            }
344 345 346 347
        }

    }

348 349 350 351 352 353 354
    /**
     * Creates a launcher for the slave.
     *
     * @return
     *      If there is no computer it will return a {@link hudson.Launcher.DummyLauncher}, otherwise it
     *      will return a {@link hudson.Launcher.RemoteLauncher} instead.
     */
K
kohsuke 已提交
355
    public Launcher createLauncher(TaskListener listener) {
356
        SlaveComputer c = getComputer();
357 358 359 360 361 362
        if (c == null) {
            listener.error("Issue with creating launcher for slave " + name + ".");
            return new Launcher.DummyLauncher(listener);
        } else {
            return new RemoteLauncher(listener, c.getChannel(), c.isUnix()).decorateFor(this);
        }
K
kohsuke 已提交
363 364
    }

K
kohsuke 已提交
365
    /**
366
     * Gets the corresponding computer object.
K
kohsuke 已提交
367
     */
368
    public SlaveComputer getComputer() {
369
        return (SlaveComputer)toComputer();
K
kohsuke 已提交
370 371
    }

372
    @Override
K
kohsuke 已提交
373 374 375 376 377 378 379 380 381
    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);
    }

382
    @Override
K
kohsuke 已提交
383 384 385 386
    public int hashCode() {
        return name.hashCode();
    }

K
kohsuke 已提交
387 388 389
    /**
     * Invoked by XStream when this object is read into memory.
     */
K
Kohsuke Kawaguchi 已提交
390
    protected Object readResolve() {
K
kohsuke 已提交
391
        // convert the old format to the new one
392 393 394 395
        if (launcher == null) {
            launcher = (agentCommand == null || agentCommand.trim().length() == 0)
                    ? new JNLPLauncher()
                    : new CommandLauncher(agentCommand);
396
        }
397
        if(nodeProperties==null)
398
            nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(Jenkins.getInstance());
K
kohsuke 已提交
399 400 401
        return this;
    }

K
kohsuke 已提交
402
    public SlaveDescriptor getDescriptor() {
403
        Descriptor d = Jenkins.getInstance().getDescriptorOrDie(getClass());
404 405 406
        if (d instanceof SlaveDescriptor)
            return (SlaveDescriptor) d;
        throw new IllegalStateException(d.getClass()+" needs to extend from SlaveDescriptor");
K
kohsuke 已提交
407
    }
408 409

    public static abstract class SlaveDescriptor extends NodeDescriptor {
K
kohsuke 已提交
410
        public FormValidation doCheckNumExecutors(@QueryParameter String value) {
411
            return FormValidation.validatePositiveInteger(value);
412
        }
K
kohsuke 已提交
413 414 415 416

        /**
         * Performs syntactical check on the remote FS for slaves.
         */
417
        public FormValidation doCheckRemoteFS(@QueryParameter String value) throws IOException, ServletException {
K
kohsuke 已提交
418
            if(Util.fixEmptyAndTrim(value)==null)
419
                return FormValidation.error(Messages.Slave_Remote_Director_Mandatory());
K
kohsuke 已提交
420

K
kohsuke 已提交
421
            if(value.startsWith("\\\\") || value.startsWith("/net/"))
422
                return FormValidation.warning(Messages.Slave_Network_Mounted_File_System_Warning());
K
kohsuke 已提交
423

424 425 426
            if (!value.contains("\\") && !value.startsWith("/")) {
                // Unix-looking path that doesn't start with '/'
                // TODO: detect Windows-looking relative path
427 428 429
                return FormValidation.error(Messages.Slave_the_remote_root_must_be_an_absolute_path());
            }

K
kohsuke 已提交
430
            return FormValidation.ok();
K
kohsuke 已提交
431
        }
432 433 434
    }


K
kohsuke 已提交
435
//
436
// backward compatibility
K
kohsuke 已提交
437
//
438 439 440
    /**
     * Command line to launch the agent, like
     * "ssh myslave java -jar /path/to/hudson-remoting.jar"
441
     * @deprecated in 1.216
442 443 444
     */
    private transient String agentCommand;

K
kohsuke 已提交
445
    /**
K
Kohsuke Kawaguchi 已提交
446 447 448 449 450 451 452 453 454 455 456
     * Obtains the clock difference between this side and that side of the channel.
     *
     * <p>
     * This is a hack to wrap the whole thing into a simple {@link Callable}.
     *
     * <ol>
     *     <li>When the callable is sent to remote, we capture the time (on this side) in {@link GetClockDifference2#startTime}
     *     <li>When the other side receives the callable it is {@link GetClockDifference2}.
     *     <li>We capture the time on the other side and {@link GetClockDifference3} gets sent from the other side
     *     <li>When it's read on this side as a return value, it morphs itself into {@link ClockDifference}.
     * </ol>
K
kohsuke 已提交
457
     */
K
Kohsuke Kawaguchi 已提交
458 459 460 461 462 463 464 465
    private static final class GetClockDifference1 implements Callable<ClockDifference,IOException> {
        public ClockDifference call() {
            // this method must be being invoked locally, which means the clock is in sync
            return new ClockDifference(0);
        }

        private Object writeReplace() {
            return new GetClockDifference2();
K
kohsuke 已提交
466 467 468 469
        }

        private static final long serialVersionUID = 1L;
    }
470

K
Kohsuke Kawaguchi 已提交
471 472 473 474 475
    private static final class GetClockDifference2 implements Callable<GetClockDifference3,IOException> {
        /**
         * Capture the time on the master when this object is sent to remote, which is when
         * {@link GetClockDifference1#writeReplace()} is run.
         */
476
        private final long startTime = System.currentTimeMillis();
K
Kohsuke Kawaguchi 已提交
477 478 479 480 481 482 483 484 485

        public GetClockDifference3 call() {
            return new GetClockDifference3(startTime);
        }

        private static final long serialVersionUID = 1L;
    }

    private static final class GetClockDifference3 implements Serializable {
486
        private final long remoteTime = System.currentTimeMillis();
K
Kohsuke Kawaguchi 已提交
487 488 489 490 491 492 493
        private final long startTime;

        public GetClockDifference3(long startTime) {
            this.startTime = startTime;
        }

        private Object readResolve() {
494 495
            long endTime = System.currentTimeMillis();
            return new ClockDifference((startTime + endTime)/2-remoteTime);
K
Kohsuke Kawaguchi 已提交
496 497 498
        }
    }

499 500 501 502
    /**
     * Determines the workspace root file name for those who really really need the shortest possible path name.
     */
    private static final String WORKSPACE_ROOT = System.getProperty(Slave.class.getName()+".workspaceRoot","workspace");
K
kohsuke 已提交
503
}