Hudson.java 115.5 KB
Newer Older
K
kohsuke 已提交
1 2 3
/*
 * The MIT License
 * 
4
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe, Stephen Connolly, Tom Huybrechts, Yahoo! Inc.
K
kohsuke 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * 
 * 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 static hudson.Util.fixNull;
41
import hudson.WebAppMain;
42
import hudson.XmlFile;
43
import hudson.UDPBroadcastThread;
44 45
import hudson.ExtensionList;
import hudson.ExtensionPoint;
46
import hudson.DescriptorExtensionList;
47
import hudson.ExtensionListView;
K
kohsuke 已提交
48
import hudson.Extension;
49 50
import hudson.tools.ToolInstallation;
import hudson.tools.ToolDescriptor;
51
import hudson.cli.CliEntryPoint;
52
import hudson.cli.CliManagerImpl;
53
import hudson.cli.declarative.CLIMethod;
K
kohsuke 已提交
54
import hudson.cli.declarative.CLIResolver;
55
import hudson.logging.LogRecorderManager;
K
kohsuke 已提交
56
import hudson.lifecycle.Lifecycle;
K
kohsuke 已提交
57
import hudson.model.Descriptor.FormException;
58
import hudson.model.listeners.ItemListener;
K
kohsuke 已提交
59
import hudson.model.listeners.JobListener;
60
import hudson.model.listeners.JobListener.JobListenerAdapter;
S
sogabe 已提交
61
import hudson.model.listeners.SCMListener;
K
kohsuke 已提交
62 63
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
64
import hudson.remoting.Channel;
K
kohsuke 已提交
65
import hudson.scm.RepositoryBrowser;
66 67
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
K
kohsuke 已提交
68
import hudson.search.CollectionSearchIndex;
69
import hudson.search.SearchIndexBuilder;
70
import hudson.security.ACL;
71
import hudson.security.AccessControlled;
72
import hudson.security.AuthorizationStrategy;
K
kohsuke 已提交
73
import hudson.security.BasicAuthenticationFilter;
74 75 76 77
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
78
import hudson.security.PermissionGroup;
K
kohsuke 已提交
79
import hudson.security.SecurityMode;
80
import hudson.security.SecurityRealm;
81
import hudson.security.csrf.CrumbIssuer;
82
import hudson.slaves.ComputerListener;
83 84
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
85
import hudson.slaves.RetentionStrategy;
K
kohsuke 已提交
86 87 88 89 90
import hudson.slaves.NodeList;
import hudson.slaves.Cloud;
import hudson.slaves.DumbSlave;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeProvisioner;
91
import hudson.slaves.OfflineCause;
92 93 94 95
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Mailer;
import hudson.tasks.Publisher;
K
kohsuke 已提交
96
import hudson.triggers.Trigger;
97
import hudson.triggers.TriggerDescriptor;
K
kohsuke 已提交
98
import hudson.util.CaseInsensitiveComparator;
K
kohsuke 已提交
99 100 101 102 103 104
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 已提交
105
import hudson.util.RemotingDiagnostics;
106
import hudson.util.TextFile;
K
kohsuke 已提交
107
import hudson.util.XStream2;
K
kohsuke 已提交
108
import hudson.util.HudsonIsRestarting;
K
kohsuke 已提交
109 110
import hudson.util.DescribableList;
import hudson.util.Futures;
111
import hudson.util.Memoizer;
112
import hudson.util.Iterators;
113
import hudson.util.FormValidation;
114
import hudson.util.VersionNumber;
115
import hudson.util.StreamTaskListener;
116
import hudson.util.AdministrativeError;
K
kohsuke 已提交
117
import hudson.widgets.Widget;
S
sogabe 已提交
118
import net.sf.json.JSONObject;
119
import org.acegisecurity.*;
S
sogabe 已提交
120 121 122
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
K
kohsuke 已提交
123
import org.apache.commons.logging.LogFactory;
124 125
import org.apache.commons.jelly.Script;
import org.apache.commons.jelly.JellyException;
126
import org.apache.commons.io.FileUtils;
S
sogabe 已提交
127 128 129 130 131
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;
132
import org.kohsuke.stapler.StaplerFallback;
133
import org.kohsuke.stapler.WebApp;
134
import org.kohsuke.stapler.QueryParameter;
135
import org.kohsuke.stapler.HttpRedirect;
K
kohsuke 已提交
136 137
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.HttpResponse;
138 139
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
K
kohsuke 已提交
140
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
S
sogabe 已提交
141
import org.kohsuke.stapler.export.Exported;
142
import org.kohsuke.stapler.export.ExportedBean;
143
import org.xml.sax.InputSource;
K
kohsuke 已提交
144

S
sogabe 已提交
145 146 147 148 149 150
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
K
kohsuke 已提交
151 152 153
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
154
import java.io.FileOutputStream;
K
kohsuke 已提交
155 156
import java.io.IOException;
import java.io.PrintWriter;
K
kohsuke 已提交
157
import java.io.InputStream;
158
import java.net.URL;
159
import java.net.BindException;
160
import java.security.SecureRandom;
161
import java.text.NumberFormat;
K
kohsuke 已提交
162
import java.text.ParseException;
163
import java.text.Collator;
K
kohsuke 已提交
164 165 166 167 168 169 170
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;
171
import java.util.Iterator;
K
kohsuke 已提交
172 173
import java.util.List;
import java.util.Map;
S
sogabe 已提交
174
import java.util.Map.Entry;
K
kohsuke 已提交
175
import java.util.Set;
176 177
import java.util.Stack;
import java.util.StringTokenizer;
178
import java.util.Timer;
K
kohsuke 已提交
179
import java.util.TreeSet;
K
kohsuke 已提交
180
import java.util.Properties;
181
import java.util.UUID;
182
import java.util.concurrent.Callable;
183
import java.util.concurrent.ConcurrentHashMap;
K
kohsuke 已提交
184
import java.util.concurrent.CopyOnWriteArrayList;
185 186 187 188 189
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;
190
import java.util.concurrent.LinkedBlockingQueue;
K
kohsuke 已提交
191
import java.util.concurrent.TimeoutException;
192
import java.util.concurrent.CopyOnWriteArraySet;
K
kohsuke 已提交
193
import java.util.logging.Level;
K
kohsuke 已提交
194
import java.util.logging.LogRecord;
195
import java.util.logging.Logger;
196
import static java.util.logging.Level.SEVERE;
197
import java.util.regex.Pattern;
198
import java.nio.charset.Charset;
199
import javax.servlet.RequestDispatcher;
200
import javax.crypto.SecretKey;
K
kohsuke 已提交
201

202 203
import groovy.lang.GroovyShell;

K
kohsuke 已提交
204 205 206 207 208
/**
 * Root object of the system.
 *
 * @author Kohsuke Kawaguchi
 */
209
@ExportedBean
210
public final class Hudson extends Node implements ItemGroup<TopLevelItem>, StaplerProxy, StaplerFallback, ViewGroup, AccessControlled, DescriptorByNameOwner {
211
    private transient final Queue queue;
K
kohsuke 已提交
212 213 214 215

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

K
kohsuke 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231
    /**
     * 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
     */
    // this field needs to be at the very top so that other components can look at this value even during unmarshalling
    private String version = "1.0";
    
K
kohsuke 已提交
232 233 234 235 236
    /**
     * Number of executors of the master node.
     */
    private int numExecutors = 2;

237 238 239 240 241
    /**
     * Job allocation strategy.
     */
    private Mode mode = Mode.NORMAL;

K
kohsuke 已提交
242 243
    /**
     * False to enable anyone to do anything.
K
kohsuke 已提交
244
     * Left as a field so that we can still read old data that uses this flag.
245 246 247
     *
     * @see #authorizationStrategy
     * @see #securityRealm
K
kohsuke 已提交
248
     */
K
kohsuke 已提交
249
    private Boolean useSecurity;
K
kohsuke 已提交
250 251

    /**
252 253 254 255 256 257 258 259
     * 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.
     */
260
    private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
261 262 263 264 265 266 267 268

    /**
     * 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.
     *
269
     * See {@link HudsonFilter} for the concrete authentication protocol.
270
     *
271 272
     * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
     * update this field.
273 274
     *
     * @see #getSecurity()
275
     * @see #setSecurityRealm(SecurityRealm)
K
kohsuke 已提交
276
     */
277
    private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
K
kohsuke 已提交
278 279 280 281 282 283 284 285 286 287 288

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

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

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

K
kohsuke 已提交
294 295 296 297 298
    /**
     * The sole instance.
     */
    private static Hudson theInstance;

K
kohsuke 已提交
299 300
    private transient volatile boolean isQuietingDown;
    private transient volatile boolean terminating;
K
kohsuke 已提交
301

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

304
    private transient volatile DependencyGraph dependencyGraph;
305

306 307 308
    /**
     * All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
     */
309 310 311 312 313
    private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
        public ExtensionList compute(Class key) {
            return ExtensionList.create(Hudson.this,key);
        }
    };
314 315

    /**
316
     * All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
317
     */
318 319
    private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
        public DescriptorExtensionList compute(Class key) {
320
            return DescriptorExtensionList.create(Hudson.this,key);
321 322
        }
    };
323

K
kohsuke 已提交
324 325 326 327 328 329 330 331 332 333
    /**
     * 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 已提交
334 335 336
        public CloudList() {// needed for XStream deserialization
        }

337
        @Override
K
kohsuke 已提交
338 339 340 341 342 343
        protected void onModified() throws IOException {
            super.onModified();
            Hudson.getInstance().trimLabels();
        }
    }

K
kohsuke 已提交
344 345
    /**
     * Set of installed cluster nodes.
K
kohsuke 已提交
346
     * <p>
K
kohsuke 已提交
347 348 349 350
     * 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 已提交
351 352 353
     * <p>
     * The field name should be really {@code nodes}, but again the backward compatibility
     * prevents us from renaming.
K
kohsuke 已提交
354
     */
K
kohsuke 已提交
355
    private volatile NodeList slaves;
K
kohsuke 已提交
356 357 358 359 360 361 362

    /**
     * Quiet period.
     *
     * This is {@link Integer} so that we can initialize it to '5' for upgrading users.
     */
    /*package*/ Integer quietPeriod;
S
 
shinodkm 已提交
363 364
    
    /**
365
     * Global default for {@link AbstractProject#getScmCheckoutRetryCount()}  
S
 
shinodkm 已提交
366
     */
367
    /*package*/ int scmCheckoutRetryCount;
K
kohsuke 已提交
368 369

    /**
370
     * {@link View}s.
K
kohsuke 已提交
371
     */
372 373 374 375
    private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();

    /**
     * Name of the primary view.
376 377 378
     * <p>
     * Start with null, so that we can upgrade pre-1.269 data well.
     * @since 1.269
379 380
     */
    private volatile String primaryView;
381

K
kohsuke 已提交
382 383 384 385 386 387 388
    private transient final FingerprintMap fingerprintMap = new FingerprintMap();

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

389
    public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
K
kohsuke 已提交
390

391 392
    private transient UDPBroadcastThread udpBroadcastThread;

393
    /**
M
mindless 已提交
394
     * List of registered {@link ItemListener}s.
395
     * @deprecated as of 1.286
396
     */
397
    private transient final CopyOnWriteList<ItemListener> itemListeners = ExtensionListView.createCopyOnWriteList(ItemListener.class);
398 399 400 401 402

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

404 405
    /**
     * List of registered {@link ComputerListener}s.
406
     * @deprecated as of 1.286
407
     */
408
    private transient final CopyOnWriteList<ComputerListener> computerListeners = ExtensionListView.createCopyOnWriteList(ComputerListener.class);
409

