Hudson.java 107.3 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, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe, 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
package hudson.model;

S
sogabe 已提交
26
import com.thoughtworks.xstream.XStream;
27
import hudson.BulkChange;
28
import hudson.FilePath;
29
import hudson.Functions;
K
kohsuke 已提交
30
import hudson.Launcher;
S
sogabe 已提交
31
import hudson.Launcher.LocalLauncher;
K
kohsuke 已提交
32 33 34
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
35
import hudson.ProxyConfiguration;
36
import hudson.StructuredForm;
K
kohsuke 已提交
37
import hudson.TcpSlaveAgentListener;
38
import hudson.Util;
S
sogabe 已提交
39
import static hudson.Util.fixEmpty;
40
import hudson.WebAppMain;
41
import hudson.XmlFile;
42
import hudson.UDPBroadcastThread;
43 44
import hudson.ExtensionList;
import hudson.ExtensionPoint;
45
import hudson.DescriptorExtensionList;
46
import hudson.ExtensionListView;
K
kohsuke 已提交
47
import hudson.LauncherDecorator;
48
import hudson.logging.LogRecorderManager;
K
kohsuke 已提交
49
import hudson.lifecycle.Lifecycle;
K
kohsuke 已提交
50
import hudson.model.Descriptor.FormException;
51
import hudson.model.listeners.ItemListener;
K
kohsuke 已提交
52
import hudson.model.listeners.JobListener;
53
import hudson.model.listeners.JobListener.JobListenerAdapter;
S
sogabe 已提交
54
import hudson.model.listeners.SCMListener;
K
kohsuke 已提交
55 56
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
K
kohsuke 已提交
57
import hudson.scm.CVSSCM;
K
kohsuke 已提交
58
import hudson.scm.RepositoryBrowser;
59 60
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
61
import hudson.scm.SubversionSCM;
K
kohsuke 已提交
62
import hudson.search.CollectionSearchIndex;
63
import hudson.search.SearchIndexBuilder;
64
import hudson.security.ACL;
65
import hudson.security.AccessControlled;
66
import hudson.security.AuthorizationStrategy;
K
kohsuke 已提交
67
import hudson.security.BasicAuthenticationFilter;
68 69 70 71
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
72
import hudson.security.PermissionGroup;
K
kohsuke 已提交
73
import hudson.security.SecurityMode;
74
import hudson.security.SecurityRealm;
75
import hudson.slaves.ComputerListener;
76 77
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
78
import hudson.slaves.RetentionStrategy;
K
kohsuke 已提交
79 80 81 82 83
import hudson.slaves.NodeList;
import hudson.slaves.Cloud;
import hudson.slaves.DumbSlave;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeProvisioner;
84 85 86 87 88 89
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.DynamicLabeler;
import hudson.tasks.LabelFinder;
import hudson.tasks.Mailer;
import hudson.tasks.Publisher;
K
kohsuke 已提交
90
import hudson.triggers.Trigger;
91
import hudson.triggers.TriggerDescriptor;
K
kohsuke 已提交
92
import hudson.util.CaseInsensitiveComparator;
K
kohsuke 已提交
93 94 95 96 97 98
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.HudsonIsLoading;
import hudson.util.MultipartFormDataParser;
K
kohsuke 已提交
99
import hudson.util.RemotingDiagnostics;
100
import hudson.util.TextFile;
K
kohsuke 已提交
101
import hudson.util.XStream2;
K
kohsuke 已提交
102
import hudson.util.HudsonIsRestarting;
K
kohsuke 已提交
103 104
import hudson.util.DescribableList;
import hudson.util.Futures;
105
import hudson.util.Memoizer;
106
import hudson.util.Iterators;
107
import hudson.util.FormValidation;
K
kohsuke 已提交
108
import hudson.widgets.Widget;
S
sogabe 已提交
109
import net.sf.json.JSONObject;
110
import org.acegisecurity.*;
S
sogabe 已提交
111 112 113 114
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import static org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY;
K
kohsuke 已提交
115
import org.apache.commons.logging.LogFactory;
116 117
import org.apache.commons.jelly.Script;
import org.apache.commons.jelly.JellyException;
118 119
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FileUtils;
S
sogabe 已提交
120 121 122 123 124
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
125
import org.kohsuke.stapler.StaplerFallback;
126
import org.kohsuke.stapler.WebApp;
127
import org.kohsuke.stapler.QueryParameter;
128 129
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
K
kohsuke 已提交
130
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
S
sogabe 已提交
131
import org.kohsuke.stapler.export.Exported;
132
import org.kohsuke.stapler.export.ExportedBean;
133
import org.xml.sax.InputSource;
K
kohsuke 已提交
134

S
sogabe 已提交
135 136 137 138 139 140 141 142
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import javax.servlet.http.HttpSession;
K
kohsuke 已提交
143 144 145
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
146
import java.io.FileOutputStream;
K
kohsuke 已提交
147 148
import java.io.IOException;
import java.io.PrintWriter;
K
kohsuke 已提交
149
import java.io.InputStream;
150
import java.net.URL;
151
import java.security.SecureRandom;
152
import java.text.NumberFormat;
K
kohsuke 已提交
153
import java.text.ParseException;
154
import java.text.Collator;
K
kohsuke 已提交
155 156 157 158 159 160 161
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
162
import java.util.Iterator;
K
kohsuke 已提交
163 164
import java.util.List;
import java.util.Map;
S
sogabe 已提交
165
import java.util.Map.Entry;
K
kohsuke 已提交
166
import java.util.Set;
167 168
import java.util.Stack;
import java.util.StringTokenizer;
169
import java.util.Timer;
K
kohsuke 已提交
170
import java.util.TreeSet;
K
kohsuke 已提交
171
import java.util.Properties;
172
import java.util.concurrent.Callable;
173
import java.util.concurrent.ConcurrentHashMap;
K
kohsuke 已提交
174
import java.util.concurrent.CopyOnWriteArrayList;
175 176 177 178 179
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
180
import java.util.concurrent.LinkedBlockingQueue;
K
kohsuke 已提交
181
import java.util.concurrent.TimeoutException;
182
import java.util.concurrent.CopyOnWriteArraySet;
K
kohsuke 已提交
183
import java.util.logging.Level;
K
kohsuke 已提交
184
import java.util.logging.LogRecord;
185
import java.util.logging.Logger;
186
import java.util.regex.Pattern;
187
import java.nio.charset.Charset;
188
import javax.servlet.RequestDispatcher;
K
kohsuke 已提交
189

190 191
import groovy.lang.GroovyShell;

K
kohsuke 已提交
192 193 194 195 196
/**
 * Root object of the system.
 *
 * @author Kohsuke Kawaguchi
 */
197
@ExportedBean
198
public final class Hudson extends Node implements ItemGroup<TopLevelItem>, StaplerProxy, StaplerFallback, ViewGroup, AccessControlled, DescriptorByNameOwner {
199
    private transient final Queue queue;
K
kohsuke 已提交
200 201 202 203

    /**
     * {@link Computer}s in this Hudson system. Read-only.
     */
K
kohsuke 已提交
204
    private transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
K
kohsuke 已提交
205 206 207 208 209 210

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

211 212 213 214 215
    /**
     * Job allocation strategy.
     */
    private Mode mode = Mode.NORMAL;

K
kohsuke 已提交
216 217
    /**
     * False to enable anyone to do anything.
K
kohsuke 已提交
218
     * Left as a field so that we can still read old data that uses this flag.
219 220 221
     *
     * @see #authorizationStrategy
     * @see #securityRealm
K
kohsuke 已提交
222
     */
K
kohsuke 已提交
223
    private Boolean useSecurity;
K
kohsuke 已提交
224 225

    /**
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
     * Controls how the
     * <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
     * is handled in Hudson.
     * <p>
     * This ultimately controls who has access to what.
     *
     * Never null.
     */
    private volatile AuthorizationStrategy authorizationStrategy;

    /**
     * Controls a part of the
     * <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
     * handling in Hudson.
     * <p>
     * Intuitively, this corresponds to the user database.
     *
243
     * See {@link HudsonFilter} for the concrete authentication protocol.
244
     *
245 246
     * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
     * update this field.
247 248
     *
     * @see #getSecurity()
249
     * @see #setSecurityRealm(SecurityRealm)
K
kohsuke 已提交
250
     */
251
    private volatile SecurityRealm securityRealm;
K
kohsuke 已提交
252 253 254 255 256 257 258 259 260 261 262

    /**
     * Message displayed in the top page.
     */
    private String systemMessage;

    /**
     * Root directory of the system.
     */
    public transient final File root;

263 264 265
    /**
     * All {@link Item}s keyed by their {@link Item#getName() name}s.
     */
K
kohsuke 已提交
266
    /*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
267

K
kohsuke 已提交
268 269 270 271 272
    /**
     * The sole instance.
     */
    private static Hudson theInstance;

K
kohsuke 已提交
273 274
    private transient volatile boolean isQuietingDown;
    private transient volatile boolean terminating;
K
kohsuke 已提交
275

276
    private List<JDK> jdks = new ArrayList<JDK>();
K
kohsuke 已提交
277

278
    private transient volatile DependencyGraph dependencyGraph;
279

280 281 282
    /**
     * All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
     */
283 284 285 286 287
    private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
        public ExtensionList compute(Class key) {
            return ExtensionList.create(Hudson.this,key);
        }
    };
288 289

    /**
290
     * All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
291
     */
292 293
    private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
        public DescriptorExtensionList compute(Class key) {
294
            return DescriptorExtensionList.create(Hudson.this,key);
295 296
        }
    };
297

K
kohsuke 已提交
298 299 300 301 302 303 304 305 306 307
    /**
     * Active {@link Cloud}s.
     */
    public final CloudList clouds = new CloudList(this);

    public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
        public CloudList(Hudson h) {
            super(h);
        }

K
kohsuke 已提交
308 309 310
        public CloudList() {// needed for XStream deserialization
        }

K
kohsuke 已提交
311 312 313 314 315 316
        protected void onModified() throws IOException {
            super.onModified();
            Hudson.getInstance().trimLabels();
        }
    }

K
kohsuke 已提交
317 318
    /**
     * Set of installed cluster nodes.
K
kohsuke 已提交
319
     * <p>
K
kohsuke 已提交
320 321 322 323
     * We use this field with copy-on-write semantics.
     * This field has mutable list (to keep the serialization look clean),
     * but it shall never be modified. Only new completely populated slave
     * list can be set here.
K
kohsuke 已提交
324 325 326
     * <p>
     * The field name should be really {@code nodes}, but again the backward compatibility
     * prevents us from renaming.
K
kohsuke 已提交
327
     */
K
kohsuke 已提交
328
    private volatile NodeList slaves;
K
kohsuke 已提交
329 330 331 332 333 334 335 336 337

    /**
     * Quiet period.
     *
     * This is {@link Integer} so that we can initialize it to '5' for upgrading users.
     */
    /*package*/ Integer quietPeriod;

    /**
338
     * {@link View}s.
K
kohsuke 已提交
339
     */
340 341 342 343
    private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();

    /**
     * Name of the primary view.
344 345 346
     * <p>
     * Start with null, so that we can upgrade pre-1.269 data well.
     * @since 1.269
347 348
     */
    private volatile String primaryView;
349

K
kohsuke 已提交
350 351 352 353 354 355 356
    private transient final FingerprintMap fingerprintMap = new FingerprintMap();

    /**
     * Loaded plugins.
     */
    public transient final PluginManager pluginManager;

357
    public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
K
kohsuke 已提交
358

359 360
    private transient UDPBroadcastThread udpBroadcastThread;

361
    /**
M
mindless 已提交
362
     * List of registered {@link ItemListener}s.
363
     * @deprecated as of 1.286
364
     */
365
    private transient final CopyOnWriteList<ItemListener> itemListeners = ExtensionListView.createCopyOnWriteList(ItemListener.class);
366 367 368 369 370

    /**
     * List of registered {@link SCMListener}s.
     */
    private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
371

372 373
    /**
     * List of registered {@link ComputerListener}s.
374
     * @deprecated as of 1.286
375
     */
376
    private transient final CopyOnWriteList<ComputerListener> computerListeners = ExtensionListView.createCopyOnWriteList(ComputerListener.class);
377

378 379
    /**
     * TCP slave agent port.
380
     * 0 for random, -1 to disable.
381 382 383
     */
    private int slaveAgentPort =0;

384 385 386 387 388
    /**
     * Whitespace-separated labels assigned to the master as a {@link Node}.
     */
    private String label="";

389 390 391 392 393
    /**
     * All labels known to Hudson. This allows us to reuse the same label instances
     * as much as possible, even though that's not a strict requirement.
     */
    private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
394
    private transient volatile Set<Label> labelSet;
395
    private transient volatile Set<Label> dynamicLabels = null;
396

K
kohsuke 已提交
397 398 399 400 401 402 403 404 405 406
    /**
     * Load statistics of the entire system.
     */
    public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();

    /**
     * {@link NodeProvisioner} that reacts to {@link OverallLoadStatistics}.
     */
    public transient final NodeProvisioner overallNodeProvisioner = new NodeProvisioner(null,overallLoad);

407 408
    public transient final ServletContext servletContext;

K
kohsuke 已提交
409 410 411 412 413 414
    /**
     * Transient action list. Useful for adding navigation items to the navigation bar
     * on the left.
     */
    private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();

415
    /**
416
     * List of master node properties
417 418 419
     */
    private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);

420 421 422 423 424
    /**
     * List of global properties
     */
    private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);

425 426 427 428 429
    /**
     * {@link AdministrativeMonitor}s installed on this system.
     *
     * @see AdministrativeMonitor
     */
430
    public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
431

K
kohsuke 已提交
432
    /*package*/ final CopyOnWriteArraySet<String> disabledAdministrativeMonitors = new CopyOnWriteArraySet<String>();
433

