Hudson.java 109.9 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;
47
import hudson.logging.LogRecorderManager;
K
kohsuke 已提交
48
import hudson.lifecycle.Lifecycle;
K
kohsuke 已提交
49
import hudson.model.Descriptor.FormException;
50
import hudson.model.listeners.ItemListener;
K
kohsuke 已提交
51
import hudson.model.listeners.JobListener;
52
import hudson.model.listeners.JobListener.JobListenerAdapter;
S
sogabe 已提交
53
import hudson.model.listeners.SCMListener;
K
kohsuke 已提交
54 55
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
K
kohsuke 已提交
56
import hudson.scm.CVSSCM;
K
kohsuke 已提交
57
import hudson.scm.RepositoryBrowser;
58 59
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
60
import hudson.scm.SubversionSCM;
K
kohsuke 已提交
61
import hudson.search.CollectionSearchIndex;
62
import hudson.search.SearchIndexBuilder;
63
import hudson.security.ACL;
64
import hudson.security.AccessControlled;
65
import hudson.security.AuthorizationStrategy;
K
kohsuke 已提交
66
import hudson.security.BasicAuthenticationFilter;
67 68 69 70
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
71
import hudson.security.PermissionGroup;
K
kohsuke 已提交
72
import hudson.security.SecurityMode;
73
import hudson.security.SecurityRealm;
74
import hudson.slaves.ComputerListener;
75 76
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
77
import hudson.slaves.RetentionStrategy;
K
kohsuke 已提交
78 79 80 81 82
import hudson.slaves.NodeList;
import hudson.slaves.Cloud;
import hudson.slaves.DumbSlave;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeProvisioner;
83 84 85 86 87 88
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 已提交
89
import hudson.triggers.Trigger;
90
import hudson.triggers.TriggerDescriptor;
K
kohsuke 已提交
91
import hudson.util.CaseInsensitiveComparator;
K
kohsuke 已提交
92 93 94 95 96 97
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 已提交
98
import hudson.util.RemotingDiagnostics;
99
import hudson.util.TextFile;
K
kohsuke 已提交
100
import hudson.util.XStream2;
K
kohsuke 已提交
101
import hudson.util.HudsonIsRestarting;
K
kohsuke 已提交
102 103
import hudson.util.DescribableList;
import hudson.util.Futures;
104
import hudson.util.Memoizer;
105
import hudson.util.Iterators;
106
import hudson.util.FormValidation;
107
import hudson.util.VersionNumber;
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
import org.apache.commons.io.FileUtils;
S
sogabe 已提交
119 120 121 122 123
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;
124
import org.kohsuke.stapler.StaplerFallback;
125
import org.kohsuke.stapler.WebApp;
126
import org.kohsuke.stapler.QueryParameter;
127 128
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
K
kohsuke 已提交
129
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
S
sogabe 已提交
130
import org.kohsuke.stapler.export.Exported;
131
import org.kohsuke.stapler.export.ExportedBean;
132
import org.xml.sax.InputSource;
K
kohsuke 已提交
133

S
sogabe 已提交
134 135 136 137 138 139 140 141
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 已提交
142 143 144
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
145
import java.io.FileOutputStream;
K
kohsuke 已提交
146 147
import java.io.IOException;
import java.io.PrintWriter;
K
kohsuke 已提交
148
import java.io.InputStream;
149
import java.net.URL;
150
import java.security.SecureRandom;
151
import java.text.NumberFormat;
K
kohsuke 已提交
152
import java.text.ParseException;
153
import java.text.Collator;
K
kohsuke 已提交
154 155 156 157 158 159 160
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;
161
import java.util.Iterator;
K
kohsuke 已提交
162 163
import java.util.List;
import java.util.Map;
S
sogabe 已提交
164
import java.util.Map.Entry;
K
kohsuke 已提交
165
import java.util.Set;
166 167
import java.util.Stack;
import java.util.StringTokenizer;
168
import java.util.Timer;
K
kohsuke 已提交
169
import java.util.TreeSet;
K
kohsuke 已提交
170
import java.util.Properties;
171
import java.util.concurrent.Callable;
172
import java.util.concurrent.ConcurrentHashMap;
K
kohsuke 已提交
173
import java.util.concurrent.CopyOnWriteArrayList;
174 175 176 177 178
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;
179
import java.util.concurrent.LinkedBlockingQueue;
K
kohsuke 已提交
180
import java.util.concurrent.TimeoutException;
181
import java.util.concurrent.CopyOnWriteArraySet;
K
kohsuke 已提交
182
import java.util.logging.Level;
K
kohsuke 已提交
183
import java.util.logging.LogRecord;
184
import java.util.logging.Logger;
185
import java.util.regex.Pattern;
186
import java.nio.charset.Charset;
187
import javax.servlet.RequestDispatcher;
K
kohsuke 已提交
188

189 190
import groovy.lang.GroovyShell;

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

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

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

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

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

    /**
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
     * 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.
     *
242
     * See {@link HudsonFilter} for the concrete authentication protocol.
243
     *
244 245
     * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
     * update this field.
246 247
     *
     * @see #getSecurity()
248
     * @see #setSecurityRealm(SecurityRealm)
K
kohsuke 已提交
249
     */
250
    private volatile SecurityRealm securityRealm;
K
kohsuke 已提交
251 252 253 254 255 256

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

257 258 259 260 261 262 263 264 265 266 267 268 269
    /**
     * We update this field to the current version of Hudson whenever we save {@code config.xml}.
     * This can be used to detect when an upgrade happens from one version to next.
     *
     * <p>
     * Since this field is introduced starting 1.301, "1.0" is used to represent every version
     * up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
     * "?", etc., so parsing needs to be done with a care.
     *
     * @since 1.301
     */
    private String version = "1.0";

K
kohsuke 已提交
270 271 272 273 274
    /**
     * Root directory of the system.
     */
    public transient final File root;

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

K
kohsuke 已提交
280 281 282 283 284
    /**
     * The sole instance.
     */
    private static Hudson theInstance;

K
kohsuke 已提交
285 286
    private transient volatile boolean isQuietingDown;
    private transient volatile boolean terminating;
K
kohsuke 已提交
287

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

290
    private transient volatile DependencyGraph dependencyGraph;
291

292 293 294
    /**
     * All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
     */
295 296 297 298 299
    private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
        public ExtensionList compute(Class key) {
            return ExtensionList.create(Hudson.this,key);
        }
    };
300 301

    /**
302
     * All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
303
     */
304 305
    private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
        public DescriptorExtensionList compute(Class key) {
306
            return DescriptorExtensionList.create(Hudson.this,key);
307 308
        }
    };
309

K
kohsuke 已提交
310 311 312 313 314 315 316 317 318 319
    /**
     * 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 已提交
320 321 322
        public CloudList() {// needed for XStream deserialization
        }

K
kohsuke 已提交
323 324 325 326 327 328
        protected void onModified() throws IOException {
            super.onModified();
            Hudson.getInstance().trimLabels();
        }
    }

K
kohsuke 已提交
329 330
    /**
     * Set of installed cluster nodes.
K
kohsuke 已提交
331
     * <p>
K
kohsuke 已提交
332 333 334 335
     * 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 已提交
336 337 338
     * <p>
     * The field name should be really {@code nodes}, but again the backward compatibility
     * prevents us from renaming.
K
kohsuke 已提交
339
     */
K
kohsuke 已提交
340
    private volatile NodeList slaves;
K
kohsuke 已提交
341 342 343 344 345 346 347 348 349

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

    /**
350
     * {@link View}s.
K
kohsuke 已提交
351
     */
352 353 354 355
    private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();

    /**
     * Name of the primary view.
356 357 358
     * <p>
     * Start with null, so that we can upgrade pre-1.269 data well.
     * @since 1.269
359 360
     */
    private volatile String primaryView;
361

K
kohsuke 已提交
362 363 364 365 366 367 368
    private transient final FingerprintMap fingerprintMap = new FingerprintMap();

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

369
    public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
K
kohsuke 已提交
370

371 372
    private transient UDPBroadcastThread udpBroadcastThread;

373
    /**
M
mindless 已提交
374
     * List of registered {@link ItemListener}s.
375
     * @deprecated as of 1.286
376
     */
377
    private transient final CopyOnWriteList<ItemListener> itemListeners = ExtensionListView.createCopyOnWriteList(ItemListener.class);
378 379 380 381 382

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

384 385
    /**
     * List of registered {@link ComputerListener}s.
386
     * @deprecated as of 1.286
387
     */
388
    private transient final CopyOnWriteList<ComputerListener> computerListeners = ExtensionListView.createCopyOnWriteList(ComputerListener.class);
389

390 391
    /**
     * TCP slave agent port.
392
     * 0 for random, -1 to disable.
393 394 395
     */
    private int slaveAgentPort =0;

396 397 398 399 400
    /**
     * Whitespace-separated labels assigned to the master as a {@link Node}.
     */
    private String label="";

401 402 403 404 405
    /**
     * 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>();
406
    private transient volatile Set<Label> labelSet;
407
    private transient volatile Set<Label> dynamicLabels = null;
408

K
kohsuke 已提交
409 410 411 412 413 414 415 416 417 418
    /**
     * 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);

419 420
    public transient final ServletContext servletContext;

K
kohsuke 已提交
421 422 423 424 425 426
    /**
     * Transient action list. Useful for adding navigation items to the navigation bar
     * on the left.
     */
    private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();

427
    /**
428
     * List of master node properties
429 430 431
     */
    private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);

432 433 434 435 436
    /**
     * List of global properties
     */
    private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);

437 438 439 440 441
    /**
     * {@link AdministrativeMonitor}s installed on this system.
     *
     * @see AdministrativeMonitor
     */