410 411
    /**
     * TCP slave agent port.
412
     * 0 for random, -1 to disable.
413 414 415
     */
    private int slaveAgentPort =0;

416 417 418 419 420
    /**
     * Whitespace-separated labels assigned to the master as a {@link Node}.
     */
    private String label="";

421 422 423 424 425
    /**
     * {@link hudson.security.csrf.CrumbIssuer}
     */
    private volatile CrumbIssuer crumbIssuer;
    
426 427 428 429 430
    /**
     * 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>();
431
    private transient volatile Set<Label> labelSet;
432

K
kohsuke 已提交
433 434 435
    /**
     * Load statistics of the entire system.
     */
436
    @Exported
K
kohsuke 已提交
437 438 439 440 441 442 443
    public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();

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

444 445
    public transient final ServletContext servletContext;

K
kohsuke 已提交
446 447 448 449 450 451
    /**
     * Transient action list. Useful for adding navigation items to the navigation bar
     * on the left.
     */
    private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();

452
    /**
453
     * List of master node properties
454 455 456
     */
    private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);

457 458 459 460 461
    /**
     * List of global properties
     */
    private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);

462 463 464 465 466
    /**
     * {@link AdministrativeMonitor}s installed on this system.
     *
     * @see AdministrativeMonitor
     */
467
    public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
468

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

471 472 473 474 475
    /**
     * Widgets on Hudson.
     */
    private transient final List<Widget> widgets = getExtensionList(Widget.class);

K
kohsuke 已提交
476 477 478 479 480
    /**
     * {@link AdjunctManager}
     */
    private transient final AdjunctManager adjuncts;

K
kohsuke 已提交
481
    @CLIResolver
K
kohsuke 已提交
482 483 484 485
    public static Hudson getInstance() {
        return theInstance;
    }

486 487
    /**
     * Secrete key generated once and used for a long time, beyond
K
kohsuke 已提交
488 489
     * container start/stop. Persisted outside <tt>config.xml</tt> to avoid
     * accidental exposure.
490
     */
K
kohsuke 已提交
491
    private transient final String secretKey;
492

493
    private transient final UpdateCenter updateCenter = new UpdateCenter();
K
kohsuke 已提交
494

495 496 497 498 499
    /**
     * True if the user opted out from the statistics tracking. We'll never send anything if this is true.
     */
    private Boolean noUsageStatistics;

500 501 502 503 504
    /**
     * HTTP proxy configuration.
     */
    public transient volatile ProxyConfiguration proxy;

K
kohsuke 已提交
505
    /**
506
     * Bound to "/log".
K
kohsuke 已提交
507
     */
508
    private transient final LogRecorderManager log = new LogRecorderManager();
509

510
    public Hudson(File root, ServletContext context) throws IOException, InterruptedException {
511
    	// As hudson is starting, grant this process full controll
K
kohsuke 已提交
512
    	SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
513
        try {
514 515 516 517 518 519
            this.root = root;
            this.servletContext = context;
            computeVersion(context);
            if(theInstance!=null)
                throw new IllegalStateException("second instance");
            theInstance = this;
K
kohsuke 已提交
520

521
            log.load();
K
kohsuke 已提交
522

523
            Trigger.timer = new Timer("Hudson cron thread");
524
            queue = new Queue(CONSISTENT_HASH?LoadBalancer.CONSISTENT_HASH:LoadBalancer.DEFAULT);
525
            
526 527 528 529 530 531 532 533
            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;
            }
534

535 536 537 538 539 540 541 542 543 544 545
            // 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 已提交
546

547 548 549
            try {
                proxy = ProxyConfiguration.load();
            } catch (IOException e) {
550
                LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
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
            // 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);
    //        }

577 578 579 580 581 582
            if(slaveAgentPort!=-1) {
                try {
                    tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
                } catch (BindException e) {
                    new AdministrativeError(getClass().getName()+".tcpBind",
                            "Failed to listen to incoming slave connection",
K
typo  
kohsuke 已提交
583
                            "Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
584 585
                }
            } else
586 587 588 589 590 591 592
                tcpSlaveAgentListener = null;

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

            updateComputerList();

593 594 595 596 597 598
            {// master is online now
                Computer c = toComputer();
                if(c!=null)
                    for (ComputerListener cl : ComputerListener.all())
                        cl.onOnline(c,new StreamTaskListener(System.out));
            }
599

600 601 602 603 604 605 606 607 608
            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);
609
                GroovyShell shell = new GroovyShell(pluginManager.uberClassLoader);
610 611 612 613 614 615
                try {
                    shell.evaluate(initScript);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
616

617 618 619 620
            File userContentDir = new File(getRootDir(), "userContent");
            if(!userContentDir.exists()) {
                userContentDir.mkdirs();
                FileUtils.writeStringToFile(new File(userContentDir,"readme.txt"),Messages.Hudson_USER_CONTENT_README());
621
            }
622

623 624
            updateCenter.load();    // this has to wait until after all plugins load, to let custom UpdateCenterConfiguration take effect first.

625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
            Trigger.init();
// pending SEZPOZ-8
//            // invoke post initialization methods
//            for ( IndexItem<PostInit,Void> i : Index.load(PostInit.class, Void.class, pluginManager.uberClassLoader)) {
//                try {
//                    Method m = (Method)i.element();
//                    if (Modifier.isStatic(m.getModifiers()))
//                        m.invoke(null);
//                    else
//                        LOGGER.severe(m+" is annotated with @PostInit but it's not a static method");
//                } catch (InstantiationException e) {
//                    LOGGER.log(SEVERE,"Failed to invoke @PostInit: "+i,e);
//                } catch (IllegalAccessException e) {
//                    LOGGER.log(SEVERE,"Failed to invoke @PostInit: "+i,e);
//                } catch (InvocationTargetException e) {
//                    LOGGER.log(SEVERE,"Failed to invoke @PostInit: "+i,e);
//                }
//            }
643 644
        } finally {
            SecurityContextHolder.clearContext();
645
        }
K
kohsuke 已提交
646 647
    }

K
kohsuke 已提交
648 649 650 651
    public TcpSlaveAgentListener getTcpSlaveAgentListener() {
        return tcpSlaveAgentListener;
    }

K
kohsuke 已提交
652 653 654 655 656 657 658 659 660
    /**
     * 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 已提交
661
    @Exported
662 663 664 665
    public int getSlaveAgentPort() {
        return slaveAgentPort;
    }

K
kohsuke 已提交
666
    /**
J
jglick 已提交
667
     * If you are calling this on Hudson something is wrong.
K
kohsuke 已提交
668 669 670
     *
     * @deprecated
     */
671
    @Deprecated @Override
K
kohsuke 已提交
672 673 674 675
    public String getNodeName() {
        return "";
    }

K
kohsuke 已提交
676 677 678 679
    public void setNodeName(String name) {
        throw new UnsupportedOperationException(); // not allowed
    }

K
kohsuke 已提交
680
    public String getNodeDescription() {
S
sogabe 已提交
681
        return Messages.Hudson_NodeDescription();
K
kohsuke 已提交
682 683
    }

684
    @Exported
K
kohsuke 已提交
685 686 687 688 689 690 691
    public String getDescription() {
        return systemMessage;
    }

    public PluginManager getPluginManager() {
        return pluginManager;
    }
692

693 694 695
    public UpdateCenter getUpdateCenter() {
        return updateCenter;
    }
K
kohsuke 已提交
696

697 698 699 700
    public boolean isUsageStatisticsCollected() {
        return noUsageStatistics==null || !noUsageStatistics;
    }

701 702 703 704 705
    public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
        this.noUsageStatistics = noUsageStatistics;
        save();
    }

706 707 708 709 710 711 712 713 714 715 716 717
    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() {
718
        return new Api(this);
719 720
    }

721 722 723
    /**
     * Returns a secret key that survives across container start/stop.
     * <p>
724
     * This value is useful for implementing some of the security features.
725 726
     */
    public String getSecretKey() {
K
kohsuke 已提交
727
        return secretKey;
728 729
    }

730 731 732 733 734 735 736 737
    /**
     * Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
     * @since 1.308
     */
    public SecretKey getSecretKeyAsAES128() {
        return Util.toAes128Key(secretKey);
    }

K
kohsuke 已提交
738 739 740 741
    /**
     * Gets the SCM descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<SCM> getScm(String shortClassName) {
742
        return findDescriptor(shortClassName,SCM.all());
K
kohsuke 已提交
743 744
    }

K
kohsuke 已提交
745 746 747 748
    /**
     * Gets the repository browser descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
749
        return findDescriptor(shortClassName,RepositoryBrowser.all());
K
kohsuke 已提交
750 751
    }

K
kohsuke 已提交
752 753 754 755
    /**
     * Gets the builder descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<Builder> getBuilder(String shortClassName) {
756
        return findDescriptor(shortClassName, Builder.all());
K
kohsuke 已提交
757 758
    }

K
kohsuke 已提交
759 760 761 762
    /**
     * Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
763
        return findDescriptor(shortClassName, BuildWrapper.all());
K
kohsuke 已提交
764 765
    }

K
kohsuke 已提交
766 767 768 769
    /**
     * Gets the publisher descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<Publisher> getPublisher(String shortClassName) {
770
        return findDescriptor(shortClassName, Publisher.all());
K
kohsuke 已提交
771 772
    }

K
kohsuke 已提交
773 774 775
    /**
     * Gets the trigger descriptor by name. Primarily used for making them web-visible.
     */
776
    public TriggerDescriptor getTrigger(String shortClassName) {
777
        return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
778 779 780 781 782 783
    }

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

787 788 789 790
    /**
     * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
     */
    public JobPropertyDescriptor getJobProperty(String shortClassName) {
K
kohsuke 已提交
791
        // combining these two lines triggers javac bug. See issue #610.
792
        Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
K
kohsuke 已提交
793
        return (JobPropertyDescriptor) d;
794 795
    }

796 797 798 799 800
    /**
     * 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.
801 802 803
     *
     * @param className
     *      Either fully qualified class name (recommended) or the short name.
804
     */
805
    public Descriptor getDescriptor(String className) {
806
        // legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
807 808 809 810 811
        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))
812
                return d;
813
        }
814 815 816
        return null;
    }

817 818 819 820 821 822 823
    /**
     * Alias for {@link #getDescriptor(String)}.
     */
    public Descriptor getDescriptorByName(String className) {
        return getDescriptor(className);
    }

K
kohsuke 已提交
824 825 826 827 828 829
    /**
     * 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.
     */
830
    public Descriptor getDescriptor(Class<? extends Describable> type) {
831
        for( Descriptor d : getExtensionList(Descriptor.class) )
832 833 834 835 836
            if(d.clazz==type)
                return d;
        return null;
    }

837 838 839 840 841 842 843 844 845 846 847 848 849
    /**
     * Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
     *
     * @throws AssertionError
     *      If the descriptor is missing.
     * @since 1.326
     */
    public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
        Descriptor d = getDescriptor(type);
        if (d==null)    throw new AssertionError(type+" is missing its descriptor");
        return d;
    }
    
850 851 852 853 854 855 856 857 858 859
    /**
     * 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;
    }

860 861 862 863
    /**
     * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
     */
    public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
864
        return findDescriptor(shortClassName,SecurityRealm.all());
865 866
    }

K
kohsuke 已提交
867 868 869 870
    /**
     * Finds a descriptor that has the specified name.
     */
    private <T extends Describable<T>>
871
    Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
K
kohsuke 已提交
872 873 874 875 876 877 878 879
        String name = '.'+shortClassName;
        for (Descriptor<T> d : descriptors) {
            if(d.clazz.getName().endsWith(name))
                return d;
        }
        return null;
    }

