Slave.java 15.6 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, Erik Ramfelt, Martin Eigenbrodt, Stephen Connolly, Tom Huybrechts
 * 
 * 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 已提交
24 25 26 27 28
package hudson.model;

import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
29
import hudson.Launcher.RemoteLauncher;
K
kohsuke 已提交
30
import hudson.model.Descriptor.FormException;
K
kohsuke 已提交
31 32
import hudson.remoting.Callable;
import hudson.remoting.VirtualChannel;
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;
42 43
import hudson.tasks.DynamicLabeler;
import hudson.tasks.LabelFinder;
K
kohsuke 已提交
44
import hudson.util.ClockDifference;
45
import hudson.util.DescribableList;
K
kohsuke 已提交
46
import hudson.util.FormValidation;
K
kohsuke 已提交
47

K
kohsuke 已提交
48 49 50 51
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
52
import java.net.MalformedURLException;
53 54
import java.net.URL;
import java.net.URLConnection;
55 56 57 58 59 60 61 62 63 64 65 66 67
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;

import org.apache.commons.io.IOUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
kohsuke 已提交
68

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

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

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

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

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

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

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

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

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

130 131 132
    private transient volatile Set<Label> dynamicLabels;
    private transient volatile int dynamicLabelsInstanceHash;

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

139 140 141 142 143 144
    @Deprecated
    public Slave(String name, String nodeDescription, String remoteFS, int numExecutors,
            Mode mode, String label, ComputerLauncher launcher, RetentionStrategy retentionStrategy) throws FormException, IOException {
    	this(name, nodeDescription, remoteFS, numExecutors, mode, label, launcher, retentionStrategy, new ArrayList());
    }
    
K
kohsuke 已提交
145
    public Slave(String name, String nodeDescription, String remoteFS, int numExecutors,
146
                 Mode mode, String label, ComputerLauncher launcher, RetentionStrategy retentionStrategy, List<? extends NodeProperty<?>> nodeProperties) throws FormException, IOException {
K
kohsuke 已提交
147
        this.name = name;
K
kohsuke 已提交
148
        this.description = nodeDescription;
K
kohsuke 已提交
149
        this.numExecutors = numExecutors;
K
kohsuke 已提交
150
        this.mode = mode;
K
kohsuke 已提交
151
        this.remoteFS = remoteFS;
152
        this.label = Util.fixNull(label).trim();
153 154
        this.launcher = launcher;
        this.retentionStrategy = retentionStrategy;
155
        getAssignedLabels();    // compute labels now
156 157
        
        this.nodeProperties.replaceBy(nodeProperties);
K
kohsuke 已提交
158

K
d'oh!  
kohsuke 已提交
159
        if (name.equals(""))
K
i18n  
kohsuke 已提交
160
            throw new FormException(Messages.Slave_InvalidConfig_NoName(), null);
K
kohsuke 已提交
161

162 163 164 165 166
        // 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 已提交
167 168 169

//        if (remoteFS.equals(""))
//            throw new FormException(Messages.Slave_InvalidConfig_NoRemoteDir(name), null);
170

171
        if (this.numExecutors<=0)
K
i18n  
kohsuke 已提交
172
            throw new FormException(Messages.Slave_InvalidConfig_Executors(name), null);
K
kohsuke 已提交
173 174
    }

175
    public ComputerLauncher getLauncher() {
176
        return launcher == null ? new JNLPLauncher() : launcher;
177 178
    }

179
    public void setLauncher(ComputerLauncher launcher) {
180
        this.launcher = launcher;
K
kohsuke 已提交
181 182 183 184 185 186
    }

    public String getRemoteFS() {
        return remoteFS;
    }

K
kohsuke 已提交
187 188
    public String getNodeName() {
        return name;
K
kohsuke 已提交
189 190
    }

K
kohsuke 已提交
191 192 193 194
    public void setNodeName(String name) {
        this.name = name; 
    }

K
kohsuke 已提交
195 196 197 198 199 200 201 202 203 204 205 206
    public String getNodeDescription() {
        return description;
    }

    public int getNumExecutors() {
        return numExecutors;
    }

    public Mode getMode() {
        return mode;
    }

K
kohsuke 已提交
207 208 209 210
    public void setMode(Mode mode) {
        this.mode = mode;
    }

211 212 213 214
    public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
    	return nodeProperties;
    }
    