442
    public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
443

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

446 447 448 449 450
    /**
     * Widgets on Hudson.
     */
    private transient final List<Widget> widgets = getExtensionList(Widget.class);

K
kohsuke 已提交
451 452 453 454 455
    /**
     * {@link AdjunctManager}
     */
    private transient final AdjunctManager adjuncts;

K
kohsuke 已提交
456 457 458 459
    public static Hudson getInstance() {
        return theInstance;
    }

460 461
    /**
     * Secrete key generated once and used for a long time, beyond
K
kohsuke 已提交
462 463
     * container start/stop. Persisted outside <tt>config.xml</tt> to avoid
     * accidental exposure.
464
     */
K
kohsuke 已提交
465
    private transient final String secretKey;
466

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

469 470 471 472 473
    /**
     * True if the user opted out from the statistics tracking. We'll never send anything if this is true.
     */
    private Boolean noUsageStatistics;

474 475 476 477 478
    /**
     * HTTP proxy configuration.
     */
    public transient volatile ProxyConfiguration proxy;

K
kohsuke 已提交
479
    /**
480
     * Bound to "/log".
K
kohsuke 已提交
481
     */
482
    private transient final LogRecorderManager log = new LogRecorderManager();
483

K
kohsuke 已提交
484
    public Hudson(File root, ServletContext context) throws IOException {
485
    	// As hudson is starting, grant this process full controll
K
kohsuke 已提交
486
    	SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
487
        try {
488 489 490 491 492 493
            this.root = root;
            this.servletContext = context;
            computeVersion(context);
            if(theInstance!=null)
                throw new IllegalStateException("second instance");
            theInstance = this;
K
kohsuke 已提交
494

495
            log.load();
K
kohsuke 已提交
496

497
            Trigger.timer = new Timer("Hudson cron thread");
498
            queue = new Queue(LoadBalancer.DEFAULT); // TODO: make this somehow pluggable
499

500 501 502 503 504 505 506 507
            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;
            }
508

509 510 511 512 513 514 515 516 517 518 519
            // 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);
            }
K
kohsuke 已提交
520

521 522 523 524 525
            try {
                proxy = ProxyConfiguration.load();
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, "Failed to load proxy configuration", e);
            }
K
kohsuke 已提交
526

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
            // run the init code of SubversionSCM before we load plugins so that plugins can change SubversionWorkspaceSelector.
            SubversionSCM.init();

            // load plugins.
            pluginManager = new PluginManager(context);
            pluginManager.initialize();

            // if we are loading old data that doesn't have this field
            if(slaves==null)    slaves = new NodeList();

            adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+VERSION_HASH);

            load();

    //        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);
    //        }

            if(slaveAgentPort!=-1)
                tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
            else
                tcpSlaveAgentListener = null;

            udpBroadcastThread = new UDPBroadcastThread(this);
            udpBroadcastThread.start();

            updateComputerList();

            getQueue().load();

            for (ItemListener l : ItemListener.all())
                l.onLoaded();

            // 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();
                }
            }
580

581 582 583 584
            File userContentDir = new File(getRootDir(), "userContent");
            if(!userContentDir.exists()) {
                userContentDir.mkdirs();
                FileUtils.writeStringToFile(new File(userContentDir,"readme.txt"),Messages.Hudson_USER_CONTENT_README());
585
            }
586

587 588 589
            Trigger.init(); // start running trigger
        } finally {
            SecurityContextHolder.clearContext();
590
        }
K
kohsuke 已提交
591 592
    }

K
kohsuke 已提交
593 594 595 596
    public TcpSlaveAgentListener getTcpSlaveAgentListener() {
        return tcpSlaveAgentListener;
    }

K
kohsuke 已提交
597 598 599 600 601 602 603 604 605
    /**
     * 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 已提交
606
    @Exported
607 608 609 610
    public int getSlaveAgentPort() {
        return slaveAgentPort;
    }

K
kohsuke 已提交
611
    /**
J
jglick 已提交
612
     * If you are calling this on Hudson something is wrong.
K
kohsuke 已提交
613 614 615
     *
     * @deprecated
     */
J
jglick 已提交
616
    @Deprecated
K
kohsuke 已提交
617 618 619 620
    public String getNodeName() {
        return "";
    }

K
kohsuke 已提交
621 622 623 624
    public void setNodeName(String name) {
        throw new UnsupportedOperationException(); // not allowed
    }

K
kohsuke 已提交
625 626 627 628
    public String getNodeDescription() {
        return "the master Hudson node";
    }

629
    @Exported
K
kohsuke 已提交
630 631 632 633 634 635 636
    public String getDescription() {
        return systemMessage;
    }

    public PluginManager getPluginManager() {
        return pluginManager;
    }
637

638 639 640
    public UpdateCenter getUpdateCenter() {
        return updateCenter;
    }
K
kohsuke 已提交
641

642 643 644 645
    public boolean isUsageStatisticsCollected() {
        return noUsageStatistics==null || !noUsageStatistics;
    }

646 647 648 649 650
    public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
        this.noUsageStatistics = noUsageStatistics;
        save();
    }

651 652 653 654 655 656 657 658 659 660 661 662
    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() {
663
        return new Api(this);
664 665
    }

666 667 668
    /**
     * Returns a secret key that survives across container start/stop.
     * <p>
669
     * This value is useful for implementing some of the security features.
670 671
     */
    public String getSecretKey() {
K
kohsuke 已提交
672
        return secretKey;
673 674
    }

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

K
kohsuke 已提交
682 683 684 685
    /**
     * Gets the repository browser descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
686
        return findDescriptor(shortClassName,RepositoryBrowser.all());
K
kohsuke 已提交
687 688
    }

K
kohsuke 已提交
689 690 691 692
    /**
     * Gets the builder descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<Builder> getBuilder(String shortClassName) {
693
        return findDescriptor(shortClassName, Builder.all());
K
kohsuke 已提交
694 695
    }

K
kohsuke 已提交
696 697 698 699
    /**
     * Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
700
        return findDescriptor(shortClassName, BuildWrapper.all());
K
kohsuke 已提交
701 702
    }

K
kohsuke 已提交
703 704 705 706
    /**
     * Gets the publisher descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<Publisher> getPublisher(String shortClassName) {
707
        return findDescriptor(shortClassName, Publisher.all());
K
kohsuke 已提交
708 709
    }

K
kohsuke 已提交
710 711 712
    /**
     * Gets the trigger descriptor by name. Primarily used for making them web-visible.
     */
713
    public TriggerDescriptor getTrigger(String shortClassName) {
714
        return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
715 716 717 718 719 720
    }

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

724 725 726 727
    /**
     * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
     */
    public JobPropertyDescriptor getJobProperty(String shortClassName) {
K
kohsuke 已提交
728
        // combining these two lines triggers javac bug. See issue #610.
729
        Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
K
kohsuke 已提交
730
        return (JobPropertyDescriptor) d;
731 732
    }

733 734 735 736 737
    /**
     * 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.
738 739 740
     *
     * @param className
     *      Either fully qualified class name (recommended) or the short name.
741
     */
742
    public Descriptor getDescriptor(String className) {
743
        // legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
744 745 746 747 748
        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))
749
                return d;
750
        }
751 752 753
        return null;
    }

754 755 756 757 758 759 760
    /**
     * Alias for {@link #getDescriptor(String)}.
     */
    public Descriptor getDescriptorByName(String className) {
        return getDescriptor(className);
    }

K
kohsuke 已提交
761 762 763 764 765 766
    /**
     * 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.
     */
767
    public Descriptor getDescriptor(Class<? extends Describable> type) {
768
        for( Descriptor d : getExtensionList(Descriptor.class) )
769 770 771 772 773
            if(d.clazz==type)
                return d;
        return null;
    }

774 775 776 777 778 779 780 781 782 783
    /**
     * 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;
    }

784 785 786 787
    /**
     * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
     */
    public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
788
        return findDescriptor(shortClassName,SecurityRealm.all());
789 790
    }

K
kohsuke 已提交
791 792 793 794
    /**
     * Finds a descriptor that has the specified name.
     */
    private <T extends Describable<T>>
795
    Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
K
kohsuke 已提交
796 797 798 799 800 801 802 803
        String name = '.'+shortClassName;
        for (Descriptor<T> d : descriptors) {
            if(d.clazz.getName().endsWith(name))
                return d;
        }
        return null;
    }

804 805 806
    /**
     * Adds a new {@link JobListener}.
     *
807
     * @deprecated
M
mindless 已提交
808
     *      Use {@code getJobListeners().add(l)} instead.
809 810
     */
    public void addListener(JobListener l) {
K
kohsuke 已提交
811
        itemListeners.add(new JobListenerAdapter(l));
812 813 814 815 816
    }

    /**
     * Deletes an existing {@link JobListener}.
     *
817
     * @deprecated
M
mindless 已提交
818
     *      Use {@code getJobListeners().remove(l)} instead.
819 820
     */
    public boolean removeListener(JobListener l ) {
K
kohsuke 已提交
821
        return itemListeners.remove(new JobListenerAdapter(l));
822 823
    }

824
    /**
825
     * Gets all the installed {@link ItemListener}s.
826 827 828
     *
     * @deprecated as of 1.286.
     *      Use {@link ItemListener#all()}.
829
     */
830
    public CopyOnWriteList<ItemListener> getJobListeners() {
K
kohsuke 已提交
831
        return itemListeners;
832 833 834 835 836 837 838 839 840
    }

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