880 881 882
    /**
     * Adds a new {@link JobListener}.
     *
M
mindless 已提交
883
     * @deprecated since 2007-01-04.
M
mindless 已提交
884
     *      Use {@code getJobListeners().add(l)} instead.
885 886
     */
    public void addListener(JobListener l) {
K
kohsuke 已提交
887
        itemListeners.add(new JobListenerAdapter(l));
888 889 890 891 892
    }

    /**
     * Deletes an existing {@link JobListener}.
     *
M
mindless 已提交
893
     * @deprecated since 2007-01-04.
M
mindless 已提交
894
     *      Use {@code getJobListeners().remove(l)} instead.
895 896
     */
    public boolean removeListener(JobListener l ) {
K
kohsuke 已提交
897
        return itemListeners.remove(new JobListenerAdapter(l));
898 899
    }

900
    /**
901
     * Gets all the installed {@link ItemListener}s.
902 903 904
     *
     * @deprecated as of 1.286.
     *      Use {@link ItemListener#all()}.
905
     */
906
    public CopyOnWriteList<ItemListener> getJobListeners() {
K
kohsuke 已提交
907
        return itemListeners;
908 909 910 911 912 913 914 915 916
    }

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

917 918
    /**
     * Gets all the installed {@link ComputerListener}s.
919 920
     *
     * @deprecated as of 1.286.
921
     *      Use {@link ComputerListener#all()}.
922 923 924 925 926
     */
    public CopyOnWriteList<ComputerListener> getComputerListeners() {
        return computerListeners;
    }

K
kohsuke 已提交
927 928 929 930 931 932 933 934 935 936
    /**
     * 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;
937
        return p.getPlugin();
K
kohsuke 已提交
938 939
    }

940 941 942 943 944 945 946 947 948 949 950 951
    /**
     * 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 已提交
952 953
    @SuppressWarnings("unchecked")
    public <P extends Plugin> P getPlugin(Class<P> clazz) {
954 955
        PluginWrapper p = pluginManager.getPlugin(clazz);
        if(p==null)     return null;
S
stephenconnolly 已提交
956
        return (P) p.getPlugin();
957 958 959 960 961 962 963 964 965
    }

    /**
     * Gets the plugin objects from their super-class.
     *
     * @param clazz The plugin class (beware class-loader fun)
     *
     * @return The plugin instances.
     */
S
stephenconnolly 已提交
966 967
    public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
        List<P> result = new ArrayList<P>();
968
        for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
S
stephenconnolly 已提交
969
            result.add((P)w.getPlugin());
970 971 972 973
        }
        return Collections.unmodifiableList(result);
    }

K
kohsuke 已提交
974 975 976 977 978 979 980
    /**
     * Synonym to {@link #getNodeDescription()}.
     */
    public String getSystemMessage() {
        return systemMessage;
    }

981 982 983 984 985 986 987 988
    /**
     * Sets the system message.
     */
    public void setSystemMessage(String message) throws IOException {
        this.systemMessage = message;
        save();
    }

K
kohsuke 已提交
989
    public Launcher createLauncher(TaskListener listener) {
K
kohsuke 已提交
990
        return new LocalLauncher(listener).decorateFor(this);
K
kohsuke 已提交
991 992
    }

K
kohsuke 已提交
993 994
    private final transient Object updateComputerLock = new Object();

K
kohsuke 已提交
995 996 997 998 999 1000 1001
    /**
     * 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 已提交
1002
    private void updateComputerList() throws IOException {
K
kohsuke 已提交
1003
        synchronized(updateComputerLock) {// just so that we don't have two code updating computer list at the same time
K
kohsuke 已提交
1004
            Map<String,Computer> byName = new HashMap<String,Computer>();
K
kohsuke 已提交
1005 1006 1007
            for (Computer c : computers.values()) {
                if(c.getNode()==null)
                    continue;   // this computer is gone
K
kohsuke 已提交
1008
                byName.put(c.getNode().getNodeName(),c);
K
kohsuke 已提交
1009
            }
K
kohsuke 已提交
1010 1011 1012 1013 1014

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

            updateComputer(this, byName, used);
K
kohsuke 已提交
1015
            for (Node s : getNodes())
K
kohsuke 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
                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 已提交
1032 1033
        if (c!=null) {
            c.setNode(n); // reuse
K
kohsuke 已提交
1034
        } else {
K
kohsuke 已提交
1035
            if(n.getNumExecutors()>0) {
K
kohsuke 已提交
1036
                computers.put(n,c=n.createComputer());
1037 1038 1039 1040 1041 1042 1043 1044 1045
                if (!n.holdOffLaunchUntilSave) {
                    RetentionStrategy retentionStrategy = c.getRetentionStrategy();
                    if (retentionStrategy != null) {
                        // if there is a retention strategy, it is responsible for deciding to start the computer
                        retentionStrategy.start(c);
                    } else {
                        // we should never get here, but just in case, we'll fall back to the legacy behaviour
                        c.connect(true);
                    }
1046
                }
K
kohsuke 已提交
1047
            }
K
kohsuke 已提交
1048 1049 1050 1051 1052
        }
        used.add(c);
    }

    /*package*/ void removeComputer(Computer computer) {
1053 1054
        for (Entry<Node, Computer> e : computers.entrySet()) {
            if (e.getValue() == computer) {
K
kohsuke 已提交
1055
                computers.remove(e.getKey());
1056
                return;
K
kohsuke 已提交
1057 1058 1059 1060 1061
            }
        }
        throw new IllegalStateException("Trying to remove unknown computer");
    }

1062 1063 1064 1065
    public String getFullName() {
        return "";
    }

1066 1067 1068 1069
    public String getFullDisplayName() {
        return "";
    }

K
kohsuke 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078
    /**
     * 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>
K
kohsuke 已提交
1079 1080
     * To register an {@link Action}, implement {@link RootAction} extension point, or write code like
     * {@code Hudson.getInstance().getActions().add(...)}.
K
kohsuke 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089
     *
     * @return
     *      Live list where the changes can be made. Can be empty but never null.
     * @since 1.172
     */
    public List<Action> getActions() {
        return actions;
    }

1090 1091 1092
    /**
     * Gets just the immediate children of {@link Hudson}.
     *
1093
     * @see #getAllItems(Class)
1094
     */
1095
    @Exported(name="jobs")
K
kohsuke 已提交
1096
    public List<TopLevelItem> getItems() {
K
kohsuke 已提交
1097 1098
        List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
        for (TopLevelItem item : items.values()) {
1099 1100
            if (item.hasPermission(Item.READ))
                viewableItems.add(item);
K
kohsuke 已提交
1101 1102 1103
        }
        
        return viewableItems;
1104 1105
    }

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    /**
     * 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 已提交
1117 1118 1119
    /**
     * Gets just the immediate children of {@link Hudson} but of the given type.
     */
K
kohsuke 已提交
1120
    public <T> List<T> getItems(Class<T> type) {
K
kohsuke 已提交
1121
        List<T> r = new ArrayList<T>();
K
kohsuke 已提交
1122
        for (TopLevelItem i : getItems())
K
kohsuke 已提交
1123 1124 1125 1126 1127
            if (type.isInstance(i))
                 r.add(type.cast(i));
        return r;
    }

1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    /**
     * 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 已提交
1141
                if(type.isInstance(i)) {
K
kohsuke 已提交
1142 1143
                    if (i.hasPermission(Item.READ))
                        r.add(type.cast(i));
K
kohsuke 已提交
1144
                }
1145 1146 1147 1148 1149 1150 1151 1152
                if(i instanceof ItemGroup)
                    q.push((ItemGroup)i);
            }
        }

        return r;
    }

K
kohsuke 已提交
1153
    /**
K
kohsuke 已提交
1154 1155 1156 1157 1158
     * 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 已提交
1159
     */
K
kohsuke 已提交
1160
    public List<Project> getProjects() {
K
kohsuke 已提交
1161
        return Util.createSubList(items.values(),Project.class);
K
kohsuke 已提交
1162 1163 1164 1165 1166
    }

    /**
     * Gets the names of all the {@link Job}s.
     */
K
kohsuke 已提交
1167
    public Collection<String> getJobNames() {
1168
        List<String> names = new ArrayList<String>();
K
kohsuke 已提交
1169
        for (Job j : getAllItems(Job.class))
1170
            names.add(j.getFullName());
1171
        return names;
K
kohsuke 已提交
1172 1173
    }

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    /**
     * 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;
    }

1184
    public synchronized View getView(String name) {
1185 1186 1187
        for (View v : views) {
            if(v.getViewName().equals(name))
                return v;
K
kohsuke 已提交
1188
        }
1189
        return null;
K
kohsuke 已提交
1190 1191 1192
    }

    /**
1193
     * Gets the read-only list of all {@link View}s.
K
kohsuke 已提交
1194
     */
1195
    @Exported
1196
    public synchronized Collection<View> getViews() {
1197
        List<View> copy = new ArrayList<View>(views);
1198 1199
        Collections.sort(copy, View.SORTER);
        return copy;
K
kohsuke 已提交
1200 1201
    }

1202 1203 1204 1205 1206
    public void addView(View v) throws IOException {
        views.add(v);
        save();
    }

1207
    public synchronized void deleteView(View view) throws IOException {
1208 1209 1210 1211
        if(views.size()<=1)
            throw new IllegalStateException();
        views.remove(view);
        save();
K
kohsuke 已提交
1212 1213
    }

1214 1215 1216 1217 1218 1219
    /**
     * 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.
K
kohsuke 已提交
1220 1221 1222 1223 1224 1225 1226
     *
     * <p>
     * To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
     * equal or younger than N. So say if you implement a feature in 1.301 and you want to check
     * if the installation upgraded from pre-1.301, pass in "1.300.*"
     *
     * @since 1.301
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
     */
    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 已提交
1237 1238 1239 1240
    /**
     * Gets the read-only list of all {@link Computer}s.
     */
    public Computer[] getComputers() {
1241 1242
        Computer[] r = computers.values().toArray(new Computer[computers.size()]);
        Arrays.sort(r,new Comparator<Computer>() {
1243
            final Collator collator = Collator.getInstance();
1244 1245 1246
            public int compare(Computer lhs, Computer rhs) {
                if(lhs.getNode()==Hudson.this)  return -1;
                if(rhs.getNode()==Hudson.this)  return 1;
1247
                return collator.compare(lhs.getDisplayName(), rhs.getDisplayName());
1248 1249 1250
            }
        });
        return r;
K
kohsuke 已提交
1251 1252
    }

1253 1254 1255 1256
    /*package*/ Computer getComputer(Node n) {
        return computers.get(n);
    }

K
kohsuke 已提交
1257
    public Computer getComputer(String name) {
K
kohsuke 已提交
1258 1259 1260
        if(name.equals("(master)"))
            name = "";

1261
        for (Computer c : computers.values()) {
K
kohsuke 已提交
1262
            if(c.getName().equals(name))
1263
                return c;
K
kohsuke 已提交
1264 1265 1266 1267
        }
        return null;
    }

K
kohsuke 已提交
1268 1269 1270 1271 1272 1273 1274 1275
    /**
     * @deprecated
     *      UI method. Not meant to be used programatically.
     */
    public ComputerSet getComputer() {
        return new ComputerSet();
    }