K
kohsuke 已提交
215 216
    public RetentionStrategy getRetentionStrategy() {
        return retentionStrategy == null ? RetentionStrategy.Always.INSTANCE : retentionStrategy;
217 218
    }

K
kohsuke 已提交
219 220
    public void setRetentionStrategy(RetentionStrategy availabilityStrategy) {
        this.retentionStrategy = availabilityStrategy;
221 222
    }

223 224 225
    public String getLabelString() {
        return Util.fixNull(label).trim();
    }
226

227
    public Set<Label> getAssignedLabels() {
228 229
        // todo refactor to make dynamic labels a bit less hacky
        if(labels==null || isChangedDynamicLabels()) {
230 231 232 233 234 235 236 237
            Set<Label> r = new HashSet<Label>();
            String ls = getLabelString();
            if(ls.length()>0) {
                for( String l : ls.split(" +")) {
                    r.add(Hudson.getInstance().getLabel(l));
                }
            }
            r.add(getSelfLabel());
238
            r.addAll(getDynamicLabels());
239 240 241 242 243
            this.labels = Collections.unmodifiableSet(r);
        }
        return labels;
    }

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    /**
     * Check if we should rebuild the list of dynamic labels.
     * @todo make less hacky
     * @return
     */
    private boolean isChangedDynamicLabels() {
        Computer comp = getComputer();
        if (comp == null) {
            return dynamicLabelsInstanceHash != 0;
        } else {
            if (dynamicLabelsInstanceHash == comp.hashCode()) {
                return false;
            }
            dynamicLabels = null; // force a re-calc
            return true;
        }
    }

    /**
     * Returns the possibly empty set of labels that it has been determined as supported by this node.
     *
     * @todo make less hacky
     * @see hudson.tasks.LabelFinder
267 268 269
     *
     * @return
     *      never null.
270 271
     */
    public Set<Label> getDynamicLabels() {
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        // another thread may preempt and set dynamicLabels field to null,
        // so a care needs to be taken to avoid race conditions under all circumstances.
        Set<Label> labels = dynamicLabels;
        if (labels != null)     return labels;

        synchronized (this) {
            labels = dynamicLabels;
            if (labels != null)     return labels;

            dynamicLabels = labels = new HashSet<Label>();
            Computer computer = getComputer();
            VirtualChannel channel;
            if (computer != null && (channel = computer.getChannel()) != null) {
                dynamicLabelsInstanceHash = computer.hashCode();
                for (DynamicLabeler labeler : LabelFinder.LABELERS) {
                    for (String label : labeler.findLabels(channel)) {
                        labels.add(Hudson.getInstance().getLabel(label));
289 290
                    }
                }
291 292
            } else {
                dynamicLabelsInstanceHash = 0;
293
            }
294 295

            return labels;
296 297
        }
    }
298

299
    public ClockDifference getClockDifference() throws IOException, InterruptedException {
K
kohsuke 已提交
300
        VirtualChannel channel = getComputer().getChannel();
K
kohsuke 已提交
301 302
        if(channel==null)
            throw new IOException(getNodeName()+" is offline");
K
kohsuke 已提交
303

K
kohsuke 已提交
304
        long startTime = System.currentTimeMillis();
K
kohsuke 已提交
305
        long slaveTime = channel.call(new GetSystemTime());
K
kohsuke 已提交
306
        long endTime = System.currentTimeMillis();
K
kohsuke 已提交
307

308
        return new ClockDifference((startTime+endTime)/2 - slaveTime);
K
kohsuke 已提交
309 310
    }

K
kohsuke 已提交
311
    public Computer createComputer() {
312
        return new SlaveComputer(this);
K
kohsuke 已提交
313 314
    }

315
    public FilePath getWorkspaceFor(TopLevelItem item) {
K
kohsuke 已提交
316 317 318
        FilePath r = getWorkspaceRoot();
        if(r==null)     return null;    // offline
        return r.child(item.getName());
319 320
    }

K
kohsuke 已提交
321
    public FilePath getRootPath() {
322 323 324
        return createPath(remoteFS);
    }

K
kohsuke 已提交
325 326
    /**
     * Root directory on this slave where all the job workspaces are laid out.
K
kohsuke 已提交
327 328
     * @return
     *      null if not connected.
K
kohsuke 已提交
329 330
     */
    public FilePath getWorkspaceRoot() {
K
kohsuke 已提交
331 332 333
        FilePath r = getRootPath();
        if(r==null) return null;
        return r.child("workspace");
K
kohsuke 已提交
334
    }