841 842
    /**
     * Gets all the installed {@link ComputerListener}s.
843 844
     *
     * @deprecated as of 1.286.
845
     *      Use {@link ComputerListener#all()}.
846 847 848 849 850
     */
    public CopyOnWriteList<ComputerListener> getComputerListeners() {
        return computerListeners;
    }

K
kohsuke 已提交
851 852 853 854 855 856 857 858 859 860
    /**
     * 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;
861
        return p.getPlugin();
K
kohsuke 已提交
862 863
    }

864 865 866 867 868 869 870 871 872 873 874 875
    /**
     * 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 已提交
876 877
    @SuppressWarnings("unchecked")
    public <P extends Plugin> P getPlugin(Class<P> clazz) {
878 879
        PluginWrapper p = pluginManager.getPlugin(clazz);
        if(p==null)     return null;
S
stephenconnolly 已提交
880
        return (P) p.getPlugin();
881 882 883 884 885 886 887 888 889
    }

    /**
     * Gets the plugin objects from their super-class.
     *
     * @param clazz The plugin class (beware class-loader fun)
     *
     * @return The plugin instances.
     */
S
stephenconnolly 已提交
890 891
    public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
        List<P> result = new ArrayList<P>();
892
        for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
S
stephenconnolly 已提交
893
            result.add((P)w.getPlugin());
894 895 896 897
        }
        return Collections.unmodifiableList(result);
    }

K
kohsuke 已提交
898 899 900 901 902 903 904
    /**
     * Synonym to {@link #getNodeDescription()}.
     */
    public String getSystemMessage() {
        return systemMessage;
    }

905 906 907 908 909 910 911 912
    /**
     * Sets the system message.
     */
    public void setSystemMessage(String message) throws IOException {
        this.systemMessage = message;
        save();
    }

K
kohsuke 已提交
913
    public Launcher createLauncher(TaskListener listener) {
K
kohsuke 已提交
914
        return new LocalLauncher(listener).decorateFor(this);
K
kohsuke 已提交
915 916
    }

K
kohsuke 已提交
917 918
    private final transient Object updateComputerLock = new Object();

K
kohsuke 已提交
919 920 921 922 923 924 925
    /**
     * 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 已提交
926
    private void updateComputerList() throws IOException {
K
kohsuke 已提交
927
        synchronized(updateComputerLock) {// just so that we don't have two code updating computer list at the same time
K
kohsuke 已提交
928
            Map<String,Computer> byName = new HashMap<String,Computer>();
K
kohsuke 已提交
929 930 931
            for (Computer c : computers.values()) {
                if(c.getNode()==null)
                    continue;   // this computer is gone
K
kohsuke 已提交
932
                byName.put(c.getNode().getNodeName(),c);
K
kohsuke 已提交
933
            }
K
kohsuke 已提交
934 935 936 937 938

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

            updateComputer(this, byName, used);
K
kohsuke 已提交
939
            for (Node s : getNodes())
K
kohsuke 已提交
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
                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 已提交
956 957
        if (c!=null) {
            c.setNode(n); // reuse
K
kohsuke 已提交
958
        } else {
K
kohsuke 已提交
959
            if(n.getNumExecutors()>0) {
K
kohsuke 已提交
960
                computers.put(n,c=n.createComputer());
961 962 963
                RetentionStrategy retentionStrategy = c.getRetentionStrategy();
                if (retentionStrategy != null) {
                    // if there is a retention strategy, it is responsible for deciding to start the computer
964
                    retentionStrategy.start(c);
965 966 967 968
                } else {
                    // we should never get here, but just in case, we'll fall back to the legacy behaviour
                    c.connect(true);
                }
K
kohsuke 已提交
969
            }
K
kohsuke 已提交
970 971 972 973 974
        }
        used.add(c);
    }

    /*package*/ void removeComputer(Computer computer) {
975 976
        for (Entry<Node, Computer> e : computers.entrySet()) {
            if (e.getValue() == computer) {
K
kohsuke 已提交
977
                computers.remove(e.getKey());
978
                return;
K
kohsuke 已提交
979 980 981 982 983
            }
        }
        throw new IllegalStateException("Trying to remove unknown computer");
    }

984 985 986 987
    public String getFullName() {
        return "";
    }

988 989 990 991
    public String getFullDisplayName() {
        return "";
    }

K
kohsuke 已提交
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    /**
     * 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;
    }

1012 1013 1014
    /**
     * Gets just the immediate children of {@link Hudson}.
     *
1015
     * @see #getAllItems(Class)
1016
     */
1017
    @Exported(name="jobs")
K
kohsuke 已提交
1018
    public List<TopLevelItem> getItems() {
K
kohsuke 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
        List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
        for (TopLevelItem item : items.values()) {
            if (item instanceof AccessControlled) {
            	if (((AccessControlled)item).hasPermission(Item.READ))
            		viewableItems.add(item);
            }
            else {
            	viewableItems.add(item);
            }
        }
        
        return viewableItems;
1031 1032
    }

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
    /**
     * 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 已提交
1044 1045 1046
    /**
     * Gets just the immediate children of {@link Hudson} but of the given type.
     */
K
kohsuke 已提交
1047
    public <T> List<T> getItems(Class<T> type) {
K
kohsuke 已提交
1048
        List<T> r = new ArrayList<T>();
K
kohsuke 已提交
1049
        for (TopLevelItem i : getItems())
K
kohsuke 已提交
1050 1051 1052 1053 1054
            if (type.isInstance(i))
                 r.add(type.cast(i));
        return r;
    }

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    /**
     * 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()) {
K
kohsuke 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076
                if(type.isInstance(i)) {
                    if (i instanceof AccessControlled) {
                    	if (((AccessControlled)i).hasPermission(Item.READ))
                    		r.add(type.cast(i));
                    }
                    else {
                    	r.add(type.cast(i));
                    }
                }
1077 1078 1079 1080 1081 1082 1083 1084
                if(i instanceof ItemGroup)
                    q.push((ItemGroup)i);
            }
        }

        return r;
    }

K
kohsuke 已提交
1085
    /**
K
kohsuke 已提交
1086 1087 1088 1089 1090
     * 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 已提交
1091
     */
K
kohsuke 已提交
1092
    public List<Project> getProjects() {
K
kohsuke 已提交
1093
        return Util.createSubList(items.values(),Project.class);
K
kohsuke 已提交
1094 1095 1096 1097 1098
    }

    /**
     * Gets the names of all the {@link Job}s.
     */
K
kohsuke 已提交
1099
    public Collection<String> getJobNames() {
1100
        List<String> names = new ArrayList<String>();
K
kohsuke 已提交
1101
        for (Job j : getAllItems(Job.class))
1102
            names.add(j.getFullName());
1103
        return names;
K
kohsuke 已提交
1104 1105
    }

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
    /**
     * 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;
    }

1116
    public synchronized View getView(String name) {
1117 1118 1119
        for (View v : views) {
            if(v.getViewName().equals(name))
                return v;
K
kohsuke 已提交
1120
        }
1121
        return null;
K
kohsuke 已提交
1122 1123 1124
    }

    /**
1125
     * Gets the read-only list of all {@link View}s.
K
kohsuke 已提交
1126
     */
1127
    @Exported
1128
    public synchronized Collection<View> getViews() {
1129
        List<View> copy = new ArrayList<View>(views);
1130 1131
        Collections.sort(copy, View.SORTER);
        return copy;
K
kohsuke 已提交
1132 1133
    }

1134 1135 1136 1137 1138
    public void addView(View v) throws IOException {
        views.add(v);
        save();
    }

1139
    public synchronized void deleteView(View view) throws IOException {
1140 1141 1142 1143
        if(views.size()<=1)
            throw new IllegalStateException();
        views.remove(view);
        save();
K
kohsuke 已提交
1144 1145
    }

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    /**
     * Returns true if the current running Hudson is upgraded from a version earlier than the specified version.
     *
     * <p>
     * This method continues to return true until the system configuration is saved, at which point
     * {@link #version} will be overwritten and Hudson forgets the upgrade history.
     */
    public boolean isUpgradedFromBefore(VersionNumber v) {
        try {
            return new VersionNumber(version).isOlderThan(v);
        } catch (IllegalArgumentException e) {
            // fail to parse this version number
            return false;
        }
    }

K
kohsuke 已提交
1162 1163 1164 1165
    /**
     * Gets the read-only list of all {@link Computer}s.
     */
    public Computer[] getComputers() {
1166 1167
        Computer[] r = computers.values().toArray(new Computer[computers.size()]);
        Arrays.sort(r,new Comparator<Computer>() {
1168
            final Collator collator = Collator.getInstance();
1169 1170 1171
            public int compare(Computer lhs, Computer rhs) {
                if(lhs.getNode()==Hudson.this)  return -1;
                if(rhs.getNode()==Hudson.this)  return 1;
1172
                return collator.compare(lhs.getDisplayName(), rhs.getDisplayName());
1173 1174 1175
            }
        });
        return r;
K
kohsuke 已提交
1176 1177
    }

1178 1179 1180 1181
    /*package*/ Computer getComputer(Node n) {
        return computers.get(n);
    }

K
kohsuke 已提交
1182
    public Computer getComputer(String name) {
K
kohsuke 已提交
1183 1184 1185
        if(name.equals("(master)"))
            name = "";

1186 1187 1188
        for (Computer c : computers.values()) {
            if(c.getNode().getNodeName().equals(name))
                return c;
K
kohsuke 已提交
1189 1190 1191 1192
        }
        return null;
    }

K
kohsuke 已提交
1193 1194 1195 1196 1197 1198 1199 1200
    /**
     * @deprecated
     *      UI method. Not meant to be used programatically.
     */
    public ComputerSet getComputer() {
        return new ComputerSet();
    }