1276 1277 1278
    /**
     * Gets the label that exists on this system by the name.
     *
1279
     * @return null if no name is null.
K
kohsuke 已提交
1280
     * @see Label#parse(String)
1281 1282
     */
    public Label getLabel(String name) {
K
kohsuke 已提交
1283
        if(name==null)  return null;
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
        while(true) {
            Label l = labels.get(name);
            if(l!=null)
                return l;

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

    /**
1295
     * Gets all the active labels in the current system.
1296 1297 1298 1299
     */
    public Set<Label> getLabels() {
        Set<Label> r = new TreeSet<Label>();
        for (Label l : labels.values()) {
K
kohsuke 已提交
1300
            if(!l.isEmpty())
1301 1302 1303 1304 1305
                r.add(l);
        }
        return r;
    }

K
kohsuke 已提交
1306 1307 1308 1309
    public Queue getQueue() {
        return queue;
    }

1310
    @Override
K
kohsuke 已提交
1311
    public String getDisplayName() {
K
i18n  
kohsuke 已提交
1312
        return Messages.Hudson_DisplayName();
K
kohsuke 已提交
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    }

    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) {
1325 1326 1327 1328 1329 1330
        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 已提交
1331 1332 1333 1334 1335 1336 1337 1338 1339
        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 已提交
1340 1341 1342
     *
     * @deprecated
     *      Use {@link #getNode(String)}. Since 1.252.
K
kohsuke 已提交
1343 1344
     */
    public Slave getSlave(String name) {
K
kohsuke 已提交
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
        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) {
K
kohsuke 已提交
1355
        for (Node s : getNodes()) {
K
kohsuke 已提交
1356 1357 1358 1359 1360 1361
            if(s.getNodeName().equals(name))
                return s;
        }
        return null;
    }

K
kohsuke 已提交
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
    /**
     * 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 已提交
1376
    public List<Slave> getSlaves() {
K
kohsuke 已提交
1377 1378 1379 1380 1381 1382 1383 1384
        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 已提交
1385 1386 1387
        return Collections.unmodifiableList(slaves);
    }

1388 1389
    /**
     * Updates the slave list.
K
kohsuke 已提交
1390 1391 1392
     *
     * @deprecated
     *      Use {@link #setNodes(List)}. Since 1.252.
1393 1394
     */
    public void setSlaves(List<Slave> slaves) throws IOException {
K
kohsuke 已提交
1395 1396 1397 1398 1399 1400 1401
        setNodes(slaves);
    }

    /**
     * Adds one more {@link Node} to Hudson.
     */
    public synchronized void addNode(Node n) throws IOException {
1402
        if(n==null)     throw new IllegalArgumentException();
K
kohsuke 已提交
1403
        ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
1404 1405
        if(!nl.contains(n)) // defensive check
            nl.add(n);
K
kohsuke 已提交
1406 1407 1408 1409 1410 1411 1412
        setNodes(nl);
    }

    /**
     * Removes a {@link Node} from Hudson.
     */
    public synchronized void removeNode(Node n) throws IOException {
1413 1414 1415
        Computer c = n.toComputer();
        if (c!=null)
            c.disconnect(OfflineCause.create(Messages._Hudson_NodeBeingRemoved()));
K
kohsuke 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428

        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);
1429
        updateComputerList();
K
kohsuke 已提交
1430 1431 1432
        trimLabels();
        save();
    }
1433

1434 1435 1436
    public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
    	return nodeProperties;
    }
1437

1438 1439 1440 1441
    public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
    	return globalNodeProperties;
    }

K
kohsuke 已提交
1442 1443 1444 1445
    /**
     * Resets all labels and remove invalid ones.
     */
    private void trimLabels() {
1446 1447 1448
        for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
            Label l = itr.next();
            l.reset();
K
kohsuke 已提交
1449
            if(l.isEmpty())
1450 1451
                itr.remove();
        }
K
kohsuke 已提交
1452
    }
1453

1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    /**
     * 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 已提交
1464 1465 1466 1467 1468
    public NodeDescriptor getDescriptor() {
        return DescriptorImpl.INSTANCE;
    }

    public static final class DescriptorImpl extends NodeDescriptor {
K
kohsuke 已提交
1469
        @Extension
K
kohsuke 已提交
1470 1471 1472 1473 1474 1475
        public static final DescriptorImpl INSTANCE = new DescriptorImpl();

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

K
kohsuke 已提交
1476 1477 1478 1479 1480
        @Override
        public boolean isInstantiable() {
            return false;
        }

1481 1482 1483 1484
        public FormValidation doCheckNumExecutors(@QueryParameter String value) {
            return FormValidation.validateNonNegativeInteger(value);
        }

K
kohsuke 已提交
1485
        // to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
K
kohsuke 已提交
1486
        public Object getDynamic(String token) {
K
kohsuke 已提交
1487 1488
            return Hudson.getInstance().getDescriptor(token);
        }
1489 1490
    }

K
kohsuke 已提交
1491 1492 1493 1494 1495 1496
    /**
     * Gets the system default quiet period.
     */
    public int getQuietPeriod() {
        return quietPeriod!=null ? quietPeriod : 5;
    }
S
 
shinodkm 已提交
1497 1498
    
    /**
1499
     * Gets the global SCM check out retry count.
S
 
shinodkm 已提交
1500
     */
1501 1502
    public int getScmCheckoutRetryCount() {
        return scmCheckoutRetryCount;
S
 
shinodkm 已提交
1503 1504 1505
    }
    
    
K
kohsuke 已提交
1506

K
kohsuke 已提交
1507 1508 1509 1510 1511
    /**
     * @deprecated
     *      Why are you calling a method that always returns ""?
     *      Perhaps you meant {@link #getRootUrl()}.
     */
K
kohsuke 已提交
1512 1513 1514 1515
    public String getUrl() {
        return "";
    }

M
mindless 已提交
1516
    @Override
1517 1518 1519 1520
    public String getSearchUrl() {
        return "";
    }

K
kohsuke 已提交
1521 1522 1523 1524
    public void onViewRenamed(View view, String oldName, String newName) {
        // implementation of Hudson is immune to view name change.
    }

1525
    @Override
1526 1527
    public SearchIndexBuilder makeSearchIndex() {
        return super.makeSearchIndex()
1528
            .add("configure", "config","configure")
K
kohsuke 已提交
1529
            .add("manage")
K
kohsuke 已提交
1530
            .add("log")
1531
            .add(getPrimaryView().makeSearchIndex())
K
kohsuke 已提交
1532 1533 1534
            .add(new CollectionSearchIndex() {// for computers
                protected Computer get(String key) { return getComputer(key); }
                protected Collection<Computer> all() { return computers.values(); }
K
kohsuke 已提交
1535
            })
K
kohsuke 已提交
1536
            .add(new CollectionSearchIndex() {// for users
K
kohsuke 已提交
1537
                protected User get(String key) { return User.get(key,false); }
K
kohsuke 已提交
1538
                protected Collection<User> all() { return User.getAll(); }
K
kohsuke 已提交
1539
            })
K
kohsuke 已提交
1540 1541
            .add(new CollectionSearchIndex() {// for views
                protected View get(String key) { return getView(key); }
1542
                protected Collection<View> all() { return views; }
K
kohsuke 已提交
1543
            });
1544 1545
    }

1546 1547 1548
    /**
     * Returns the primary {@link View} that renders the top-page of Hudson.
     */
1549
    @Exported
1550 1551 1552 1553 1554 1555 1556
    public View getPrimaryView() {
        View v = getView(primaryView);
        if(v==null) // fallback
            v = views.get(0);
        return v;
    }

1557 1558 1559 1560
    public String getUrlChildPrefix() {
        return "job";
    }

K
kohsuke 已提交
1561 1562 1563 1564 1565
    /**
     * Gets the absolute URL of Hudson,
     * such as "http://localhost/hudson/".
     *
     * <p>
1566 1567 1568 1569
     * This method first tries to use the manually configured value, then
     * fall back to {@link StaplerRequest#getRootPath()}.
     * It is done in this order so that it can work correctly even in the face
     * of a reverse proxy.
K
kohsuke 已提交
1570 1571 1572 1573 1574 1575
     *
     * @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 已提交
1576
     * @see Descriptor#getCheckUrl(String)
K
renamed  
kohsuke 已提交
1577
     * @see #getRootUrlFromRequest()
K
kohsuke 已提交
1578 1579 1580
     */
    public String getRootUrl() {
        // for compatibility. the actual data is stored in Mailer
1581
        String url = Mailer.descriptor().getUrl();
1582 1583 1584
        if(url!=null)   return url;

        StaplerRequest req = Stapler.getCurrentRequest();
K
kohsuke 已提交
1585
        if(req!=null)
K
renamed  
kohsuke 已提交
1586
            return getRootUrlFromRequest();
1587
        return null;
K
kohsuke 已提交
1588 1589
    }

K
kohsuke 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
    /**
     * 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 已提交
1602
    public String getRootUrlFromRequest() {
K
kohsuke 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
        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 已提交
1613 1614 1615 1616
    public File getRootDir() {
        return root;
    }

1617 1618 1619 1620
    public FilePath getWorkspaceFor(TopLevelItem item) {
        return new FilePath(new File(item.getRootDir(),"workspace"));
    }

K
kohsuke 已提交
1621 1622 1623 1624
    public FilePath getRootPath() {
        return new FilePath(getRootDir());
    }

1625
    @Override
1626 1627 1628 1629
    public FilePath createPath(String absolutePath) {
        return new FilePath((VirtualChannel)null,absolutePath);
    }

1630 1631
    public ClockDifference getClockDifference() {
        return ClockDifference.ZERO;
K
kohsuke 已提交
1632 1633
    }

1634 1635 1636 1637 1638 1639 1640 1641 1642
    /**
     * 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 已提交
1643
    /**
1644 1645
     * A convenience method to check if there's some security
     * restrictions in place.
K
kohsuke 已提交
1646
     */
1647
    @Exported
K
kohsuke 已提交
1648
    public boolean isUseSecurity() {
1649
        return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
1650 1651
    }

1652 1653 1654 1655 1656
    /**
     * If true, all the POST requests to Hudson would have to have crumb in it to protect
     * Hudson from CSRF vulnerabilities.
     */
    @Exported
1657
    public boolean isUseCrumbs() {
1658
        return crumbIssuer!=null;
1659 1660
    }
    
K
kohsuke 已提交
1661
    /**
1662 1663
     * Returns the constant that captures the three basic security modes
     * in Hudson.
K
kohsuke 已提交
1664
     */
1665 1666 1667 1668 1669 1670 1671 1672 1673
    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 已提交
1674 1675
    }

K
kohsuke 已提交
1676 1677 1678 1679 1680 1681 1682 1683
    /**
     * @return
     *      never null.
     */
    public SecurityRealm getSecurityRealm() {
        return securityRealm;
    }

1684
    public void setSecurityRealm(SecurityRealm securityRealm) {
1685 1686
        if(securityRealm==null)
            securityRealm= SecurityRealm.NO_AUTHENTICATION;
1687
        this.securityRealm = securityRealm;
1688 1689
        // reset the filters and proxies for the new SecurityRealm
        try {
K
kohsuke 已提交
1690 1691 1692 1693
            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 已提交
1694
                LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
K
kohsuke 已提交
1695
            } else {
K
kohsuke 已提交
1696
                LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
K
kohsuke 已提交
1697
                filter.reset(securityRealm);
K
kohsuke 已提交
1698
                LOGGER.fine("Security is now fully set up");
K
kohsuke 已提交
1699
            }
1700 1701 1702 1703
        } catch (ServletException e) {
            // for binary compatibility, this method cannot throw a checked exception
            throw new AcegiSecurityException("Failed to configure filter",e) {};
        }
1704
    }
1705

1706 1707 1708 1709 1710 1711
    public void setAuthorizationStrategy(AuthorizationStrategy a) {
        if (a == null)
            a = AuthorizationStrategy.UNSECURED;
        authorizationStrategy = a;
    }

1712 1713 1714
    public Lifecycle getLifecycle() {
        return Lifecycle.get();
    }
1715

1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
    /**
     * 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) {
1727
        return extensionLists.get(extensionType);
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
    }

    /**
     * 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"})
1738
    public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
1739
        return descriptorLists.get(type);
1740 1741
    }

1742 1743 1744 1745 1746
    /**
     * Returns the root {@link ACL}.
     *
     * @see AuthorizationStrategy#getRootACL()
     */