434 435 436 437 438
    /**
     * Widgets on Hudson.
     */
    private transient final List<Widget> widgets = getExtensionList(Widget.class);

K
kohsuke 已提交
439 440 441 442 443
    /**
     * {@link AdjunctManager}
     */
    private transient final AdjunctManager adjuncts;

K
kohsuke 已提交
444 445 446 447
    public static Hudson getInstance() {
        return theInstance;
    }

448 449
    /**
     * Secrete key generated once and used for a long time, beyond
K
kohsuke 已提交
450 451
     * container start/stop. Persisted outside <tt>config.xml</tt> to avoid
     * accidental exposure.
452
     */
K
kohsuke 已提交
453
    private transient final String secretKey;
454

455
    private transient final UpdateCenter updateCenter = new UpdateCenter(this);
K
kohsuke 已提交
456

457 458 459 460 461
    /**
     * True if the user opted out from the statistics tracking. We'll never send anything if this is true.
     */
    private Boolean noUsageStatistics;

462 463 464 465 466
    /**
     * HTTP proxy configuration.
     */
    public transient volatile ProxyConfiguration proxy;

K
kohsuke 已提交
467
    /**
468
     * Bound to "/log".
K
kohsuke 已提交
469
     */
470
    private transient final LogRecorderManager log = new LogRecorderManager();
471

K
kohsuke 已提交
472 473
    public Hudson(File root, ServletContext context) throws IOException {
        this.root = root;
474
        this.servletContext = context;
K
kohsuke 已提交
475
        computeVersion(context);
K
kohsuke 已提交
476 477 478
        if(theInstance!=null)
            throw new IllegalStateException("second instance");
        theInstance = this;
479 480

        log.load();
481

K
kohsuke 已提交
482
        Trigger.timer = new Timer("Hudson cron thread");
483
        queue = new Queue();
K
kohsuke 已提交
484

485 486 487 488 489 490 491 492 493
        try {
            dependencyGraph = DependencyGraph.EMPTY;
        } catch (InternalError e) {
            if(e.getMessage().contains("window server")) {
                throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
            }
            throw e;
        }

494 495 496 497 498 499 500 501 502 503 504 505
        // get or create the secret
        TextFile secretFile = new TextFile(new File(Hudson.getInstance().getRootDir(),"secret.key"));
        if(secretFile.exists()) {
            secretKey = secretFile.readTrim();
        } else {
            SecureRandom sr = new SecureRandom();
            byte[] random = new byte[32];
            sr.nextBytes(random);
            secretKey = Util.toHexString(random);
            secretFile.write(secretKey);
        }

506 507 508 509 510 511
        try {
            proxy = ProxyConfiguration.load();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to load proxy configuration", e);
        }

512
        // run the init code of SubversionSCM before we load plugins so that plugins can change SubversionWorkspaceSelector.
K
kohsuke 已提交
513
        SubversionSCM.init();
514

K
kohsuke 已提交
515 516 517
        // load plugins.
        pluginManager = new PluginManager(context);

K
kohsuke 已提交
518
        // if we are loading old data that doesn't have this field
K
kohsuke 已提交
519
        if(slaves==null)    slaves = new NodeList();
K
kohsuke 已提交
520

K
kohsuke 已提交
521
        adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+VERSION_HASH);
522

K
kohsuke 已提交
523
        load();
524

525 526 527 528 529 530 531 532 533 534 535 536 537
//        try {
//            // fill up the cache
//            load();
//
//            Controller c = new Controller();
//            c.startCPUProfiling(ProfilingModes.CPU_TRACING,""); // "java.*");
//            load();
//            c.stopCPUProfiling();
//            c.captureSnapshot(ProfilingModes.SNAPSHOT_WITHOUT_HEAP);
//        } catch (Exception e) {
//            throw new Error(e);
//        }

538 539 540 541 542
        if(slaveAgentPort!=-1)
            tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
        else
            tcpSlaveAgentListener = null;

543 544 545
        udpBroadcastThread = new UDPBroadcastThread(this);
        udpBroadcastThread.start();

K
kohsuke 已提交
546 547 548
        updateComputerList();

        getQueue().load();
K
kohsuke 已提交
549

550
        for (ItemListener l : ItemListener.all())
551
            l.onLoaded();
552

553 554 555 556 557 558 559 560 561 562 563
        // run the initialization script, if it exists.
        File initScript = new File(getRootDir(),"init.groovy");
        if(initScript.exists()) {
            LOGGER.info("Executing "+initScript);
            GroovyShell shell = new GroovyShell();
            try {
                shell.evaluate(initScript);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
564

565 566 567 568 569 570
        File userContentDir = new File(getRootDir(), "userContent");
        if(!userContentDir.exists()) {
            userContentDir.mkdirs();
            FileUtils.writeStringToFile(new File(userContentDir,"readme.txt"),Messages.Hudson_USER_CONTENT_README());
        }

571
        Trigger.init(); // start running trigger
K
kohsuke 已提交
572 573
    }

K
kohsuke 已提交
574 575 576 577
    public TcpSlaveAgentListener getTcpSlaveAgentListener() {
        return tcpSlaveAgentListener;
    }

K
kohsuke 已提交
578 579 580 581 582 583 584 585 586
    /**
     * Makes {@link AdjunctManager} URL-bound.
     * The dummy parameter allows us to use different URLs for the same adjunct,
     * for proper cache handling.
     */
    public AdjunctManager getAdjuncts(String dummy) {
        return adjuncts;
    }

K
kohsuke 已提交
587
    @Exported
588 589 590 591
    public int getSlaveAgentPort() {
        return slaveAgentPort;
    }

K
kohsuke 已提交
592
    /**
J
jglick 已提交
593
     * If you are calling this on Hudson something is wrong.
K
kohsuke 已提交
594 595 596
     *
     * @deprecated
     */
J
jglick 已提交
597
    @Deprecated
K
kohsuke 已提交
598 599 600 601
    public String getNodeName() {
        return "";
    }

K
kohsuke 已提交
602 603 604 605
    public void setNodeName(String name) {
        throw new UnsupportedOperationException(); // not allowed
    }

K
kohsuke 已提交
606 607 608 609
    public String getNodeDescription() {
        return "the master Hudson node";
    }

610
    @Exported
K
kohsuke 已提交
611 612 613 614 615 616 617
    public String getDescription() {
        return systemMessage;
    }

    public PluginManager getPluginManager() {
        return pluginManager;
    }
618

619 620 621
    public UpdateCenter getUpdateCenter() {
        return updateCenter;
    }
K
kohsuke 已提交
622

623 624 625 626
    public boolean isUsageStatisticsCollected() {
        return noUsageStatistics==null || !noUsageStatistics;
    }

627 628 629 630 631
    public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
        this.noUsageStatistics = noUsageStatistics;
        save();
    }

632 633 634 635 636 637 638 639 640 641 642 643
    public View.People getPeople() {
        return new View.People(this);
    }

    /**
     * Does this {@link View} has any associated user information recorded?
     */
    public final boolean hasPeople() {
        return View.People.isApplicable(items.values());
    }

    public Api getApi() {
644
        return new Api(this);
645 646
    }

647 648 649
    /**
     * Returns a secret key that survives across container start/stop.
     * <p>
650
     * This value is useful for implementing some of the security features.
651 652
     */
    public String getSecretKey() {
K
kohsuke 已提交
653
        return secretKey;
654 655
    }

K
kohsuke 已提交
656 657 658 659
    /**
     * Gets the SCM descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<SCM> getScm(String shortClassName) {
660
        return findDescriptor(shortClassName,SCM.all());
K
kohsuke 已提交
661 662
    }

K
kohsuke 已提交
663 664 665 666
    /**
     * Gets the repository browser descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
667
        return findDescriptor(shortClassName,RepositoryBrowser.all());
K
kohsuke 已提交
668 669
    }

K
kohsuke 已提交
670 671 672 673
    /**
     * Gets the builder descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<Builder> getBuilder(String shortClassName) {
674
        return findDescriptor(shortClassName, Builder.all());
K
kohsuke 已提交
675 676
    }

K
kohsuke 已提交
677 678 679 680
    /**
     * Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
681
        return findDescriptor(shortClassName, BuildWrapper.all());
K
kohsuke 已提交
682 683
    }

K
kohsuke 已提交
684 685 686 687
    /**
     * Gets the publisher descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<Publisher> getPublisher(String shortClassName) {
688
        return findDescriptor(shortClassName, Publisher.all());
K
kohsuke 已提交
689 690
    }

K
kohsuke 已提交
691 692 693
    /**
     * Gets the trigger descriptor by name. Primarily used for making them web-visible.
     */
694
    public TriggerDescriptor getTrigger(String shortClassName) {
695
        return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
696 697 698 699 700 701
    }

    /**
     * Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
702
        return findDescriptor(shortClassName, RetentionStrategy.all());
K
kohsuke 已提交
703 704
    }

705 706 707 708
    /**
     * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
     */
    public JobPropertyDescriptor getJobProperty(String shortClassName) {
K
kohsuke 已提交
709
        // combining these two lines triggers javac bug. See issue #610.
710
        Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
K
kohsuke 已提交
711
        return (JobPropertyDescriptor) d;
712 713
    }

714 715 716 717 718
    /**
     * Exposes {@link Descriptor} by its name to URL.
     *
     * After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
     * this just doesn't scale.
719 720 721
     *
     * @param className
     *      Either fully qualified class name (recommended) or the short name.
722
     */
723
    public Descriptor getDescriptor(String className) {
724
        // legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
725 726 727 728 729
        for( Descriptor d : Iterators.sequence(getExtensionList(Descriptor.class),DescriptorExtensionList.listLegacyInstances()) ) {
            String name = d.clazz.getName();
            if(name.equals(className))
                return d;
            if(name.substring(name.lastIndexOf('.')+1).equals(className))
730
                return d;
731
        }
732 733 734
        return null;
    }

735 736 737 738 739 740 741
    /**
     * Alias for {@link #getDescriptor(String)}.
     */
    public Descriptor getDescriptorByName(String className) {
        return getDescriptor(className);
    }

K
kohsuke 已提交
742 743 744 745 746 747
    /**
     * Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
     * <p>
     * If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
     * you'll get the same instance that this method returns.
     */
748
    public Descriptor getDescriptor(Class<? extends Describable> type) {
749
        for( Descriptor d : getExtensionList(Descriptor.class) )
750 751 752 753 754
            if(d.clazz==type)
                return d;
        return null;
    }

755 756 757 758 759 760 761 762 763 764
    /**
     * Gets the {@link Descriptor} instance in the current Hudson by its type.
     */
    public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
        for( Descriptor d : getExtensionList(Descriptor.class) )
            if(d.getClass()==type)
                return type.cast(d);
        return null;
    }

765 766 767 768
    /**
     * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
     */
    public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
769
        return findDescriptor(shortClassName,SecurityRealm.all());
770 771
    }

K
kohsuke 已提交
772 773 774 775
    /**
     * Finds a descriptor that has the specified name.
     */
    private <T extends Describable<T>>
776
    Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
K
kohsuke 已提交
777 778 779 780 781 782 783 784
        String name = '.'+shortClassName;
        for (Descriptor<T> d : descriptors) {
            if(d.clazz.getName().endsWith(name))
                return d;
        }
        return null;
    }

785 786 787
    /**
     * Adds a new {@link JobListener}.
     *
788
     * @deprecated
M
mindless 已提交
789
     *      Use {@code getJobListeners().add(l)} instead.
790 791
     */
    public void addListener(JobListener l) {
K
kohsuke 已提交
792
        itemListeners.add(new JobListenerAdapter(l));
793 794 795 796 797
    }

    /**
     * Deletes an existing {@link JobListener}.
     *
798
     * @deprecated
M
mindless 已提交
799
     *      Use {@code getJobListeners().remove(l)} instead.
800 801
     */
    public boolean removeListener(JobListener l ) {
K
kohsuke 已提交
802
        return itemListeners.remove(new JobListenerAdapter(l));
803 804
    }

805
    /**
806
     * Gets all the installed {@link ItemListener}s.
807 808 809
     *
     * @deprecated as of 1.286.
     *      Use {@link ItemListener#all()}.
810
     */
811
    public CopyOnWriteList<ItemListener> getJobListeners() {
K
kohsuke 已提交
812
        return itemListeners;
813 814 815 816 817 818 819 820 821
    }

    /**
     * Gets all the installed {@link SCMListener}s.
     */
    public CopyOnWriteList<SCMListener> getSCMListeners() {
        return scmListeners;
    }

822 823
    /**
     * Gets all the installed {@link ComputerListener}s.
824 825
     *
     * @deprecated as of 1.286.
826
     *      Use {@link ComputerListener#all()}.
827 828 829 830 831
     */
    public CopyOnWriteList<ComputerListener> getComputerListeners() {
        return computerListeners;
    }

K
kohsuke 已提交
832 833 834 835 836 837 838 839 840 841
    /**
     * Gets the plugin object from its short name.
     *
     * <p>
     * This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
     * of the plugin class.
     */
    public Plugin getPlugin(String shortName) {
        PluginWrapper p = pluginManager.getPlugin(shortName);
        if(p==null)     return null;
842
        return p.getPlugin();
K
kohsuke 已提交
843 844
    }

845 846 847 848 849 850 851 852 853 854 855 856
    /**
     * Gets the plugin object from its class.
     *
     * <p>
     * This allows easy storage of plugin information in the plugin singleton without
     * every plugin reimplementing the singleton pattern.
     *
     * @param clazz The plugin class (beware class-loader fun, this will probably only work
     * from within the hpi that defines the plugin class, it may or may not work in other cases)
     *
     * @return The plugin instance.
     */
S
stephenconnolly 已提交
857 858
    @SuppressWarnings("unchecked")
    public <P extends Plugin> P getPlugin(Class<P> clazz) {
859 860
        PluginWrapper p = pluginManager.getPlugin(clazz);
        if(p==null)     return null;
S
stephenconnolly 已提交
861
        return (P) p.getPlugin();
862 863 864 865 866 867 868 869 870
    }

    /**
     * Gets the plugin objects from their super-class.
     *
     * @param clazz The plugin class (beware class-loader fun)
     *
     * @return The plugin instances.
     */