1201 1202 1203 1204 1205 1206
    /**
     * 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 已提交
1207
        if(name==null)  return null;
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
        while(true) {
            Label l = labels.get(name);
            if(l!=null)
                return l;

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

    /**
1219
     * Gets all the active labels in the current system.
1220 1221 1222 1223
     */
    public Set<Label> getLabels() {
        Set<Label> r = new TreeSet<Label>();
        for (Label l : labels.values()) {
K
kohsuke 已提交
1224
            if(!l.isEmpty())
1225 1226 1227 1228 1229
                r.add(l);
        }
        return r;
    }

K
kohsuke 已提交
1230 1231 1232 1233 1234
    public Queue getQueue() {
        return queue;
    }

    public String getDisplayName() {
K
i18n  
kohsuke 已提交
1235
        return Messages.Hudson_DisplayName();
K
kohsuke 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
    }

    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) {
1248 1249 1250 1251 1252 1253
        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 已提交
1254 1255 1256 1257 1258 1259 1260 1261 1262
        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 已提交
1263 1264 1265
     *
     * @deprecated
     *      Use {@link #getNode(String)}. Since 1.252.
K
kohsuke 已提交
1266 1267
     */
    public Slave getSlave(String name) {
K
kohsuke 已提交
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
        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 已提交
1279 1280 1281 1282 1283 1284
            if(s.getNodeName().equals(name))
                return s;
        }
        return null;
    }

K
kohsuke 已提交
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
    /**
     * 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 已提交
1299
    public List<Slave> getSlaves() {
K
kohsuke 已提交
1300 1301 1302 1303 1304 1305 1306 1307
        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 已提交
1308 1309 1310
        return Collections.unmodifiableList(slaves);
    }

1311 1312
    /**
     * Updates the slave list.
K
kohsuke 已提交
1313 1314 1315
     *
     * @deprecated
     *      Use {@link #setNodes(List)}. Since 1.252.
1316 1317
     */
    public void setSlaves(List<Slave> slaves) throws IOException {
K
kohsuke 已提交
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
        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);
1348
        updateComputerList();
K
kohsuke 已提交
1349 1350 1351
        trimLabels();
        save();
    }
1352

1353 1354 1355
    public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
    	return nodeProperties;
    }
1356

1357 1358 1359 1360
    public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
    	return globalNodeProperties;
    }

K
kohsuke 已提交
1361 1362 1363 1364
    /**
     * Resets all labels and remove invalid ones.
     */
    private void trimLabels() {
1365 1366 1367
        for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
            Label l = itr.next();
            l.reset();
K
kohsuke 已提交
1368
            if(l.isEmpty())
1369 1370
                itr.remove();
        }
K
kohsuke 已提交
1371
    }
1372

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    /**
     * 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 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    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);
        }
1398 1399
    }

K
kohsuke 已提交
1400 1401 1402 1403 1404 1405 1406
    /**
     * Gets the system default quiet period.
     */
    public int getQuietPeriod() {
        return quietPeriod!=null ? quietPeriod : 5;
    }

K
kohsuke 已提交
1407 1408 1409 1410 1411
    /**
     * @deprecated
     *      Why are you calling a method that always returns ""?
     *      Perhaps you meant {@link #getRootUrl()}.
     */
K
kohsuke 已提交
1412 1413 1414 1415
    public String getUrl() {
        return "";
    }

1416 1417 1418 1419
    public String getSearchUrl() {
        return "";
    }

K
kohsuke 已提交
1420 1421 1422 1423
    public void onViewRenamed(View view, String oldName, String newName) {
        // implementation of Hudson is immune to view name change.
    }

1424
    @Override
1425 1426
    public SearchIndexBuilder makeSearchIndex() {
        return super.makeSearchIndex()
1427
            .add("configure", "config","configure")
K
kohsuke 已提交
1428
            .add("manage")
K
kohsuke 已提交
1429
            .add("log")
1430
            .add(getPrimaryView().makeSearchIndex())
K
kohsuke 已提交
1431 1432 1433
            .add(new CollectionSearchIndex() {// for computers
                protected Computer get(String key) { return getComputer(key); }
                protected Collection<Computer> all() { return computers.values(); }
K
kohsuke 已提交
1434
            })
K
kohsuke 已提交
1435
            .add(new CollectionSearchIndex() {// for users
K
kohsuke 已提交
1436
                protected User get(String key) { return User.get(key,false); }
K
kohsuke 已提交
1437
                protected Collection<User> all() { return User.getAll(); }
K
kohsuke 已提交
1438
            })
K
kohsuke 已提交
1439 1440
            .add(new CollectionSearchIndex() {// for views
                protected View get(String key) { return getView(key); }
1441
                protected Collection<View> all() { return views; }
K
kohsuke 已提交
1442
            });
1443 1444
    }

1445 1446 1447
    /**
     * Returns the primary {@link View} that renders the top-page of Hudson.
     */
1448
    @Exported
1449 1450 1451 1452 1453 1454 1455
    public View getPrimaryView() {
        View v = getView(primaryView);
        if(v==null) // fallback
            v = views.get(0);
        return v;
    }

1456 1457 1458 1459
    public String getUrlChildPrefix() {
        return "job";
    }

K
kohsuke 已提交
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
    /**
     * 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 已提交
1479
     * @see Descriptor#getCheckUrl(String)
K
renamed  
kohsuke 已提交
1480
     * @see #getRootUrlFromRequest()
K
kohsuke 已提交
1481 1482 1483
     */
    public String getRootUrl() {
        // for compatibility. the actual data is stored in Mailer
1484
        String url = Mailer.descriptor().getUrl();
1485 1486 1487
        if(url!=null)   return url;

        StaplerRequest req = Stapler.getCurrentRequest();
K
kohsuke 已提交
1488
        if(req!=null)
K
renamed  
kohsuke 已提交
1489
            return getRootUrlFromRequest();
1490
        return null;
K
kohsuke 已提交
1491 1492
    }

K
kohsuke 已提交
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
    /**
     * 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 已提交
1505
    public String getRootUrlFromRequest() {
K
kohsuke 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
        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 已提交
1516 1517 1518 1519
    public File getRootDir() {
        return root;
    }

1520 1521 1522 1523
    public FilePath getWorkspaceFor(TopLevelItem item) {
        return new FilePath(new File(item.getRootDir(),"workspace"));
    }

K
kohsuke 已提交
1524 1525 1526 1527
    public FilePath getRootPath() {
        return new FilePath(getRootDir());
    }

1528 1529 1530 1531
    public FilePath createPath(String absolutePath) {
        return new FilePath((VirtualChannel)null,absolutePath);
    }

1532 1533
    public ClockDifference getClockDifference() {
        return ClockDifference.ZERO;
K
kohsuke 已提交
1534 1535
    }

1536 1537 1538 1539 1540 1541 1542 1543 1544
    /**
     * 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 已提交
1545
    /**
1546 1547
     * A convenience method to check if there's some security
     * restrictions in place.
K
kohsuke 已提交
1548
     */
K
kohsuke 已提交
1549
    public boolean isUseSecurity() {
1550
        return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
1551 1552
    }

K
kohsuke 已提交
1553
    /**
1554 1555
     * Returns the constant that captures the three basic security modes
     * in Hudson.
K
kohsuke 已提交
1556
     */
1557 1558 1559 1560 1561 1562 1563 1564 1565
    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 已提交
1566 1567
    }

K
kohsuke 已提交
1568 1569 1570 1571 1572 1573 1574 1575
    /**
     * @return
     *      never null.
     */
    public SecurityRealm getSecurityRealm() {
        return securityRealm;
    }

1576
    public void setSecurityRealm(SecurityRealm securityRealm) {
1577 1578
        if(securityRealm==null)
            securityRealm= SecurityRealm.NO_AUTHENTICATION;
1579
        this.securityRealm = securityRealm;
1580 1581
        // reset the filters and proxies for the new SecurityRealm
        try {
K
kohsuke 已提交
1582 1583 1584 1585
            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 已提交
1586
                LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
K
kohsuke 已提交
1587
            } else {
K
kohsuke 已提交
1588
                LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
K
kohsuke 已提交
1589
                filter.reset(securityRealm);
K
kohsuke 已提交
1590
                LOGGER.fine("Security is now fully set up");
K
kohsuke 已提交
1591
            }
1592 1593 1594 1595
        } catch (ServletException e) {
            // for binary compatibility, this method cannot throw a checked exception
            throw new AcegiSecurityException("Failed to configure filter",e) {};
        }
1596
    }
1597

1598 1599 1600 1601 1602 1603
    public void setAuthorizationStrategy(AuthorizationStrategy a) {
        if (a == null)
            a = AuthorizationStrategy.UNSECURED;
        authorizationStrategy = a;
    }

1604 1605 1606
    public Lifecycle getLifecycle() {
        return Lifecycle.get();
    }
1607

1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
    /**
     * 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) {
1619
        return extensionLists.get(extensionType);
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
    }

    /**
     * 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"})
1630
    public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
1631
        return descriptorLists.get(type);
1632 1633
    }

1634 1635 1636 1637 1638 1639 1640
    /**
     * Returns the root {@link ACL}.
     *
     * @see AuthorizationStrategy#getRootACL()
     */
    public ACL getACL() {
        return authorizationStrategy.getRootACL();
K
kohsuke 已提交
1641 1642
    }

1643 1644 1645 1646 1647 1648
    /**
     * @return
     *      never null.
     */
    public AuthorizationStrategy getAuthorizationStrategy() {
        return authorizationStrategy;
K
kohsuke 已提交
1649 1650
    }