1747
    @Override
1748 1749
    public ACL getACL() {
        return authorizationStrategy.getRootACL();
K
kohsuke 已提交
1750 1751
    }

1752 1753 1754 1755 1756 1757
    /**
     * @return
     *      never null.
     */
    public AuthorizationStrategy getAuthorizationStrategy() {
        return authorizationStrategy;
K
kohsuke 已提交
1758 1759
    }

K
kohsuke 已提交
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
    /**
     * 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;
    }

1778 1779 1780 1781 1782
    public void setNumExecutors(int n) throws IOException {
        this.numExecutors = n;
        save();
    }

K
kohsuke 已提交
1783
    /**
1784 1785 1786
     * @deprecated
     *      Left only for the compatibility of URLs.
     *      Should not be invoked for any other purpose.
K
kohsuke 已提交
1787
     */
1788 1789
    public TopLevelItem getJob(String name) {
        return getItem(name);
K
kohsuke 已提交
1790 1791
    }

1792 1793 1794 1795 1796 1797
    /**
     * @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 已提交
1798
            if(Functions.toEmailSafeString(e.getKey()).equalsIgnoreCase(Functions.toEmailSafeString(name)))
1799 1800 1801 1802 1803
                return e.getValue();
        }
        return null;
    }

K
kohsuke 已提交
1804 1805 1806 1807 1808
    /**
     * {@inheritDoc}.
     *
     * Note that the look up is case-insensitive.
     */
K
kohsuke 已提交
1809
    public TopLevelItem getItem(String name) {
K
kohsuke 已提交
1810
    	TopLevelItem item = items.get(name);
K
NPE fix  
kohsuke 已提交
1811
        if (item==null || !item.hasPermission(Item.READ))
K
kohsuke 已提交
1812
            return null;
K
kohsuke 已提交
1813
        return item;
1814 1815
    }

1816
    public File getRootDirFor(TopLevelItem child) {
1817 1818 1819 1820 1821
        return getRootDirFor(child.getName());
    }

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

1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
    /**
     * 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;

K
kohsuke 已提交
1837 1838
        if(!tokens.hasMoreTokens()) return null;    // for example, empty full name.

1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
        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 已提交
1855 1856 1857 1858
    public Item getItemByFullName(String fullName) {
        return getItemByFullName(fullName,Item.class);
    }

K
kohsuke 已提交
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
    /**
     * 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.
     */
1875
    public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
K
kohsuke 已提交
1876
        if(items.containsKey(name))
K
kohsuke 已提交
1877 1878
            throw new IllegalArgumentException();

K
kohsuke 已提交
1879
        TopLevelItem item;
K
kohsuke 已提交
1880
        try {
K
kohsuke 已提交
1881
            item = type.newInstance(name);
K
kohsuke 已提交
1882 1883 1884 1885
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }

K
kohsuke 已提交
1886 1887 1888
        item.save();
        items.put(name,item);
        return item;
K
kohsuke 已提交
1889 1890
    }

K
kohsuke 已提交
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
    /**
     * 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 已提交
1904 1905 1906
    /**
     * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
     */
1907
    /*package*/ void deleteJob(TopLevelItem item) throws IOException {
1908
        for (ItemListener l : ItemListener.all())
1909
            l.onDeleted(item);
1910

1911
        items.remove(item.getName());
1912 1913 1914
        for (View v : views)
            v.onJobRenamed(item, item.getName(), null);
        save();
K
kohsuke 已提交
1915 1916 1917 1918 1919 1920
    }

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

1925 1926 1927
        for (View v : views)
            v.onJobRenamed(job, oldName, newName);
        save();
K
kohsuke 已提交
1928 1929 1930 1931 1932 1933
    }

    public FingerprintMap getFingerprintMap() {
        return fingerprintMap;
    }

K
kohsuke 已提交
1934
    // if no finger print matches, display "not found page".
K
kohsuke 已提交
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
    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() {
1961
        return mode;
K
kohsuke 已提交
1962 1963
    }

1964
    public String getLabelString() {
1965
        return fixNull(label).trim();
1966 1967
    }

1968
    @Override
1969 1970 1971 1972
    public Label getSelfLabel() {
        return getLabel("master");
    }

K
kohsuke 已提交
1973 1974 1975 1976
    public Computer createComputer() {
        return new MasterComputer();
    }

K
kohsuke 已提交
1977
    private synchronized void load() throws IOException {
1978
        long startTime = System.currentTimeMillis();
K
kohsuke 已提交
1979
        XmlFile cfg = getConfigFile();
1980 1981 1982 1983
        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;
1984
            views.clear();
K
kohsuke 已提交
1985
            cfg.unmarshal(this);
1986
        }
K
kohsuke 已提交
1987
        clouds.setOwner(this);
K
kohsuke 已提交
1988 1989 1990 1991 1992 1993 1994 1995 1996

        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) {
1997
                return child.isDirectory() && Items.getConfigFile(child).exists();
K
kohsuke 已提交
1998 1999
            }
        });
2000
        items.clear();
2001
        if(PARALLEL_LOAD) {
2002
            // load jobs in parallel for better performance
2003
            LOGGER.info("Loading in "+TWICE_CPU_NUM+" parallel threads");
2004 2005 2006 2007
            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 {
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
                        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);
                        }
2020 2021 2022 2023 2024 2025 2026 2027 2028
                    }
                }));
            }

            for (Future<TopLevelItem> loader : loaders) {
                try {
                    TopLevelItem item = loader.get();
                    items.put(item.getName(), item);
                } catch (ExecutionException e) {
K
typo  
kohsuke 已提交
2029
                    LOGGER.log(Level.WARNING, "Failed to load a project",e.getCause());
2030 2031 2032 2033 2034 2035 2036
                } catch (InterruptedException e) {
                    e.printStackTrace(); // this is probably not the right thing to do
                }
            }
        } else {
            for (File subdir : subdirs) {
                try {
2037
                    long start = System.currentTimeMillis();
2038
                    TopLevelItem item = (TopLevelItem)Items.load(this,subdir);
2039 2040
                    if(LOG_STARTUP_PERFORMANCE)
                        LOGGER.info("Loaded "+item.getName()+" in "+(System.currentTimeMillis()-start)+"ms");
2041 2042 2043
                    items.put(item.getName(), item);
                } catch (Error e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
2044 2045
                } catch (RuntimeException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
2046 2047 2048
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
                }
K
kohsuke 已提交
2049 2050
            }
        }
2051
        rebuildDependencyGraph();
2052

2053
        {// recompute label objects - populates the labels mapping.
K
kohsuke 已提交
2054
            for (Node slave : slaves)
2055 2056
                // Note that all labels are not visible until the slaves have
                // connected.
2057
                slave.getAssignedLabels();
2058
            getAssignedLabels();
2059
        }
K
kohsuke 已提交
2060

2061 2062 2063 2064 2065 2066 2067 2068 2069
        // 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 已提交
2070
        // read in old data that doesn't have the security field set
2071 2072 2073 2074 2075 2076 2077 2078
        if(authorizationStrategy==null) {
            if(useSecurity==null || !useSecurity)
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
            else
                authorizationStrategy = new LegacyAuthorizationStrategy();
        }
        if(securityRealm==null) {
            if(useSecurity==null || !useSecurity)
2079
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
2080
            else
2081 2082 2083 2084
                setSecurityRealm(new LegacySecurityRealm());
        } else {
            // force the set to proxy
            setSecurityRealm(securityRealm);
2085
        }
2086

K
kohsuke 已提交
2087 2088 2089 2090
        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;
2091
            setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
K
kohsuke 已提交
2092
        }
2093

2094 2095
        // Initialize the filter with the crumb issuer
        setCrumbIssuer(crumbIssuer);
2096 2097

        // auto register root actions
2098 2099
        for (Action a : getExtensionList(RootAction.class))
            if (!actions.contains(a)) actions.add(a);
2100
        
2101
        LOGGER.info(String.format("Took %s ms to load",System.currentTimeMillis()-startTime));
2102 2103
        if(KILL_AFTER_LOAD)
            System.exit(0);
K
kohsuke 已提交
2104 2105 2106 2107 2108 2109
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
2110
        if(BulkChange.contains(this))   return;
K
kohsuke 已提交
2111 2112 2113 2114 2115 2116 2117 2118
        getConfigFile().write(this);
    }


    /**
     * Called to shut down the system.
     */
    public void cleanUp() {
K
kohsuke 已提交
2119
        Set<Future<?>> pending = new HashSet<Future<?>>();
K
kohsuke 已提交
2120
        terminating = true;
2121 2122 2123
        for( Computer c : computers.values() ) {
            c.interrupt();
            c.kill();
M
mindless 已提交
2124
            pending.add(c.disconnect(null));
K
kohsuke 已提交
2125
        }
2126 2127
        if(udpBroadcastThread!=null)
            udpBroadcastThread.shutdown();
K
kohsuke 已提交
2128 2129
        ExternalJob.reloadThread.interrupt();
        Trigger.timer.cancel();
K
kohsuke 已提交
2130
        // TODO: how to wait for the completion of the last job?
K
kohsuke 已提交
2131
        Trigger.timer = null;
2132 2133
        if(tcpSlaveAgentListener!=null)
            tcpSlaveAgentListener.shutdown();
K
kohsuke 已提交
2134 2135 2136 2137

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

2138 2139 2140 2141
        if(getRootDir().exists())
            // if we are aborting because we failed to create HUDSON_HOME,
            // don't try to save. Issue #536
            getQueue().save();
2142 2143

        threadPoolForLoad.shutdown();
K
kohsuke 已提交
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
        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 已提交
2156
        LogFactory.releaseAll();
2157 2158

        theInstance = null;
K
kohsuke 已提交
2159 2160
    }

K
kohsuke 已提交
2161
    public Object getDynamic(String token) {
K
kohsuke 已提交
2162
        for (Action a : getActions())
2163
            if(a.getUrlName().equals(token) || a.getUrlName().equals('/'+token))
K
kohsuke 已提交
2164
                return a;
2165 2166 2167
        for (Action a : getManagementLinks())
            if(a.getUrlName().equals(token))
                return a;
K
kohsuke 已提交
2168 2169
        return null;
    }
K
kohsuke 已提交
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179


//
//
// actions
//
//
    /**
     * Accepts submission from the configuration page.
     */
2180
    public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
K
kohsuke 已提交
2181
        BulkChange bc = new BulkChange(this);
