Hudson.java 90.8 KB
Newer Older
K
kohsuke 已提交
1 2
package hudson.model;

S
sogabe 已提交
3
import com.thoughtworks.xstream.XStream;
4
import hudson.BulkChange;
5
import hudson.FilePath;
6
import hudson.Functions;
K
kohsuke 已提交
7
import hudson.Launcher;
S
sogabe 已提交
8
import hudson.Launcher.LocalLauncher;
K
kohsuke 已提交
9 10 11
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
12
import hudson.ProxyConfiguration;
13
import hudson.StructuredForm;
K
kohsuke 已提交
14
import hudson.TcpSlaveAgentListener;
15
import hudson.Util;
S
sogabe 已提交
16
import static hudson.Util.fixEmpty;
17
import hudson.WebAppMain;
18
import hudson.XmlFile;
19
import hudson.logging.LogRecorderManager;
20
import hudson.lifecycle.WindowsInstallerLink;
K
kohsuke 已提交
21
import hudson.lifecycle.Lifecycle;
K
kohsuke 已提交
22
import hudson.model.Descriptor.FormException;
23
import hudson.model.listeners.ItemListener;
K
kohsuke 已提交
24
import hudson.model.listeners.JobListener;
25
import hudson.model.listeners.JobListener.JobListenerAdapter;
S
sogabe 已提交
26
import hudson.model.listeners.SCMListener;
K
kohsuke 已提交
27 28
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
K
kohsuke 已提交
29
import hudson.scm.CVSSCM;
K
kohsuke 已提交
30 31
import hudson.scm.RepositoryBrowser;
import hudson.scm.RepositoryBrowsers;
32 33 34
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMS;
35
import hudson.scm.SubversionSCM;
K
kohsuke 已提交
36
import hudson.search.CollectionSearchIndex;
37
import hudson.search.SearchIndexBuilder;
38
import hudson.security.ACL;
39
import hudson.security.AccessControlled;
40
import hudson.security.AuthorizationStrategy;
K
kohsuke 已提交
41
import hudson.security.BasicAuthenticationFilter;
42 43 44 45
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
46
import hudson.security.PermissionGroup;
K
kohsuke 已提交
47
import hudson.security.SecurityMode;
48
import hudson.security.SecurityRealm;
49
import hudson.security.SecurityRealm.SecurityComponents;
S
sogabe 已提交
50
import hudson.security.TokenBasedRememberMeServices2;
51 52
import hudson.slaves.ComputerListener;
import hudson.slaves.RetentionStrategy;
53 54 55 56 57 58 59 60
import hudson.tasks.BuildStep;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrappers;
import hudson.tasks.Builder;
import hudson.tasks.DynamicLabeler;
import hudson.tasks.LabelFinder;
import hudson.tasks.Mailer;
import hudson.tasks.Publisher;
K
kohsuke 已提交
61
import hudson.triggers.Trigger;
62
import hudson.triggers.TriggerDescriptor;
63
import hudson.triggers.Triggers;
K
kohsuke 已提交
64
import hudson.util.CaseInsensitiveComparator;
K
kohsuke 已提交
65 66 67 68 69 70 71
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.FormFieldValidator;
import hudson.util.HudsonIsLoading;
import hudson.util.MultipartFormDataParser;
K
kohsuke 已提交
72
import hudson.util.RemotingDiagnostics;
73
import hudson.util.TextFile;
K
kohsuke 已提交
74
import hudson.util.XStream2;
K
kohsuke 已提交
75
import hudson.util.HudsonIsRestarting;
K
kohsuke 已提交
76
import hudson.widgets.Widget;
S
sogabe 已提交
77 78 79 80 81 82 83 84 85
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import static org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY;
K
kohsuke 已提交
86
import org.apache.commons.logging.LogFactory;
S
sogabe 已提交
87 88 89 90 91 92 93
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
K
kohsuke 已提交
94

S
sogabe 已提交
95 96 97 98 99 100 101 102
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import javax.servlet.http.HttpSession;
K
kohsuke 已提交
103 104 105
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
106
import java.io.FileOutputStream;
K
kohsuke 已提交
107 108
import java.io.IOException;
import java.io.PrintWriter;
109
import java.net.URL;
110
import java.security.SecureRandom;
111
import java.text.NumberFormat;
K
kohsuke 已提交
112 113 114 115 116 117 118 119
import java.text.ParseException;
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;
120
import java.util.Iterator;
K
kohsuke 已提交
121 122
import java.util.List;
import java.util.Map;
S
sogabe 已提交
123
import java.util.Map.Entry;
K
kohsuke 已提交
124
import java.util.Set;
125 126
import java.util.Stack;
import java.util.StringTokenizer;
127
import java.util.Timer;
K
kohsuke 已提交
128 129
import java.util.TreeSet;
import java.util.Vector;
130
import java.util.concurrent.Callable;
131
import java.util.concurrent.ConcurrentHashMap;
K
kohsuke 已提交
132
import java.util.concurrent.CopyOnWriteArrayList;
133 134 135 136 137
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;
138
import java.util.concurrent.LinkedBlockingQueue;
K
kohsuke 已提交
139
import java.util.logging.Level;
K
kohsuke 已提交
140
import java.util.logging.LogRecord;
141
import java.util.logging.Logger;
142
import java.util.regex.Pattern;
143
import java.nio.charset.Charset;
144
import javax.servlet.RequestDispatcher;
K
kohsuke 已提交
145 146 147 148 149 150

/**
 * Root object of the system.
 *
 * @author Kohsuke Kawaguchi
 */
151
public final class Hudson extends View implements ItemGroup<TopLevelItem>, Node, StaplerProxy {
152
    private transient final Queue queue;
K
kohsuke 已提交
153 154 155 156

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

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

164 165 166 167 168
    /**
     * Job allocation strategy.
     */
    private Mode mode = Mode.NORMAL;

K
kohsuke 已提交
169 170
    /**
     * False to enable anyone to do anything.
K
kohsuke 已提交
171
     * Left as a field so that we can still read old data that uses this flag.
172 173 174
     *
     * @see #authorizationStrategy
     * @see #securityRealm
K
kohsuke 已提交
175
     */
K
kohsuke 已提交
176
    private Boolean useSecurity;
K
kohsuke 已提交
177 178

    /**
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
     * Controls how the
     * <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
     * is handled in Hudson.
     * <p>
     * This ultimately controls who has access to what.
     *
     * Never null.
     */
    private volatile AuthorizationStrategy authorizationStrategy;

    /**
     * Controls a part of the
     * <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
     * handling in Hudson.
     * <p>
     * Intuitively, this corresponds to the user database.
     *
196
     * See {@link HudsonFilter} for the concrete authentication protocol.
197
     *
198 199
     * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
     * update this field.
200 201
     *
     * @see #getSecurity()
202
     * @see #setSecurityRealm(SecurityRealm)
K
kohsuke 已提交
203
     */
204
    private volatile SecurityRealm securityRealm;
K
kohsuke 已提交
205 206 207 208 209 210 211 212 213 214 215

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

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

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

K
kohsuke 已提交
221 222 223 224 225
    /**
     * The sole instance.
     */
    private static Hudson theInstance;

K
kohsuke 已提交
226 227
    private transient volatile boolean isQuietingDown;
    private transient volatile boolean terminating;
K
kohsuke 已提交
228

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

K
kohsuke 已提交
231 232 233 234 235
    /**
     * Widgets on Hudson.
     */
    private transient final List<Widget> widgets = new CopyOnWriteArrayList<Widget>();

236
    private transient volatile DependencyGraph dependencyGraph;
237

K
kohsuke 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    /**
     * Set of installed cluster nodes.
     *
     * 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.
     */
    private volatile List<Slave> slaves;

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

    /**
256
     * {@link ListView}s.
K
kohsuke 已提交
257
     */
258
    private List<ListView> views;   // can't initialize it eagerly for backward compatibility
K
kohsuke 已提交
259

260 261
    private transient MyView myView = new MyView(this);

K
kohsuke 已提交
262 263 264 265 266 267 268
    private transient final FingerprintMap fingerprintMap = new FingerprintMap();

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

269
    public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
K
kohsuke 已提交
270

271
    /**
K
kohsuke 已提交
272
     * List of registered {@link JobListener}s.
273
     */
K
kohsuke 已提交
274
    private transient final CopyOnWriteList<ItemListener> itemListeners = new CopyOnWriteList<ItemListener>();
275 276 277 278 279

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

281 282 283 284 285
    /**
     * List of registered {@link ComputerListener}s.
     */
    private transient final CopyOnWriteList<ComputerListener> computerListeners = new CopyOnWriteList<ComputerListener>();

286 287
    /**
     * TCP slave agent port.
288
     * 0 for random, -1 to disable.
289 290 291
     */
    private int slaveAgentPort =0;

292 293 294 295 296
    /**
     * 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>();
297
    private transient Set<Label> labelSet;
298
    private transient volatile Set<Label> dynamicLabels = null;
299

300 301
    public transient final ServletContext servletContext;

K
kohsuke 已提交
302 303 304 305 306 307
    /**
     * Transient action list. Useful for adding navigation items to the navigation bar
     * on the left.
     */
    private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();

K
kohsuke 已提交
308 309 310 311
    public static Hudson getInstance() {
        return theInstance;
    }

312 313 314 315 316 317
    /**
     * Secrete key generated once and used for a long time, beyond
     * container start/stop.
     */
    private final String secretKey;

318
    private transient final UpdateCenter updateCenter = new UpdateCenter();
K
kohsuke 已提交
319

320 321 322 323 324
    /**
     * True if the user opted out from the statistics tracking. We'll never send anything if this is true.
     */
    private Boolean noUsageStatistics;

325 326 327 328 329
    /**
     * HTTP proxy configuration.
     */
    public transient volatile ProxyConfiguration proxy;

K
kohsuke 已提交
330
    /**
331
     * Bound to "/log".
K
kohsuke 已提交
332
     */
333
    private transient final LogRecorderManager log = new LogRecorderManager();
334

K
kohsuke 已提交
335 336
    public Hudson(File root, ServletContext context) throws IOException {
        this.root = root;
337
        this.servletContext = context;
K
kohsuke 已提交
338 339 340
        if(theInstance!=null)
            throw new IllegalStateException("second instance");
        theInstance = this;
341 342 343

        log.load();
        
K
kohsuke 已提交
344
        Trigger.timer = new Timer("Hudson cron thread");
345
        queue = new Queue();
K
kohsuke 已提交
346

347 348 349 350 351 352 353 354 355
        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;
        }

356 357 358 359 360 361 362 363 364 365 366 367
        // 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);
        }