S
stephenconnolly 已提交
871 872
    public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
        List<P> result = new ArrayList<P>();
873
        for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
S
stephenconnolly 已提交
874
            result.add((P)w.getPlugin());
875 876 877 878
        }
        return Collections.unmodifiableList(result);
    }

K
kohsuke 已提交
879 880 881 882 883 884 885
    /**
     * Synonym to {@link #getNodeDescription()}.
     */
    public String getSystemMessage() {
        return systemMessage;
    }

886 887 888 889 890 891 892 893
    /**
     * Sets the system message.
     */
    public void setSystemMessage(String message) throws IOException {
        this.systemMessage = message;
        save();
    }

K
kohsuke 已提交
894
    public Launcher createLauncher(TaskListener listener) {
K
kohsuke 已提交
895
        return new LocalLauncher(listener).decorateFor(this);
K
kohsuke 已提交
896 897
    }

K
kohsuke 已提交
898 899
    private final transient Object updateComputerLock = new Object();

K
kohsuke 已提交
900 901 902 903 904 905 906
    /**
     * Updates {@link #computers} by using {@link #getSlaves()}.
     *
     * <p>
     * This method tries to reuse existing {@link Computer} objects
     * so that we won't upset {@link Executor}s running in it.
     */
K
kohsuke 已提交
907
    private void updateComputerList() throws IOException {
K
kohsuke 已提交
908
        synchronized(updateComputerLock) {// just so that we don't have two code updating computer list at the same time
K
kohsuke 已提交
909
            Map<String,Computer> byName = new HashMap<String,Computer>();
K
kohsuke 已提交
910 911 912
            for (Computer c : computers.values()) {
                if(c.getNode()==null)
                    continue;   // this computer is gone
K
kohsuke 已提交
913
                byName.put(c.getNode().getNodeName(),c);
K
kohsuke 已提交
914
            }
K
kohsuke 已提交
915 916 917 918 919

            Set<Computer> old = new HashSet<Computer>(computers.values());
            Set<Computer> used = new HashSet<Computer>();

            updateComputer(this, byName, used);
K
kohsuke 已提交
920
            for (Node s : getNodes())
K
kohsuke 已提交
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
                updateComputer(s, byName, used);

            // find out what computers are removed, and kill off all executors.
            // when all executors exit, it will be removed from the computers map.
            // so don't remove too quickly
            old.removeAll(used);
            for (Computer c : old) {
                c.kill();
            }
        }
        getQueue().scheduleMaintenance();
    }

    private void updateComputer(Node n, Map<String,Computer> byNameMap, Set<Computer> used) {
        Computer c;
        c = byNameMap.get(n.getNodeName());
K
kohsuke 已提交
937 938
        if (c!=null) {
            c.setNode(n); // reuse
K
kohsuke 已提交
939
        } else {
K
kohsuke 已提交
940
            if(n.getNumExecutors()>0) {
K
kohsuke 已提交
941
                computers.put(n,c=n.createComputer());
942 943 944
                RetentionStrategy retentionStrategy = c.getRetentionStrategy();
                if (retentionStrategy != null) {
                    // if there is a retention strategy, it is responsible for deciding to start the computer
945
                    retentionStrategy.start(c);
946 947 948 949
                } else {
                    // we should never get here, but just in case, we'll fall back to the legacy behaviour
                    c.connect(true);
                }
K
kohsuke 已提交
950
            }
K
kohsuke 已提交
951 952 953 954 955
        }
        used.add(c);
    }

    /*package*/ void removeComputer(Computer computer) {
956 957
        for (Entry<Node, Computer> e : computers.entrySet()) {
            if (e.getValue() == computer) {
K
kohsuke 已提交
958
                computers.remove(e.getKey());
959
                return;
K
kohsuke 已提交
960 961 962 963 964
            }
        }
        throw new IllegalStateException("Trying to remove unknown computer");
    }

965 966 967 968
    public String getFullName() {
        return "";
    }

969 970 971 972
    public String getFullDisplayName() {
        return "";
    }

K
kohsuke 已提交
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
    /**
     * Returns the transient {@link Action}s associated with the top page.
     *
     * <p>
     * Adding {@link Action} is primarily useful for plugins to contribute
     * an item to the navigation bar of the top page. See existing {@link Action}
     * implementation for it affects the GUI.
     *
     * <p>
     * To register an {@link Action}, write code like
     * {@code Hudson.getInstance().getActions().add(...)}
     *
     * @return
     *      Live list where the changes can be made. Can be empty but never null.
     * @since 1.172
     */
    public List<Action> getActions() {
        return actions;
    }

993 994 995
    /**
     * Gets just the immediate children of {@link Hudson}.
     *
996
     * @see #getAllItems(Class)
997
     */
998
    @Exported(name="jobs")
K
kohsuke 已提交
999
    public List<TopLevelItem> getItems() {
1000
        return new ArrayList<TopLevelItem>(items.values());
1001 1002
    }

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    /**
     * Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
     * <p>
     * This method is efficient, as it doesn't involve any copying.
     * 
     * @since 1.296
     */
    public Map<String,TopLevelItem> getItemMap() {
        return Collections.unmodifiableMap(items);
    }

K
kohsuke 已提交
1014 1015 1016
    /**
     * Gets just the immediate children of {@link Hudson} but of the given type.
     */
K
kohsuke 已提交
1017
    public <T> List<T> getItems(Class<T> type) {
K
kohsuke 已提交
1018 1019 1020 1021 1022 1023 1024
        List<T> r = new ArrayList<T>();
        for (TopLevelItem i : items.values())
            if (type.isInstance(i))
                 r.add(type.cast(i));
        return r;
    }

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    /**
     * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
     * and filter them by the given type.
     */
    public <T extends Item> List<T> getAllItems(Class<T> type) {
        List<T> r = new ArrayList<T>();

        Stack<ItemGroup> q = new Stack<ItemGroup>();
        q.push(this);

        while(!q.isEmpty()) {
            ItemGroup<?> parent = q.pop();
            for (Item i : parent.getItems()) {
                if(type.isInstance(i))
K
typo.  
kohsuke 已提交
1039
                    r.add(type.cast(i));
1040 1041 1042 1043 1044 1045 1046 1047
                if(i instanceof ItemGroup)
                    q.push((ItemGroup)i);
            }
        }

        return r;
    }

K
kohsuke 已提交
1048
    /**
K
kohsuke 已提交
1049 1050 1051 1052 1053
     * Gets the list of all the projects.
     *
     * <p>
     * Since {@link Project} can only show up under {@link Hudson},
     * no need to search recursively.
K
kohsuke 已提交
1054
     */
K
kohsuke 已提交
1055
    public List<Project> getProjects() {
K
kohsuke 已提交
1056
        return Util.createSubList(items.values(),Project.class);
K
kohsuke 已提交
1057 1058 1059 1060 1061
    }

    /**
     * Gets the names of all the {@link Job}s.
     */
K
kohsuke 已提交
1062
    public Collection<String> getJobNames() {
1063
        List<String> names = new ArrayList<String>();
K
kohsuke 已提交
1064
        for (Job j : getAllItems(Job.class))
1065
            names.add(j.getFullName());
1066
        return names;
K
kohsuke 已提交
1067 1068
    }

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    /**
     * Gets the names of all the {@link TopLevelItem}s.
     */
    public Collection<String> getTopLevelItemNames() {
        List<String> names = new ArrayList<String>();
        for (TopLevelItem j : items.values())
            names.add(j.getName());
        return names;
    }

1079
    public synchronized View getView(String name) {
1080 1081 1082
        for (View v : views) {
            if(v.getViewName().equals(name))
                return v;
K
kohsuke 已提交
1083
        }
1084
        return null;
K
kohsuke 已提交
1085 1086 1087
    }

    /**
1088
     * Gets the read-only list of all {@link View}s.
K
kohsuke 已提交
1089
     */
1090
    @Exported
1091
    public synchronized Collection<View> getViews() {
1092
        List<View> copy = new ArrayList<View>(views);
1093 1094
        Collections.sort(copy, View.SORTER);
        return copy;
K
kohsuke 已提交
1095 1096
    }

1097 1098 1099 1100 1101
    public void addView(View v) throws IOException {
        views.add(v);
        save();
    }

1102
    public synchronized void deleteView(View view) throws IOException {
1103 1104 1105 1106
        if(views.size()<=1)
            throw new IllegalStateException();
        views.remove(view);
        save();
K
kohsuke 已提交
1107 1108 1109 1110 1111 1112
    }

    /**
     * Gets the read-only list of all {@link Computer}s.
     */
    public Computer[] getComputers() {
1113 1114
        Computer[] r = computers.values().toArray(new Computer[computers.size()]);
        Arrays.sort(r,new Comparator<Computer>() {
1115
            final Collator collator = Collator.getInstance();
1116 1117 1118
            public int compare(Computer lhs, Computer rhs) {
                if(lhs.getNode()==Hudson.this)  return -1;
                if(rhs.getNode()==Hudson.this)  return 1;
1119
                return collator.compare(lhs.getDisplayName(), rhs.getDisplayName());
1120 1121 1122
            }
        });
        return r;
K
kohsuke 已提交
1123 1124
    }

1125 1126 1127 1128
    /*package*/ Computer getComputer(Node n) {
        return computers.get(n);
    }

K
kohsuke 已提交
1129
    public Computer getComputer(String name) {
K
kohsuke 已提交
1130 1131 1132
        if(name.equals("(master)"))
            name = "";

1133 1134 1135
        for (Computer c : computers.values()) {
            if(c.getNode().getNodeName().equals(name))
                return c;
K
kohsuke 已提交
1136 1137 1138 1139
        }
        return null;
    }

K
kohsuke 已提交
1140 1141 1142 1143 1144 1145 1146 1147
    /**
     * @deprecated
     *      UI method. Not meant to be used programatically.
     */
    public ComputerSet getComputer() {
        return new ComputerSet();
    }

1148 1149 1150 1151 1152 1153
    /**
     * Gets the label that exists on this system by the name.
     *
     * @return null if no such label exists.
     */
    public Label getLabel(String name) {
K
kohsuke 已提交
1154
        if(name==null)  return null;
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        while(true) {
            Label l = labels.get(name);
            if(l!=null)
                return l;

            // non-existent
            labels.putIfAbsent(name,new Label(name));
        }
    }

    /**
1166
     * Gets all the active labels in the current system.
1167 1168 1169 1170
     */
    public Set<Label> getLabels() {
        Set<Label> r = new TreeSet<Label>();
        for (Label l : labels.values()) {
K
kohsuke 已提交
1171
            if(!l.isEmpty())
1172 1173 1174 1175 1176
                r.add(l);
        }
        return r;
    }

K
kohsuke 已提交
1177 1178 1179 1180 1181
    public Queue getQueue() {
        return queue;
    }

    public String getDisplayName() {
K
i18n  
kohsuke 已提交
1182
        return Messages.Hudson_DisplayName();
K
kohsuke 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    }

    public List<JDK> getJDKs() {
        if(jdks==null)
            jdks = new ArrayList<JDK>();
        return jdks;
    }

    /**
     * Gets the JDK installation of the given name, or returns null.
     */
    public JDK getJDK(String name) {
1195 1196 1197 1198 1199 1200
        if(name==null) {
            // if only one JDK is configured, "default JDK" should mean that JDK.
            List<JDK> jdks = getJDKs();
            if(jdks.size()==1)  return jdks.get(0);
            return null;
        }
K
kohsuke 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209
        for (JDK j : getJDKs()) {
            if(j.getName().equals(name))
                return j;
        }
        return null;
    }

    /**
     * Gets the slave node of the give name, hooked under this Hudson.
K
kohsuke 已提交
1210 1211 1212
     *
     * @deprecated
     *      Use {@link #getNode(String)}. Since 1.252.
K
kohsuke 已提交
1213 1214
     */
    public Slave getSlave(String name) {
K
kohsuke 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
        Node n = getNode(name);
        if (n instanceof Slave)
            return (Slave)n;
        return null;
    }

    /**
     * Gets the slave node of the give name, hooked under this Hudson.
     */
    public Node getNode(String name) {
        for (Node s : getSlaves()) {
K
kohsuke 已提交
1226 1227 1228 1229 1230 1231
            if(s.getNodeName().equals(name))
                return s;
        }
        return null;
    }

K
kohsuke 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
    /**
     * Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
     */
    public Cloud getCloud(String name) {
        for (Cloud nf : clouds)
            if(nf.name.equals(name))
                return nf;
        return null;
    }

    /**
     * @deprecated
     *      Use {@link #getNodes()}. Since 1.252.
     */
K
kohsuke 已提交
1246
    public List<Slave> getSlaves() {
K
kohsuke 已提交
1247 1248 1249 1250 1251 1252 1253 1254
        return (List)Collections.unmodifiableList(slaves);
    }

    /**
     * Returns all {@link Node}s in the system, excluding {@link Hudson} instance itself which
     * represents the master.
     */
    public List<Node> getNodes() {
K
kohsuke 已提交
1255 1256 1257
        return Collections.unmodifiableList(slaves);
    }

1258 1259
    /**
     * Updates the slave list.
K
kohsuke 已提交
1260 1261 1262
     *
     * @deprecated
     *      Use {@link #setNodes(List)}. Since 1.252.
1263 1264
     */
    public void setSlaves(List<Slave> slaves) throws IOException {
K
kohsuke 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
        setNodes(slaves);
    }

    /**
     * Adds one more {@link Node} to Hudson.
     */
    public synchronized void addNode(Node n) throws IOException {
        ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
        nl.add(n);
        setNodes(nl);
    }

    /**
     * Removes a {@link Node} from Hudson.
     */
    public synchronized void removeNode(Node n) throws IOException {
        n.toComputer().disconnect();

        ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
        nl.remove(n);
        setNodes(nl);
    }

    public void setNodes(List<? extends Node> nodes) throws IOException {
        // make sure that all names are unique
        Set<String> names = new HashSet<String>();
        for (Node n : nodes)
            if(!names.add(n.getNodeName()))
                throw new IllegalArgumentException(n.getNodeName()+" is defined more than once");
        this.slaves = new NodeList(nodes);
1295
        updateComputerList();
K
kohsuke 已提交
1296 1297 1298
        trimLabels();
        save();
    }