K
kohsuke 已提交
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
    /**
     * 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;
    }

1669 1670 1671 1672 1673
    public void setNumExecutors(int n) throws IOException {
        this.numExecutors = n;
        save();
    }

K
kohsuke 已提交
1674
    /**
1675 1676 1677
     * @deprecated
     *      Left only for the compatibility of URLs.
     *      Should not be invoked for any other purpose.
K
kohsuke 已提交
1678
     */
1679 1680
    public TopLevelItem getJob(String name) {
        return getItem(name);
K
kohsuke 已提交
1681 1682
    }

1683 1684 1685 1686 1687 1688
    /**
     * @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 已提交
1689
            if(Functions.toEmailSafeString(e.getKey()).equalsIgnoreCase(Functions.toEmailSafeString(name)))
1690 1691 1692 1693 1694
                return e.getValue();
        }
        return null;
    }

K
kohsuke 已提交
1695 1696 1697 1698 1699
    /**
     * {@inheritDoc}.
     *
     * Note that the look up is case-insensitive.
     */
K
kohsuke 已提交
1700
    public TopLevelItem getItem(String name) {
K
kohsuke 已提交
1701 1702 1703 1704 1705 1706 1707
    	TopLevelItem item = items.get(name);
        if (item instanceof AccessControlled) {
        	if (!((AccessControlled) item).hasPermission(Item.READ)) {
        		return null;
        	}
        }
        return item;
1708 1709
    }

1710
    public File getRootDirFor(TopLevelItem child) {
1711 1712 1713 1714 1715
        return getRootDirFor(child.getName());
    }

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

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
    /**
     * 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 已提交
1747 1748 1749 1750
    public Item getItemByFullName(String fullName) {
        return getItemByFullName(fullName,Item.class);
    }

K
kohsuke 已提交
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
    /**
     * 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.
     */
1767
    public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
K
kohsuke 已提交
1768
        if(items.containsKey(name))
K
kohsuke 已提交
1769 1770
            throw new IllegalArgumentException();

K
kohsuke 已提交
1771
        TopLevelItem item;
K
kohsuke 已提交
1772
        try {
K
kohsuke 已提交
1773
            item = type.newInstance(name);
K
kohsuke 已提交
1774 1775 1776 1777
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }

K
kohsuke 已提交
1778 1779 1780
        item.save();
        items.put(name,item);
        return item;
K
kohsuke 已提交
1781 1782
    }

K
kohsuke 已提交
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
    /**
     * 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 已提交
1796 1797 1798
    /**
     * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
     */
1799
    /*package*/ void deleteJob(TopLevelItem item) throws IOException {
1800
        for (ItemListener l : ItemListener.all())
1801
            l.onDeleted(item);
1802

1803
        items.remove(item.getName());
1804 1805 1806
        for (View v : views)
            v.onJobRenamed(item, item.getName(), null);
        save();
K
kohsuke 已提交
1807 1808 1809 1810 1811 1812
    }

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

1817 1818 1819
        for (View v : views)
            v.onJobRenamed(job, oldName, newName);
        save();
K
kohsuke 已提交
1820 1821 1822 1823 1824 1825
    }

    public FingerprintMap getFingerprintMap() {
        return fingerprintMap;
    }

K
kohsuke 已提交
1826
    // if no finger print matches, display "not found page".
K
kohsuke 已提交
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
    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() {
1853
        return mode;
K
kohsuke 已提交
1854 1855
    }

1856 1857 1858 1859
    public String getLabelString() {
        return Util.fixNull(label).trim();
    }

1860
    public Set<Label> getAssignedLabels() {
1861 1862
        Set<Label> lset = labelSet; // labelSet may be set by another thread while we are in this method, so capture it.
        if (lset == null) {
1863
            Set<Label> r = new HashSet<Label>();
1864 1865 1866 1867
            String ls = getLabelString();
            if(ls.length()>0)
                for( String l : ls.split(" +"))
                    r.add(Hudson.getInstance().getLabel(l));
1868 1869
            r.addAll(getDynamicLabels());
            r.add(getSelfLabel());
1870
            this.labelSet = lset = Collections.unmodifiableSet(r);
1871
        }
1872
        return lset;
1873 1874 1875 1876 1877 1878 1879 1880 1881
    }

    /**
     * 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) {
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
            // 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));
1893 1894 1895 1896
                        }
                    }
                }
            }
1897
            dynamicLabels = r;
1898 1899
        }
        return dynamicLabels;
1900 1901 1902 1903 1904 1905
    }

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

K
kohsuke 已提交
1906 1907 1908 1909
    public Computer createComputer() {
        return new MasterComputer();
    }

K
kohsuke 已提交
1910
    private synchronized void load() throws IOException {
1911
        long startTime = System.currentTimeMillis();
K
kohsuke 已提交
1912
        XmlFile cfg = getConfigFile();
1913 1914 1915 1916
        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;
1917
            views.clear();
K
kohsuke 已提交
1918
            cfg.unmarshal(this);
1919
        }
K
kohsuke 已提交
1920
        clouds.setOwner(this);
K
kohsuke 已提交
1921 1922 1923 1924 1925 1926 1927 1928 1929

        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) {
1930
                return child.isDirectory() && Items.getConfigFile(child).exists();
K
kohsuke 已提交
1931 1932
            }
        });
1933
        items.clear();
1934
        if(PARALLEL_LOAD) {
1935
            // load jobs in parallel for better performance
1936
            LOGGER.info("Loading in "+TWICE_CPU_NUM+" parallel threads");
1937 1938 1939 1940
            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 {
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
                        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);
                        }
1953 1954 1955 1956 1957 1958 1959 1960 1961
                    }
                }));
            }

            for (Future<TopLevelItem> loader : loaders) {
                try {
                    TopLevelItem item = loader.get();
                    items.put(item.getName(), item);
                } catch (ExecutionException e) {
K
typo  
kohsuke 已提交
1962
                    LOGGER.log(Level.WARNING, "Failed to load a project",e.getCause());
1963 1964 1965 1966 1967 1968 1969
                } catch (InterruptedException e) {
                    e.printStackTrace(); // this is probably not the right thing to do
                }
            }
        } else {
            for (File subdir : subdirs) {
                try {
1970
                    long start = System.currentTimeMillis();
1971
                    TopLevelItem item = (TopLevelItem)Items.load(this,subdir);
1972 1973
                    if(LOG_STARTUP_PERFORMANCE)
                        LOGGER.info("Loaded "+item.getName()+" in "+(System.currentTimeMillis()-start)+"ms");
1974 1975 1976
                    items.put(item.getName(), item);
                } catch (Error e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
1977 1978
                } catch (RuntimeException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
1979 1980 1981
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
                }
K
kohsuke 已提交
1982 1983
            }
        }
1984
        rebuildDependencyGraph();
1985 1986

        // recompute label objects
1987
        if (null != slaves) { // only if we have slaves
K
kohsuke 已提交
1988
            for (Node slave : slaves)
1989 1990
                slave.getAssignedLabels();
        }
K
kohsuke 已提交
1991

1992 1993 1994 1995 1996 1997 1998 1999 2000
        // 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 已提交
2001
        // read in old data that doesn't have the security field set
2002 2003 2004 2005 2006 2007 2008 2009
        if(authorizationStrategy==null) {
            if(useSecurity==null || !useSecurity)
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
            else
                authorizationStrategy = new LegacyAuthorizationStrategy();
        }
        if(securityRealm==null) {
            if(useSecurity==null || !useSecurity)
2010
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
2011
            else
2012 2013 2014 2015
                setSecurityRealm(new LegacySecurityRealm());
        } else {
            // force the set to proxy
            setSecurityRealm(securityRealm);
2016
        }
2017

K
kohsuke 已提交
2018 2019 2020 2021
        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;
2022
            setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
K
kohsuke 已提交
2023
        }
2024

2025
        LOGGER.info(String.format("Took %s ms to load",System.currentTimeMillis()-startTime));
2026 2027
        if(KILL_AFTER_LOAD)
            System.exit(0);
K
kohsuke 已提交
2028 2029 2030 2031 2032 2033
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
2034
        if(BulkChange.contains(this))   return;
K
kohsuke 已提交
2035 2036 2037 2038 2039 2040 2041 2042
        getConfigFile().write(this);
    }


    /**
     * Called to shut down the system.
     */
    public void cleanUp() {
K
kohsuke 已提交
2043
        Set<Future<?>> pending = new HashSet<Future<?>>();
K
kohsuke 已提交
2044
        terminating = true;
2045 2046 2047
        for( Computer c : computers.values() ) {
            c.interrupt();
            c.kill();
K
kohsuke 已提交
2048
            pending.add(c.disconnect());
K
kohsuke 已提交
2049
        }
2050 2051
        if(udpBroadcastThread!=null)
            udpBroadcastThread.shutdown();
K
kohsuke 已提交
2052 2053
        ExternalJob.reloadThread.interrupt();
        Trigger.timer.cancel();
K
kohsuke 已提交
2054
        // TODO: how to wait for the completion of the last job?
K
kohsuke 已提交
2055
        Trigger.timer = null;
2056 2057
        if(tcpSlaveAgentListener!=null)
            tcpSlaveAgentListener.shutdown();
K
kohsuke 已提交
2058 2059 2060 2061

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

2062 2063 2064 2065
        if(getRootDir().exists())
            // if we are aborting because we failed to create HUDSON_HOME,
            // don't try to save. Issue #536
            getQueue().save();
2066 2067

        threadPoolForLoad.shutdown();
K
kohsuke 已提交
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
        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 已提交
2080
        LogFactory.releaseAll();
2081 2082

        theInstance = null;
K
kohsuke 已提交
2083 2084
    }

K
kohsuke 已提交
2085 2086
    public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
        for (Action a : getActions())