368 369 370 371 372 373
        try {
            proxy = ProxyConfiguration.load();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to load proxy configuration", e);
        }

374 375
        // run the init code of SubversionSCM before we load plugins so that plugins can change SubversionWorkspaceSelector.
        SubversionSCM.DescriptorImpl.DESCRIPTOR.getDisplayName();
376

K
kohsuke 已提交
377 378 379
        // load plugins.
        pluginManager = new PluginManager(context);

K
kohsuke 已提交
380 381 382
        // if we are loading old data that doesn't have this field
        if(slaves==null)    slaves = new ArrayList<Slave>();

383
        // work around to have MavenModule register itself until we either move it to a plugin
384
        // or make it a part of the core.
385
        Items.LIST.hashCode();
386

K
kohsuke 已提交
387
        load();
388

389 390 391 392 393 394 395 396 397 398 399 400 401
//        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);
//        }

402 403 404 405 406
        if(slaveAgentPort!=-1)
            tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
        else
            tcpSlaveAgentListener = null;

K
kohsuke 已提交
407 408 409
        updateComputerList();

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

K
kohsuke 已提交
411
        for (ItemListener l : itemListeners)
412
            l.onLoaded();
413 414 415 416 417 418 419

        // create TokenBasedRememberMeServices, which depends on the availability of the secret key
        TokenBasedRememberMeServices2 rms = new TokenBasedRememberMeServices2();
        rms.setUserDetailsService(HudsonFilter.USER_DETAILS_SERVICE_PROXY);
        rms.setKey(getSecretKey());
        rms.setParameter("remember_me"); // this is the form field name in login.jelly
        HudsonFilter.REMEMBER_ME_SERVICES_PROXY.setDelegate(rms);
420 421

        WindowsInstallerLink.registerIfApplicable();
422
        UsageStatistics.register();
K
kohsuke 已提交
423 424
    }

K
kohsuke 已提交
425 426 427 428
    public TcpSlaveAgentListener getTcpSlaveAgentListener() {
        return tcpSlaveAgentListener;
    }

K
kohsuke 已提交
429
    @Exported
430 431 432 433
    public int getSlaveAgentPort() {
        return slaveAgentPort;
    }

K
kohsuke 已提交
434
    /**
J
jglick 已提交
435
     * If you are calling this on Hudson something is wrong.
K
kohsuke 已提交
436 437 438
     *
     * @deprecated
     */
J
jglick 已提交
439
    @Deprecated
K
kohsuke 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
    public String getNodeName() {
        return "";
    }

    public String getNodeDescription() {
        return "the master Hudson node";
    }

    public String getDescription() {
        return systemMessage;
    }

    public PluginManager getPluginManager() {
        return pluginManager;
    }
455

456 457 458
    public UpdateCenter getUpdateCenter() {
        return updateCenter;
    }
K
kohsuke 已提交
459

460 461 462 463
    public boolean isUsageStatisticsCollected() {
        return noUsageStatistics==null || !noUsageStatistics;
    }

464 465 466
    /**
     * Returns a secret key that survives across container start/stop.
     * <p>
467
     * This value is useful for implementing some of the security features.
468 469 470 471 472
     */
    public String getSecretKey() {
        return  secretKey;
    }

K
kohsuke 已提交
473 474 475 476 477 478 479
    /**
     * Gets the SCM descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<SCM> getScm(String shortClassName) {
        return findDescriptor(shortClassName,SCMS.SCMS);
    }

K
kohsuke 已提交
480 481 482 483 484 485 486
    /**
     * Gets the repository browser descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
        return findDescriptor(shortClassName,RepositoryBrowsers.LIST);
    }

K
kohsuke 已提交
487 488 489 490 491 492 493
    /**
     * Gets the builder descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<Builder> getBuilder(String shortClassName) {
        return findDescriptor(shortClassName, BuildStep.BUILDERS);
    }

K
kohsuke 已提交
494 495 496 497 498 499 500
    /**
     * Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
        return findDescriptor(shortClassName, BuildWrappers.WRAPPERS);
    }

K
kohsuke 已提交
501 502 503 504 505 506 507
    /**
     * Gets the publisher descriptor by name. Primarily used for making them web-visible.
     */
    public Descriptor<Publisher> getPublisher(String shortClassName) {
        return findDescriptor(shortClassName, BuildStep.PUBLISHERS);
    }

K
kohsuke 已提交
508 509 510
    /**
     * Gets the trigger descriptor by name. Primarily used for making them web-visible.
     */
511 512
    public TriggerDescriptor getTrigger(String shortClassName) {
        return (TriggerDescriptor)findDescriptor(shortClassName, Triggers.TRIGGERS);
K
kohsuke 已提交
513 514
    }

515 516 517 518
    /**
     * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
     */
    public JobPropertyDescriptor getJobProperty(String shortClassName) {
K
kohsuke 已提交
519 520 521
        // combining these two lines triggers javac bug. See issue #610.
        Descriptor d = findDescriptor(shortClassName, Jobs.PROPERTIES);
        return (JobPropertyDescriptor) d;
522 523
    }

524 525 526 527 528 529 530 531 532 533 534 535 536
    /**
     * 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.
     */
    public Descriptor getDescriptor(String fullyQualifiedClassName) {
        for( Descriptor d : Descriptor.ALL )
            if(d.clazz.getName().equals(fullyQualifiedClassName))
                return d;
        return null;
    }

537 538 539 540 541 542 543
    /**
     * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
     */
    public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
        return findDescriptor(shortClassName,SecurityRealm.LIST);
    }

K
kohsuke 已提交
544 545 546 547
    /**
     * Finds a descriptor that has the specified name.
     */
    private <T extends Describable<T>>
548
    Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
K
kohsuke 已提交
549 550 551 552 553 554 555 556
        String name = '.'+shortClassName;
        for (Descriptor<T> d : descriptors) {
            if(d.clazz.getName().endsWith(name))
                return d;
        }
        return null;
    }

557 558 559
    /**
     * Adds a new {@link JobListener}.
     *
560 561
     * @deprecated
     *      Use {@code getJobListners().add(l)} instead.
562 563
     */
    public void addListener(JobListener l) {
K
kohsuke 已提交
564
        itemListeners.add(new JobListenerAdapter(l));
565 566 567 568 569
    }

    /**
     * Deletes an existing {@link JobListener}.
     *
570 571
     * @deprecated
     *      Use {@code getJobListners().remove(l)} instead.
572 573
     */
    public boolean removeListener(JobListener l ) {
K
kohsuke 已提交
574
        return itemListeners.remove(new JobListenerAdapter(l));
575 576
    }

577
    /**
578
     * Gets all the installed {@link ItemListener}s.
579
     */
580
    public CopyOnWriteList<ItemListener> getJobListeners() {
K
kohsuke 已提交
581
        return itemListeners;
582 583 584 585 586 587 588 589 590
    }

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

591 592 593 594 595 596 597
    /**
     * Gets all the installed {@link ComputerListener}s.
     */
    public CopyOnWriteList<ComputerListener> getComputerListeners() {
        return computerListeners;
    }

K
kohsuke 已提交
598 599 600 601 602 603 604 605 606 607
    /**
     * 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;
608
        return p.getPlugin();
K
kohsuke 已提交
609 610
    }

611 612 613 614 615 616 617 618 619 620 621 622
    /**
     * 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 已提交
623 624
    @SuppressWarnings("unchecked")
    public <P extends Plugin> P getPlugin(Class<P> clazz) {
625 626
        PluginWrapper p = pluginManager.getPlugin(clazz);
        if(p==null)     return null;
S
stephenconnolly 已提交
627
        return (P) p.getPlugin();
628 629 630 631 632 633 634 635 636
    }

    /**
     * Gets the plugin objects from their super-class.
     *
     * @param clazz The plugin class (beware class-loader fun)
     *
     * @return The plugin instances.
     */
S
stephenconnolly 已提交
637 638
    public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
        List<P> result = new ArrayList<P>();
639
        for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
S
stephenconnolly 已提交
640
            result.add((P)w.getPlugin());
641 642 643 644
        }
        return Collections.unmodifiableList(result);
    }

K
kohsuke 已提交
645 646 647 648 649 650 651 652
    /**
     * Synonym to {@link #getNodeDescription()}.
     */
    public String getSystemMessage() {
        return systemMessage;
    }

    public Launcher createLauncher(TaskListener listener) {
K
kohsuke 已提交
653
        return new LocalLauncher(listener);
K
kohsuke 已提交
654 655 656 657 658 659 660 661 662
    }

    /**
     * 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 已提交
663
    private void updateComputerList() throws IOException {
664
        synchronized(computers) {// this synchronization is still necessary so that no two update happens concurrently
K
kohsuke 已提交
665
            Map<String,Computer> byName = new HashMap<String,Computer>();
K
kohsuke 已提交
666 667 668
            for (Computer c : computers.values()) {
                if(c.getNode()==null)
                    continue;   // this computer is gone
K
kohsuke 已提交
669
                byName.put(c.getNode().getNodeName(),c);
K
kohsuke 已提交
670
            }
K
kohsuke 已提交
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

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

            updateComputer(this, byName, used);
            for (Slave s : getSlaves())
                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 已提交
693 694
        if (c!=null) {
            c.setNode(n); // reuse
K
kohsuke 已提交
695
        } else {
K
kohsuke 已提交
696 697
            if(n.getNumExecutors()>0)
                computers.put(n,c=n.createComputer());
K
kohsuke 已提交
698 699 700 701 702
        }
        used.add(c);
    }

    /*package*/ void removeComputer(Computer computer) {
703 704
        for (Entry<Node, Computer> e : computers.entrySet()) {
            if (e.getValue() == computer) {
K
kohsuke 已提交
705
                computers.remove(e.getKey());
706
                return;
K
kohsuke 已提交
707 708 709 710 711
            }
        }
        throw new IllegalStateException("Trying to remove unknown computer");
    }