K
kohsuke 已提交
2182
        try {
K
kohsuke 已提交
2183
            checkPermission(ADMINISTER);
K
kohsuke 已提交
2184 2185 2186

            req.setCharacterEncoding("UTF-8");

2187
            JSONObject json = req.getSubmittedForm();
2188

2189 2190 2191
            // keep using 'useSecurity' field as the main configuration setting
            // until we get the new security implementation working
            // useSecurity = null;
2192
            if (json.has("use_security")) {
K
kohsuke 已提交
2193
                useSecurity = true;
K
kohsuke 已提交
2194
                JSONObject security = json.getJSONObject("use_security");
2195
                setSecurityRealm(SecurityRealm.all().newInstanceFromRadioList(security,"realm"));
2196
                setAuthorizationStrategy(AuthorizationStrategy.all().newInstanceFromRadioList(security, "authorization"));
K
kohsuke 已提交
2197
            } else {
2198
                useSecurity = null;
2199
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
2200
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
2201
            }
K
kohsuke 已提交
2202

2203 2204 2205 2206 2207 2208
            if (json.has("csrf")) {
            	JSONObject csrf = json.getJSONObject("csrf");
            	setCrumbIssuer(CrumbIssuer.all().newInstanceFromRadioList(csrf, "issuer"));
            } else {
            	setCrumbIssuer(null);
            }
K
kohsuke 已提交
2209 2210

            primaryView = json.has("primaryView") ? json.getString("primaryView") : getViews().iterator().next().getViewName();
2211
            
2212 2213
            noUsageStatistics = json.has("usageStatisticsCollected") ? null : true;

2214 2215
            {
                String v = req.getParameter("slaveAgentPortType");
2216
                if(!isUseSecurity() || v==null || v.equals("random"))
2217 2218 2219 2220 2221 2222 2223 2224
                    slaveAgentPort = 0;
                else
                if(v.equals("disable"))
                    slaveAgentPort = -1;
                else {
                    try {
                        slaveAgentPort = Integer.parseInt(req.getParameter("slaveAgentPort"));
                    } catch (NumberFormatException e) {
K
i18n  
kohsuke 已提交
2225
                        throw new FormException(Messages.Hudson_BadPortNumber(req.getParameter("slaveAgentPort")),"slaveAgentPort");
2226 2227
                    }
                }
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240

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

K
kohsuke 已提交
2243
            numExecutors = Integer.parseInt(req.getParameter("_.numExecutors"));
K
kohsuke 已提交
2244 2245 2246 2247 2248
            if(req.hasParameter("master.mode"))
                mode = Mode.valueOf(req.getParameter("master.mode"));
            else
                mode = Mode.NORMAL;

2249
            label = fixNull(req.getParameter("_.labelString"));
2250 2251
            labelSet=null;

K
kohsuke 已提交
2252
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
S
 
shinodkm 已提交
2253
            
2254
            scmCheckoutRetryCount = Integer.parseInt(req.getParameter("retry_count"));
K
kohsuke 已提交
2255 2256 2257

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

K
kohsuke 已提交
2258 2259
            jdks.clear();
            jdks.addAll(req.bindJSONToList(JDK.class,json.get("jdks")));
K
kohsuke 已提交
2260 2261 2262

            boolean result = true;

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

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

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

2272
            for( SCMDescriptor scmd : SCM.all() )
K
kohsuke 已提交
2273
                result &= configureDescriptor(req,json,scmd);
K
kohsuke 已提交
2274

2275
            for( TriggerDescriptor d : Trigger.all() )
K
kohsuke 已提交
2276
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
2277

2278
            for( JobPropertyDescriptor d : JobPropertyDescriptor.all() )
K
kohsuke 已提交
2279
                result &= configureDescriptor(req,json,d);
2280

2281
            for( PageDecorator d : PageDecorator.all() )
2282 2283
                result &= configureDescriptor(req,json,d);

2284 2285 2286
            for( Descriptor<CrumbIssuer> d : CrumbIssuer.all() )
                result &= configureDescriptor(req,json, d);
            
2287 2288 2289
            for( ToolDescriptor d : ToolInstallation.all() )
                result &= configureDescriptor(req,json,d);

2290
            for( JSONObject o : StructuredForm.toList(json,"plugin"))
K
kohsuke 已提交
2291
                pluginManager.getPlugin(o.getString("name")).getPlugin().configure(req, o);
2292

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

2295 2296 2297 2298
            JSONObject np = json.getJSONObject("globalNodeProperties");
            if (np != null) {
                globalNodeProperties.rebuild(req, np, NodeProperty.for_(this));
            }
2299

2300 2301
            version = VERSION;

K
kohsuke 已提交
2302
            save();
2303
            updateComputerList();
K
kohsuke 已提交
2304
            if(result)
2305
                rsp.sendRedirect(req.getContextPath()+'/');  // go to the top page
K
kohsuke 已提交
2306 2307
            else
                rsp.sendRedirect("configure"); // back to config
K
kohsuke 已提交
2308 2309
        } finally {
            bc.commit();
K
kohsuke 已提交
2310 2311 2312
        }
    }

2313 2314 2315 2316 2317 2318 2319 2320
    public CrumbIssuer getCrumbIssuer() {
        return crumbIssuer;
    }
    
    public void setCrumbIssuer(CrumbIssuer issuer) {
        crumbIssuer = issuer;
    }

2321 2322 2323 2324 2325
    public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        JSONObject form = req.getSubmittedForm();
        rsp.sendRedirect("foo");
    }

2326
    private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
2327 2328 2329
        // 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.
2330 2331 2332 2333
        json.putAll(js);
        return d.configure(req, js);
    }

2334 2335 2336 2337
    /**
     * Accepts submission from the configuration page.
     */
    public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2338
        checkPermission(ADMINISTER);
2339

2340 2341 2342
        BulkChange bc = new BulkChange(this);
        try {
            JSONObject json = req.getSubmittedForm();
2343

2344
            setNumExecutors(Integer.parseInt(req.getParameter("numExecutors")));
2345 2346 2347 2348
            if(req.hasParameter("master.mode"))
                mode = Mode.valueOf(req.getParameter("master.mode"));
            else
                mode = Mode.NORMAL;
S
stephenconnolly 已提交
2349

K
kohsuke 已提交
2350
            setNodes(req.bindJSONToList(Slave.class,json.get("slaves")));
2351 2352 2353
        } finally {
            bc.commit();
        }
S
stephenconnolly 已提交
2354

2355
        rsp.sendRedirect(req.getContextPath()+'/');  // go to the top page
2356 2357
    }

K
kohsuke 已提交
2358 2359 2360 2361
    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2362
        getPrimaryView().doSubmitDescription(req,rsp);
K
kohsuke 已提交
2363 2364
    }

2365 2366 2367 2368 2369 2370 2371 2372
    /**
     * @deprecated as of 1.317
     *      Use {@link #doQuietDown()} instead.
     */
    public synchronized void doQuietDown(StaplerResponse rsp) throws IOException, ServletException {
        doQuietDown().generateResponse(null,rsp,this);
    }

K
kohsuke 已提交
2373
    @CLIMethod(name="quiet-down")
2374
    public synchronized HttpRedirect doQuietDown() throws IOException, ServletException {
K
kohsuke 已提交
2375
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2376
        isQuietingDown = true;
2377
        return new HttpRedirect(".");
K
kohsuke 已提交
2378 2379
    }

K
kohsuke 已提交
2380
    @CLIMethod(name="cancel-quiet-down")
2381
    public synchronized HttpRedirect doCancelQuietDown() throws IOException, ServletException {
K
kohsuke 已提交
2382
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2383 2384
        isQuietingDown = false;
        getQueue().scheduleMaintenance();
2385
        return new HttpRedirect(".");
K
kohsuke 已提交
2386 2387
    }

2388 2389 2390
    /**
     * Backward compatibility. Redirect to the thread dump.
     */
2391
    public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
2392 2393 2394
        rsp.sendRedirect2("threadDump");
    }

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

2398 2399
        TopLevelItem result;

K
kohsuke 已提交
2400 2401 2402 2403 2404 2405
        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");
2406 2407 2408 2409 2410 2411 2412
        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");
        }
2413 2414

        String name = req.getParameter("name");
K
typo.  
kohsuke 已提交
2415
        if(name==null) {
2416 2417 2418
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Query parameter 'name' is required");
            return null;
        }
K
kohsuke 已提交
2419 2420

        try {
2421
            name = checkJobName(name);
K
kohsuke 已提交
2422
        } catch (ParseException e) {
K
kohsuke 已提交
2423
            rsp.setStatus(SC_BAD_REQUEST);
K
kohsuke 已提交
2424 2425 2426 2427
            sendError(e,req,rsp);
            return null;
        }

2428
        String mode = req.getParameter("mode");
K
kohsuke 已提交
2429
        if(mode!=null && mode.equals("copy")) {
2430 2431
            String from = req.getParameter("from");
            TopLevelItem src = getItem(from);
K
kohsuke 已提交
2432
            if(src==null) {
2433 2434 2435 2436 2437
                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 已提交
2438 2439 2440
                return null;
            }

K
kohsuke 已提交
2441
            result = copy(src,name);
2442
        } else {
2443
            if(isXmlSubmission) {
K
kohsuke 已提交
2444 2445 2446
                result = createProjectFromXML(name, req.getInputStream());
                rsp.setStatus(HttpServletResponse.SC_OK);
                return result;
2447 2448 2449
            } else {
                // create empty job and redirect to the project config screen
                if(mode==null) {
K
kohsuke 已提交
2450
                    rsp.sendError(SC_BAD_REQUEST);
2451 2452 2453 2454
                    return null;
                }
                result = createProject(Items.getDescriptor(mode), name);
            }
K
kohsuke 已提交
2455

2456
            for (ItemListener l : ItemListener.all())
K
kohsuke 已提交
2457 2458
                l.onCreated(result);
        }
2459

K
kohsuke 已提交
2460 2461
        // send the browser to the config page
        rsp.sendRedirect2(result.getUrl()+"configure");
K
kohsuke 已提交
2462 2463 2464
        return result;
    }

K
kohsuke 已提交
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
    /**
     * Creates a new job from its configuration XML. The type of the job created will be determined by
     * what's in this XML.
     * @since 1.319
     */
    public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
        // place it as config.xml
        File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
        configXml.getParentFile().mkdirs();
        try {
            FileOutputStream fos = new FileOutputStream(configXml);
            try {
                Util.copyStream(xml,fos);
            } finally {
                fos.close();
            }

            // load it
            TopLevelItem result = (TopLevelItem)Items.load(this,configXml.getParentFile());
            items.put(name,result);
            return result;
        } catch (IOException e) {
            // if anything fails, delete the config file to avoid further confusion
            Util.deleteRecursive(configXml.getParentFile());
            throw e;
        }
    }

K
kohsuke 已提交
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
    /**
     * 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);

2515
        for (ItemListener l : ItemListener.all())
2516
            l.onCopied(src,result);
K
kohsuke 已提交
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526

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

2527
    public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
2528 2529
        try {
            checkPermission(View.CREATE);
2530
            addView(View.create(req,rsp, this));
K
kohsuke 已提交
2531 2532
        } catch (ParseException e) {
            sendError(e,req,rsp);
2533
        }
K
kohsuke 已提交
2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
    }

    /**
     * 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 已提交
2545
            throw new ParseException(Messages.Hudson_NoName(),0);
K
kohsuke 已提交
2546 2547 2548

        for( int i=0; i<name.length(); i++ ) {
            char ch = name.charAt(i);
2549 2550 2551
            if(Character.isISOControl(ch)) {
                throw new ParseException(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)),i);
            }
K
kohsuke 已提交
2552
            if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
K
i18n  
kohsuke 已提交
2553
                throw new ParseException(Messages.Hudson_UnsafeChar(ch),i);
K
kohsuke 已提交
2554 2555 2556 2557 2558
        }

        // looks good
    }

2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
    /**
     * Makes sure that the given name is good as a job name.
     * @return trimmed name if valid; throws ParseException if not
     */
    private String checkJobName(String name) throws ParseException {
        checkGoodName(name);
        name = name.trim();
        if(getItem(name)!=null)
            throw new ParseException(Messages.Hudson_JobAlreadyExists(name),0);
        // looks good
        return name;
    }

2572
    private static String toPrintableName(String name) {
K
kohsuke 已提交
2573
        StringBuilder printableName = new StringBuilder();
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583
        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();
    }

2584
    /**
2585 2586 2587
     * Checks if the user was successfully authenticated.
     *
     * @see BasicAuthenticationFilter
2588 2589
     */
    public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2590 2591
        if(req.getUserPrincipal()==null) {
            // authentication must have failed
2592 2593 2594 2595
            rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

2596
        // the user is now authenticated, so send him back to the target
2597
        String path = req.getContextPath()+req.getOriginalRestOfPath();
2598 2599
        String q = req.getQueryString();
        if(q!=null)
2600
            path += '?'+q;
2601

2602
        rsp.sendRedirect2(path);
2603 2604
    }