2087
            if(a.getUrlName().equals(token) || a.getUrlName().equals('/'+token))
K
kohsuke 已提交
2088
                return a;
2089 2090 2091
        for (Action a : getManagementLinks())
            if(a.getUrlName().equals(token))
                return a;
K
kohsuke 已提交
2092 2093
        return null;
    }
K
kohsuke 已提交
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104


//
//
// actions
//
//
    /**
     * Accepts submission from the configuration page.
     */
    public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
K
kohsuke 已提交
2105
        BulkChange bc = new BulkChange(this);
K
kohsuke 已提交
2106
        try {
K
kohsuke 已提交
2107
            checkPermission(ADMINISTER);
K
kohsuke 已提交
2108 2109 2110

            req.setCharacterEncoding("UTF-8");

2111
            JSONObject json = req.getSubmittedForm();
2112

2113 2114 2115
            // keep using 'useSecurity' field as the main configuration setting
            // until we get the new security implementation working
            // useSecurity = null;
2116
            if (json.has("use_security")) {
K
kohsuke 已提交
2117
                useSecurity = true;
K
kohsuke 已提交
2118
                JSONObject security = json.getJSONObject("use_security");
2119
                setSecurityRealm(SecurityRealm.all().newInstanceFromRadioList(security,"realm"));
2120
                setAuthorizationStrategy(AuthorizationStrategy.all().newInstanceFromRadioList(security, "authorization"));
K
kohsuke 已提交
2121
            } else {
2122
                useSecurity = null;
2123
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
2124
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
2125
            }
K
kohsuke 已提交
2126

2127 2128
            noUsageStatistics = json.has("usageStatisticsCollected") ? null : true;

2129 2130
            {
                String v = req.getParameter("slaveAgentPortType");
2131
                if(!isUseSecurity() || v==null || v.equals("random"))
2132 2133 2134 2135 2136 2137 2138 2139
                    slaveAgentPort = 0;
                else
                if(v.equals("disable"))
                    slaveAgentPort = -1;
                else {
                    try {
                        slaveAgentPort = Integer.parseInt(req.getParameter("slaveAgentPort"));
                    } catch (NumberFormatException e) {
K
i18n  
kohsuke 已提交
2140
                        throw new FormException(Messages.Hudson_BadPortNumber(req.getParameter("slaveAgentPort")),"slaveAgentPort");
2141 2142
                    }
                }
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155

                // 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);
                    }
                }
2156 2157
            }

K
kohsuke 已提交
2158 2159 2160 2161 2162 2163
            numExecutors = Integer.parseInt(req.getParameter("numExecutors"));
            if(req.hasParameter("master.mode"))
                mode = Mode.valueOf(req.getParameter("master.mode"));
            else
                mode = Mode.NORMAL;

2164 2165 2166
            label = Util.fixNull(req.getParameter("label"));
            labelSet=null;

K
kohsuke 已提交
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
            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;

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

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

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

2194
            for( SCMDescriptor scmd : SCM.all() )
K
kohsuke 已提交
2195
                result &= configureDescriptor(req,json,scmd);
K
kohsuke 已提交
2196

2197
            for( TriggerDescriptor d : Trigger.all() )
K
kohsuke 已提交
2198
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
2199

2200
            for( JobPropertyDescriptor d : JobPropertyDescriptor.all() )
K
kohsuke 已提交
2201
                result &= configureDescriptor(req,json,d);
2202

2203
            for( PageDecorator d : PageDecorator.all() )
2204 2205
                result &= configureDescriptor(req,json,d);

2206 2207 2208
            for( JSONObject o : StructuredForm.toList(json,"plugin"))
                pluginManager.getPlugin(o.getString("name")).getPlugin().configure(o);

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

2211 2212 2213 2214
            JSONObject np = json.getJSONObject("globalNodeProperties");
            if (np != null) {
                globalNodeProperties.rebuild(req, np, NodeProperty.for_(this));
            }
2215

2216 2217
            version = VERSION;

K
kohsuke 已提交
2218 2219
            save();
            if(result)
2220
                rsp.sendRedirect(req.getContextPath()+'/');  // go to the top page
K
kohsuke 已提交
2221 2222 2223 2224
            else
                rsp.sendRedirect("configure"); // back to config
        } catch (FormException e) {
            sendError(e,req,rsp);
K
kohsuke 已提交
2225 2226
        } finally {
            bc.commit();
K
kohsuke 已提交
2227 2228 2229
        }
    }

2230 2231 2232 2233 2234
    public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        JSONObject form = req.getSubmittedForm();
        rsp.sendRedirect("foo");
    }

2235
    private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
2236 2237 2238
        // 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.
2239 2240 2241 2242
        json.putAll(js);
        return d.configure(req, js);
    }

2243 2244 2245 2246
    /**
     * Accepts submission from the configuration page.
     */
    public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2247
        checkPermission(ADMINISTER);
2248

2249 2250 2251
        BulkChange bc = new BulkChange(this);
        try {
            JSONObject json = req.getSubmittedForm();
2252

2253
            setNumExecutors(Integer.parseInt(req.getParameter("numExecutors")));
2254 2255 2256 2257
            if(req.hasParameter("master.mode"))
                mode = Mode.valueOf(req.getParameter("master.mode"));
            else
                mode = Mode.NORMAL;
S
stephenconnolly 已提交
2258

2259 2260 2261 2262
            setSlaves(req.bindJSONToList(Slave.class,json.get("slaves")));
        } finally {
            bc.commit();
        }
S
stephenconnolly 已提交
2263

2264
        rsp.sendRedirect(req.getContextPath()+'/');  // go to the top page
2265 2266
    }

K
kohsuke 已提交
2267 2268 2269 2270
    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2271
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2272 2273 2274 2275 2276 2277 2278

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

2279
    public synchronized void doQuietDown(StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
2280
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2281 2282 2283 2284
        isQuietingDown = true;
        rsp.sendRedirect2(".");
    }

2285
    public synchronized void doCancelQuietDown(StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
2286
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2287 2288 2289 2290 2291
        isQuietingDown = false;
        getQueue().scheduleMaintenance();
        rsp.sendRedirect2(".");
    }

2292 2293 2294
    /**
     * Backward compatibility. Redirect to the thread dump.
     */
2295
    public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
2296 2297 2298
        rsp.sendRedirect2("threadDump");
    }

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

2302 2303
        TopLevelItem result;

K
kohsuke 已提交
2304 2305 2306 2307 2308 2309
        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");
2310 2311 2312 2313 2314 2315 2316
        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");
        }
2317 2318

        String name = req.getParameter("name");
K
typo.  
kohsuke 已提交
2319
        if(name==null) {
2320 2321 2322 2323
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Query parameter 'name' is required");
            return null;
        }
        name = name.trim();
K
kohsuke 已提交
2324 2325 2326 2327 2328
        String mode = req.getParameter("mode");

        try {
            checkGoodName(name);
        } catch (ParseException e) {
K
kohsuke 已提交
2329
            rsp.setStatus(SC_BAD_REQUEST);
K
kohsuke 已提交
2330 2331 2332 2333
            sendError(e,req,rsp);
            return null;
        }

2334
        if(getItem(name)!=null) {
K
kohsuke 已提交
2335
            rsp.setStatus(SC_BAD_REQUEST);
K
i18n  
kohsuke 已提交
2336
            sendError(Messages.Hudson_JobAlreadyExists(name),req,rsp);
K
kohsuke 已提交
2337 2338 2339
            return null;
        }

K
kohsuke 已提交
2340
        if(mode!=null && mode.equals("copy")) {
2341 2342
            String from = req.getParameter("from");
            TopLevelItem src = getItem(from);
K
kohsuke 已提交
2343
            if(src==null) {
2344 2345 2346 2347 2348
                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 已提交
2349 2350 2351
                return null;
            }

K
kohsuke 已提交
2352
            result = copy(src,name);
2353
        } else {
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
            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 已提交
2379
                    rsp.sendError(SC_BAD_REQUEST);
2380 2381 2382 2383
                    return null;
                }
                result = createProject(Items.getDescriptor(mode), name);
            }
K
kohsuke 已提交
2384

2385
            for (ItemListener l : ItemListener.all())
K
kohsuke 已提交
2386 2387
                l.onCreated(result);
        }
2388

2389 2390 2391 2392 2393
        if(isXmlSubmission) {
            // it worked
            rsp.setStatus(HttpServletResponse.SC_OK);
        } else {
            // send the browser to the config page
2394
            rsp.sendRedirect2(result.getUrl()+"configure");
2395 2396
        }

K
kohsuke 已提交
2397 2398 2399
        return result;
    }

K
kohsuke 已提交
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
    /**
     * 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);

2422
        for (ItemListener l : ItemListener.all())
K
kohsuke 已提交
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433
            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 已提交
2434
    public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2435 2436
        try {
            checkPermission(View.CREATE);
2437
            addView(View.create(req,rsp, this));
K
kohsuke 已提交
2438 2439
        } catch (ParseException e) {
            sendError(e,req,rsp);
2440 2441 2442
        } catch (FormException e) {
            sendError(e,req,rsp);
        }
K
kohsuke 已提交
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
    }

    /**
     * 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 已提交
2454
            throw new ParseException(Messages.Hudson_NoName(),0);
K
kohsuke 已提交
2455 2456 2457

        for( int i=0; i<name.length(); i++ ) {
            char ch = name.charAt(i);
2458 2459 2460
            if(Character.isISOControl(ch)) {
                throw new ParseException(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)),i);
            }
K
kohsuke 已提交
2461
            if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
K
i18n  
kohsuke 已提交
2462
                throw new ParseException(Messages.Hudson_UnsafeChar(ch),i);
K
kohsuke 已提交
2463 2464 2465 2466 2467
        }

        // looks good
    }

2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
    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();
    }

2480
    /**
2481 2482 2483
     * Checks if the user was successfully authenticated.
     *
     * @see BasicAuthenticationFilter
2484 2485
     */
    public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2486 2487
        if(req.getUserPrincipal()==null) {
            // authentication must have failed
2488 2489 2490 2491
            rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

2492
        // the user is now authenticated, so send him back to the target
2493 2494 2495
        String path = req.getContextPath()+req.getRestOfPath();
        String q = req.getQueryString();
        if(q!=null)
2496
            path += '?'+q;
2497

2498
        rsp.sendRedirect2(path);
2499 2500
    }