712 713 714 715
    public String getFullName() {
        return "";
    }

716 717 718 719
    public String getFullDisplayName() {
        return "";
    }

K
kohsuke 已提交
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    /**
     * Returns the transient {@link Action}s associated with the top page.
     *
     * <p>
     * Adding {@link Action} is primarily useful for plugins to contribute
     * an item to the navigation bar of the top page. See existing {@link Action}
     * implementation for it affects the GUI.
     *
     * <p>
     * To register an {@link Action}, write code like
     * {@code Hudson.getInstance().getActions().add(...)}
     *
     * @return
     *      Live list where the changes can be made. Can be empty but never null.
     * @since 1.172
     */
    public List<Action> getActions() {
        return actions;
    }

740 741 742
    /**
     * Gets just the immediate children of {@link Hudson}.
     *
743
     * @see #getAllItems(Class)
744
     */
K
kohsuke 已提交
745
    public List<TopLevelItem> getItems() {
746
        return new ArrayList<TopLevelItem>(items.values());
747 748
    }

K
kohsuke 已提交
749 750 751
    /**
     * Gets just the immediate children of {@link Hudson} but of the given type.
     */
K
kohsuke 已提交
752
    public <T> List<T> getItems(Class<T> type) {
K
kohsuke 已提交
753 754 755 756 757 758 759
        List<T> r = new ArrayList<T>();
        for (TopLevelItem i : items.values())
            if (type.isInstance(i))
                 r.add(type.cast(i));
        return r;
    }

760 761 762 763 764 765 766 767 768 769 770 771 772 773
    /**
     * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
     * and filter them by the given type.
     */
    public <T extends Item> List<T> getAllItems(Class<T> type) {
        List<T> r = new ArrayList<T>();

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

        while(!q.isEmpty()) {
            ItemGroup<?> parent = q.pop();
            for (Item i : parent.getItems()) {
                if(type.isInstance(i))
K
typo.  
kohsuke 已提交
774
                    r.add(type.cast(i));
775 776 777 778 779 780 781 782
                if(i instanceof ItemGroup)
                    q.push((ItemGroup)i);
            }
        }

        return r;
    }

K
kohsuke 已提交
783
    /**
K
kohsuke 已提交
784 785 786 787 788
     * 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 已提交
789
     */
K
kohsuke 已提交
790
    public List<Project> getProjects() {
K
kohsuke 已提交
791
        return Util.createSubList(items.values(),Project.class);
K
kohsuke 已提交
792 793 794 795 796
    }

    /**
     * Gets the names of all the {@link Job}s.
     */
K
kohsuke 已提交
797
    public Collection<String> getJobNames() {
798
        List<String> names = new ArrayList<String>();
K
kohsuke 已提交
799
        for (Job j : getAllItems(Job.class))
800
            names.add(j.getFullName());
801
        return names;
K
kohsuke 已提交
802 803
    }

804 805 806 807 808 809 810 811 812 813
    /**
     * 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;
    }

K
kohsuke 已提交
814 815 816 817 818 819
    /**
     * Every job belongs to us.
     *
     * @deprecated
     *      why are you calling a method that always return true?
     */
J
jglick 已提交
820
    @Deprecated
821
    public boolean contains(TopLevelItem view) {
K
kohsuke 已提交
822 823 824
        return true;
    }

825
    public synchronized View getView(String name) {
K
kohsuke 已提交
826
        if(views!=null) {
827
            for (ListView v : views) {
K
kohsuke 已提交
828 829 830 831
                if(v.getViewName().equals(name))
                    return v;
            }
        }
832
        if (this.getViewName().equals(name)) {
K
kohsuke 已提交
833
            return this;
834 835 836
        } else if (myView.getViewName().equals(name)) {
            return myView;
        } else
K
kohsuke 已提交
837 838 839 840
            return null;
    }

    /**
841
     * Gets the read-only list of all {@link View}s.
K
kohsuke 已提交
842
     */
843
    @Exported
844
    public synchronized View[] getViews() {
K
kohsuke 已提交
845
        if(views==null)
846
            views = new ArrayList<ListView>();
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866

        if(Functions.isAnonymous()) {
            View[] r = new View[views.size()+1];
            views.toArray(r);
            // sort Views and put "all" at the very beginning
            r[r.length-1] = r[0];
            Arrays.sort(r,1,r.length, View.SORTER);
            r[0] = this;
            return r;
        } else {
            // this is an authenticated user, so let's have the "my projects" view
            View[] r = new View[views.size()+2];
            views.toArray(r);
            r[r.length-2] = r[0];
            r[r.length-1] = r[1];
            Arrays.sort(r,2,r.length, View.SORTER);
            r[0] = myView;
            r[1] = this;
            return r;
        }
K
kohsuke 已提交
867 868
    }

869
    public synchronized void deleteView(ListView view) throws IOException {
K
kohsuke 已提交
870 871 872 873 874 875 876
        if(views!=null) {
            views.remove(view);
            save();
        }
    }

    public String getViewName() {
K
i18n  
kohsuke 已提交
877
        return Messages.Hudson_ViewName();
K
kohsuke 已提交
878 879 880 881 882 883
    }

    /**
     * Gets the read-only list of all {@link Computer}s.
     */
    public Computer[] getComputers() {
884 885 886 887 888
        Computer[] r = computers.values().toArray(new Computer[computers.size()]);
        Arrays.sort(r,new Comparator<Computer>() {
            public int compare(Computer lhs, Computer rhs) {
                if(lhs.getNode()==Hudson.this)  return -1;
                if(rhs.getNode()==Hudson.this)  return 1;
K
kohsuke 已提交
889
                return lhs.getDisplayName().compareTo(rhs.getDisplayName());
890 891 892
            }
        });
        return r;
K
kohsuke 已提交
893 894
    }

895 896 897 898
    /*package*/ Computer getComputer(Node n) {
        return computers.get(n);
    }

K
kohsuke 已提交
899
    public Computer getComputer(String name) {
K
kohsuke 已提交
900 901 902
        if(name.equals("(master)"))
            name = "";

903 904 905
        for (Computer c : computers.values()) {
            if(c.getNode().getNodeName().equals(name))
                return c;
K
kohsuke 已提交
906 907 908 909
        }
        return null;
    }

K
kohsuke 已提交
910 911 912 913 914 915 916 917
    /**
     * @deprecated
     *      UI method. Not meant to be used programatically.
     */
    public ComputerSet getComputer() {
        return new ComputerSet();
    }

918
    public Computer toComputer() {
919
        return getComputer(this);
920 921
    }