1299

1300 1301 1302
    public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
    	return nodeProperties;
    }
1303

1304 1305 1306 1307
    public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
    	return globalNodeProperties;
    }

K
kohsuke 已提交
1308 1309 1310 1311
    /**
     * Resets all labels and remove invalid ones.
     */
    private void trimLabels() {
1312 1313 1314
        for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
            Label l = itr.next();
            l.reset();
K
kohsuke 已提交
1315
            if(l.isEmpty())
1316 1317
                itr.remove();
        }
K
kohsuke 已提交
1318
    }
1319

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
    /**
     * Binds {@link AdministrativeMonitor}s to URL.
     */
    public AdministrativeMonitor getAdministrativeMonitor(String id) {
        for (AdministrativeMonitor m : administrativeMonitors)
            if(m.id.equals(id))
                return m;
        return null;
    }

K
kohsuke 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    public NodeDescriptor getDescriptor() {
        return DescriptorImpl.INSTANCE;
    }

    public static final class DescriptorImpl extends NodeDescriptor {
        public static final DescriptorImpl INSTANCE = new DescriptorImpl();

        public String getDisplayName() {
            throw new UnsupportedOperationException();
        }

        // to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
        public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
            return Hudson.getInstance().getDescriptor(token);
        }
1345 1346
    }

K
kohsuke 已提交
1347 1348 1349 1350 1351 1352 1353
    /**
     * Gets the system default quiet period.
     */
    public int getQuietPeriod() {
        return quietPeriod!=null ? quietPeriod : 5;
    }

K
kohsuke 已提交
1354 1355 1356 1357 1358
    /**
     * @deprecated
     *      Why are you calling a method that always returns ""?
     *      Perhaps you meant {@link #getRootUrl()}.
     */
K
kohsuke 已提交
1359 1360 1361 1362
    public String getUrl() {
        return "";
    }

1363 1364 1365 1366
    public String getSearchUrl() {
        return "";
    }

K
kohsuke 已提交
1367 1368 1369 1370
    public void onViewRenamed(View view, String oldName, String newName) {
        // implementation of Hudson is immune to view name change.
    }

1371
    @Override
1372 1373
    public SearchIndexBuilder makeSearchIndex() {
        return super.makeSearchIndex()
1374
            .add("configure", "config","configure")
K
kohsuke 已提交
1375
            .add("manage")
K
kohsuke 已提交
1376
            .add("log")
1377
            .add(getPrimaryView().makeSearchIndex())
K
kohsuke 已提交
1378 1379 1380
            .add(new CollectionSearchIndex() {// for computers
                protected Computer get(String key) { return getComputer(key); }
                protected Collection<Computer> all() { return computers.values(); }
K
kohsuke 已提交
1381
            })
K
kohsuke 已提交
1382
            .add(new CollectionSearchIndex() {// for users
K
kohsuke 已提交
1383
                protected User get(String key) { return User.get(key,false); }
K
kohsuke 已提交
1384
                protected Collection<User> all() { return User.getAll(); }
K
kohsuke 已提交
1385
            })
K
kohsuke 已提交
1386 1387
            .add(new CollectionSearchIndex() {// for views
                protected View get(String key) { return getView(key); }
1388
                protected Collection<View> all() { return views; }
K
kohsuke 已提交
1389
            });
1390 1391
    }

1392 1393 1394
    /**
     * Returns the primary {@link View} that renders the top-page of Hudson.
     */
1395
    @Exported
1396 1397 1398 1399 1400 1401 1402
    public View getPrimaryView() {
        View v = getView(primaryView);
        if(v==null) // fallback
            v = views.get(0);
        return v;
    }

1403 1404 1405 1406
    public String getUrlChildPrefix() {
        return "job";
    }

K
kohsuke 已提交
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
    /**
     * Gets the absolute URL of Hudson,
     * such as "http://localhost/hudson/".
     *
     * <p>
     * Also note that when serving user requests from HTTP, you should always use
     * {@link HttpServletRequest} to determine the full URL, instead of using this
     * (this is because one host may have multiple names, and {@link HttpServletRequest}
     * accurately represents what the current user used.)
     *
     * <p>
     * This information is rather only meant to be useful for sending out messages
     * via non-HTTP channels, like SMTP or IRC, with a link back to Hudson website.
     *
     * @return
     *      This method returns null if this parameter is not configured by the user.
     *      The caller must gracefully deal with this situation.
     *      The returned URL will always have the trailing '/'.
     * @since 1.66
K
kohsuke 已提交
1426
     * @see Descriptor#getCheckUrl(String)
K
renamed  
kohsuke 已提交
1427
     * @see #getRootUrlFromRequest()
K
kohsuke 已提交
1428 1429 1430
     */
    public String getRootUrl() {
        // for compatibility. the actual data is stored in Mailer
1431
        String url = Mailer.descriptor().getUrl();
1432 1433 1434
        if(url!=null)   return url;

        StaplerRequest req = Stapler.getCurrentRequest();
K
kohsuke 已提交
1435
        if(req!=null)
K
renamed  
kohsuke 已提交
1436
            return getRootUrlFromRequest();
1437
        return null;
K
kohsuke 已提交
1438 1439
    }

K
kohsuke 已提交
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
    /**
     * Gets the absolute URL of Hudson top page, such as "http://localhost/hudson/".
     *
     * <p>
     * Unlike {@link #getRootUrl()}, which uses the manually configured value,
     * this one uses the current request to reconstruct the URL. The benefit is
     * that this is immune to the configuration mistake (users often fail to set the root URL
     * correctly, especially when a migration is involved), but the downside
     * is that unless you are processing a request, this method doesn't work.
     *
     * @since 1.263
     */
K
renamed  
kohsuke 已提交
1452
    public String getRootUrlFromRequest() {
K
kohsuke 已提交
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
        StaplerRequest req = Stapler.getCurrentRequest();
        StringBuilder buf = new StringBuilder();
        buf.append("http://");
        buf.append(req.getServerName());
        if(req.getServerPort()!=80)
            buf.append(':').append(req.getServerPort());
        buf.append(req.getContextPath()).append('/');
        return buf.toString();
    }

K
kohsuke 已提交
1463 1464 1465 1466
    public File getRootDir() {
        return root;
    }

1467 1468 1469 1470
    public FilePath getWorkspaceFor(TopLevelItem item) {
        return new FilePath(new File(item.getRootDir(),"workspace"));
    }

K
kohsuke 已提交
1471 1472 1473 1474
    public FilePath getRootPath() {
        return new FilePath(getRootDir());
    }

1475 1476 1477 1478
    public FilePath createPath(String absolutePath) {
        return new FilePath((VirtualChannel)null,absolutePath);
    }

1479 1480
    public ClockDifference getClockDifference() {
        return ClockDifference.ZERO;
K
kohsuke 已提交
1481 1482
    }

1483 1484 1485 1486 1487 1488 1489 1490 1491
    /**
     * For binding {@link LogRecorderManager} to "/log".
     * Everything below here is admin-only, so do the check here.
     */
    public LogRecorderManager getLog() {
        checkPermission(ADMINISTER);
        return log;
    }

K
kohsuke 已提交
1492
    /**
1493 1494
     * A convenience method to check if there's some security
     * restrictions in place.
K
kohsuke 已提交
1495
     */
K
kohsuke 已提交
1496
    public boolean isUseSecurity() {
1497
        return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
1498 1499
    }

K
kohsuke 已提交
1500
    /**
1501 1502
     * Returns the constant that captures the three basic security modes
     * in Hudson.
K
kohsuke 已提交
1503
     */
1504 1505 1506 1507 1508 1509 1510 1511 1512
    public SecurityMode getSecurity() {
        // fix the variable so that this code works under concurrent modification to securityRealm.
        SecurityRealm realm = securityRealm;

        if(realm==SecurityRealm.NO_AUTHENTICATION)
            return SecurityMode.UNSECURED;
        if(realm instanceof LegacySecurityRealm)
            return SecurityMode.LEGACY;
        return SecurityMode.SECURED;
K
kohsuke 已提交
1513 1514
    }

K
kohsuke 已提交
1515 1516 1517 1518 1519 1520 1521 1522
    /**
     * @return
     *      never null.
     */
    public SecurityRealm getSecurityRealm() {
        return securityRealm;
    }

1523
    public void setSecurityRealm(SecurityRealm securityRealm) {
1524 1525
        if(securityRealm==null)
            securityRealm= SecurityRealm.NO_AUTHENTICATION;
1526
        this.securityRealm = securityRealm;
1527 1528
        // reset the filters and proxies for the new SecurityRealm
        try {
K
kohsuke 已提交
1529 1530 1531 1532
            HudsonFilter filter = HudsonFilter.get(servletContext);
            if (filter == null) {
                // Fix for #3069: This filter is not necessarily initialized before the servlets.
                // when HudsonFilter does come back, it'll initialize itself.
K
kohsuke 已提交
1533
                LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
K
kohsuke 已提交
1534
            } else {
K
kohsuke 已提交
1535
                LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
K
kohsuke 已提交
1536
                filter.reset(securityRealm);
K
kohsuke 已提交
1537
                LOGGER.fine("Security is now fully set up");
K
kohsuke 已提交
1538
            }
1539 1540 1541 1542
        } catch (ServletException e) {
            // for binary compatibility, this method cannot throw a checked exception
            throw new AcegiSecurityException("Failed to configure filter",e) {};
        }
1543
    }
1544

1545 1546 1547 1548 1549 1550
    public void setAuthorizationStrategy(AuthorizationStrategy a) {
        if (a == null)
            a = AuthorizationStrategy.UNSECURED;
        authorizationStrategy = a;
    }

1551 1552 1553
    public Lifecycle getLifecycle() {
        return Lifecycle.get();
    }
1554

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
    /**
     * Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
     *
     * @param extensionType
     *      The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
     *      but that's not a hard requirement.
     * @return
     *      Can be an empty list but never null.
     */
    @SuppressWarnings({"unchecked"})
    public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
1566
        return extensionLists.get(extensionType);
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    }

    /**
     * Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
     * kind of {@link Describable}.
     *
     * @return
     *      Can be an empty list but never null.
     */
    @SuppressWarnings({"unchecked"})
1577
    public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
1578
        return descriptorLists.get(type);
1579 1580
    }

1581 1582 1583 1584 1585 1586 1587
    /**
     * Returns the root {@link ACL}.
     *
     * @see AuthorizationStrategy#getRootACL()
     */
    public ACL getACL() {
        return authorizationStrategy.getRootACL();
K
kohsuke 已提交
1588 1589
    }

1590 1591 1592 1593 1594 1595
    /**
     * @return
     *      never null.
     */
    public AuthorizationStrategy getAuthorizationStrategy() {
        return authorizationStrategy;
K
kohsuke 已提交
1596 1597
    }

K
kohsuke 已提交
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
    /**
     * Returns true if Hudson is quieting down.
     * <p>
     * No further jobs will be executed unless it
     * can be finished while other current pending builds
     * are still in progress.
     */
    public boolean isQuietingDown() {
        return isQuietingDown;
    }

    /**
     * Returns true if the container initiated the termination of the web application.
     */
    public boolean isTerminating() {
        return terminating;
    }

1616 1617 1618 1619 1620
    public void setNumExecutors(int n) throws IOException {
        this.numExecutors = n;
        save();
    }

K
kohsuke 已提交
1621
    /**
1622 1623 1624
     * @deprecated
     *      Left only for the compatibility of URLs.
     *      Should not be invoked for any other purpose.
K
kohsuke 已提交
1625
     */
1626 1627
    public TopLevelItem getJob(String name) {
        return getItem(name);
K
kohsuke 已提交
1628 1629
    }

1630 1631 1632 1633 1634 1635
    /**
     * @deprecated
     *      Used only for mapping jobs to URL in a case-insensitive fashion.
     */
    public TopLevelItem getJobCaseInsensitive(String name) {
        for (Entry<String, TopLevelItem> e : items.entrySet()) {
K
kohsuke 已提交
1636
            if(Functions.toEmailSafeString(e.getKey()).equalsIgnoreCase(Functions.toEmailSafeString(name)))
1637 1638 1639 1640 1641
                return e.getValue();
        }
        return null;
    }

K
kohsuke 已提交
1642 1643 1644 1645 1646
    /**
     * {@inheritDoc}.
     *
     * Note that the look up is case-insensitive.
     */
K
kohsuke 已提交
1647
    public TopLevelItem getItem(String name) {
1648 1649 1650
        return items.get(name);
    }

1651
    public File getRootDirFor(TopLevelItem child) {
1652 1653 1654 1655 1656
        return getRootDirFor(child.getName());
    }

    private File getRootDirFor(String name) {
        return new File(new File(getRootDir(),"jobs"), name);
1657 1658
    }

1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
    /**
     * Gets the {@link Item} object by its full name.
     * Full names are like path names, where each name of {@link Item} is
     * combined by '/'.
     *
     * @return
     *      null if either such {@link Item} doesn't exist under the given full name,
     *      or it exists but it's no an instance of the given type.
     */
    public <T extends Item> T getItemByFullName(String fullName, Class<T> type) {
        StringTokenizer tokens = new StringTokenizer(fullName,"/");
        ItemGroup parent = this;

        while(true) {
            Item item = parent.getItem(tokens.nextToken());
            if(!tokens.hasMoreTokens()) {
                if(type.isInstance(item))
                    return type.cast(item);
                else
                    return null;
            }

            if(!(item instanceof ItemGroup))
                return null;    // this item can't have any children

            parent = (ItemGroup) item;
        }
    }

