Slave.java 13.2 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 33
import hudson.remoting.Callable;
import hudson.remoting.VirtualChannel;
34 35 36 37 38 39 40 41 42
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 已提交
43
import hudson.util.ClockDifference;
44
import hudson.util.DescribableList;
K
kohsuke 已提交
45
import hudson.util.FormValidation;
K
kohsuke 已提交
46

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

import javax.servlet.ServletException;

60
import jenkins.model.Jenkins;
61 62
import org.apache.commons.io.IOUtils;
import org.kohsuke.stapler.DataBoundConstructor;
63
import org.kohsuke.stapler.HttpResponse;
64 65 66
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
kohsuke 已提交
67

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

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

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

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

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

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

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

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

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

129
    @DataBoundConstructor
K
kohsuke 已提交
130
    public Slave(String name, String nodeDescription, String remoteFS, String numExecutors,
K
kohsuke 已提交
131 132
                 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 已提交
133 134
    }

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

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

K
kohsuke 已提交
161 162
//        if (remoteFS.equals(""))
//            throw new FormException(Messages.Slave_InvalidConfig_NoRemoteDir(name), null);
163

164
        if (this.numExecutors<=0)
K
i18n  
kohsuke 已提交
165
            throw new FormException(Messages.Slave_InvalidConfig_Executors(name), null);
K
kohsuke 已提交
166 167
    }

168
    public ComputerLauncher getLauncher() {
169
        return launcher == null ? new JNLPLauncher() : launcher;
170 171
    }

172
    public void setLauncher(ComputerLauncher launcher) {
173
        this.launcher = launcher;
K
kohsuke 已提交
174 175 176 177 178 179
    }

    public String getRemoteFS() {
        return remoteFS;
    }

K
kohsuke 已提交
180 181
    public String getNodeName() {
        return name;
K
kohsuke 已提交
182 183
    }

K
kohsuke 已提交
184 185 186 187
    public void setNodeName(String name) {
        this.name = name; 
    }

K
kohsuke 已提交
188 189 190 191 192 193 194 195 196 197 198 199
    public String getNodeDescription() {
        return description;
    }

    public int getNumExecutors() {
        return numExecutors;
    }

    public Mode getMode() {
        return mode;
    }

K
kohsuke 已提交
200 201 202 203
    public void setMode(Mode mode) {
        this.mode = mode;
    }

204 205 206 207
    public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
    	return nodeProperties;
    }
    
K
kohsuke 已提交
208 209
    public RetentionStrategy getRetentionStrategy() {
        return retentionStrategy == null ? RetentionStrategy.Always.INSTANCE : retentionStrategy;
210 211
    }

K
kohsuke 已提交
212 213
    public void setRetentionStrategy(RetentionStrategy availabilityStrategy) {
        this.retentionStrategy = availabilityStrategy;
214 215
    }

216 217 218
    public String getLabelString() {
        return Util.fixNull(label).trim();
    }
219

220
    public ClockDifference getClockDifference() throws IOException, InterruptedException {
K
kohsuke 已提交
221
        VirtualChannel channel = getChannel();
K
kohsuke 已提交
222 223
        if(channel==null)
            throw new IOException(getNodeName()+" is offline");
K
kohsuke 已提交
224

K
kohsuke 已提交
225
        long startTime = System.currentTimeMillis();
K
kohsuke 已提交
226
        long slaveTime = channel.call(new GetSystemTime());
K
kohsuke 已提交
227
        long endTime = System.currentTimeMillis();
K
kohsuke 已提交
228

229
        return new ClockDifference((startTime+endTime)/2 - slaveTime);
K
kohsuke 已提交
230 231
    }

K
kohsuke 已提交
232
    public Computer createComputer() {
233
        return new SlaveComputer(this);
K
kohsuke 已提交
234 235
    }

236
    public FilePath getWorkspaceFor(TopLevelItem item) {
K
kohsuke 已提交
237 238 239
        FilePath r = getWorkspaceRoot();
        if(r==null)     return null;    // offline
        return r.child(item.getName());
240 241
    }

K
kohsuke 已提交
242
    public FilePath getRootPath() {
243 244 245
        return createPath(remoteFS);
    }

K
kohsuke 已提交
246 247
    /**
     * Root directory on this slave where all the job workspaces are laid out.
K
kohsuke 已提交
248 249
     * @return
     *      null if not connected.
K
kohsuke 已提交
250 251
     */
    public FilePath getWorkspaceRoot() {
K
kohsuke 已提交
252 253
        FilePath r = getRootPath();
        if(r==null) return null;
254
        return r.child(WORKSPACE_ROOT);
K
kohsuke 已提交
255
    }
K
kohsuke 已提交
256