922 923 924 925 926 927
    /**
     * Gets the label that exists on this system by the name.
     *
     * @return null if no such label exists.
     */
    public Label getLabel(String name) {
K
kohsuke 已提交
928
        if(name==null)  return null;
929 930 931 932 933 934 935 936 937 938 939
        while(true) {
            Label l = labels.get(name);
            if(l!=null)
                return l;

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

    /**
940
     * Gets all the active labels in the current system.
941 942 943 944 945 946 947 948 949 950
     */
    public Set<Label> getLabels() {
        Set<Label> r = new TreeSet<Label>();
        for (Label l : labels.values()) {
            if(!l.getNodes().isEmpty())
                r.add(l);
        }
        return r;
    }

K
kohsuke 已提交
951 952 953 954 955
    public Queue getQueue() {
        return queue;
    }

    public String getDisplayName() {
K
i18n  
kohsuke 已提交
956
        return Messages.Hudson_DisplayName();
K
kohsuke 已提交
957 958 959 960 961 962 963 964 965 966 967 968
    }

    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) {
969 970 971 972 973 974
        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 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
        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.
     */
    public Slave getSlave(String name) {
        for (Slave s : getSlaves()) {
            if(s.getNodeName().equals(name))
                return s;
        }
        return null;
    }

    public List<Slave> getSlaves() {
        return Collections.unmodifiableList(slaves);
    }

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    /**
     * Updates the slave list.
     */
    public void setSlaves(List<Slave> slaves) throws IOException {
        this.slaves = new ArrayList<Slave>(slaves);
        updateComputerList();

        // label trim off
        for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
            Label l = itr.next();
            l.reset();
            if(l.getNodes().isEmpty())
                itr.remove();
        }

        save();
    }

K
kohsuke 已提交
1015 1016 1017 1018 1019 1020 1021
    /**
     * Gets the system default quiet period.
     */
    public int getQuietPeriod() {
        return quietPeriod!=null ? quietPeriod : 5;
    }

K
kohsuke 已提交
1022 1023 1024 1025 1026
    /**
     * @deprecated
     *      Why are you calling a method that always returns ""?
     *      Perhaps you meant {@link #getRootUrl()}.
     */
K
kohsuke 已提交
1027 1028 1029 1030
    public String getUrl() {
        return "";
    }

1031
    @Override
1032 1033
    public SearchIndexBuilder makeSearchIndex() {
        return super.makeSearchIndex()
1034
            .add("configure", "config","configure")
K
kohsuke 已提交
1035
            .add("manage")
K
kohsuke 已提交
1036 1037 1038 1039
            .add("log")
            .add(new CollectionSearchIndex() {// for computers
                protected Computer get(String key) { return getComputer(key); }
                protected Collection<Computer> all() { return computers.values(); }
K
kohsuke 已提交
1040
            })
K
kohsuke 已提交
1041
            .add(new CollectionSearchIndex() {// for users
K
kohsuke 已提交
1042
                protected User get(String key) { return User.get(key,false); }
K
kohsuke 已提交
1043
                protected Collection<User> all() { return User.getAll(); }
K
kohsuke 已提交
1044
            })
K
kohsuke 已提交
1045 1046 1047
            .add(new CollectionSearchIndex() {// for views
                protected View get(String key) { return getView(key); }
                protected Collection<ListView> all() { return views; }
K
kohsuke 已提交
1048
            });
1049 1050
    }

1051 1052 1053 1054
    public String getUrlChildPrefix() {
        return "job";
    }

K
kohsuke 已提交
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    /**
     * Gets the absolute URL of Hudson,
     * such as "http://localhost/hudson/".
     *
     * <p>
     * Also note that when serving user requests from HTTP, you should always use
     * {@link HttpServletRequest} to determine the full URL, instead of using this
     * (this is because one host may have multiple names, and {@link HttpServletRequest}
     * accurately represents what the current user used.)
     *
     * <p>
     * This information is rather only meant to be useful for sending out messages
     * via non-HTTP channels, like SMTP or IRC, with a link back to Hudson website.
     *
     * @return
     *      This method returns null if this parameter is not configured by the user.
     *      The caller must gracefully deal with this situation.
     *      The returned URL will always have the trailing '/'.
     * @since 1.66
K
kohsuke 已提交
1074
     * @see Descriptor#getCheckUrl(String)
K
renamed  
kohsuke 已提交
1075
     * @see #getRootUrlFromRequest()
K
kohsuke 已提交
1076 1077 1078
     */
    public String getRootUrl() {
        // for compatibility. the actual data is stored in Mailer
1079 1080 1081 1082
        String url = Mailer.DESCRIPTOR.getUrl();
        if(url!=null)   return url;

        StaplerRequest req = Stapler.getCurrentRequest();
K
kohsuke 已提交
1083
        if(req!=null)
K
renamed  
kohsuke 已提交
1084
            return getRootUrlFromRequest();
1085
        return null;
K
kohsuke 已提交
1086 1087
    }

K
kohsuke 已提交
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
    /**
     * 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 已提交
1100
    public String getRootUrlFromRequest() {
K
kohsuke 已提交
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
        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 已提交
1111 1112 1113 1114
    public File getRootDir() {
        return root;
    }

1115 1116 1117 1118
    public FilePath getWorkspaceFor(TopLevelItem item) {
        return new FilePath(new File(item.getRootDir(),"workspace"));
    }

K
kohsuke 已提交
1119 1120 1121 1122
    public FilePath getRootPath() {
        return new FilePath(getRootDir());
    }

1123 1124 1125 1126
    public FilePath createPath(String absolutePath) {
        return new FilePath((VirtualChannel)null,absolutePath);
    }

1127 1128
    public ClockDifference getClockDifference() {
        return ClockDifference.ZERO;
K
kohsuke 已提交
1129 1130
    }

1131 1132 1133 1134 1135 1136 1137 1138 1139
    /**
     * 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 已提交
1140
    /**
1141 1142
     * A convenience method to check if there's some security
     * restrictions in place.
K
kohsuke 已提交
1143
     */
K
kohsuke 已提交
1144
    public boolean isUseSecurity() {
1145
        return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
1146 1147
    }

K
kohsuke 已提交
1148
    /**
1149 1150
     * Returns the constant that captures the three basic security modes
     * in Hudson.
K
kohsuke 已提交
1151
     */
1152 1153 1154 1155 1156 1157 1158 1159 1160
    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 已提交
1161 1162
    }

K
kohsuke 已提交
1163 1164 1165 1166 1167 1168 1169 1170
    /**
     * @return
     *      never null.
     */
    public SecurityRealm getSecurityRealm() {
        return securityRealm;
    }

1171
    public void setSecurityRealm(SecurityRealm securityRealm) {
1172 1173
        if(securityRealm==null)
            securityRealm= SecurityRealm.NO_AUTHENTICATION;
1174
        this.securityRealm = securityRealm;
K
kohsuke 已提交
1175 1176 1177
        SecurityComponents sc = securityRealm.createSecurityComponents();
        HudsonFilter.AUTHENTICATION_MANAGER.setDelegate(sc.manager);
        HudsonFilter.USER_DETAILS_SERVICE_PROXY.setDelegate(sc.userDetails);
1178
    }
1179 1180 1181 1182
    
    public Lifecycle getLifecycle() {
        return Lifecycle.get();
    }
1183

1184 1185 1186 1187 1188 1189 1190
    /**
     * Returns the root {@link ACL}.
     *
     * @see AuthorizationStrategy#getRootACL()
     */
    public ACL getACL() {
        return authorizationStrategy.getRootACL();
K
kohsuke 已提交
1191 1192
    }

1193 1194 1195 1196 1197 1198
    /**
     * @return
     *      never null.
     */
    public AuthorizationStrategy getAuthorizationStrategy() {
        return authorizationStrategy;
K
kohsuke 已提交
1199 1200
    }

K
kohsuke 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    /**
     * 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;
    }

1219 1220 1221 1222 1223
    public void setNumExecutors(int n) throws IOException {
        this.numExecutors = n;
        save();
    }

K
kohsuke 已提交
1224
    /**
1225 1226 1227
     * @deprecated
     *      Left only for the compatibility of URLs.
     *      Should not be invoked for any other purpose.
K
kohsuke 已提交
1228
     */
1229 1230
    public TopLevelItem getJob(String name) {
        return getItem(name);
K
kohsuke 已提交
1231 1232
    }

1233 1234 1235 1236 1237 1238
    /**
     * @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 已提交
1239
            if(Functions.toEmailSafeString(e.getKey()).equalsIgnoreCase(Functions.toEmailSafeString(name)))
1240 1241 1242 1243 1244
                return e.getValue();
        }
        return null;
    }

K
kohsuke 已提交
1245 1246 1247 1248 1249
    /**
     * {@inheritDoc}.
     *
     * Note that the look up is case-insensitive.
     */
1250
    @Override
K
kohsuke 已提交
1251
    public TopLevelItem getItem(String name) {
1252 1253 1254
        return items.get(name);
    }

1255
    public File getRootDirFor(TopLevelItem child) {
1256 1257 1258 1259 1260
        return getRootDirFor(child.getName());
    }

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

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    /**
     * Gets the {@link Item} object by its full name.
     * Full names are like path names, where each name of {@link Item} is
     * combined by '/'.
     *
     * @return
     *      null if either such {@link Item} doesn't exist under the given full name,
     *      or it exists but it's no an instance of the given type.
     */
    public <T extends Item> T getItemByFullName(String fullName, Class<T> type) {
        StringTokenizer tokens = new StringTokenizer(fullName,"/");
        ItemGroup parent = this;

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

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

            parent = (ItemGroup) item;
        }
    }

K
kohsuke 已提交
1292 1293 1294 1295
    public Item getItemByFullName(String fullName) {
        return getItemByFullName(fullName,Item.class);
    }

K
kohsuke 已提交
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    /**
     * 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.
     */
1312
    public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
K
kohsuke 已提交
1313
        if(items.containsKey(name))
K
kohsuke 已提交
1314 1315
            throw new IllegalArgumentException();

K
kohsuke 已提交
1316
        TopLevelItem item;
K
kohsuke 已提交
1317
        try {
K
kohsuke 已提交
1318
            item = type.newInstance(name);
K
kohsuke 已提交
1319 1320 1321 1322
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }

K
kohsuke 已提交
1323 1324 1325
        item.save();
        items.put(name,item);
        return item;
K
kohsuke 已提交
1326 1327 1328 1329 1330
    }

    /**
     * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
     */
1331
    /*package*/ void deleteJob(TopLevelItem item) throws IOException {
K
kohsuke 已提交
1332
        for (ItemListener l : itemListeners)
1333
            l.onDeleted(item);
1334

1335
        items.remove(item.getName());
K
kohsuke 已提交
1336
        if(views!=null) {
1337
            for (ListView v : views) {
K
kohsuke 已提交
1338
                synchronized(v) {
1339
                    v.jobNames.remove(item.getName());
K
kohsuke 已提交
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
                }
            }
            save();
        }
    }

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

        if(views!=null) {
1355
            for (ListView v : views) {
K
kohsuke 已提交
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
                synchronized(v) {
                    if(v.jobNames.remove(oldName))
                        v.jobNames.add(newName);
                }
            }
            save();
        }
    }

    public FingerprintMap getFingerprintMap() {
        return fingerprintMap;
    }

K
kohsuke 已提交
1369
    // if no finger print matches, display "not found page".
K
kohsuke 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
    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() {
1396
        return mode;
K
kohsuke 已提交
1397 1398
    }

1399
    public Set<Label> getAssignedLabels() {
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
        if (labelSet == null) {
            Set<Label> r = new HashSet<Label>();
            r.addAll(getDynamicLabels());
            r.add(getSelfLabel());
            this.labelSet = Collections.unmodifiableSet(r);
        }
        return labelSet;
    }

    /**
     * Returns the possibly empty set of labels that it has been determined as supported by this node.
     *
     * @see hudson.tasks.LabelFinder
     */
    public Set<Label> getDynamicLabels() {
        if (dynamicLabels == null) {
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
            // in the worst cast, two threads end up doing the same computation twice,
            // but that won't break the semantics.
            // OTOH, not locking prevents dead-lock. See #1390
            Set<Label> r = new HashSet<Label>();
            Computer comp = getComputer("");
            if (comp != null) {
                VirtualChannel channel = comp.getChannel();
                if (channel != null) {
                    for (DynamicLabeler labeler : LabelFinder.LABELERS) {
                        for (String label : labeler.findLabels(channel)) {
                            r.add(getLabel(label));
1427 1428 1429 1430
                        }
                    }
                }
            }
1431
            dynamicLabels = r;
1432 1433
        }
        return dynamicLabels;
1434 1435 1436 1437 1438 1439
    }

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