K
kohsuke 已提交
335

336 337 338 339
    /**
     * Web-bound object used to serve jar files for JNLP.
     */
    public static final class JnlpJar {
K
kohsuke 已提交
340
        private final String fileName;
341

K
kohsuke 已提交
342 343
        public JnlpJar(String fileName) {
            this.fileName = fileName;
344 345 346
        }

        public void doIndex( StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359
            URLConnection con = connect();
            InputStream in = con.getInputStream();
            rsp.serveFile(req, in, con.getLastModified(), con.getContentLength(), "*.jar" );
            in.close();
        }

        private URLConnection connect() throws IOException {
            URL res = getURL();
            return res.openConnection();
        }

        public URL getURL() throws MalformedURLException {
            URL res = Hudson.getInstance().servletContext.getResource("/WEB-INF/" + fileName);
K
kohsuke 已提交
360 361 362
            if(res==null) {
                // during the development this path doesn't have the files.
                res = new URL(new File(".").getAbsoluteFile().toURL(),"target/generated-resources/WEB-INF/"+fileName);
363
            }
K
kohsuke 已提交
364 365
            return res;
        }
366

K
kohsuke 已提交
367 368 369 370 371 372 373
        public byte[] readFully() throws IOException {
            InputStream in = connect().getInputStream();
            try {
                return IOUtils.toByteArray(in);
            } finally {
                in.close();
            }
374 375 376 377
        }

    }

K
kohsuke 已提交
378
    public Launcher createLauncher(TaskListener listener) {
379
        SlaveComputer c = getComputer();
380
        return new RemoteLauncher(listener, c.getChannel(), c.isUnix());
K
kohsuke 已提交
381 382
    }

K
kohsuke 已提交
383
    /**
384
     * Gets the corresponding computer object.
K
kohsuke 已提交
385
     */
386 387
    public SlaveComputer getComputer() {
        return (SlaveComputer)Hudson.getInstance().getComputer(this);
K
kohsuke 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    }

    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 已提交
403 404 405 406 407 408 409 410 411
    /**
     * 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";
        }
412 413 414 415
        if (launcher == null) {
            launcher = (agentCommand == null || agentCommand.trim().length() == 0)
                    ? new JNLPLauncher()
                    : new CommandLauncher(agentCommand);
416
        }
417 418
        if(nodeProperties==null)
            nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(Hudson.getInstance());
K
kohsuke 已提交
419 420 421
        return this;
    }

K
kohsuke 已提交
422 423 424
    public SlaveDescriptor getDescriptor() {
        return (SlaveDescriptor)Hudson.getInstance().getDescriptor(getClass());
    }
425 426

    public static abstract class SlaveDescriptor extends NodeDescriptor {
K
kohsuke 已提交
427 428
        public FormValidation doCheckNumExecutors(@QueryParameter String value) {
            return FormValidation.validateNonNegativeInteger(value);
429
        }
K
kohsuke 已提交
430 431 432 433

        /**
         * Performs syntactical check on the remote FS for slaves.
         */
K
kohsuke 已提交
434 435 436
        public FormValidation doCheckRemoteFs(@QueryParameter String value) throws IOException, ServletException {
            if(Util.fixEmptyAndTrim(value)==null)
                return FormValidation.error("Remote directory is mandatory");
K
kohsuke 已提交
437

K
kohsuke 已提交
438 439 440
            if(value.startsWith("\\\\") || value.startsWith("/net/"))
                return FormValidation.warning("Are you sure you want to use network mounted file system for FS root? " +
                        "Note that this directory needs not be visible to the master.");
K
kohsuke 已提交
441

K
kohsuke 已提交
442
            return FormValidation.ok();
K
kohsuke 已提交
443
        }
444 445 446
    }


K
kohsuke 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
//
// 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;
466 467 468 469 470 471
    /**
     * Command line to launch the agent, like
     * "ssh myslave java -jar /path/to/hudson-remoting.jar"
     */
    private transient String agentCommand;

K
kohsuke 已提交
472 473 474 475 476 477 478 479 480 481
    /**
     * Obtains the system clock.
     */
    private static final class GetSystemTime implements Callable<Long,RuntimeException> {
        public Long call() {
            return System.currentTimeMillis();
        }

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