K
kohsuke 已提交
2605 2606 2607
    /**
     * Called once the user logs in. Just forward to the top page.
     */
K
kohsuke 已提交
2608
    public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
2609 2610
        if(req.getUserPrincipal()==null)
            rsp.sendRedirect2("noPrincipal");
2611 2612

        String from = req.getParameter("from");
2613
        if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
2614
            rsp.sendRedirect2(from);    // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
            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 已提交
2627 2628 2629
    }

    /**
2630
     * Logs out the user.
K
kohsuke 已提交
2631
     */
2632 2633
    public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        securityRealm.doLogout(req,rsp);
K
kohsuke 已提交
2634 2635
    }

2636 2637 2638 2639 2640 2641 2642
    /**
     * Serves jar files for JNLP slave agents.
     */
    public Slave.JnlpJar getJnlpJars(String fileName) {
        return new Slave.JnlpJar(fileName);
    }

K
kohsuke 已提交
2643 2644
    /**
     * RSS feed for log entries.
2645 2646 2647
     *
     * @deprecated
     *   As on 1.267, moved to "/log/rss..."
K
kohsuke 已提交
2648 2649
     */
    public void doLogRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2650 2651
        String qs = req.getQueryString();
        rsp.sendRedirect2("./log/rss"+(qs==null?"":'?'+qs));
K
kohsuke 已提交
2652 2653
    }

K
kohsuke 已提交
2654 2655 2656
    /**
     * Reloads the configuration.
     */
K
kohsuke 已提交
2657
    @CLIMethod(name="reload-configuration")
K
kohsuke 已提交
2658
    public synchronized HttpResponse doReload() throws IOException {
K
kohsuke 已提交
2659
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2660

2661
        // engage "loading ..." UI and then run the actual task in a separate thread
K
kohsuke 已提交
2662
        servletContext.setAttribute("app",new HudsonIsLoading());
2663 2664

        new Thread("Hudson config reload thread") {
2665
            @Override
2666 2667 2668 2669
            public void run() {
                try {
                    load();
                    User.reload();
K
kohsuke 已提交
2670
                    servletContext.setAttribute("app",Hudson.this);
2671
                } catch (IOException e) {
2672
                    LOGGER.log(SEVERE,"Failed to reload Hudson config",e);
2673 2674 2675
                }
            }
        }.start();
K
kohsuke 已提交
2676 2677

        return HttpResponses.redirectViaContextPath("/");
K
kohsuke 已提交
2678 2679 2680 2681 2682 2683
    }

    /**
     * Do a finger-print check.
     */
    public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2684 2685
        // Parse the request
        MultipartFormDataParser p = new MultipartFormDataParser(req);
2686 2687 2688
        if(Hudson.getInstance().isUseCrumbs() && !Hudson.getInstance().getCrumbIssuer().validateCrumb(req, p)) {
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");                
        }
K
kohsuke 已提交
2689 2690
        try {
            rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
2691 2692 2693
                Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
        } finally {
            p.cleanUp();
K
kohsuke 已提交
2694 2695 2696 2697 2698 2699 2700
        }
    }

    /**
     * Serves static resources without the "Last-Modified" header to work around
     * a bug in Firefox.
     *
K
kohsuke 已提交
2701 2702
     * <p>
     * See https://bugzilla.mozilla.org/show_bug.cgi?id=89419
K
kohsuke 已提交
2703 2704 2705 2706 2707 2708 2709 2710 2711
     */
    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 已提交
2712
            rsp.sendError(SC_BAD_REQUEST);
K
kohsuke 已提交
2713 2714 2715 2716 2717
            return;
        }

        File f = new File(req.getServletContext().getRealPath("/images"),path.substring(1));
        if(!f.exists()) {
2718
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
            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 已提交
2733
        Util.copyStream(in,rsp.getOutputStream());
K
kohsuke 已提交
2734 2735 2736 2737
        in.close();
    }

    /**
K
kohsuke 已提交
2738
     * For debugging. Expose URL to perform GC.
K
kohsuke 已提交
2739
     */
2740
    public void doGc(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2741 2742 2743 2744 2745 2746
        System.gc();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("GCed");
    }

2747 2748 2749
    private transient final Map<UUID,FullDuplexHttpChannel> duplexChannels = new HashMap<UUID, FullDuplexHttpChannel>();

    /**
2750
     * Handles HTTP requests for duplex channels for CLI.
2751
     */
2752
    public void doCli(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
2753
        checkPermission(READ);
2754 2755 2756 2757 2758
        if(!"POST".equals(Stapler.getCurrentRequest().getMethod())) {
            // for GET request, serve _cli.jelly, assuming this is a browser
            req.getView(this,"_cli.jelly").forward(req,rsp);
            return;
        }
2759 2760

        UUID uuid = UUID.fromString(req.getHeader("Session"));
2761
        rsp.setHeader("Hudson-Duplex",""); // set the header so that the client would know
2762
        final Authentication auth = getAuthentication();
2763 2764 2765

        FullDuplexHttpChannel server;
        if(req.getHeader("Side").equals("download")) {
2766 2767
            duplexChannels.put(uuid,server=new FullDuplexHttpChannel(uuid, !hasPermission(ADMINISTER)) {
                protected void main(Channel channel) throws IOException, InterruptedException {
2768
                    channel.setProperty(CliEntryPoint.class.getName(),new CliManagerImpl(auth));
2769 2770
                }
            });
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
            try {
                server.download(req,rsp);
            } finally {
                duplexChannels.remove(uuid);
            }
        } else {
            duplexChannels.get(uuid).upload(req,rsp);
        }
    }

2781 2782 2783 2784 2785 2786 2787
    /**
     * Binds /userContent/... to $HUDSON_HOME/userContent.
     */
    public DirectoryBrowserSupport doUserContent() {
        return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.gif",true);
    }

K
kohsuke 已提交
2788 2789
    /**
     * Perform a restart of Hudson, if we can.
2790 2791
     *
     * This first replaces "app" to {@link HudsonIsRestarting}
K
kohsuke 已提交
2792 2793 2794
     */
    public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        checkPermission(ADMINISTER);
2795 2796 2797
        if(Stapler.getCurrentRequest().getMethod().equals("GET")) {
            req.getView(this,"_restart.jelly").forward(req,rsp);
            return;
K
kohsuke 已提交
2798
        }
2799

2800 2801 2802 2803 2804 2805 2806 2807
        restart();

        rsp.sendRedirect2(".");
    }

    /**
     * Performs a restart.
     */
2808
    @CLIMethod(name="restart")
2809
    public void restart() {
2810 2811
        final Lifecycle lifecycle = Lifecycle.get();
        if(!lifecycle.canRestart())
2812
            throw new Failure("Restart is not supported in this running mode.");
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828
        servletContext.setAttribute("app",new HudsonIsRestarting());

        new Thread("restart thread") {
            @Override
            public void run() {
                try {
                    // give some time for the browser to load the "reloading" page
                    Thread.sleep(5000);
                    lifecycle.restart();
                } catch (InterruptedException e) {
                    LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
                }
            }
        }.start();
K
kohsuke 已提交
2829 2830
    }

K
kohsuke 已提交
2831 2832 2833 2834 2835
    /**
     * Shutdown the system.
     * @since 1.161
     */
    public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
2836
        checkPermission(ADMINISTER);
2837
        LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
K
kohsuke 已提交
2838
                getAuthentication(), req.getRemoteAddr()));
K
kohsuke 已提交
2839 2840 2841 2842 2843
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        PrintWriter w = rsp.getWriter();
        w.println("Shutting down");
        w.close();
2844

K
kohsuke 已提交
2845 2846 2847
        System.exit(0);
    }

K
kohsuke 已提交
2848 2849 2850 2851 2852
    /**
     * Gets the {@link Authentication} object that represents the user
     * associated with the current request.
     */
    public static Authentication getAuthentication() {
K
kohsuke 已提交
2853 2854 2855 2856 2857
        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 已提交
2858 2859
        if(a==null)
            a = new AnonymousAuthenticationToken("anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
K
kohsuke 已提交
2860
        return a;
K
kohsuke 已提交
2861 2862
    }

K
kohsuke 已提交
2863 2864
    /**
     * For system diagnostics.
K
kohsuke 已提交
2865
     * Run arbitrary Groovy script.
K
kohsuke 已提交
2866
     */
2867 2868 2869
    public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        doScript(req, rsp, req.getView(this, "_script.jelly"));
    }
2870

2871 2872 2873 2874 2875 2876 2877 2878
    /**
     * 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 {
2879 2880
        // ability to run arbitrary script is dangerous
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2881 2882

        String text = req.getParameter("script");
2883
        if (text != null) {
K
kohsuke 已提交
2884
            try {
2885
                req.setAttribute("output",
2886
                        RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel));
2887 2888
            } catch (InterruptedException e) {
                throw new ServletException(e);
K
kohsuke 已提交
2889 2890 2891
            }
        }

2892
        view.forward(req, rsp);
K
kohsuke 已提交
2893 2894
    }

2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
    /**
     * 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 已提交
2913 2914 2915 2916 2917 2918 2919
    /**
     * 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 已提交
2920 2921 2922
    /**
     * Changes the icon size by changing the cookie
     */
K
kohsuke 已提交
2923 2924
    public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        String qs = req.getQueryString();
J
jglick 已提交
2925
        if(qs==null || !ICON_SIZE.matcher(qs).matches())
K
kohsuke 已提交
2926
            throw new ServletException();
2927 2928 2929
        Cookie cookie = new Cookie("iconSize", qs);
        cookie.setMaxAge(/* ~4 mo. */9999999); // #762
        rsp.addCookie(cookie);
K
kohsuke 已提交
2930 2931 2932
        String ref = req.getHeader("Referer");
        if(ref==null)   ref=".";
        rsp.sendRedirect2(ref);
K
kohsuke 已提交
2933 2934
    }

2935
    public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2936 2937 2938 2939 2940 2941
        FingerprintCleanupThread.invoke();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("Invoked");
    }

2942
    public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2943 2944 2945 2946 2947 2948
        WorkspaceCleanupThread.invoke();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("Invoked");
    }

K
kohsuke 已提交
2949 2950 2951
    /**
     * If the user chose the default JDK, make sure we got 'java' in PATH.
     */
2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962
    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 已提交
2963 2964
    }

K
kohsuke 已提交
2965
    /**
2966
     * Makes sure that the given name is good as a job name.
K
kohsuke 已提交
2967
     */
2968
    public FormValidation doCheckJobName(@QueryParameter String value) {
K
kohsuke 已提交
2969 2970
        // this method can be used to check if a file exists anywhere in the file system,
        // so it should be protected.
2971 2972
        checkPermission(Item.CREATE);
        
2973
        if(fixEmpty(value)==null)
K
kohsuke 已提交
2974
            return FormValidation.ok();
2975

2976 2977
        try {
            checkJobName(value);
2978
            return FormValidation.ok();
2979 2980 2981
        } catch (ParseException e) {
            return FormValidation.error(e.getMessage());
        }
K
kohsuke 已提交
2982
    }
2983 2984 2985 2986

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

2990
        String view = fixEmpty(value);
K
kohsuke 已提交
2991
        if(view==null) return FormValidation.ok();
2992 2993 2994 2995 2996

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

2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
    /**
     * @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);
    }
3010

3011 3012 3013
    /**
     * 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
3014 3015
     * as an error text. If the parameter "errorText" is not set, then the parameter "warningText"
     * is displayed as a warning text.
K
kohsuke 已提交
3016
     * <p>
3017 3018
     * 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".
3019 3020 3021 3022
     *
     * @deprecated as of 1.324
     *      Either use client-side validation (e.g. class="required number")
     *      or define your own check method, instead of relying on this generic one.
K
kohsuke 已提交
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034
     */
    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().");
        }