K
kohsuke 已提交
1440 1441 1442 1443
    public Computer createComputer() {
        return new MasterComputer();
    }

K
kohsuke 已提交
1444
    private synchronized void load() throws IOException {
1445
        long startTime = System.currentTimeMillis();
K
kohsuke 已提交
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
        XmlFile cfg = getConfigFile();
        if(cfg.exists())
            cfg.unmarshal(this);

        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) {
1458
                return child.isDirectory() && Items.getConfigFile(child).exists();
K
kohsuke 已提交
1459 1460
            }
        });
1461
        items.clear();
1462
        if(PARALLEL_LOAD) {
1463
            // load jobs in parallel for better performance
1464
            LOGGER.info("Loading in "+TWICE_CPU_NUM+" parallel threads");
1465 1466 1467 1468
            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 {
1469 1470
                        long start = System.currentTimeMillis();
                        TopLevelItem item = (TopLevelItem) Items.load(Hudson.this, subdir);
1471 1472
                        if(LOG_STARTUP_PERFORMANCE)
                            LOGGER.info("Loaded "+item.getName()+" in "+(System.currentTimeMillis()-start)+"ms by "+Thread.currentThread().getName());
1473
                        return item;
1474 1475 1476 1477 1478 1479 1480 1481 1482
                    }
                }));
            }

            for (Future<TopLevelItem> loader : loaders) {
                try {
                    TopLevelItem item = loader.get();
                    items.put(item.getName(), item);
                } catch (ExecutionException e) {
K
typo  
kohsuke 已提交
1483
                    LOGGER.log(Level.WARNING, "Failed to load a project",e.getCause());
1484 1485 1486 1487 1488 1489 1490
                } catch (InterruptedException e) {
                    e.printStackTrace(); // this is probably not the right thing to do
                }
            }
        } else {
            for (File subdir : subdirs) {
                try {
1491
                    long start = System.currentTimeMillis();
1492
                    TopLevelItem item = (TopLevelItem)Items.load(this,subdir);
1493 1494
                    if(LOG_STARTUP_PERFORMANCE)
                        LOGGER.info("Loaded "+item.getName()+" in "+(System.currentTimeMillis()-start)+"ms");
1495 1496 1497
                    items.put(item.getName(), item);
                } catch (Error e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
1498 1499
                } catch (RuntimeException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
1500 1501 1502
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
                }
K
kohsuke 已提交
1503 1504
            }
        }
1505
        rebuildDependencyGraph();
1506 1507

        // recompute label objects
1508 1509 1510 1511
        if (null != slaves) { // only if we have slaves
            for (Slave slave : slaves)
                slave.getAssignedLabels();
        }
K
kohsuke 已提交
1512

K
typo.  
kohsuke 已提交
1513
        // read in old data that doesn't have the security field set
1514 1515 1516 1517 1518 1519 1520 1521
        if(authorizationStrategy==null) {
            if(useSecurity==null || !useSecurity)
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
            else
                authorizationStrategy = new LegacyAuthorizationStrategy();
        }
        if(securityRealm==null) {
            if(useSecurity==null || !useSecurity)
1522
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
1523
            else
1524 1525 1526 1527
                setSecurityRealm(new LegacySecurityRealm());
        } else {
            // force the set to proxy
            setSecurityRealm(securityRealm);
1528
        }
1529

K
kohsuke 已提交
1530 1531 1532 1533
        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;
1534
            setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
K
kohsuke 已提交
1535
        }
1536

K
kohsuke 已提交
1537

1538
        LOGGER.info(String.format("Took %s ms to load",System.currentTimeMillis()-startTime));
1539 1540
        if(KILL_AFTER_LOAD)
            System.exit(0);
K
kohsuke 已提交
1541 1542 1543 1544 1545 1546
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
1547
        if(BulkChange.contains(this))   return;
K
kohsuke 已提交
1548 1549 1550 1551 1552 1553 1554 1555 1556
        getConfigFile().write(this);
    }


    /**
     * Called to shut down the system.
     */
    public void cleanUp() {
        terminating = true;
1557 1558 1559
        for( Computer c : computers.values() ) {
            c.interrupt();
            c.kill();
1560
            c.disconnect();
K
kohsuke 已提交
1561 1562 1563
        }
        ExternalJob.reloadThread.interrupt();
        Trigger.timer.cancel();
K
kohsuke 已提交
1564
        Trigger.timer = null;
1565 1566
        if(tcpSlaveAgentListener!=null)
            tcpSlaveAgentListener.shutdown();
K
kohsuke 已提交
1567 1568 1569 1570

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

1571 1572 1573 1574
        if(getRootDir().exists())
            // if we are aborting because we failed to create HUDSON_HOME,
            // don't try to save. Issue #536
            getQueue().save();
1575 1576

        threadPoolForLoad.shutdown();
K
kohsuke 已提交
1577 1578
        
        LogFactory.releaseAll();
1579 1580

        theInstance = null;
K
kohsuke 已提交
1581 1582
    }

K
kohsuke 已提交
1583 1584 1585 1586
    public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
        for (Action a : getActions())
            if(a.getUrlName().equals(token))
                return a;
1587 1588 1589
        for (Action a : getManagementLinks())
            if(a.getUrlName().equals(token))
                return a;
K
kohsuke 已提交
1590 1591
        return null;
    }
K
kohsuke 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603


//
//
// actions
//
//
    /**
     * Accepts submission from the configuration page.
     */
    public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        try {
K
kohsuke 已提交
1604
            checkPermission(ADMINISTER);
K
kohsuke 已提交
1605 1606 1607

            req.setCharacterEncoding("UTF-8");

1608
            JSONObject json = req.getSubmittedForm();
1609

1610 1611 1612
            // keep using 'useSecurity' field as the main configuration setting
            // until we get the new security implementation working
            // useSecurity = null;
1613
            if (json.has("use_security")) {
K
kohsuke 已提交
1614
                useSecurity = true;
K
kohsuke 已提交
1615 1616 1617
                JSONObject security = json.getJSONObject("use_security");
                setSecurityRealm(SecurityRealm.LIST.newInstanceFromRadioList(security,"realm"));
                authorizationStrategy = AuthorizationStrategy.LIST.newInstanceFromRadioList(security,"authorization");
1618 1619
                if(authorizationStrategy==null)
                    authorizationStrategy = AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
1620
            } else {
1621
                useSecurity = null;
1622
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
1623
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
1624
            }
K
kohsuke 已提交
1625

1626 1627
            noUsageStatistics = json.has("usageStatisticsCollected") ? null : true;

1628 1629
            {
                String v = req.getParameter("slaveAgentPortType");
1630
                if(!isUseSecurity() || v==null || v.equals("random"))
1631 1632 1633 1634 1635 1636 1637 1638
                    slaveAgentPort = 0;
                else
                if(v.equals("disable"))
                    slaveAgentPort = -1;
                else {
                    try {
                        slaveAgentPort = Integer.parseInt(req.getParameter("slaveAgentPort"));
                    } catch (NumberFormatException e) {
K
i18n  
kohsuke 已提交
1639
                        throw new FormException(Messages.Hudson_BadPortNumber(req.getParameter("slaveAgentPort")),"slaveAgentPort");
1640 1641
                    }
                }
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654

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

K
kohsuke 已提交
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));

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

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

            boolean result = true;

            for( Descriptor<Builder> d : BuildStep.BUILDERS )
1676
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
1677 1678

            for( Descriptor<Publisher> d : BuildStep.PUBLISHERS )
1679
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
1680

K
kohsuke 已提交
1681
            for( Descriptor<BuildWrapper> d : BuildWrappers.WRAPPERS )
K
kohsuke 已提交
1682
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
1683

1684
            for( SCMDescriptor scmd : SCMS.SCMS )
K
kohsuke 已提交
1685
                result &= configureDescriptor(req,json,scmd);
K
kohsuke 已提交
1686

1687
            for( TriggerDescriptor d : Triggers.TRIGGERS )
K
kohsuke 已提交
1688
                result &= configureDescriptor(req,json,d);
K
kohsuke 已提交
1689

1690
            for( JobPropertyDescriptor d : Jobs.PROPERTIES )
K
kohsuke 已提交
1691
                result &= configureDescriptor(req,json,d);
1692

1693 1694 1695
            for( PageDecorator d : PageDecorator.ALL )
                result &= configureDescriptor(req,json,d);

1696 1697 1698
            for( JSONObject o : StructuredForm.toList(json,"plugin"))
                pluginManager.getPlugin(o.getString("name")).getPlugin().configure(o);

K
kohsuke 已提交
1699 1700
            save();
            if(result)
1701
                rsp.sendRedirect(req.getContextPath()+'/');  // go to the top page
K
kohsuke 已提交
1702 1703 1704 1705 1706 1707 1708
            else
                rsp.sendRedirect("configure"); // back to config
        } catch (FormException e) {
            sendError(e,req,rsp);
        }
    }

1709 1710 1711 1712 1713
    public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        JSONObject form = req.getSubmittedForm();
        rsp.sendRedirect("foo");
    }

1714
    private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
1715 1716 1717
        // 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.
1718 1719 1720 1721
        json.putAll(js);
        return d.configure(req, js);
    }

1722 1723 1724 1725
    /**
     * Accepts submission from the configuration page.
     */
    public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1726
        checkPermission(ADMINISTER);
1727

1728 1729 1730
        BulkChange bc = new BulkChange(this);
        try {
            JSONObject json = req.getSubmittedForm();
1731

1732
            setNumExecutors(Integer.parseInt(req.getParameter("numExecutors")));
1733 1734 1735 1736
            if(req.hasParameter("master.mode"))
                mode = Mode.valueOf(req.getParameter("master.mode"));
            else
                mode = Mode.NORMAL;
S
stephenconnolly 已提交
1737

1738 1739 1740 1741
            setSlaves(req.bindJSONToList(Slave.class,json.get("slaves")));
        } finally {
            bc.commit();
        }