K
kohsuke 已提交
1688 1689 1690 1691
    public Item getItemByFullName(String fullName) {
        return getItemByFullName(fullName,Item.class);
    }

K
kohsuke 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
    /**
     * Gets the user of the given name.
     *
     * @return
     *      This method returns a non-null object for any user name, without validation.
     */
    public User getUser(String name) {
        return User.get(name);
    }

    /**
     * Creates a new job.
     *
     * @throws IllegalArgumentException
     *      if the project of the given name already exists.
     */
1708
    public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
K
kohsuke 已提交
1709
        if(items.containsKey(name))
K
kohsuke 已提交
1710 1711
            throw new IllegalArgumentException();

K
kohsuke 已提交
1712
        TopLevelItem item;
K
kohsuke 已提交
1713
        try {
K
kohsuke 已提交
1714
            item = type.newInstance(name);
K
kohsuke 已提交
1715 1716 1717 1718
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }

K
kohsuke 已提交
1719 1720 1721
        item.save();
        items.put(name,item);
        return item;
K
kohsuke 已提交
1722 1723
    }

K
kohsuke 已提交
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
    /**
     * Creates a new job.
     *
     * <p>
     * This version infers the descriptor from the type of the top-level item.
     *
     * @throws IllegalArgumentException
     *      if the project of the given name already exists.
     */
    public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
        return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
    }

K
kohsuke 已提交
1737 1738 1739
    /**
     * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
     */
1740
    /*package*/ void deleteJob(TopLevelItem item) throws IOException {
1741
        for (ItemListener l : ItemListener.all())
1742
            l.onDeleted(item);
1743

1744
        items.remove(item.getName());
1745 1746 1747
        for (View v : views)
            v.onJobRenamed(item, item.getName(), null);
        save();
K
kohsuke 已提交
1748 1749 1750 1751 1752 1753
    }

    /**
     * Called by {@link Job#renameTo(String)} to update relevant data structure.
     * assumed to be synchronized on Hudson by the caller.
     */
K
kohsuke 已提交
1754 1755 1756
    /*package*/ void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
        items.remove(oldName);
        items.put(newName,job);
K
kohsuke 已提交
1757

1758 1759 1760
        for (View v : views)
            v.onJobRenamed(job, oldName, newName);
        save();
K
kohsuke 已提交
1761 1762 1763 1764 1765 1766
    }

    public FingerprintMap getFingerprintMap() {
        return fingerprintMap;
    }

K
kohsuke 已提交
1767
    // if no finger print matches, display "not found page".
K
kohsuke 已提交
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
    public Object getFingerprint( String md5sum ) throws IOException {
        Fingerprint r = fingerprintMap.get(md5sum);
        if(r==null)     return new NoFingerprintMatch(md5sum);
        else            return r;
    }

    /**
     * Gets a {@link Fingerprint} object if it exists.
     * Otherwise null.
     */
    public Fingerprint _getFingerprint( String md5sum ) throws IOException {
        return fingerprintMap.get(md5sum);
    }

    /**
     * The file we save our configuration.
     */
    private XmlFile getConfigFile() {
        return new XmlFile(XSTREAM, new File(root,"config.xml"));
    }

    public int getNumExecutors() {
        return numExecutors;
    }

    public Mode getMode() {
1794
        return mode;
K
kohsuke 已提交
1795 1796
    }

1797 1798 1799 1800
    public String getLabelString() {
        return Util.fixNull(label).trim();
    }

1801
    public Set<Label> getAssignedLabels() {
1802 1803
        Set<Label> lset = labelSet; // labelSet may be set by another thread while we are in this method, so capture it.
        if (lset == null) {
1804
            Set<Label> r = new HashSet<Label>();
1805 1806 1807 1808
            String ls = getLabelString();
            if(ls.length()>0)
                for( String l : ls.split(" +"))
                    r.add(Hudson.getInstance().getLabel(l));
1809 1810
            r.addAll(getDynamicLabels());
            r.add(getSelfLabel());
1811
            this.labelSet = lset = Collections.unmodifiableSet(r);
1812
        }
1813
        return lset;
1814 1815 1816 1817 1818 1819 1820 1821 1822
    }

    /**
     * Returns the possibly empty set of labels that it has been determined as supported by this node.
     *
     * @see hudson.tasks.LabelFinder
     */
    public Set<Label> getDynamicLabels() {
        if (dynamicLabels == null) {
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
            // in the worst cast, two threads end up doing the same computation twice,
            // but that won't break the semantics.
            // OTOH, not locking prevents dead-lock. See #1390
            Set<Label> r = new HashSet<Label>();
            Computer comp = getComputer("");
            if (comp != null) {
                VirtualChannel channel = comp.getChannel();
                if (channel != null) {
                    for (DynamicLabeler labeler : LabelFinder.LABELERS) {
                        for (String label : labeler.findLabels(channel)) {
                            r.add(getLabel(label));
1834 1835 1836 1837
                        }
                    }
                }
            }
1838
            dynamicLabels = r;
1839 1840
        }
        return dynamicLabels;
1841 1842 1843 1844 1845 1846
    }

    public Label getSelfLabel() {
        return getLabel("master");
    }

K
kohsuke 已提交
1847 1848 1849 1850
    public Computer createComputer() {
        return new MasterComputer();
    }

K
kohsuke 已提交
1851
    private synchronized void load() throws IOException {
1852
        long startTime = System.currentTimeMillis();
K
kohsuke 已提交
1853
        XmlFile cfg = getConfigFile();
1854 1855 1856 1857
        if(cfg.exists()) {
            // reset some data that may not exit in the disk file
            // so that we can take a proper compensation action later.
            primaryView = null;
1858
            views.clear();
K
kohsuke 已提交
1859
            cfg.unmarshal(this);
1860
        }
K
kohsuke 已提交
1861
        clouds.setOwner(this);
K
kohsuke 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870

        File projectsDir = new File(root,"jobs");
        if(!projectsDir.isDirectory() && !projectsDir.mkdirs()) {
            if(projectsDir.exists())
                throw new IOException(projectsDir+" is not a directory");
            throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
        }
        File[] subdirs = projectsDir.listFiles(new FileFilter() {
            public boolean accept(File child) {
1871
                return child.isDirectory() && Items.getConfigFile(child).exists();
K
kohsuke 已提交
1872 1873
            }
        });
1874
        items.clear();
1875
        if(PARALLEL_LOAD) {
1876
            // load jobs in parallel for better performance
1877
            LOGGER.info("Loading in "+TWICE_CPU_NUM+" parallel threads");
1878 1879 1880 1881
            List<Future<TopLevelItem>> loaders = new ArrayList<Future<TopLevelItem>>();
            for (final File subdir : subdirs) {
                loaders.add(threadPoolForLoad.submit(new Callable<TopLevelItem>() {
                    public TopLevelItem call() throws Exception {
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
                        Thread t = Thread.currentThread();
                        String name = t.getName();
                        t.setName("Loading "+subdir);
                        try {
                            long start = System.currentTimeMillis();
                            TopLevelItem item = (TopLevelItem) Items.load(Hudson.this, subdir);
                            if(LOG_STARTUP_PERFORMANCE)
                                LOGGER.info("Loaded "+item.getName()+" in "+(System.currentTimeMillis()-start)+"ms by "+name);
                            return item;
                        } finally {
                            t.setName(name);
                        }
1894 1895 1896 1897 1898 1899 1900 1901 1902
                    }
                }));
            }

            for (Future<TopLevelItem> loader : loaders) {
                try {
                    TopLevelItem item = loader.get();
                    items.put(item.getName(), item);
                } catch (ExecutionException e) {
K
typo  
kohsuke 已提交
1903
                    LOGGER.log(Level.WARNING, "Failed to load a project",e.getCause());
1904 1905 1906 1907 1908 1909 1910
                } catch (InterruptedException e) {
                    e.printStackTrace(); // this is probably not the right thing to do
                }
            }
        } else {
            for (File subdir : subdirs) {
                try {
1911
                    long start = System.currentTimeMillis();
1912
                    TopLevelItem item = (TopLevelItem)Items.load(this,subdir);
1913 1914
                    if(LOG_STARTUP_PERFORMANCE)
                        LOGGER.info("Loaded "+item.getName()+" in "+(System.currentTimeMillis()-start)+"ms");
1915 1916 1917
                    items.put(item.getName(), item);
                } catch (Error e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
1918 1919
                } catch (RuntimeException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
1920 1921 1922
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
                }
K
kohsuke 已提交
1923 1924
            }
        }
1925
        rebuildDependencyGraph();
1926 1927

        // recompute label objects
1928
        if (null != slaves) { // only if we have slaves
K
kohsuke 已提交
1929
            for (Node slave : slaves)
1930 1931
                slave.getAssignedLabels();
        }
K
kohsuke 已提交
1932

1933 1934 1935 1936 1937 1938 1939 1940 1941
        // initialize views by inserting the default view if necessary
        // this is both for clean Hudson and for backward compatibility.
        if(views.size()==0 || primaryView==null) {
            View v = new AllView(Messages.Hudson_ViewName());
            v.owner = this;
            views.add(0,v);
            primaryView = v.getViewName();
        }

K
typo.  
kohsuke 已提交
1942
        // read in old data that doesn't have the security field set
1943 1944 1945 1946 1947 1948 1949 1950
        if(authorizationStrategy==null) {
            if(useSecurity==null || !useSecurity)
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
            else
                authorizationStrategy = new LegacyAuthorizationStrategy();
        }
        if(securityRealm==null) {
            if(useSecurity==null || !useSecurity)
1951
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
1952
            else
1953 1954 1955 1956
                setSecurityRealm(new LegacySecurityRealm());
        } else {
            // force the set to proxy
            setSecurityRealm(securityRealm);
1957
        }
1958

K
kohsuke 已提交
1959 1960 1961 1962
        if(useSecurity!=null && !useSecurity) {
            // forced reset to the unsecure mode.
            // this works as an escape hatch for people who locked themselves out.
            authorizationStrategy = AuthorizationStrategy.UNSECURED;
1963
            setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
K
kohsuke 已提交
1964
        }
1965

1966
        LOGGER.info(String.format("Took %s ms to load",System.currentTimeMillis()-startTime));
1967 1968
        if(KILL_AFTER_LOAD)
            System.exit(0);
K
kohsuke 已提交
1969 1970 1971 1972 1973 1974
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
1975
        if(BulkChange.contains(this))   return;
K
kohsuke 已提交
1976 1977 1978 1979 1980 1981 1982 1983
        getConfigFile().write(this);
    }


    /**
     * Called to shut down the system.
     */
    public void cleanUp() {
K
kohsuke 已提交
1984
        Set<Future<?>> pending = new HashSet<Future<?>>();
K
kohsuke 已提交
1985
        terminating = true;
1986 1987 1988
        for( Computer c : computers.values() ) {
            c.interrupt();
            c.kill();
K
kohsuke 已提交
1989
            pending.add(c.disconnect());
K
kohsuke 已提交
1990
        }
1991 1992
        if(udpBroadcastThread!=null)
            udpBroadcastThread.shutdown();
K
kohsuke 已提交
1993 1994
        ExternalJob.reloadThread.interrupt();
        Trigger.timer.cancel();
K
kohsuke 已提交
1995
        // TODO: how to wait for the completion of the last job?
K
kohsuke 已提交
1996
        Trigger.timer = null;
1997 1998
        if(tcpSlaveAgentListener!=null)
            tcpSlaveAgentListener.shutdown();
K
kohsuke 已提交
1999 2000 2001 2002

        if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
            pluginManager.stop();

2003 2004 2005 2006
        if(getRootDir().exists())
            // if we are aborting because we failed to create HUDSON_HOME,
            // don't try to save. Issue #536
            getQueue().save();
2007 2008

        threadPoolForLoad.shutdown();
K
kohsuke 已提交
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
        for (Future<?> f : pending)
            try {
                f.get(10, TimeUnit.SECONDS);    // if clean up operation didn't complete in time, we fail the test
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;  // someone wants us to die now. quick!
            } catch (ExecutionException e) {
                LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
            } catch (TimeoutException e) {
                LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
            }

K
kohsuke 已提交
2021
        LogFactory.releaseAll();
2022 2023

        theInstance = null;
K
kohsuke 已提交
2024 2025
    }

K
kohsuke 已提交
2026 2027 2028 2029
    public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
        for (Action a : getActions())
            if(a.getUrlName().equals(token))
                return a;
2030 2031 2032
        for (Action a : getManagementLinks())
            if(a.getUrlName().equals(token))
                return a;
K
kohsuke 已提交
2033 2034
        return null;
    }
K
kohsuke 已提交
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045


//
//
// actions
//
//
    /**
     * Accepts submission from the configuration page.
     */
    public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
K
kohsuke 已提交
2046
        BulkChange bc = new BulkChange(this);