257 258 259
    /**
     * Web-bound object used to serve jar files for JNLP.
     */
260
    public static final class JnlpJar implements HttpResponse {
K
kohsuke 已提交
261
        private final String fileName;
262

K
kohsuke 已提交
263 264
        public JnlpJar(String fileName) {
            this.fileName = fileName;
265 266 267
        }

        public void doIndex( StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
268
            URLConnection con = connect();
269 270
            // 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.
271 272
            // 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 已提交
273 274 275 276 277
            InputStream in = con.getInputStream();
            rsp.serveFile(req, in, con.getLastModified(), con.getContentLength(), "*.jar" );
            in.close();
        }

278 279 280 281
        public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
            doIndex(req,rsp);
        }

K
kohsuke 已提交
282 283 284 285 286 287
        private URLConnection connect() throws IOException {
            URL res = getURL();
            return res.openConnection();
        }

        public URL getURL() throws MalformedURLException {
288 289
            String name = fileName;
            if (name.equals("hudson-cli.jar"))  name="jenkins-cli.jar";
290
            URL res = Jenkins.getInstance().servletContext.getResource("/WEB-INF/" + name);
K
kohsuke 已提交
291 292
            if(res==null) {
                // during the development this path doesn't have the files.
293
                res = new URL(new File(".").getAbsoluteFile().toURI().toURL(),"target/generated-resources/WEB-INF/"+name);
294
            }
K
kohsuke 已提交
295 296
            return res;
        }
297

K
kohsuke 已提交
298 299 300 301 302 303 304
        public byte[] readFully() throws IOException {
            InputStream in = connect().getInputStream();
            try {
                return IOUtils.toByteArray(in);
            } finally {
                in.close();
            }
305 306 307 308
        }

    }

K
kohsuke 已提交
309
    public Launcher createLauncher(TaskListener listener) {
310
        SlaveComputer c = getComputer();
K
kohsuke 已提交
311
        return new RemoteLauncher(listener, c.getChannel(), c.isUnix()).decorateFor(this);
K
kohsuke 已提交
312 313
    }

K
kohsuke 已提交
314
    /**
315
     * Gets the corresponding computer object.
K
kohsuke 已提交
316
     */
317
    public SlaveComputer getComputer() {
318
        return (SlaveComputer)toComputer();
K
kohsuke 已提交
319 320
    }

321
    @Override
K
kohsuke 已提交
322 323 324 325 326 327 328 329 330
    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);
    }

331
    @Override
K
kohsuke 已提交
332 333 334 335
    public int hashCode() {
        return name.hashCode();
    }

K
kohsuke 已提交
336 337 338 339 340
    /**
     * Invoked by XStream when this object is read into memory.
     */
    private Object readResolve() {
        // convert the old format to the new one
341 342 343 344
        if (launcher == null) {
            launcher = (agentCommand == null || agentCommand.trim().length() == 0)
                    ? new JNLPLauncher()
                    : new CommandLauncher(agentCommand);
345
        }
346
        if(nodeProperties==null)
347
            nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(Jenkins.getInstance());
K
kohsuke 已提交
348 349 350
        return this;
    }

K
kohsuke 已提交
351
    public SlaveDescriptor getDescriptor() {
352
        Descriptor d = Jenkins.getInstance().getDescriptorOrDie(getClass());
353 354 355
        if (d instanceof SlaveDescriptor)
            return (SlaveDescriptor) d;
        throw new IllegalStateException(d.getClass()+" needs to extend from SlaveDescriptor");
K
kohsuke 已提交
356
    }
357 358

    public static abstract class SlaveDescriptor extends NodeDescriptor {
K
kohsuke 已提交
359
        public FormValidation doCheckNumExecutors(@QueryParameter String value) {
360
            return FormValidation.validatePositiveInteger(value);
361
        }
K
kohsuke 已提交
362 363 364 365

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

K
kohsuke 已提交
370
            if(value.startsWith("\\\\") || value.startsWith("/net/"))
371
                return FormValidation.warning(Messages.Slave_Network_Mounted_File_System_Warning());
K
kohsuke 已提交
372

K
kohsuke 已提交
373
            return FormValidation.ok();
K
kohsuke 已提交
374
        }
375 376 377
    }


K
kohsuke 已提交
378
//
379
// backward compatibility
K
kohsuke 已提交
380
//
381 382 383
    /**
     * Command line to launch the agent, like
     * "ssh myslave java -jar /path/to/hudson-remoting.jar"
384
     * @deprecated in 1.216
385 386 387
     */
    private transient String agentCommand;

K
kohsuke 已提交
388 389 390 391 392 393 394 395 396 397
    /**
     * 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;
    }
398 399 400 401 402

    /**
     * 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 已提交
403
}