S
stephenconnolly 已提交
1742

1743
        rsp.sendRedirect(req.getContextPath()+'/');  // go to the top page
1744 1745
    }

K
kohsuke 已提交
1746 1747 1748 1749
    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1750
        checkPermission(ADMINISTER);
K
kohsuke 已提交
1751 1752 1753 1754 1755 1756 1757

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

1758
    public synchronized void doQuietDown(StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
1759
        checkPermission(ADMINISTER);
K
kohsuke 已提交
1760 1761 1762 1763
        isQuietingDown = true;
        rsp.sendRedirect2(".");
    }

1764
    public synchronized void doCancelQuietDown(StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
1765
        checkPermission(ADMINISTER);
K
kohsuke 已提交
1766 1767 1768 1769 1770
        isQuietingDown = false;
        getQueue().scheduleMaintenance();
        rsp.sendRedirect2(".");
    }

1771 1772 1773
    /**
     * Backward compatibility. Redirect to the thread dump.
     */
1774
    public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
1775 1776 1777
        rsp.sendRedirect2("threadDump");
    }

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

1781 1782
        TopLevelItem result;

K
kohsuke 已提交
1783 1784 1785 1786 1787 1788
        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");
1789 1790 1791 1792 1793 1794 1795
        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");
        }
1796 1797

        String name = req.getParameter("name");
K
typo.  
kohsuke 已提交
1798
        if(name==null) {
1799 1800 1801 1802
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Query parameter 'name' is required");
            return null;
        }
        name = name.trim();
K
kohsuke 已提交
1803 1804 1805 1806 1807
        String mode = req.getParameter("mode");

        try {
            checkGoodName(name);
        } catch (ParseException e) {
K
kohsuke 已提交
1808
            rsp.setStatus(SC_BAD_REQUEST);
K
kohsuke 已提交
1809 1810 1811 1812
            sendError(e,req,rsp);
            return null;
        }

1813
        if(getItem(name)!=null) {
K
kohsuke 已提交
1814
            rsp.setStatus(SC_BAD_REQUEST);
K
i18n  
kohsuke 已提交
1815
            sendError(Messages.Hudson_JobAlreadyExists(name),req,rsp);
K
kohsuke 已提交
1816 1817 1818
            return null;
        }

1819
        if(mode!=null && mode.equals("copyJob")) {
1820 1821
            String from = req.getParameter("from");
            TopLevelItem src = getItem(from);
K
kohsuke 已提交
1822
            if(src==null) {
1823 1824 1825 1826 1827
                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 已提交
1828 1829 1830
                return null;
            }

1831
            result = createProject(src.getDescriptor(),name);
K
kohsuke 已提交
1832 1833

            // copy config
1834
            Util.copyFile(Items.getConfigFile(src).getFile(),Items.getConfigFile(result).getFile());
K
kohsuke 已提交
1835 1836

            // reload from the new config
1837
            result = (TopLevelItem)Items.load(this,result.getRootDir());
1838 1839
            result.onCopiedFrom(src);
            items.put(name,result);
1840
        } else {
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
            if(isXmlSubmission) {
                // config.xml submission

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

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

K
kohsuke 已提交
1873
        for (ItemListener l : itemListeners)
1874
            l.onCreated(result);
1875

1876 1877 1878 1879 1880
        if(isXmlSubmission) {
            // it worked
            rsp.setStatus(HttpServletResponse.SC_OK);
        } else {
            // send the browser to the config page
1881
            rsp.sendRedirect2(result.getUrl()+"configure");
1882 1883
        }

K
kohsuke 已提交
1884 1885 1886 1887
        return result;
    }

    public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1888
        checkPermission(View.CREATE);
K
kohsuke 已提交
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900

        req.setCharacterEncoding("UTF-8");

        String name = req.getParameter("name");

        try {
            checkGoodName(name);
        } catch (ParseException e) {
            sendError(e, req, rsp);
            return;
        }

1901
        ListView v = new ListView(this, name);
K
kohsuke 已提交
1902
        if(views==null)
1903
            views = new Vector<ListView>();
K
kohsuke 已提交
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
        views.add(v);
        save();

        // redirect to the config screen
        rsp.sendRedirect2("./"+v.getUrl()+"configure");
    }

    /**
     * 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 已提交
1920
            throw new ParseException(Messages.Hudson_NoName(),0);
K
kohsuke 已提交
1921 1922 1923

        for( int i=0; i<name.length(); i++ ) {
            char ch = name.charAt(i);
1924 1925 1926
            if(Character.isISOControl(ch)) {
                throw new ParseException(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)),i);
            }
K
kohsuke 已提交
1927
            if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
K
i18n  
kohsuke 已提交
1928
                throw new ParseException(Messages.Hudson_UnsafeChar(ch),i);
K
kohsuke 已提交
1929 1930 1931 1932 1933
        }

        // looks good
    }

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
    private static String toPrintableName(String name) {
        StringBuffer printableName = new StringBuffer();
        for( int i=0; i<name.length(); i++ ) {
            char ch = name.charAt(i);
            if(Character.isISOControl(ch))
                printableName.append("\\u").append((int)ch).append(';');
            else
                printableName.append(ch);
        }
        return printableName.toString();
    }

1946
    /**
1947 1948 1949
     * Checks if the user was successfully authenticated.
     *
     * @see BasicAuthenticationFilter
1950 1951
     */
    public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1952 1953
        if(req.getUserPrincipal()==null) {
            // authentication must have failed
1954 1955 1956 1957
            rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

1958
        // the user is now authenticated, so send him back to the target
1959 1960 1961
        String path = req.getContextPath()+req.getRestOfPath();
        String q = req.getQueryString();
        if(q!=null)
1962
            path += '?'+q;
1963

1964
        rsp.sendRedirect2(path);
1965 1966
    }

K
kohsuke 已提交
1967 1968 1969
    /**
     * Called once the user logs in. Just forward to the top page.
     */
K
kohsuke 已提交
1970
    public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
1971 1972
        if(req.getUserPrincipal()==null)
            rsp.sendRedirect2("noPrincipal");
1973 1974

        String from = req.getParameter("from");
1975
        if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
1976
            rsp.sendRedirect2(from);    // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
            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 已提交
1989 1990 1991 1992 1993
    }

    /**
     * Called once the user logs in. Just forward to the top page.
     */
K
kohsuke 已提交
1994
    public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
1995 1996 1997
        HttpSession session = req.getSession(false);
        if(session!=null)
            session.invalidate();
1998
        SecurityContextHolder.clearContext();
1999 2000 2001 2002 2003 2004

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

K
kohsuke 已提交
2005 2006 2007
        rsp.sendRedirect2(req.getContextPath()+"/");
    }

2008 2009 2010 2011 2012 2013 2014
    /**
     * Serves jar files for JNLP slave agents.
     */
    public Slave.JnlpJar getJnlpJars(String fileName) {
        return new Slave.JnlpJar(fileName);
    }

K
kohsuke 已提交
2015 2016
    /**
     * RSS feed for log entries.
2017 2018 2019
     *
     * @deprecated
     *   As on 1.267, moved to "/log/rss..."
K
kohsuke 已提交
2020 2021
     */
    public void doLogRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2022 2023
        String qs = req.getQueryString();
        rsp.sendRedirect2("./log/rss"+(qs==null?"":'?'+qs));
K
kohsuke 已提交
2024 2025
    }

K
kohsuke 已提交
2026 2027 2028 2029
    /**
     * Reloads the configuration.
     */
    public synchronized void doReload( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
2030
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2031

2032 2033 2034 2035
        // engage "loading ..." UI and then run the actual task in a separate thread
        final ServletContext context = req.getServletContext();
        context.setAttribute("app",new HudsonIsLoading());

K
kohsuke 已提交
2036
        rsp.sendRedirect2(req.getContextPath()+"/");
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048

        new Thread("Hudson config reload thread") {
            public void run() {
                try {
                    load();
                    User.reload();
                    context.setAttribute("app",Hudson.this);
                } catch (IOException e) {
                    LOGGER.log(Level.SEVERE,"Failed to reload Hudson config",e);
                }
            }
        }.start();
K
kohsuke 已提交
2049 2050 2051 2052 2053 2054
    }

    /**
     * Do a finger-print check.
     */
    public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2055 2056
        // Parse the request
        MultipartFormDataParser p = new MultipartFormDataParser(req);
K
kohsuke 已提交
2057 2058
        try {
            rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
2059 2060 2061
                Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
        } finally {
            p.cleanUp();
K
kohsuke 已提交
2062 2063 2064 2065 2066 2067 2068
        }
    }

    /**
     * Serves static resources without the "Last-Modified" header to work around
     * a bug in Firefox.
     *
K
kohsuke 已提交
2069 2070
     * <p>
     * See https://bugzilla.mozilla.org/show_bug.cgi?id=89419
K
kohsuke 已提交
2071 2072 2073 2074 2075 2076 2077 2078 2079
     */
    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 已提交
2080
            rsp.sendError(SC_BAD_REQUEST);
K
kohsuke 已提交
2081 2082 2083 2084 2085
            return;
        }

        File f = new File(req.getServletContext().getRealPath("/images"),path.substring(1));
        if(!f.exists()) {
2086
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
            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 已提交
2101
        Util.copyStream(in,rsp.getOutputStream());
K
kohsuke 已提交
2102 2103 2104 2105
        in.close();
    }

    /**
K
kohsuke 已提交
2106
     * For debugging. Expose URL to perform GC.
K
kohsuke 已提交
2107
     */
2108
    public void doGc(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2109 2110 2111 2112 2113 2114
        System.gc();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("GCed");
    }

K
kohsuke 已提交
2115 2116 2117 2118
    /**
     * Perform a restart of Hudson, if we can.
     */
    public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