K
kohsuke 已提交
2501 2502 2503
    /**
     * Called once the user logs in. Just forward to the top page.
     */
K
kohsuke 已提交
2504
    public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
2505 2506
        if(req.getUserPrincipal()==null)
            rsp.sendRedirect2("noPrincipal");
2507 2508

        String from = req.getParameter("from");
2509
        if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
2510
            rsp.sendRedirect2(from);    // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
            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 已提交
2523 2524 2525 2526 2527
    }

    /**
     * Called once the user logs in. Just forward to the top page.
     */
K
kohsuke 已提交
2528
    public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
2529 2530 2531
        HttpSession session = req.getSession(false);
        if(session!=null)
            session.invalidate();
2532
        SecurityContextHolder.clearContext();
2533 2534 2535 2536 2537 2538

        // 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 已提交
2539 2540 2541
        rsp.sendRedirect2(req.getContextPath()+"/");
    }

2542 2543 2544 2545 2546 2547 2548
    /**
     * Serves jar files for JNLP slave agents.
     */
    public Slave.JnlpJar getJnlpJars(String fileName) {
        return new Slave.JnlpJar(fileName);
    }

K
kohsuke 已提交
2549 2550
    /**
     * RSS feed for log entries.
2551 2552 2553
     *
     * @deprecated
     *   As on 1.267, moved to "/log/rss..."
K
kohsuke 已提交
2554 2555
     */
    public void doLogRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2556 2557
        String qs = req.getQueryString();
        rsp.sendRedirect2("./log/rss"+(qs==null?"":'?'+qs));
K
kohsuke 已提交
2558 2559
    }

K
kohsuke 已提交
2560 2561 2562 2563
    /**
     * Reloads the configuration.
     */
    public synchronized void doReload( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
2564
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2565

2566 2567 2568 2569
        // 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 已提交
2570
        rsp.sendRedirect2(req.getContextPath()+"/");
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582

        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 已提交
2583 2584 2585 2586 2587 2588
    }

    /**
     * Do a finger-print check.
     */
    public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2589 2590
        // Parse the request
        MultipartFormDataParser p = new MultipartFormDataParser(req);
K
kohsuke 已提交
2591 2592
        try {
            rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
2593 2594 2595
                Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
        } finally {
            p.cleanUp();
K
kohsuke 已提交
2596 2597 2598 2599 2600 2601 2602
        }
    }

    /**
     * Serves static resources without the "Last-Modified" header to work around
     * a bug in Firefox.
     *
K
kohsuke 已提交
2603 2604
     * <p>
     * See https://bugzilla.mozilla.org/show_bug.cgi?id=89419
K
kohsuke 已提交
2605 2606 2607 2608 2609 2610 2611 2612 2613
     */
    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 已提交
2614
            rsp.sendError(SC_BAD_REQUEST);
K
kohsuke 已提交
2615 2616 2617 2618 2619
            return;
        }

        File f = new File(req.getServletContext().getRealPath("/images"),path.substring(1));
        if(!f.exists()) {
2620
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
            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 已提交
2635
        Util.copyStream(in,rsp.getOutputStream());
K
kohsuke 已提交
2636 2637 2638 2639
        in.close();
    }

    /**
K
kohsuke 已提交
2640
     * For debugging. Expose URL to perform GC.
K
kohsuke 已提交
2641
     */
2642
    public void doGc(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2643 2644 2645 2646 2647 2648
        System.gc();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("GCed");
    }

2649 2650 2651 2652 2653 2654 2655
    /**
     * Binds /userContent/... to $HUDSON_HOME/userContent.
     */
    public DirectoryBrowserSupport doUserContent() {
        return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.gif",true);
    }

K
kohsuke 已提交
2656 2657 2658 2659
    /**
     * Perform a restart of Hudson, if we can.
     */
    public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
2660
        requirePOST();
K
kohsuke 已提交
2661 2662 2663 2664 2665 2666 2667
        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);
2668 2669 2670 2671
        } catch (IOException e) {
            sendError(e,req,rsp);
        } catch (InterruptedException e) {
            sendError(e,req,rsp);
K
kohsuke 已提交
2672 2673 2674
        }
    }

K
kohsuke 已提交
2675 2676 2677 2678 2679
    /**
     * Shutdown the system.
     * @since 1.161
     */
    public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
2680
        checkPermission(ADMINISTER);
2681
        LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
K
kohsuke 已提交
2682
                getAuthentication(), req.getRemoteAddr()));
K
kohsuke 已提交
2683 2684 2685 2686 2687
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        PrintWriter w = rsp.getWriter();
        w.println("Shutting down");
        w.close();
2688

K
kohsuke 已提交
2689 2690 2691
        System.exit(0);
    }

K
kohsuke 已提交
2692 2693 2694 2695 2696
    /**
     * Gets the {@link Authentication} object that represents the user
     * associated with the current request.
     */
    public static Authentication getAuthentication() {
K
kohsuke 已提交
2697 2698 2699 2700 2701
        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 已提交
2702 2703
        if(a==null)
            a = new AnonymousAuthenticationToken("anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
K
kohsuke 已提交
2704
        return a;
K
kohsuke 已提交
2705 2706
    }

K
kohsuke 已提交
2707 2708
    /**
     * For system diagnostics.
K
kohsuke 已提交
2709
     * Run arbitrary Groovy script.
K
kohsuke 已提交
2710
     */
2711 2712 2713
    public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        doScript(req, rsp, req.getView(this, "_script.jelly"));
    }
2714

2715 2716 2717 2718 2719 2720 2721 2722
    /**
     * 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 {
2723 2724
        // ability to run arbitrary script is dangerous
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2725 2726

        String text = req.getParameter("script");
2727
        if (text != null) {
K
kohsuke 已提交
2728
            try {
2729
                req.setAttribute("output",
2730
                        RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel));
2731 2732
            } catch (InterruptedException e) {
                throw new ServletException(e);
K
kohsuke 已提交
2733 2734 2735
            }
        }

2736
        view.forward(req, rsp);
K
kohsuke 已提交
2737 2738
    }

2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
    /**
     * 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 已提交
2757 2758 2759 2760 2761 2762 2763
    /**
     * 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 已提交
2764 2765 2766
    /**
     * Changes the icon size by changing the cookie
     */
K
kohsuke 已提交
2767 2768
    public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        String qs = req.getQueryString();
J
jglick 已提交
2769
        if(qs==null || !ICON_SIZE.matcher(qs).matches())
K
kohsuke 已提交
2770
            throw new ServletException();
2771 2772 2773
        Cookie cookie = new Cookie("iconSize", qs);
        cookie.setMaxAge(/* ~4 mo. */9999999); // #762
        rsp.addCookie(cookie);
K
kohsuke 已提交
2774 2775 2776
        String ref = req.getHeader("Referer");
        if(ref==null)   ref=".";
        rsp.sendRedirect2(ref);
K
kohsuke 已提交
2777 2778
    }

2779
    public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2780 2781 2782 2783 2784 2785
        FingerprintCleanupThread.invoke();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("Invoked");
    }

2786
    public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2787 2788 2789 2790 2791 2792 2793 2794 2795
        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.
     */
2796
    public FormValidation doJavaHomeCheck(@QueryParameter File value) {
K
kohsuke 已提交
2797
        // this can be used to check the existence of a file on the server, so needs to be protected
2798
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2799

2800 2801
        if(!value.isDirectory())
            return FormValidation.error(Messages.Hudson_NotADirectory(value));
K
kohsuke 已提交
2802

2803 2804 2805 2806 2807 2808
        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 已提交
2809 2810
    }

K
kohsuke 已提交
2811 2812 2813
    /**
     * If the user chose the default JDK, make sure we got 'java' in PATH.
     */
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
    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 已提交
2825 2826
    }

K
kohsuke 已提交
2827 2828 2829
    /**
     * Checks if the top-level item with the given name exists.
     */
2830
    public FormValidation doItemExistsCheck(@QueryParameter String value) {
K
kohsuke 已提交
2831 2832
        // this method can be used to check if a file exists anywhere in the file system,
        // so it should be protected.
2833 2834 2835 2836
        checkPermission(Item.CREATE);
        
        String job = fixEmpty(value);
        if(job==null)
K
kohsuke 已提交
2837
            return FormValidation.ok();
2838 2839 2840 2841 2842

        if(getItem(job)==null)
            return FormValidation.ok();
        else
            return FormValidation.error(Messages.Hudson_JobAlreadyExists(job));
K
kohsuke 已提交
2843
    }
2844 2845 2846 2847

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

2851
        String view = fixEmpty(value);
K
kohsuke 已提交
2852
        if(view==null) return FormValidation.ok();
2853 2854 2855 2856 2857

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

2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
    /**
     * @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);
    }
2871

2872 2873 2874 2875 2876
    /**
     * 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 已提交
2877
     * <p>
2878 2879
     * 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 已提交
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
     */
    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().");
        }
2892

K
kohsuke 已提交
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
        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());