K
kohsuke 已提交
2047
        try {
K
kohsuke 已提交
2048
            checkPermission(ADMINISTER);
K
kohsuke 已提交
2049 2050 2051

            req.setCharacterEncoding("UTF-8");

2052
            JSONObject json = req.getSubmittedForm();
2053

2054 2055 2056
            // keep using 'useSecurity' field as the main configuration setting
            // until we get the new security implementation working
            // useSecurity = null;
2057
            if (json.has("use_security")) {
K
kohsuke 已提交
2058
                useSecurity = true;
K
kohsuke 已提交
2059
                JSONObject security = json.getJSONObject("use_security");
2060
                setSecurityRealm(SecurityRealm.all().newInstanceFromRadioList(security,"realm"));
2061
                setAuthorizationStrategy(AuthorizationStrategy.all().newInstanceFromRadioList(security, "authorization"));
K
kohsuke 已提交
2062
            } else {
2063
                useSecurity = null;
2064
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
2065
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
2066
            }
K
kohsuke 已提交
2067

2068 2069
            noUsageStatistics = json.has("usageStatisticsCollected") ? null : true;

2070 2071
            {
                String v = req.getParameter("slaveAgentPortType");
2072
                if(!isUseSecurity() || v==null || v.equals("random"))
2073 2074 2075 2076 2077 2078 2079 2080
                    slaveAgentPort = 0;
                else
                if(v.equals("disable"))
                    slaveAgentPort = -1;
                else {
                    try {
                        slaveAgentPort = Integer.parseInt(req.getParameter("slaveAgentPort"));
                    } catch (NumberFormatException e) {
K
i18n  
kohsuke 已提交
2081
                        throw new FormException(Messages.Hudson_BadPortNumber(req.getParameter("slaveAgentPort")),"slaveAgentPort");
2082 2083
                    }
                }
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096

                // relaunch the agent
                if(tcpSlaveAgentListener==null) {
                    if(slaveAgentPort!=-1)
                        tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
                } else {
                    if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
                        tcpSlaveAgentListener.shutdown();
                        tcpSlaveAgentListener = null;
                        if(slaveAgentPort!=-1)
                            tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
                    }
                }
2097 2098
            }

K
kohsuke 已提交
2099 2100 2101 2102 2103 2104
            numExecutors = Integer.parseInt(req.getParameter("numExecutors"));
            if(req.hasParameter("master.mode"))
                mode = Mode.valueOf(req.getParameter("master.mode"));
            else
                mode = Mode.NORMAL;

2105 2106 2107
            label = Util.fixNull(req.getParameter("label"));
            labelSet=null;

K
kohsuke 已提交
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));

            systemMessage = Util.nullify(req.getParameter("system_message"));

            {// update JDK installations
                jdks.clear();
                String[] names = req.getParameterValues("jdk_name");
                String[] homes = req.getParameterValues("jdk_home");
                if(names!=null && homes!=null) {
                    int len = Math.min(names.length,homes.length);
                    for(int i=0;i<len;i++) {
                        jdks.add(new JDK(names[i],homes[i]));
                    }
                }
            }

            boolean result = true;

2126
            for( Descriptor<Builder> d : Builder.all() )
2127
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
2128

2129
            for( Descriptor<Publisher> d : Publisher.all() )
2130
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
2131

2132
            for( Descriptor<BuildWrapper> d : BuildWrapper.all() )
K
kohsuke 已提交
2133
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
2134

2135
            for( SCMDescriptor scmd : SCM.all() )
K
kohsuke 已提交
2136
                result &= configureDescriptor(req,json,scmd);
K
kohsuke 已提交
2137

2138
            for( TriggerDescriptor d : Trigger.all() )
K
kohsuke 已提交
2139
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
2140

2141
            for( JobPropertyDescriptor d : JobPropertyDescriptor.all() )
K
kohsuke 已提交
2142
                result &= configureDescriptor(req,json,d);
2143

2144
            for( PageDecorator d : PageDecorator.all() )
2145 2146
                result &= configureDescriptor(req,json,d);

2147 2148 2149
            for( JSONObject o : StructuredForm.toList(json,"plugin"))
                pluginManager.getPlugin(o.getString("name")).getPlugin().configure(o);

2150
            clouds.rebuildHetero(req,json, Cloud.all(), "cloud");
K
kohsuke 已提交
2151

2152 2153 2154 2155
            JSONObject np = json.getJSONObject("globalNodeProperties");
            if (np != null) {
                globalNodeProperties.rebuild(req, np, NodeProperty.for_(this));
            }
2156

K
kohsuke 已提交
2157 2158
            save();
            if(result)
2159
                rsp.sendRedirect(req.getContextPath()+'/');  // go to the top page
K
kohsuke 已提交
2160 2161 2162 2163
            else
                rsp.sendRedirect("configure"); // back to config
        } catch (FormException e) {
            sendError(e,req,rsp);
K
kohsuke 已提交
2164 2165
        } finally {
            bc.commit();
K
kohsuke 已提交
2166 2167 2168
        }
    }

2169 2170 2171 2172 2173
    public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        JSONObject form = req.getSubmittedForm();
        rsp.sendRedirect("foo");
    }

2174
    private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
2175 2176 2177
        // collapse the structure to remain backward compatible with the JSON structure before 1.
        String name = d.getJsonSafeClassName();
        JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
2178 2179 2180 2181
        json.putAll(js);
        return d.configure(req, js);
    }

2182 2183 2184 2185
    /**
     * Accepts submission from the configuration page.
     */
    public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2186
        checkPermission(ADMINISTER);
2187

2188 2189 2190
        BulkChange bc = new BulkChange(this);
        try {
            JSONObject json = req.getSubmittedForm();
2191

2192
            setNumExecutors(Integer.parseInt(req.getParameter("numExecutors")));
2193 2194 2195 2196
            if(req.hasParameter("master.mode"))
                mode = Mode.valueOf(req.getParameter("master.mode"));
            else
                mode = Mode.NORMAL;
S
stephenconnolly 已提交
2197

2198 2199 2200 2201
            setSlaves(req.bindJSONToList(Slave.class,json.get("slaves")));
        } finally {
            bc.commit();
        }
S
stephenconnolly 已提交
2202

2203
        rsp.sendRedirect(req.getContextPath()+'/');  // go to the top page
2204 2205
    }

K
kohsuke 已提交
2206 2207 2208 2209
    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2210
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2211 2212 2213 2214 2215 2216 2217

        req.setCharacterEncoding("UTF-8");
        systemMessage = req.getParameter("description");
        save();
        rsp.sendRedirect(".");
    }

2218
    public synchronized void doQuietDown(StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
2219
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2220 2221 2222 2223
        isQuietingDown = true;
        rsp.sendRedirect2(".");
    }

2224
    public synchronized void doCancelQuietDown(StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
2225
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2226 2227 2228 2229 2230
        isQuietingDown = false;
        getQueue().scheduleMaintenance();
        rsp.sendRedirect2(".");
    }

2231 2232 2233
    /**
     * Backward compatibility. Redirect to the thread dump.
     */
2234
    public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
2235 2236 2237
        rsp.sendRedirect2("threadDump");
    }

K
kohsuke 已提交
2238
    public synchronized Item doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2239
        checkPermission(Job.CREATE);
K
kohsuke 已提交
2240

2241 2242
        TopLevelItem result;

K
kohsuke 已提交
2243 2244 2245 2246 2247 2248
        String requestContentType = req.getContentType();
        if(requestContentType==null) {
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"No Content-Type header set");
            return null;
        }
        boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml");
2249 2250 2251 2252 2253 2254 2255
        if(!isXmlSubmission) {
            // containers often implement RFCs incorrectly in that it doesn't interpret query parameter
            // decoding with UTF-8. This will ensure we get it right.
            // but doing this for config.xml submission could potentiall overwrite valid
            // "text/xml;charset=xxx"
            req.setCharacterEncoding("UTF-8");
        }
2256 2257

        String name = req.getParameter("name");
K
typo.  
kohsuke 已提交
2258
        if(name==null) {
2259 2260 2261 2262
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Query parameter 'name' is required");
            return null;
        }
        name = name.trim();
K
kohsuke 已提交
2263 2264 2265 2266 2267
        String mode = req.getParameter("mode");

        try {
            checkGoodName(name);
        } catch (ParseException e) {
K
kohsuke 已提交
2268
            rsp.setStatus(SC_BAD_REQUEST);
K
kohsuke 已提交
2269 2270 2271 2272
            sendError(e,req,rsp);
            return null;
        }

2273
        if(getItem(name)!=null) {
K
kohsuke 已提交
2274
            rsp.setStatus(SC_BAD_REQUEST);
K
i18n  
kohsuke 已提交
2275
            sendError(Messages.Hudson_JobAlreadyExists(name),req,rsp);
K
kohsuke 已提交
2276 2277 2278
            return null;
        }

K
kohsuke 已提交
2279
        if(mode!=null && mode.equals("copy")) {
2280 2281
            String from = req.getParameter("from");
            TopLevelItem src = getItem(from);
K
kohsuke 已提交
2282
            if(src==null) {
2283 2284 2285 2286 2287
                rsp.setStatus(SC_BAD_REQUEST);
                if(Util.fixEmpty(from)==null)
                    sendError("Specify which job to copy",req,rsp);
                else
                    sendError("No such job: "+from,req,rsp);
K
kohsuke 已提交
2288 2289 2290
                return null;
            }

K
kohsuke 已提交
2291
            result = copy(src,name);
2292
        } else {
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
            if(isXmlSubmission) {
                // config.xml submission

                // first copy it as config.xml
                File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
                configXml.getParentFile().mkdirs();
                try {
                    FileOutputStream fos = new FileOutputStream(configXml);
                    try {
                        Util.copyStream(req.getInputStream(),fos);
                    } finally {
                        fos.close();
                    }

                    // load it
                    result = (TopLevelItem)Items.load(this,configXml.getParentFile());
                    items.put(name,result);
                } catch (IOException e) {
                    // if anything fails, delete the config file to avoid further confusion
                    Util.deleteRecursive(configXml.getParentFile());
                    throw e;
                }
            } else {
                // create empty job and redirect to the project config screen
                if(mode==null) {
K
kohsuke 已提交
2318
                    rsp.sendError(SC_BAD_REQUEST);
2319 2320 2321 2322
                    return null;
                }
                result = createProject(Items.getDescriptor(mode), name);
            }
K
kohsuke 已提交
2323

2324
            for (ItemListener l : ItemListener.all())
K
kohsuke 已提交
2325 2326
                l.onCreated(result);
        }
2327

2328 2329 2330 2331 2332
        if(isXmlSubmission) {
            // it worked
            rsp.setStatus(HttpServletResponse.SC_OK);
        } else {
            // send the browser to the config page
2333
            rsp.sendRedirect2(result.getUrl()+"configure");
2334 2335
        }

K
kohsuke 已提交
2336 2337 2338
        return result;
    }

K
kohsuke 已提交
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
    /**
     * Copys a job.
     *
     * @param src
     *      A {@link TopLevelItem} to be copied.
     * @param name
     *      Name of the newly created project.
     * @return
     *      Newly created {@link TopLevelItem}.
     */
    @SuppressWarnings({"unchecked"})
    public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
        T result = (T)createProject(src.getDescriptor(),name);

        // copy config
        Util.copyFile(Items.getConfigFile(src).getFile(),Items.getConfigFile(result).getFile());

        // reload from the new config
        result = (T)Items.load(this,result.getRootDir());
        result.onCopiedFrom(src);
        items.put(name,result);

2361
        for (ItemListener l : ItemListener.all())
K
kohsuke 已提交
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
            l.onCreated(result);

        return result;
    }

    // a little more convenient overloading that assumes the caller gives us the right type
    // (or else it will fail with ClassCastException)
    public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
        return (T)copy((TopLevelItem)src,name);
    }

K
kohsuke 已提交
2373
    public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2374 2375
        try {
            checkPermission(View.CREATE);
2376
            addView(View.create(req,rsp, this));
K
kohsuke 已提交
2377 2378
        } catch (ParseException e) {
            sendError(e,req,rsp);
2379 2380 2381
        } catch (FormException e) {
            sendError(e,req,rsp);
        }
K
kohsuke 已提交
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
    }

    /**
     * Check if the given name is suitable as a name
     * for job, view, etc.
     *
     * @throws ParseException
     *      if the given name is not good
     */
    public static void checkGoodName(String name) throws ParseException {
        if(name==null || name.length()==0)
K
i18n  
kohsuke 已提交
2393
            throw new ParseException(Messages.Hudson_NoName(),0);
K
kohsuke 已提交
2394 2395 2396

        for( int i=0; i<name.length(); i++ ) {
            char ch = name.charAt(i);
2397 2398 2399
            if(Character.isISOControl(ch)) {
                throw new ParseException(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)),i);
            }
K
kohsuke 已提交
2400
            if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
K
i18n  
kohsuke 已提交
2401
                throw new ParseException(Messages.Hudson_UnsafeChar(ch),i);
K
kohsuke 已提交
2402 2403 2404 2405 2406
        }

        // looks good
    }

2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
    private static String toPrintableName(String name) {
        StringBuffer printableName = new StringBuffer();
        for( int i=0; i<name.length(); i++ ) {
            char ch = name.charAt(i);
            if(Character.isISOControl(ch))
                printableName.append("\\u").append((int)ch).append(';');
            else
                printableName.append(ch);
        }
        return printableName.toString();
    }

2419
    /**
2420 2421 2422
     * Checks if the user was successfully authenticated.
     *
     * @see BasicAuthenticationFilter
2423 2424
     */
    public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2425 2426
        if(req.getUserPrincipal()==null) {
            // authentication must have failed
2427 2428 2429 2430
            rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

2431
        // the user is now authenticated, so send him back to the target
2432 2433 2434
        String path = req.getContextPath()+req.getRestOfPath();
        String q = req.getQueryString();
        if(q!=null)
2435
            path += '?'+q;
2436

2437
        rsp.sendRedirect2(path);
2438 2439
    }

K
kohsuke 已提交
2440 2441 2442
    /**
     * Called once the user logs in. Just forward to the top page.
     */
K
kohsuke 已提交
2443
    public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
2444 2445
        if(req.getUserPrincipal()==null)
            rsp.sendRedirect2("noPrincipal");
2446 2447

        String from = req.getParameter("from");
2448
        if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
2449
            rsp.sendRedirect2(from);    // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
            return;
        }

        String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
        if(url!=null) {
            // if the login redirect is initiated by Acegi
            // this should send the user back to where s/he was from.
            rsp.sendRedirect2(url);
            return;
        }

        rsp.sendRedirect2(".");
K
kohsuke 已提交
2462 2463 2464 2465 2466
    }

    /**
     * Called once the user logs in. Just forward to the top page.
     */