2119
        requirePOST();
K
kohsuke 已提交
2120 2121 2122 2123 2124 2125 2126
        checkPermission(ADMINISTER);
        try {
            Lifecycle.get().restart();
            servletContext.setAttribute("app",new HudsonIsRestarting());
            rsp.sendRedirect2(".");
        } catch (UnsupportedOperationException e) {
            sendError("Restart is not supported in this running mode.",req,rsp);
2127 2128 2129 2130
        } catch (IOException e) {
            sendError(e,req,rsp);
        } catch (InterruptedException e) {
            sendError(e,req,rsp);
K
kohsuke 已提交
2131 2132 2133
        }
    }

K
kohsuke 已提交
2134 2135 2136 2137 2138
    /**
     * Shutdown the system.
     * @since 1.161
     */
    public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
2139
        checkPermission(ADMINISTER);
2140
        LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
K
kohsuke 已提交
2141
                getAuthentication(), req.getRemoteAddr()));
K
kohsuke 已提交
2142 2143 2144 2145 2146
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        PrintWriter w = rsp.getWriter();
        w.println("Shutting down");
        w.close();
2147

K
kohsuke 已提交
2148 2149 2150
        System.exit(0);
    }

K
kohsuke 已提交
2151 2152 2153 2154 2155
    /**
     * Gets the {@link Authentication} object that represents the user
     * associated with the current request.
     */
    public static Authentication getAuthentication() {
K
kohsuke 已提交
2156 2157 2158 2159 2160
        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 已提交
2161 2162
        if(a==null)
            a = new AnonymousAuthenticationToken("anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
K
kohsuke 已提交
2163
        return a;
K
kohsuke 已提交
2164 2165
    }

2166 2167 2168
    /**
     * Configure the logging level.
     */
2169
    public void doConfigLogger(StaplerResponse rsp, @QueryParameter String name, @QueryParameter String level) throws IOException {
K
kohsuke 已提交
2170
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2171 2172 2173 2174 2175 2176
        Level lv;
        if(level.equals("inherit"))
            lv = null;
        else
            lv = Level.parse(level.toUpperCase());
        Logger.getLogger(name).setLevel(lv);
2177 2178 2179
        rsp.sendRedirect2("log");
    }

K
kohsuke 已提交
2180 2181
    /**
     * For system diagnostics.
K
kohsuke 已提交
2182
     * Run arbitrary Groovy script.
K
kohsuke 已提交
2183
     */
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
    public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        doScript(req, rsp, req.getView(this, "_script.jelly"));
    }
    
    /**
     * 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 {
2196 2197
        // ability to run arbitrary script is dangerous
        checkPermission(ADMINISTER);
K
kohsuke 已提交
2198 2199

        String text = req.getParameter("script");
2200
        if (text != null) {
K
kohsuke 已提交
2201
            try {
2202
                req.setAttribute("output",
2203
                        RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel));
2204 2205
            } catch (InterruptedException e) {
                throw new ServletException(e);
K
kohsuke 已提交
2206 2207 2208
            }
        }

2209
        view.forward(req, rsp);
K
kohsuke 已提交
2210 2211
    }

K
kohsuke 已提交
2212 2213 2214 2215 2216 2217 2218
    /**
     * 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 已提交
2219 2220 2221
    /**
     * Changes the icon size by changing the cookie
     */
K
kohsuke 已提交
2222 2223
    public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        String qs = req.getQueryString();
J
jglick 已提交
2224
        if(qs==null || !ICON_SIZE.matcher(qs).matches())
K
kohsuke 已提交
2225
            throw new ServletException();
2226 2227 2228
        Cookie cookie = new Cookie("iconSize", qs);
        cookie.setMaxAge(/* ~4 mo. */9999999); // #762
        rsp.addCookie(cookie);
K
kohsuke 已提交
2229 2230 2231
        String ref = req.getHeader("Referer");
        if(ref==null)   ref=".";
        rsp.sendRedirect2(ref);
K
kohsuke 已提交
2232 2233
    }

2234
    public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2235 2236 2237 2238 2239 2240
        FingerprintCleanupThread.invoke();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("Invoked");
    }

2241
    public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
        WorkspaceCleanupThread.invoke();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("Invoked");
    }

    /**
     * Checks if the path is a valid path.
     */
    public void doCheckLocalFSRoot( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        // this can be used to check the existence of a file on the server, so needs to be protected
K
i18n  
kohsuke 已提交
2253
        new FormFieldValidator.WorkspaceDirectory(req,rsp,true).process();
K
kohsuke 已提交
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
    }

    /**
     * Checks if the JAVA_HOME is a valid JAVA_HOME path.
     */
    public void doJavaHomeCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        // this can be used to check the existence of a file on the server, so needs to be protected
        new FormFieldValidator(req,rsp,true) {
            public void check() throws IOException, ServletException {
                File f = getFileParameter("value");
                if(!f.isDirectory()) {
K
i18n  
kohsuke 已提交
2265
                    error(Messages.Hudson_NotADirectory(f));
K
kohsuke 已提交
2266 2267 2268 2269
                    return;
                }

                File toolsJar = new File(f,"lib/tools.jar");
2270
                File mac = new File(f,"lib/dt.jar");
K
kohsuke 已提交
2271
                if(!toolsJar.exists() && !mac.exists()) {
K
i18n  
kohsuke 已提交
2272
                    error(Messages.Hudson_NotJDKDir(f));
K
kohsuke 已提交
2273 2274 2275 2276 2277 2278 2279 2280
                    return;
                }

                ok();
            }
        }.process();
    }

K
kohsuke 已提交
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
    /**
     * If the user chose the default JDK, make sure we got 'java' in PATH.
     */
    public void doDefaultJDKCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        new FormFieldValidator(req,rsp,true) {
            public void check() throws IOException, ServletException {
                String v = request.getParameter("value");
                if(!v.equals("(Default)"))
                    // assume the user configured named ones properly in system config ---
                    // or else system config should have reported form field validation errors.
                    ok();
                else {
                    // default JDK selected. Does such java really exist?
                    if(JDK.isDefaultJDKValid(Hudson.this))
                        ok();
                    else
K
i18n  
kohsuke 已提交
2297
                        errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
K
kohsuke 已提交
2298 2299 2300 2301 2302
                }
            }
        }.process();
    }

K
kohsuke 已提交
2303 2304 2305 2306 2307 2308
    /**
     * Checks if the top-level item with the given name exists.
     */
    public void doItemExistsCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        // this method can be used to check if a file exists anywhere in the file system,
        // so it should be protected.
2309
        new FormFieldValidator(req,rsp,Item.CREATE) {
K
kohsuke 已提交
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
            protected void check() throws IOException, ServletException {
                String job = fixEmpty(request.getParameter("value"));
                if(job==null) {
                    ok(); // nothing is entered yet
                    return;
                }

                if(getItem(job)==null)
                    ok();
                else
K
i18n  
kohsuke 已提交
2320
                    error(Messages.Hudson_JobAlreadyExists(job));
K
kohsuke 已提交
2321 2322 2323
            }
        }.process();
    }
2324 2325 2326 2327 2328
    /**
     * Checks if the value for a field is set; if not an error or warning text is displayed.
     * If the parameter "value" is not set then the parameter "errorText" is displayed
     * as an error text. If the parameter "errorText" is not set, then the parameter "warningText" is
     * displayed as a warning text.
2329
     * <p/>
2330 2331 2332 2333 2334 2335 2336 2337 2338
     * 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".
     * @param req containing the parameter value and the errorText to display if the value isnt set
     * @param rsp used by FormFieldValidator
     * @throws IOException thrown by FormFieldValidator.check()
     * @throws ServletException thrown by FormFieldValidator.check()
     */
    public void doFieldCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        new FormFieldValidator(req, rsp, false) {
2339

2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
            /**
             * Display the error text or warning text.
             */
            private void fieldCheckFailed() throws IOException, ServletException {
                String v = fixEmpty(request.getParameter("errorText"));
                if (v != null) {
                    error(v);
                    return;
                }
                v = fixEmpty(request.getParameter("warningText"));
                if (v != null) {
                    warning(v);
                    return;
                }
                error("No error or warning text was set for fieldCheck().");
2355
                return;
2356
            }
2357

2358 2359 2360 2361 2362 2363 2364 2365 2366
            /**
             * Checks if the value is of the correct type.
             * @param type the type of string
             * @param value the actual value to check
             * @return true, if the type was valid; false otherwise
             */
            private boolean checkType(String type, String value) throws IOException, ServletException {
                try {
                    if (type.equalsIgnoreCase("number")) {
2367
                        NumberFormat.getInstance().parse(value);
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
                    } else if (type.equalsIgnoreCase("number-positive")) {
                        if (NumberFormat.getInstance().parse(value).floatValue() <= 0) {
                            error(Messages.Hudson_NotAPositiveNumber());
                            return false;
                        }
                    } else if (type.equalsIgnoreCase("number-negative")) {
                        if (NumberFormat.getInstance().parse(value).floatValue() >= 0) {
                            error(Messages.Hudson_NotANegativeNumber());
                            return false;
                        }
                    }
                } catch (ParseException e) {
                    error(Messages.Hudson_NotANumber());
                    return false;
                }
                return true;
            }
2385

2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
            @Override
            protected void check() throws IOException, ServletException {
                String value = fixEmpty(request.getParameter("value"));
                if (value == null) {
                    fieldCheckFailed();
                    return;
                }
                String type = fixEmpty(request.getParameter("type"));
                if (type != null) {
                    if (!checkType(type, value)) {
                        return;
                    }
                }
                ok();
            }
        }.process();
    }
K
kohsuke 已提交
2403

K
kohsuke 已提交
2404 2405 2406 2407 2408
    /**
     * Performs syntactical check on the remote FS for slaves.
     *
     * TODO: find a better home for this method.
     */