3035

K
kohsuke 已提交
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
        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());
3046
                }
K
kohsuke 已提交
3047 3048
            } catch (ParseException e) {
                return FormValidation.error(Messages.Hudson_NotANumber());
3049
            }
K
kohsuke 已提交
3050
        }
3051

K
kohsuke 已提交
3052
        return FormValidation.ok();
3053
    }
K
kohsuke 已提交
3054

3055 3056 3057 3058 3059 3060 3061 3062
    /**
     * 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.
     */
3063
    public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
3064
        String path = req.getRestOfPath();
3065 3066 3067 3068 3069 3070
        // 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);

3071 3072 3073
        int idx = path.lastIndexOf('.');
        String extension = path.substring(idx+1);
        if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
3074 3075 3076 3077
            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);
3078 3079 3080 3081 3082 3083
                return;
            }
        }
        rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

S
sogabe 已提交
3084 3085 3086 3087 3088 3089 3090 3091
    /**
     * 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("\\|")
    ));

3092 3093 3094
    /**
     * Checks if container uses UTF-8 to decode URLs. See
     * http://hudson.gotdns.com/wiki/display/HUDSON/Tomcat#Tomcat-i18n
K
kohsuke 已提交
3095
     */
3096
    public FormValidation doCheckURIEncoding(StaplerRequest request, StaplerResponse response) throws IOException {
K
kohsuke 已提交
3097 3098 3099
        request.setCharacterEncoding("UTF-8");
        // expected is non-ASCII String
        final String expected = "\u57f7\u4e8b";
3100
        final String value = fixEmpty(request.getParameter("value"));
K
kohsuke 已提交
3101 3102 3103
        if (!expected.equals(value))
            return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
        return FormValidation.ok();
3104
    }
S
sogabe 已提交
3105

3106 3107 3108 3109 3110 3111
    /**
     * 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 已提交
3112 3113 3114 3115

    public static boolean isWindows() {
        return File.pathSeparatorChar==';';
    }
3116 3117 3118
    
    public static boolean isDarwin() {
        // according to http://developer.apple.com/technotes/tn2002/tn2110.html
3119
        return System.getProperty("os.name").toLowerCase().startsWith("mac");
3120
    }
K
kohsuke 已提交
3121

3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
    /**
     * Rebuilds the dependency map.
     */
    public void rebuildDependencyGraph() {
        dependencyGraph = new DependencyGraph();
    }

    public DependencyGraph getDependencyGraph() {
        return dependencyGraph;
    }

3133 3134
    // for Jelly
    public List<ManagementLink> getManagementLinks() {
3135
        return ManagementLink.all();
3136 3137
    }

3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
    /**
     * Exposes the current user to <tt>/me</tt> URL.
     */
    public User getMe() {
        User u = User.current();
        if (u == null)
            throw new AccessDeniedException("/me is not available when not logged in");
        return u;
    }

K
kohsuke 已提交
3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
    /**
     * 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 已提交
3159
    public Object getTarget() {
K
kohsuke 已提交
3160 3161 3162 3163 3164 3165 3166
        try {
            checkPermission(READ);
        } catch (AccessDeniedException e) {
            String rest = Stapler.getCurrentRequest().getRestOfPath();
            if(rest.startsWith("/login")
            || rest.startsWith("/logout")
            || rest.startsWith("/accessDenied")
3167
            || rest.startsWith("/signup")
3168
            || rest.startsWith("/jnlpJars/")
3169
            || rest.startsWith("/tcpSlaveAgentListener")
K
kohsuke 已提交
3170 3171 3172 3173
            || rest.startsWith("/securityRealm"))
                return this;    // URLs that are always visible without READ permission
            throw e;
        }
K
kohsuke 已提交
3174 3175 3176
        return this;
    }

3177 3178 3179 3180 3181 3182 3183
    /**
     * Fallback to the primary view.
     */
    public View getStaplerFallback() {
        return getPrimaryView();
    }

K
kohsuke 已提交
3184 3185 3186 3187 3188
    public static final class MasterComputer extends Computer {
        private MasterComputer() {
            super(Hudson.getInstance());
        }

3189 3190 3191
        /**
         * Returns "" to match with {@link Hudson#getNodeName()}.
         */
3192
        @Override
3193 3194 3195 3196
        public String getName() {
            return "";
        }

K
kohsuke 已提交
3197 3198 3199 3200 3201
        @Override
        public boolean isConnecting() {
            return false;
        }

K
kohsuke 已提交
3202 3203
        @Override
        public String getDisplayName() {
K
i18n  
kohsuke 已提交
3204
            return Messages.Hudson_Computer_DisplayName();
K
kohsuke 已提交
3205 3206 3207 3208
        }

        @Override
        public String getCaption() {
K
i18n  
kohsuke 已提交
3209
            return Messages.Hudson_Computer_Caption();
K
kohsuke 已提交
3210 3211
        }

3212
        @Override
K
kohsuke 已提交
3213 3214 3215 3216
        public String getUrl() {
            return "computer/(master)/";
        }

3217
        public RetentionStrategy getRetentionStrategy() {
K
kohsuke 已提交
3218
            return RetentionStrategy.NOOP;
3219 3220
        }

3221 3222 3223 3224 3225 3226 3227 3228
        /**
         * Report an error.
         */
        @Override
        public void doDoDelete(StaplerResponse rsp) throws IOException {
            rsp.sendError(SC_BAD_REQUEST);
        }

3229
        @Override
K
kohsuke 已提交
3230 3231 3232 3233 3234
        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();
        }

3235 3236 3237 3238 3239 3240 3241 3242 3243
        @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 已提交
3244 3245 3246 3247 3248
        @Override
        public VirtualChannel getChannel() {
            return localChannel;
        }

3249 3250 3251 3252 3253
        @Override
        public Charset getDefaultCharset() {
            return Charset.defaultCharset();
        }

K
kohsuke 已提交
3254 3255 3256 3257
        public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
            return logRecords;
        }

K
kohsuke 已提交
3258 3259 3260
        public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            // this computer never returns null from channel, so
            // this method shall never be invoked.
3261
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
3262 3263
        }

3264 3265 3266 3267 3268 3269 3270
        /**
         * Redirect the master configuration to /configure.
         */
        public void doConfigure(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            rsp.sendRedirect2(req.getContextPath()+"/configure");
        }

3271
        protected Future<?> _connect(boolean forceReconnect) {
K
kohsuke 已提交
3272
            return Futures.precomputed(null);
3273 3274
        }

K
kohsuke 已提交
3275 3276 3277 3278 3279 3280
        /**
         * {@link LocalChannel} instance that can be used to execute programs locally.
         */
        public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
    }

3281
    /**
M
mindless 已提交
3282
     * @deprecated since 2007-12-18.
3283 3284
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
3285 3286 3287 3288
    public static boolean adminCheck() throws IOException {
        return adminCheck(Stapler.getCurrentRequest(), Stapler.getCurrentResponse());
    }

3289
    /**
M
mindless 已提交
3290
     * @deprecated since 2007-12-18.
3291 3292
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
3293
    public static boolean adminCheck(StaplerRequest req,StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
3294 3295 3296 3297 3298 3299
        if (isAdmin(req)) return true;

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

K
kohsuke 已提交
3300 3301 3302
    /**
     * Checks if the current user (for which we are processing the current request)
     * has the admin access.
3303
     *
M
mindless 已提交
3304
     * @deprecated since 2007-12-18.
K
kohsuke 已提交
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
     *      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
3316
     *      against.
K
kohsuke 已提交
3317
     */
K
kohsuke 已提交
3318
    public static boolean isAdmin() {
3319
        return Hudson.getInstance().getACL().hasPermission(ADMINISTER);
K
kohsuke 已提交
3320 3321
    }

3322
    /**
M
mindless 已提交
3323
     * @deprecated since 2007-12-18.
3324
     *      Define a custom {@link Permission} and check against ACL.
K
kohsuke 已提交
3325
     *      See {@link #isAdmin()} for more instructions.
3326
     */
K
kohsuke 已提交
3327
    public static boolean isAdmin(StaplerRequest req) {
3328
        return isAdmin();
K
kohsuke 已提交
3329 3330 3331 3332 3333
    }

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

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

3341 3342
    private static final int TWICE_CPU_NUM = Runtime.getRuntime().availableProcessors() * 2;

3343 3344 3345 3346 3347
    /**
     * 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.
     */
3348
    /*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
3349 3350
        TWICE_CPU_NUM, TWICE_CPU_NUM,
        5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory());
3351 3352


K
kohsuke 已提交
3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368
    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);

K
kohsuke 已提交
3369
        if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
K
kohsuke 已提交
3370 3371 3372 3373 3374 3375
            RESOURCE_PATH = "";
        else
            RESOURCE_PATH = "/static/"+VERSION_HASH;

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

3377 3378 3379
    /**
     * Version number of this Hudson.
     */
3380
    public static String VERSION="?";
3381

K
kohsuke 已提交
3382 3383 3384 3385 3386
    /**
     * Hash of {@link #VERSION}.
     */
    public static String VERSION_HASH;

3387 3388 3389
    /**
     * Prefix to static resources like images and javascripts in the war file.
     * Either "" or strings like "/static/VERSION", which avoids Hudson to pick up
3390
     * stale cache when the user upgrades to a different version.
3391 3392
     * <p>
     * Value computed in {@link WebAppMain}.
3393
     */
3394
    public static String RESOURCE_PATH = "";
3395

3396 3397 3398 3399
    /**
     * 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.
3400 3401
     * <p>
     * Value computed in {@link WebAppMain}.
3402
     */
3403
    public static String VIEW_RESOURCE_PATH = "/resources/TBD";
3404

3405
    public static boolean PARALLEL_LOAD = !"false".equals(System.getProperty(Hudson.class.getName()+".parallelLoad"));
3406
    public static boolean KILL_AFTER_LOAD = Boolean.getBoolean(Hudson.class.getName()+".killAfterLoad");
3407
    public static boolean LOG_STARTUP_PERFORMANCE = Boolean.getBoolean(Hudson.class.getName()+".logStartupPerformance");
3408
    private static final boolean CONSISTENT_HASH = true; // Boolean.getBoolean(Hudson.class.getName()+".consistentHash");
3409
    public static boolean FLYWEIGHT_SUPPORT = Boolean.getBoolean(Hudson.class.getName()+".flyweightSupport");
3410

K
kohsuke 已提交
3411 3412 3413 3414 3415 3416 3417 3418
    /**
     * Tentative switch to activate the concurrent build behavior.
     * When we merge this back to the trunk, this allows us to keep
     * this feature hidden for a while until we iron out the kinks.
     * @see AbstractProject#isConcurrentBuild()
     */
    public static boolean CONCURRENT_BUILD = true;

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

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

3423 3424
    public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
    public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
3425
    public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ);
K
kohsuke 已提交
3426

K
kohsuke 已提交
3427 3428
    static {
        XSTREAM.alias("hudson",Hudson.class);
K
kohsuke 已提交
3429
        XSTREAM.alias("slave", DumbSlave.class);
K
kohsuke 已提交
3430
        XSTREAM.alias("jdk",JDK.class);
3431 3432 3433
        // for backward compatibility with <1.75, recognize the tag name "view" as well.
        XSTREAM.alias("view", ListView.class);
        XSTREAM.alias("listView", ListView.class);
3434 3435
        // this seems to be necessary to force registration of converter early enough
        Mode.class.getEnumConstants();
3436 3437 3438 3439

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