K
kohsuke 已提交
2467
    public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
2468 2469 2470
        HttpSession session = req.getSession(false);
        if(session!=null)
            session.invalidate();
2471
        SecurityContextHolder.clearContext();
2472 2473 2474 2475 2476 2477

        // reset remember-me cookie
        Cookie cookie = new Cookie(ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY,"");
        cookie.setPath(req.getContextPath().length()>0 ? req.getContextPath() : "/");
        rsp.addCookie(cookie);

K
kohsuke 已提交
2478 2479 2480
        rsp.sendRedirect2(req.getContextPath()+"/");
    }

2481 2482 2483 2484 2485 2486 2487
    /**
     * Serves jar files for JNLP slave agents.
     */
    public Slave.JnlpJar getJnlpJars(String fileName) {
        return new Slave.JnlpJar(fileName);
    }

K
kohsuke 已提交
2488 2489
    /**
     * RSS feed for log entries.
2490 2491 2492
     *
     * @deprecated
     *   As on 1.267, moved to "/log/rss..."
K
kohsuke 已提交
2493 2494
     */
    public void doLogRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2495 2496
        String qs = req.getQueryString();
        rsp.sendRedirect2("./log/rss"+(qs==null?"":'?'+qs));
K
kohsuke 已提交
2497 2498
    }

K
kohsuke 已提交
2499 2500 2501 2502
    /**
     * Reloads the configuration.
     */
    public synchronized void doReload( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
2503
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2504

2505 2506 2507 2508
        // engage "loading ..." UI and then run the actual task in a separate thread
        final ServletContext context = req.getServletContext();
        context.setAttribute("app",new HudsonIsLoading());

K
kohsuke 已提交
2509
        rsp.sendRedirect2(req.getContextPath()+"/");
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521

        new Thread("Hudson config reload thread") {
            public void run() {
                try {
                    load();
                    User.reload();
                    context.setAttribute("app",Hudson.this);
                } catch (IOException e) {
                    LOGGER.log(Level.SEVERE,"Failed to reload Hudson config",e);
                }
            }
        }.start();
K
kohsuke 已提交
2522 2523 2524 2525 2526 2527
    }

    /**
     * Do a finger-print check.
     */
    public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2528 2529
        // Parse the request
        MultipartFormDataParser p = new MultipartFormDataParser(req);
K
kohsuke 已提交
2530 2531
        try {
            rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
2532 2533 2534
                Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
        } finally {
            p.cleanUp();
K
kohsuke 已提交
2535 2536 2537 2538 2539 2540 2541
        }
    }

    /**
     * Serves static resources without the "Last-Modified" header to work around
     * a bug in Firefox.
     *
K
kohsuke 已提交
2542 2543
     * <p>
     * See https://bugzilla.mozilla.org/show_bug.cgi?id=89419
K
kohsuke 已提交
2544 2545 2546 2547 2548 2549 2550 2551 2552
     */
    public void doNocacheImages( StaplerRequest req, StaplerResponse rsp ) throws IOException {
        String path = req.getRestOfPath();

        if(path.length()==0)
            path = "/";

        if(path.indexOf("..")!=-1 || path.length()<1) {
            // don't serve anything other than files in the artifacts dir
K
kohsuke 已提交
2553
            rsp.sendError(SC_BAD_REQUEST);
K
kohsuke 已提交
2554 2555 2556 2557 2558
            return;
        }

        File f = new File(req.getServletContext().getRealPath("/images"),path.substring(1));
        if(!f.exists()) {
2559
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
            return;
        }

        if(f.isDirectory()) {
            // listing not allowed
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        FileInputStream in = new FileInputStream(f);
        // serve the file
        String contentType = req.getServletContext().getMimeType(f.getPath());
        rsp.setContentType(contentType);
        rsp.setContentLength((int)f.length());
K
kohsuke 已提交
2574
        Util.copyStream(in,rsp.getOutputStream());
K
kohsuke 已提交
2575 2576 2577 2578
        in.close();
    }

    /**
K
kohsuke 已提交
2579
     * For debugging. Expose URL to perform GC.
K
kohsuke 已提交
2580
     */
2581
    public void doGc(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2582 2583 2584 2585 2586 2587
        System.gc();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("GCed");
    }

2588 2589 2590 2591 2592 2593 2594
    /**
     * Binds /userContent/... to $HUDSON_HOME/userContent.
     */
    public DirectoryBrowserSupport doUserContent() {
        return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.gif",true);
    }

K
kohsuke 已提交
2595 2596 2597 2598
    /**
     * Perform a restart of Hudson, if we can.
     */
    public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
2599
        requirePOST();
K
kohsuke 已提交
2600 2601 2602 2603 2604 2605 2606
        checkPermission(ADMINISTER);
        try {
            Lifecycle.get().restart();
            servletContext.setAttribute("app",new HudsonIsRestarting());
            rsp.sendRedirect2(".");
        } catch (UnsupportedOperationException e) {
            sendError("Restart is not supported in this running mode.",req,rsp);
2607 2608 2609 2610
        } catch (IOException e) {
            sendError(e,req,rsp);
        } catch (InterruptedException e) {
            sendError(e,req,rsp);
K
kohsuke 已提交
2611 2612 2613
        }
    }

K
kohsuke 已提交
2614 2615 2616 2617 2618
    /**
     * Shutdown the system.
     * @since 1.161
     */
    public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
2619
        checkPermission(ADMINISTER);
2620
        LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
K
kohsuke 已提交
2621
                getAuthentication(), req.getRemoteAddr()));
K
kohsuke 已提交
2622 2623 2624 2625 2626
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        PrintWriter w = rsp.getWriter();
        w.println("Shutting down");
        w.close();
2627

K
kohsuke 已提交
2628 2629 2630
        System.exit(0);
    }

K
kohsuke 已提交
2631 2632 2633 2634 2635
    /**
     * Gets the {@link Authentication} object that represents the user
     * associated with the current request.
     */
    public static Authentication getAuthentication() {
K
kohsuke 已提交
2636 2637 2638 2639 2640
        Authentication a = SecurityContextHolder.getContext().getAuthentication();
        // on Tomcat while serving the login page, this is null despite the fact
        // that we have filters. Looking at the stack trace, Tomcat doesn't seem to
        // run the request through filters when this is the login request.
        // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
K
kohsuke 已提交
2641 2642
        if(a==null)
            a = new AnonymousAuthenticationToken("anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
K
kohsuke 已提交
2643
        return a;
K
kohsuke 已提交
2644 2645
    }

K
kohsuke 已提交
2646 2647
    /**
     * For system diagnostics.
K
kohsuke 已提交
2648
     * Run arbitrary Groovy script.
K
kohsuke 已提交
2649
     */
2650 2651 2652
    public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        doScript(req, rsp, req.getView(this, "_script.jelly"));
    }
2653

2654 2655 2656 2657 2658 2659 2660 2661
    /**
     * Run arbitrary Groovy script and return result as plain text.
     */
    public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        doScript(req, rsp, req.getView(this, "_scriptText.jelly"));
    }

    private void doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view) throws IOException, ServletException {
2662 2663
        // ability to run arbitrary script is dangerous
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2664 2665

        String text = req.getParameter("script");
2666
        if (text != null) {
K
kohsuke 已提交
2667
            try {
2668
                req.setAttribute("output",
2669
                        RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel));
2670 2671
            } catch (InterruptedException e) {
                throw new ServletException(e);
K
kohsuke 已提交
2672 2673 2674
            }
        }

2675
        view.forward(req, rsp);
K
kohsuke 已提交
2676 2677
    }

2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
    /**
     * Evaluates the Jelly script submitted by the client.
     *
     * This is useful for system administration as well as unit testing.
     */
    public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        checkPermission(ADMINISTER);
        requirePOST();

        try {
            MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
            Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
            new JellyRequestDispatcher(this,script).forward(req,rsp);
        } catch (JellyException e) {
            throw new ServletException(e);
        }
    }

K
kohsuke 已提交
2696 2697 2698 2699 2700 2701 2702
    /**
     * Sign up for the user account.
     */
    public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        req.getView(getSecurityRealm(),"signup.jelly").forward(req,rsp);
    }

K
kohsuke 已提交
2703 2704 2705
    /**
     * Changes the icon size by changing the cookie
     */
K
kohsuke 已提交
2706 2707
    public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        String qs = req.getQueryString();
J
jglick 已提交
2708
        if(qs==null || !ICON_SIZE.matcher(qs).matches())
K
kohsuke 已提交
2709
            throw new ServletException();
2710 2711 2712
        Cookie cookie = new Cookie("iconSize", qs);
        cookie.setMaxAge(/* ~4 mo. */9999999); // #762
        rsp.addCookie(cookie);
K
kohsuke 已提交
2713 2714 2715
        String ref = req.getHeader("Referer");
        if(ref==null)   ref=".";
        rsp.sendRedirect2(ref);
K
kohsuke 已提交
2716 2717
    }

2718
    public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2719 2720 2721 2722 2723 2724
        FingerprintCleanupThread.invoke();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("Invoked");
    }

2725
    public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2726 2727 2728 2729 2730 2731 2732 2733 2734
        WorkspaceCleanupThread.invoke();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("Invoked");
    }

    /**
     * Checks if the JAVA_HOME is a valid JAVA_HOME path.
     */
2735
    public FormValidation doJavaHomeCheck(@QueryParameter File value) {
K
kohsuke 已提交
2736
        // this can be used to check the existence of a file on the server, so needs to be protected
2737
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2738

2739 2740
        if(!value.isDirectory())
            return FormValidation.error(Messages.Hudson_NotADirectory(value));
K
kohsuke 已提交
2741

2742 2743 2744 2745 2746 2747
        File toolsJar = new File(value,"lib/tools.jar");
        File mac = new File(value,"lib/dt.jar");
        if(!toolsJar.exists() && !mac.exists())
            return FormValidation.error(Messages.Hudson_NotJDKDir(value));

        return FormValidation.ok();
K
kohsuke 已提交
2748 2749
    }

K
kohsuke 已提交
2750 2751 2752
    /**
     * If the user chose the default JDK, make sure we got 'java' in PATH.
     */
2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
    public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
        if(!value.equals("(Default)"))
            // assume the user configured named ones properly in system config ---
            // or else system config should have reported form field validation errors.
            return FormValidation.ok();

        // default JDK selected. Does such java really exist?
        if(JDK.isDefaultJDKValid(Hudson.this))
            return FormValidation.ok();
        else
            return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
K
kohsuke 已提交
2764 2765
    }

K
kohsuke 已提交
2766 2767 2768
    /**
     * Checks if the top-level item with the given name exists.
     */
2769
    public FormValidation doItemExistsCheck(@QueryParameter String value) {
K
kohsuke 已提交
2770 2771
        // this method can be used to check if a file exists anywhere in the file system,
        // so it should be protected.
2772 2773 2774 2775
        checkPermission(Item.CREATE);
        
        String job = fixEmpty(value);
        if(job==null)
K
kohsuke 已提交
2776
            return FormValidation.ok();
2777 2778 2779 2780 2781

        if(getItem(job)==null)
            return FormValidation.ok();
        else
            return FormValidation.error(Messages.Hudson_JobAlreadyExists(job));
K
kohsuke 已提交
2782
    }
2783 2784 2785 2786

    /**
     * Checks if a top-level view with the given name exists.
     */
2787 2788
    public FormValidation doViewExistsCheck(@QueryParameter String value) {
        checkPermission(View.CREATE);
2789

2790
        String view = fixEmpty(value);
K
kohsuke 已提交
2791
        if(view==null) return FormValidation.ok();
2792 2793 2794 2795 2796

        if(getView(view)==null)
            return FormValidation.ok();
        else
            return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
2797 2798
    }

2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809
    /**
     * @deprecated as of 1.294
     *      Define your own check method, instead of relying on this generic one.
     */
    public void doFieldCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        doFieldCheck(
                fixEmpty(req.getParameter("value")),
                fixEmpty(req.getParameter("type")),
                fixEmpty(req.getParameter("errorText")),
                fixEmpty(req.getParameter("warningText"))).generateResponse(req,rsp,this);
    }
2810

2811 2812 2813 2814 2815
    /**
     * Checks if the value for a field is set; if not an error or warning text is displayed.
     * If the parameter "value" is not set then the parameter "errorText" is displayed
     * as an error text. If the parameter "errorText" is not set, then the parameter "warningText" is
     * displayed as a warning text.
K
kohsuke 已提交
2816
     * <p>
2817 2818
     * If the text is set and the parameter "type" is set, it will validate that the value is of the
     * correct type. Supported types are "number, "number-positive" and "number-negative".
K
kohsuke 已提交
2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
     */
    public FormValidation doFieldCheck(@QueryParameter(fixEmpty=true) String value,
                                       @QueryParameter(fixEmpty=true) String type,
                                       @QueryParameter(fixEmpty=true) String errorText,
                                       @QueryParameter(fixEmpty=true) String warningText) {
        if (value == null) {
            if (errorText != null)
                return FormValidation.error(errorText);
            if (warningText != null)
                return FormValidation.warning(warningText);
            return FormValidation.error("No error or warning text was set for fieldCheck().");
        }
2831

K
kohsuke 已提交
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
        if (type != null) {
            try {
                if (type.equalsIgnoreCase("number")) {
                    NumberFormat.getInstance().parse(value);
                } else if (type.equalsIgnoreCase("number-positive")) {
                    if (NumberFormat.getInstance().parse(value).floatValue() <= 0)
                        return FormValidation.error(Messages.Hudson_NotAPositiveNumber());
                } else if (type.equalsIgnoreCase("number-negative")) {
                    if (NumberFormat.getInstance().parse(value).floatValue() >= 0)
                        return FormValidation.error(Messages.Hudson_NotANegativeNumber());
2842
                }
K
kohsuke 已提交
2843 2844
            } catch (ParseException e) {
                return FormValidation.error(Messages.Hudson_NotANumber());
2845
            }
K
kohsuke 已提交
2846
        }
2847

K
kohsuke 已提交
2848
        return FormValidation.ok();
2849
    }