2409
    public void doRemoteFSCheck(StaplerRequest req, StaplerResponse rsp, @QueryParameter final String value) throws IOException, ServletException {
K
kohsuke 已提交
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427
        new FormFieldValidator(req,rsp,false) {
            protected void check() throws IOException, ServletException {
                if(Util.fixEmptyAndTrim(value)==null) {
                    error("Remote directory is mandatory");
                    return;
                }

                if(value.startsWith("\\\\") || value.startsWith("/net/")) {
                    warning("Are you sure you want to use network mounted file system for FS root? " +
                            "Note that this directory needs not be visible to the master.");
                    return;
                }

                ok();
            }
        }.process();
    }

2428 2429 2430 2431 2432 2433 2434 2435
    /**
     * 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.
     */
2436
    public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
2437
        String path = req.getRestOfPath();
2438 2439 2440 2441 2442 2443
        // 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);

2444 2445 2446
        int idx = path.lastIndexOf('.');
        String extension = path.substring(idx+1);
        if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
2447 2448 2449 2450
            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);
2451 2452 2453 2454 2455 2456
                return;
            }
        }
        rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

S
sogabe 已提交
2457 2458 2459 2460 2461 2462 2463 2464
    /**
     * 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("\\|")
    ));

2465 2466 2467
    /**
     * Checks if container uses UTF-8 to decode URLs. See
     * http://hudson.gotdns.com/wiki/display/HUDSON/Tomcat#Tomcat-i18n
S
sogabe 已提交
2468
     *
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489
     * @param req containing the parameter value
     * @param rsp used by FormFieldValidator
     * @throws IOException thrown by FormFieldValidator.check()
     * @throws ServletException thrown by FormFieldValidator.check()
     */
    public void doCheckURIEncoding(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        new FormFieldValidator(req, rsp, true) {
            @Override
            protected void check() throws IOException, ServletException {
                request.setCharacterEncoding("UTF-8");
                // expected is non-ASCII String
                final String expected = "\u57f7\u4e8b";
                final String value = fixEmpty(request.getParameter("value"));
                if (!expected.equals(value)) {
                    warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
                    return;
                }
                ok();
            }
        }.process();
    }
S
sogabe 已提交
2490

2491 2492 2493 2494 2495 2496
    /**
     * 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 已提交
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511

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

    /**
     * Returns all {@code CVSROOT} strings used in the current Hudson installation.
     *
     * <p>
     * Ideally this shouldn't be defined in here
     * but EL doesn't provide a convenient way of invoking a static function,
     * so I'm putting it here for now.
     */
    public Set<String> getAllCvsRoots() {
        Set<String> r = new TreeSet<String>();
K
kohsuke 已提交
2512
        for( AbstractProject p : getAllItems(AbstractProject.class) ) {
K
kohsuke 已提交
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
            SCM scm = p.getScm();
            if (scm instanceof CVSSCM) {
                CVSSCM cvsscm = (CVSSCM) scm;
                r.add(cvsscm.getCvsRoot());
            }
        }

        return r;
    }

2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
    /**
     * Rebuilds the dependency map.
     */
    public void rebuildDependencyGraph() {
        dependencyGraph = new DependencyGraph();
    }

    public DependencyGraph getDependencyGraph() {
        return dependencyGraph;
    }

2534 2535 2536 2537 2538
    // for Jelly
    public List<ManagementLink> getManagementLinks() {
        return ManagementLink.LIST;
    }

K
kohsuke 已提交
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
    /**
     * 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 已提交
2550
    public Object getTarget() {
K
kohsuke 已提交
2551 2552 2553 2554 2555 2556 2557
        try {
            checkPermission(READ);
        } catch (AccessDeniedException e) {
            String rest = Stapler.getCurrentRequest().getRestOfPath();
            if(rest.startsWith("/login")
            || rest.startsWith("/logout")
            || rest.startsWith("/accessDenied")
2558
            || rest.startsWith("/signup")
2559
            || rest.startsWith("/jnlpJars/")
K
kohsuke 已提交
2560 2561 2562 2563
            || rest.startsWith("/securityRealm"))
                return this;    // URLs that are always visible without READ permission
            throw e;
        }
K
kohsuke 已提交
2564 2565 2566
        return this;
    }

K
kohsuke 已提交
2567 2568 2569 2570 2571
    public static final class MasterComputer extends Computer {
        private MasterComputer() {
            super(Hudson.getInstance());
        }

2572 2573 2574 2575 2576 2577 2578
        /**
         * Returns "" to match with {@link Hudson#getNodeName()}.
         */
        public String getName() {
            return "";
        }

K
kohsuke 已提交
2579 2580
        @Override
        public String getDisplayName() {
K
i18n  
kohsuke 已提交
2581
            return Messages.Hudson_Computer_DisplayName();
K
kohsuke 已提交
2582 2583 2584 2585
        }

        @Override
        public String getCaption() {
K
i18n  
kohsuke 已提交
2586
            return Messages.Hudson_Computer_Caption();
K
kohsuke 已提交
2587 2588
        }

K
kohsuke 已提交
2589 2590 2591 2592
        public String getUrl() {
            return "computer/(master)/";
        }

2593
        public RetentionStrategy getRetentionStrategy() {
K
kohsuke 已提交
2594
            return RetentionStrategy.NOOP;
2595 2596
        }

K
kohsuke 已提交
2597 2598 2599 2600 2601
        @Override
        public VirtualChannel getChannel() {
            return localChannel;
        }

2602 2603 2604 2605 2606
        @Override
        public Charset getDefaultCharset() {
            return Charset.defaultCharset();
        }

K
kohsuke 已提交
2607 2608 2609 2610
        public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
            return logRecords;
        }

K
kohsuke 已提交
2611 2612 2613
        public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            // this computer never returns null from channel, so
            // this method shall never be invoked.
2614
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
2615 2616
        }

2617 2618 2619 2620
        public void launch() {
            // noop
        }

K
kohsuke 已提交
2621 2622 2623 2624 2625 2626
        /**
         * {@link LocalChannel} instance that can be used to execute programs locally.
         */
        public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
    }

2627 2628 2629 2630
    /**
     * @deprecated
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
2631 2632 2633 2634
    public static boolean adminCheck() throws IOException {
        return adminCheck(Stapler.getCurrentRequest(), Stapler.getCurrentResponse());
    }

2635 2636 2637 2638
    /**
     * @deprecated
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
2639
    public static boolean adminCheck(StaplerRequest req,StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2640 2641 2642 2643 2644 2645
        if (isAdmin(req)) return true;

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

K
kohsuke 已提交
2646 2647 2648
    /**
     * Checks if the current user (for which we are processing the current request)
     * has the admin access.
2649 2650
     *
     * @deprecated
K
kohsuke 已提交
2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
     *      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
     *      against. 
K
kohsuke 已提交
2663
     */
K
kohsuke 已提交
2664
    public static boolean isAdmin() {
2665
        return Hudson.getInstance().getACL().hasPermission(ADMINISTER);
K
kohsuke 已提交
2666 2667
    }

2668 2669 2670
    /**
     * @deprecated
     *      Define a custom {@link Permission} and check against ACL.
K
kohsuke 已提交
2671
     *      See {@link #isAdmin()} for more instructions.
2672
     */
K
kohsuke 已提交
2673
    public static boolean isAdmin(StaplerRequest req) {
2674
        return isAdmin();
K
kohsuke 已提交
2675 2676 2677 2678 2679
    }

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

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

2687 2688
    private static final int TWICE_CPU_NUM = Runtime.getRuntime().availableProcessors() * 2;

2689 2690 2691 2692 2693 2694
    /**
     * Thread pool used to load configuration in parallel, to improve the start up time.
     * <p>
     * The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
     */
    /*package*/ static final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
2695 2696
        TWICE_CPU_NUM, TWICE_CPU_NUM,
        5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory());
2697 2698 2699



2700 2701 2702
    /**
     * Version number of this Hudson.
     */
2703
    public static String VERSION="?";
2704

2705 2706 2707
    /**
     * Prefix to static resources like images and javascripts in the war file.
     * Either "" or strings like "/static/VERSION", which avoids Hudson to pick up
2708
     * stale cache when the user upgrades to a different version.
2709 2710
     * <p>
     * Value computed in {@link WebAppMain}.
2711
     */
2712
    public static String RESOURCE_PATH = "";
2713

2714 2715 2716 2717
    /**
     * 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.
2718 2719
     * <p>
     * Value computed in {@link WebAppMain}.
2720
     */
2721
    public static String VIEW_RESOURCE_PATH = "/resources/TBD";
2722

2723
    public static boolean PARALLEL_LOAD = Boolean.getBoolean(Hudson.class.getName()+".parallelLoad");
2724
    public static boolean KILL_AFTER_LOAD = Boolean.getBoolean(Hudson.class.getName()+".killAfterLoad");
2725
    public static boolean LOG_STARTUP_PERFORMANCE = Boolean.getBoolean(Hudson.class.getName()+".logStartupPerformance");
2726

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

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

2731
    public static final PermissionGroup PERMISSIONS = new PermissionGroup(Hudson.class,Messages._Hudson_Permissions_Title());
2732 2733
    public static final Permission ADMINISTER = new Permission(PERMISSIONS,"Administer",Messages._Hudson_AdministerPermission_Description(), Permission.FULL_CONTROL);
    public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ);
K
kohsuke 已提交
2734

K
kohsuke 已提交
2735 2736 2737 2738
    static {
        XSTREAM.alias("hudson",Hudson.class);
        XSTREAM.alias("slave",Slave.class);
        XSTREAM.alias("jdk",JDK.class);
2739 2740 2741
        // for backward compatibility with <1.75, recognize the tag name "view" as well.
        XSTREAM.alias("view", ListView.class);
        XSTREAM.alias("listView", ListView.class);
2742 2743
        // this seems to be necessary to force registration of converter early enough
        Mode.class.getEnumConstants();
K
kohsuke 已提交
2744 2745
    }
}