2903
                }
K
kohsuke 已提交
2904 2905
            } catch (ParseException e) {
                return FormValidation.error(Messages.Hudson_NotANumber());
2906
            }
K
kohsuke 已提交
2907
        }
2908

K
kohsuke 已提交
2909
        return FormValidation.ok();
2910
    }
K
kohsuke 已提交
2911

2912 2913 2914 2915 2916 2917 2918 2919
    /**
     * 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.
     */
2920
    public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
2921
        String path = req.getRestOfPath();
2922 2923 2924 2925 2926 2927
        // 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);

2928 2929 2930
        int idx = path.lastIndexOf('.');
        String extension = path.substring(idx+1);
        if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
2931 2932 2933 2934
            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);
2935 2936 2937 2938 2939 2940
                return;
            }
        }
        rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

S
sogabe 已提交
2941 2942 2943 2944 2945 2946 2947 2948
    /**
     * 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("\\|")
    ));

2949 2950 2951
    /**
     * Checks if container uses UTF-8 to decode URLs. See
     * http://hudson.gotdns.com/wiki/display/HUDSON/Tomcat#Tomcat-i18n
K
kohsuke 已提交
2952 2953 2954 2955 2956 2957 2958 2959 2960
     */
    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();
2961
    }
S
sogabe 已提交
2962

2963 2964 2965 2966 2967 2968
    /**
     * 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 已提交
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983

    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 已提交
2984
        for( AbstractProject p : getAllItems(AbstractProject.class) ) {
K
kohsuke 已提交
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994
            SCM scm = p.getScm();
            if (scm instanceof CVSSCM) {
                CVSSCM cvsscm = (CVSSCM) scm;
                r.add(cvsscm.getCvsRoot());
            }
        }

        return r;
    }

2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
    /**
     * Rebuilds the dependency map.
     */
    public void rebuildDependencyGraph() {
        dependencyGraph = new DependencyGraph();
    }

    public DependencyGraph getDependencyGraph() {
        return dependencyGraph;
    }

3006 3007
    // for Jelly
    public List<ManagementLink> getManagementLinks() {
3008
        return ManagementLink.all();
3009 3010
    }

K
kohsuke 已提交
3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
    /**
     * 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 已提交
3022
    public Object getTarget() {
K
kohsuke 已提交
3023 3024 3025 3026 3027 3028 3029
        try {
            checkPermission(READ);
        } catch (AccessDeniedException e) {
            String rest = Stapler.getCurrentRequest().getRestOfPath();
            if(rest.startsWith("/login")
            || rest.startsWith("/logout")
            || rest.startsWith("/accessDenied")
3030
            || rest.startsWith("/signup")
3031
            || rest.startsWith("/jnlpJars/")
3032
            || rest.startsWith("/tcpSlaveAgentListener")
K
kohsuke 已提交
3033 3034 3035 3036
            || rest.startsWith("/securityRealm"))
                return this;    // URLs that are always visible without READ permission
            throw e;
        }
K
kohsuke 已提交
3037 3038 3039
        return this;
    }

3040 3041 3042 3043 3044 3045 3046
    /**
     * Fallback to the primary view.
     */
    public View getStaplerFallback() {
        return getPrimaryView();
    }

K
kohsuke 已提交
3047 3048 3049 3050 3051
    public static final class MasterComputer extends Computer {
        private MasterComputer() {
            super(Hudson.getInstance());
        }

3052 3053 3054 3055 3056 3057 3058
        /**
         * Returns "" to match with {@link Hudson#getNodeName()}.
         */
        public String getName() {
            return "";
        }

K
kohsuke 已提交
3059 3060 3061 3062 3063
        @Override
        public boolean isConnecting() {
            return false;
        }

K
kohsuke 已提交
3064 3065
        @Override
        public String getDisplayName() {
K
i18n  
kohsuke 已提交
3066
            return Messages.Hudson_Computer_DisplayName();
K
kohsuke 已提交
3067 3068 3069 3070
        }

        @Override
        public String getCaption() {
K
i18n  
kohsuke 已提交
3071
            return Messages.Hudson_Computer_Caption();
K
kohsuke 已提交
3072 3073
        }

K
kohsuke 已提交
3074 3075 3076 3077
        public String getUrl() {
            return "computer/(master)/";
        }

3078
        public RetentionStrategy getRetentionStrategy() {
K
kohsuke 已提交
3079
            return RetentionStrategy.NOOP;
3080 3081
        }

3082 3083 3084 3085 3086 3087 3088 3089
        /**
         * Report an error.
         */
        @Override
        public void doDoDelete(StaplerResponse rsp) throws IOException {
            rsp.sendError(SC_BAD_REQUEST);
        }

K
kohsuke 已提交
3090 3091 3092 3093 3094
        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();
        }

3095 3096 3097 3098 3099 3100 3101 3102 3103
        @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 已提交
3104 3105 3106 3107 3108
        @Override
        public VirtualChannel getChannel() {
            return localChannel;
        }

3109 3110 3111 3112 3113
        @Override
        public Charset getDefaultCharset() {
            return Charset.defaultCharset();
        }

K
kohsuke 已提交
3114 3115 3116 3117
        public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
            return logRecords;
        }

K
kohsuke 已提交
3118 3119 3120
        public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            // this computer never returns null from channel, so
            // this method shall never be invoked.
3121
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
3122 3123
        }

3124 3125 3126 3127 3128 3129 3130
        /**
         * Redirect the master configuration to /configure.
         */
        public void doConfigure(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            rsp.sendRedirect2(req.getContextPath()+"/configure");
        }

K
kohsuke 已提交
3131 3132
        public Future<?> connect(boolean forceReconnect) {
            return Futures.precomputed(null);
3133 3134
        }

K
kohsuke 已提交
3135 3136 3137 3138 3139 3140
        /**
         * {@link LocalChannel} instance that can be used to execute programs locally.
         */
        public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
    }

3141 3142 3143 3144
    /**
     * @deprecated
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
3145 3146 3147 3148
    public static boolean adminCheck() throws IOException {
        return adminCheck(Stapler.getCurrentRequest(), Stapler.getCurrentResponse());
    }

3149 3150 3151 3152
    /**
     * @deprecated
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
3153
    public static boolean adminCheck(StaplerRequest req,StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
3154 3155 3156 3157 3158 3159
        if (isAdmin(req)) return true;

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

K
kohsuke 已提交
3160 3161 3162
    /**
     * Checks if the current user (for which we are processing the current request)
     * has the admin access.
3163 3164
     *
     * @deprecated
K
kohsuke 已提交
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
     *      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
3176
     *      against.
K
kohsuke 已提交
3177
     */
K
kohsuke 已提交
3178
    public static boolean isAdmin() {
3179
        return Hudson.getInstance().getACL().hasPermission(ADMINISTER);
K
kohsuke 已提交
3180 3181
    }

3182 3183 3184
    /**
     * @deprecated
     *      Define a custom {@link Permission} and check against ACL.
K
kohsuke 已提交
3185
     *      See {@link #isAdmin()} for more instructions.
3186
     */
K
kohsuke 已提交
3187
    public static boolean isAdmin(StaplerRequest req) {
3188
        return isAdmin();
K
kohsuke 已提交
3189 3190 3191 3192 3193
    }

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

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

3201 3202
    private static final int TWICE_CPU_NUM = Runtime.getRuntime().availableProcessors() * 2;

3203 3204 3205 3206 3207 3208
    /**
     * 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(
3209 3210
        TWICE_CPU_NUM, TWICE_CPU_NUM,
        5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory());
3211 3212


K
kohsuke 已提交
3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235
    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;
    }
3236

3237 3238 3239
    /**
     * Version number of this Hudson.
     */
3240
    public static String VERSION="?";
3241

K
kohsuke 已提交
3242 3243 3244 3245 3246
    /**
     * Hash of {@link #VERSION}.
     */
    public static String VERSION_HASH;

3247 3248 3249
    /**
     * Prefix to static resources like images and javascripts in the war file.
     * Either "" or strings like "/static/VERSION", which avoids Hudson to pick up
3250
     * stale cache when the user upgrades to a different version.
3251 3252
     * <p>
     * Value computed in {@link WebAppMain}.
3253
     */
3254
    public static String RESOURCE_PATH = "";
3255

3256 3257 3258 3259
    /**
     * 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.
3260 3261
     * <p>
     * Value computed in {@link WebAppMain}.
3262
     */
3263
    public static String VIEW_RESOURCE_PATH = "/resources/TBD";
3264

3265
    public static boolean PARALLEL_LOAD = !"false".equals(System.getProperty(Hudson.class.getName()+".parallelLoad"));
3266
    public static boolean KILL_AFTER_LOAD = Boolean.getBoolean(Hudson.class.getName()+".killAfterLoad");
3267
    public static boolean LOG_STARTUP_PERFORMANCE = Boolean.getBoolean(Hudson.class.getName()+".logStartupPerformance");
3268

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

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

3273 3274
    public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
    public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
3275
    public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ);
K
kohsuke 已提交
3276

K
kohsuke 已提交
3277 3278
    static {
        XSTREAM.alias("hudson",Hudson.class);
K
kohsuke 已提交
3279
        XSTREAM.alias("slave", DumbSlave.class);
K
kohsuke 已提交
3280
        XSTREAM.alias("jdk",JDK.class);
3281 3282 3283
        // for backward compatibility with <1.75, recognize the tag name "view" as well.
        XSTREAM.alias("view", ListView.class);
        XSTREAM.alias("listView", ListView.class);
3284 3285
        // this seems to be necessary to force registration of converter early enough
        Mode.class.getEnumConstants();
3286 3287 3288 3289

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