K
kohsuke 已提交
2850

2851 2852 2853 2854 2855 2856 2857 2858
    /**
     * Serves static resources placed along with Jelly view files.
     * <p>
     * This method can serve a lot of files, so care needs to be taken
     * to make this method secure. It's not clear to me what's the best
     * strategy here, though the current implementation is based on
     * file extensions.
     */
2859
    public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
2860
        String path = req.getRestOfPath();
2861 2862 2863 2864 2865 2866
        // cut off the "..." portion of /resources/.../path/to/file
        // as this is only used to make path unique (which in turn
        // allows us to set a long expiration date
        path = path.substring(1);
        path = path.substring(path.indexOf('/')+1);

2867 2868 2869
        int idx = path.lastIndexOf('.');
        String extension = path.substring(idx+1);
        if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
2870 2871 2872 2873
            URL url = pluginManager.uberClassLoader.getResource(path);
            if(url!=null) {
                long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
                rsp.serveFile(req,url,expires);
2874 2875 2876 2877 2878 2879
                return;
            }
        }
        rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

S
sogabe 已提交
2880 2881 2882 2883 2884 2885 2886 2887
    /**
     * Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
     * This set is mutable to allow plugins to add additional extensions.
     */
    public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
        "js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
    ));

2888 2889 2890
    /**
     * Checks if container uses UTF-8 to decode URLs. See
     * http://hudson.gotdns.com/wiki/display/HUDSON/Tomcat#Tomcat-i18n
K
kohsuke 已提交
2891 2892 2893 2894 2895 2896 2897 2898 2899
     */
    public FormValidation doCheckURIEncoding(StaplerRequest request, @QueryParameter String value) throws IOException {
        request.setCharacterEncoding("UTF-8");
        // expected is non-ASCII String
        final String expected = "\u57f7\u4e8b";
        value = fixEmpty(value);
        if (!expected.equals(value))
            return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
        return FormValidation.ok();
2900
    }
S
sogabe 已提交
2901

2902 2903 2904 2905 2906 2907
    /**
     * Does not check when system default encoding is "ISO-8859-1".
     */
    public static boolean isCheckURIEncodingEnabled() {
        return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
    }
K
kohsuke 已提交
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922

    public static boolean isWindows() {
        return File.pathSeparatorChar==';';
    }

    /**
     * Returns all {@code CVSROOT} strings used in the current Hudson installation.
     *
     * <p>
     * Ideally this shouldn't be defined in here
     * but EL doesn't provide a convenient way of invoking a static function,
     * so I'm putting it here for now.
     */
    public Set<String> getAllCvsRoots() {
        Set<String> r = new TreeSet<String>();
K
kohsuke 已提交
2923
        for( AbstractProject p : getAllItems(AbstractProject.class) ) {
K
kohsuke 已提交
2924 2925 2926 2927 2928 2929 2930 2931 2932 2933
            SCM scm = p.getScm();
            if (scm instanceof CVSSCM) {
                CVSSCM cvsscm = (CVSSCM) scm;
                r.add(cvsscm.getCvsRoot());
            }
        }

        return r;
    }

2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
    /**
     * Rebuilds the dependency map.
     */
    public void rebuildDependencyGraph() {
        dependencyGraph = new DependencyGraph();
    }

    public DependencyGraph getDependencyGraph() {
        return dependencyGraph;
    }

2945 2946
    // for Jelly
    public List<ManagementLink> getManagementLinks() {
2947
        return ManagementLink.all();
2948 2949
    }

K
kohsuke 已提交
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
    /**
     * Gets the {@link Widget}s registered on this object.
     *
     * <p>
     * Plugins who wish to contribute boxes on the side panel can add widgets
     * by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
     */
    public List<Widget> getWidgets() {
        return widgets;
    }

K
kohsuke 已提交
2961
    public Object getTarget() {
K
kohsuke 已提交
2962 2963 2964 2965 2966 2967 2968
        try {
            checkPermission(READ);
        } catch (AccessDeniedException e) {
            String rest = Stapler.getCurrentRequest().getRestOfPath();
            if(rest.startsWith("/login")
            || rest.startsWith("/logout")
            || rest.startsWith("/accessDenied")
2969
            || rest.startsWith("/signup")
2970
            || rest.startsWith("/jnlpJars/")
2971
            || rest.startsWith("/tcpSlaveAgentListener")
K
kohsuke 已提交
2972 2973 2974 2975
            || rest.startsWith("/securityRealm"))
                return this;    // URLs that are always visible without READ permission
            throw e;
        }
K
kohsuke 已提交
2976 2977 2978
        return this;
    }

2979 2980 2981 2982 2983 2984 2985
    /**
     * Fallback to the primary view.
     */
    public View getStaplerFallback() {
        return getPrimaryView();
    }

K
kohsuke 已提交
2986 2987 2988 2989 2990
    public static final class MasterComputer extends Computer {
        private MasterComputer() {
            super(Hudson.getInstance());
        }

2991 2992 2993 2994 2995 2996 2997
        /**
         * Returns "" to match with {@link Hudson#getNodeName()}.
         */
        public String getName() {
            return "";
        }

K
kohsuke 已提交
2998 2999 3000 3001 3002
        @Override
        public boolean isConnecting() {
            return false;
        }

K
kohsuke 已提交
3003 3004
        @Override
        public String getDisplayName() {
K
i18n  
kohsuke 已提交
3005
            return Messages.Hudson_Computer_DisplayName();
K
kohsuke 已提交
3006 3007 3008 3009
        }

        @Override
        public String getCaption() {
K
i18n  
kohsuke 已提交
3010
            return Messages.Hudson_Computer_Caption();
K
kohsuke 已提交
3011 3012
        }

K
kohsuke 已提交
3013 3014 3015 3016
        public String getUrl() {
            return "computer/(master)/";
        }

3017
        public RetentionStrategy getRetentionStrategy() {
K
kohsuke 已提交
3018
            return RetentionStrategy.NOOP;
3019 3020
        }

3021 3022 3023 3024 3025 3026 3027 3028
        /**
         * Report an error.
         */
        @Override
        public void doDoDelete(StaplerResponse rsp) throws IOException {
            rsp.sendError(SC_BAD_REQUEST);
        }

K
kohsuke 已提交
3029 3030 3031 3032 3033
        public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            // the master node isn't in the Hudson.getNodes(), so this method makes no sense.
            throw new UnsupportedOperationException();
        }

3034 3035 3036 3037 3038 3039 3040 3041 3042
        @Override
        public boolean hasPermission(Permission permission) {
            // no one should be allowed to delete the master.
            // this hides the "delete" link from the /computer/(master) page.
            if(permission==Computer.DELETE)
                return false;
            return super.hasPermission(permission);
        }

K
kohsuke 已提交
3043 3044 3045 3046 3047
        @Override
        public VirtualChannel getChannel() {
            return localChannel;
        }

3048 3049 3050 3051 3052
        @Override
        public Charset getDefaultCharset() {
            return Charset.defaultCharset();
        }

K
kohsuke 已提交
3053 3054 3055 3056
        public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
            return logRecords;
        }

K
kohsuke 已提交
3057 3058 3059
        public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            // this computer never returns null from channel, so
            // this method shall never be invoked.
3060
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
3061 3062
        }

3063 3064 3065 3066 3067 3068 3069
        /**
         * Redirect the master configuration to /configure.
         */
        public void doConfigure(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            rsp.sendRedirect2(req.getContextPath()+"/configure");
        }

K
kohsuke 已提交
3070 3071
        public Future<?> connect(boolean forceReconnect) {
            return Futures.precomputed(null);
3072 3073
        }

K
kohsuke 已提交
3074 3075 3076 3077 3078 3079
        /**
         * {@link LocalChannel} instance that can be used to execute programs locally.
         */
        public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
    }

3080 3081 3082 3083
    /**
     * @deprecated
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
3084 3085 3086 3087
    public static boolean adminCheck() throws IOException {
        return adminCheck(Stapler.getCurrentRequest(), Stapler.getCurrentResponse());
    }

3088 3089 3090 3091
    /**
     * @deprecated
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
3092
    public static boolean adminCheck(StaplerRequest req,StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
3093 3094 3095 3096 3097 3098
        if (isAdmin(req)) return true;

        rsp.sendError(StaplerResponse.SC_FORBIDDEN);
        return false;
    }

K
kohsuke 已提交
3099 3100 3101
    /**
     * Checks if the current user (for which we are processing the current request)
     * has the admin access.
3102 3103
     *
     * @deprecated
K
kohsuke 已提交
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
     *      This method is deprecated when Hudson moved from simple Unix root-like model
     *      of "admin gets to do everything, and others don't have any privilege" to more
     *      complex {@link ACL} and {@link Permission} based scheme.
     *
     *      <p>
     *      For a quick migration, use {@code Hudson.getInstance().getACL().hasPermission(Hudson.ADMINISTER)}
     *      To check if the user has the 'administer' role in Hudson.
     *
     *      <p>
     *      But ideally, your plugin should first identify a suitable {@link Permission} (or create one,
     *      if appropriate), then identify a suitable {@link AccessControlled} object to check its permission
3115
     *      against.
K
kohsuke 已提交
3116
     */
K
kohsuke 已提交
3117
    public static boolean isAdmin() {
3118
        return Hudson.getInstance().getACL().hasPermission(ADMINISTER);
K
kohsuke 已提交
3119 3120
    }

3121 3122 3123
    /**
     * @deprecated
     *      Define a custom {@link Permission} and check against ACL.
K
kohsuke 已提交
3124
     *      See {@link #isAdmin()} for more instructions.
3125
     */
K
kohsuke 已提交
3126
    public static boolean isAdmin(StaplerRequest req) {
3127
        return isAdmin();
K
kohsuke 已提交
3128 3129 3130 3131 3132
    }

    /**
     * Live view of recent {@link LogRecord}s produced by Hudson.
     */
J
jglick 已提交
3133
    public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
K
kohsuke 已提交
3134 3135 3136 3137

    /**
     * Thread-safe reusable {@link XStream}.
     */
3138
    public static final XStream XSTREAM = new XStream2();
K
kohsuke 已提交
3139

3140 3141
    private static final int TWICE_CPU_NUM = Runtime.getRuntime().availableProcessors() * 2;

3142 3143 3144 3145 3146 3147
    /**
     * Thread pool used to load configuration in parallel, to improve the start up time.
     * <p>
     * The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
     */
    /*package*/ static final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
3148 3149
        TWICE_CPU_NUM, TWICE_CPU_NUM,
        5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory());
3150 3151


K
kohsuke 已提交
3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
    private static void computeVersion(ServletContext context) {
        // set the version
        Properties props = new Properties();
        try {
            InputStream is = Hudson.class.getResourceAsStream("hudson-version.properties");
            if(is!=null)
                props.load(is);
        } catch (IOException e) {
            e.printStackTrace(); // if the version properties is missing, that's OK.
        }
        String ver = props.getProperty("version");
        if(ver==null)   ver="?";
        VERSION = ver;
        context.setAttribute("version",ver);
        VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);

        if(ver.equals("?"))
            RESOURCE_PATH = "";
        else
            RESOURCE_PATH = "/static/"+VERSION_HASH;

        VIEW_RESOURCE_PATH = "/resources/"+ VERSION_HASH;
    }
3175

3176 3177 3178
    /**
     * Version number of this Hudson.
     */
3179
    public static String VERSION="?";
3180

K
kohsuke 已提交
3181 3182 3183 3184 3185
    /**
     * Hash of {@link #VERSION}.
     */
    public static String VERSION_HASH;

3186 3187 3188
    /**
     * Prefix to static resources like images and javascripts in the war file.
     * Either "" or strings like "/static/VERSION", which avoids Hudson to pick up
3189
     * stale cache when the user upgrades to a different version.
3190 3191
     * <p>
     * Value computed in {@link WebAppMain}.
3192
     */
3193
    public static String RESOURCE_PATH = "";
3194

3195 3196 3197 3198
    /**
     * Prefix to resources alongside view scripts.
     * Strings like "/resources/VERSION", which avoids Hudson to pick up
     * stale cache when the user upgrades to a different version.
3199 3200
     * <p>
     * Value computed in {@link WebAppMain}.
3201
     */
3202
    public static String VIEW_RESOURCE_PATH = "/resources/TBD";
3203

3204
    public static boolean PARALLEL_LOAD = Boolean.getBoolean(Hudson.class.getName()+".parallelLoad");
3205
    public static boolean KILL_AFTER_LOAD = Boolean.getBoolean(Hudson.class.getName()+".killAfterLoad");
3206
    public static boolean LOG_STARTUP_PERFORMANCE = Boolean.getBoolean(Hudson.class.getName()+".logStartupPerformance");
3207

K
kohsuke 已提交
3208 3209
    private static final Logger LOGGER = Logger.getLogger(Hudson.class.getName());

K
kohsuke 已提交
3210 3211
    private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+");

3212 3213
    public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
    public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
3214
    public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ);
K
kohsuke 已提交
3215

K
kohsuke 已提交
3216 3217
    static {
        XSTREAM.alias("hudson",Hudson.class);
K
kohsuke 已提交
3218
        XSTREAM.alias("slave", DumbSlave.class);
K
kohsuke 已提交
3219
        XSTREAM.alias("jdk",JDK.class);
3220 3221 3222
        // for backward compatibility with <1.75, recognize the tag name "view" as well.
        XSTREAM.alias("view", ListView.class);
        XSTREAM.alias("listView", ListView.class);
3223 3224
        // this seems to be necessary to force registration of converter early enough
        Mode.class.getEnumConstants();
3225 3226 3227 3228

        // doule check that initialization order didn't do any harm
        assert PERMISSIONS!=null;
        assert ADMINISTER!=null;
K
kohsuke 已提交
3229 3230
    }
}