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

import com.thoughtworks.xstream.XStream;
import groovy.lang.GroovyShell;
K
kohsuke 已提交
5
import hudson.FeedAdapter;
6
import hudson.FilePath;
7
import hudson.Functions;
K
kohsuke 已提交
8
import hudson.Launcher;
K
kohsuke 已提交
9
import hudson.Launcher.LocalLauncher;
K
kohsuke 已提交
10 11 12
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
13
import hudson.StructuredForm;
K
kohsuke 已提交
14
import hudson.TcpSlaveAgentListener;
15
import hudson.Util;
K
kohsuke 已提交
16
import static hudson.Util.fixEmpty;
17
import hudson.XmlFile;
K
kohsuke 已提交
18
import hudson.model.Descriptor.FormException;
19
import hudson.model.listeners.ItemListener;
K
kohsuke 已提交
20
import hudson.model.listeners.JobListener;
21
import hudson.model.listeners.JobListener.JobListenerAdapter;
K
kohsuke 已提交
22
import hudson.model.listeners.SCMListener;
K
kohsuke 已提交
23 24
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
K
kohsuke 已提交
25
import hudson.scm.CVSSCM;
K
kohsuke 已提交
26 27
import hudson.scm.RepositoryBrowser;
import hudson.scm.RepositoryBrowsers;
28 29 30
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMS;
K
kohsuke 已提交
31
import hudson.search.CollectionSearchIndex;
32
import hudson.search.SearchIndexBuilder;
33 34
import hudson.security.ACL;
import hudson.security.AuthorizationStrategy;
K
kohsuke 已提交
35
import hudson.security.BasicAuthenticationFilter;
36 37 38 39
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
K
kohsuke 已提交
40
import hudson.security.SecurityMode;
41
import hudson.security.SecurityRealm;
42 43 44 45 46 47 48 49
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 已提交
50
import hudson.triggers.Trigger;
51
import hudson.triggers.TriggerDescriptor;
52
import hudson.triggers.Triggers;
K
kohsuke 已提交
53 54 55 56 57 58 59 60 61
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;
import hudson.util.XStream2;
import hudson.widgets.Widget;
62
import net.sf.json.JSONObject;
63
import org.acegisecurity.Authentication;
64 65
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.ui.AbstractProcessingFilter;
K
kohsuke 已提交
66 67 68
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
69
import org.kohsuke.stapler.MetaClass;
70
import org.kohsuke.stapler.QueryParameter;
71
import org.kohsuke.stapler.Stapler;
72
import org.kohsuke.stapler.StaplerProxy;
K
kohsuke 已提交
73 74
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
75
import org.kohsuke.stapler.export.Exported;
K
kohsuke 已提交
76 77 78

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
K
kohsuke 已提交
79
import javax.servlet.http.Cookie;
K
kohsuke 已提交
80
import javax.servlet.http.HttpServletRequest;
K
kohsuke 已提交
81
import javax.servlet.http.HttpServletResponse;
82
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
K
kohsuke 已提交
83
import javax.servlet.http.HttpSession;
K
kohsuke 已提交
84 85 86
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
87
import java.io.FileOutputStream;
K
kohsuke 已提交
88 89 90
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
91
import java.net.URL;
K
kohsuke 已提交
92 93 94
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
K
kohsuke 已提交
95
import java.util.Calendar;
K
kohsuke 已提交
96 97 98
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
K
kohsuke 已提交
99
import java.util.GregorianCalendar;
K
kohsuke 已提交
100 101 102 103 104 105
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
106 107
import java.util.Stack;
import java.util.StringTokenizer;
K
kohsuke 已提交
108 109
import java.util.TreeSet;
import java.util.Vector;
110
import java.util.concurrent.Callable;
111
import java.util.concurrent.ConcurrentHashMap;
K
kohsuke 已提交
112
import java.util.concurrent.CopyOnWriteArrayList;
113 114 115 116 117 118
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
K
kohsuke 已提交
119
import java.util.logging.Level;
K
kohsuke 已提交
120
import java.util.logging.LogRecord;
121
import java.util.logging.Logger;
122
import java.util.regex.Pattern;
K
kohsuke 已提交
123 124 125 126 127 128

/**
 * Root object of the system.
 *
 * @author Kohsuke Kawaguchi
 */
K
kohsuke 已提交
129
public final class Hudson extends View implements ItemGroup<TopLevelItem>, Node, StaplerProxy {
K
kohsuke 已提交
130 131 132 133 134
    private transient final Queue queue = new Queue();

    /**
     * {@link Computer}s in this Hudson system. Read-only.
     */
K
kohsuke 已提交
135
    private transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
K
kohsuke 已提交
136 137 138 139 140 141 142 143

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

    /**
     * False to enable anyone to do anything.
K
kohsuke 已提交
144
     * Left as a field so that we can still read old data that uses this flag.
145 146 147
     *
     * @see #authorizationStrategy
     * @see #securityRealm
K
kohsuke 已提交
148
     */
K
kohsuke 已提交
149
    private Boolean useSecurity;
K
kohsuke 已提交
150 151

    /**
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
     * 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.
     *
     * See {@link HudsonFilter} for the concrete authentication protocol. 
     *
171 172
     * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
     * update this field.
173 174
     *
     * @see #getSecurity()
175
     * @see #setSecurityRealm(SecurityRealm)
K
kohsuke 已提交
176
     */
177
    private volatile SecurityRealm securityRealm;
K
kohsuke 已提交
178 179 180 181 182 183 184 185 186 187 188

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

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

189 190 191
    /**
     * All {@link Item}s keyed by their {@link Item#getName() name}s.
     */
K
kohsuke 已提交
192
    /*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>();
193

K
kohsuke 已提交
194 195 196 197 198 199 200 201
    /**
     * The sole instance.
     */
    private static Hudson theInstance;

    private transient boolean isQuietingDown;
    private transient boolean terminating;

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

K
kohsuke 已提交
204 205 206 207 208
    /**
     * Widgets on Hudson.
     */
    private transient final List<Widget> widgets = new CopyOnWriteArrayList<Widget>();

209 210
    private transient volatile DependencyGraph dependencyGraph = DependencyGraph.EMPTY;

K
kohsuke 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    /**
     * 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;

    /**
229
     * {@link ListView}s.
K
kohsuke 已提交
230
     */
231
    private List<ListView> views;   // can't initialize it eagerly for backward compatibility
K
kohsuke 已提交
232 233 234 235 236 237 238 239

    private transient final FingerprintMap fingerprintMap = new FingerprintMap();

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

240
    public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
K
kohsuke 已提交
241

242
    /**
K
kohsuke 已提交
243
     * List of registered {@link JobListener}s.
244
     */
K
kohsuke 已提交
245
    private transient final CopyOnWriteList<ItemListener> itemListeners = new CopyOnWriteList<ItemListener>();
246 247 248 249 250

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

252 253
    /**
     * TCP slave agent port.
254
     * 0 for random, -1 to disable.
255 256 257
     */
    private int slaveAgentPort =0;

258 259 260 261 262 263 264
    /**
     * Once plugin is uploaded, this flag becomes true.
     * This is used to report a message that Hudson needs to be restarted
     * for new plugins to take effect.
     */
    private transient boolean pluginUploaded =false;

265 266 267 268 269
    /**
     * 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>();
270 271
    private transient Set<Label> labelSet;
    private transient Set<Label> dynamicLabels = null;
272

273 274
    public transient final ServletContext servletContext;

K
kohsuke 已提交
275 276 277 278 279 280 281
    public static Hudson getInstance() {
        return theInstance;
    }


    public Hudson(File root, ServletContext context) throws IOException {
        this.root = root;
282
        this.servletContext = context;
K
kohsuke 已提交
283 284 285 286 287 288 289
        if(theInstance!=null)
            throw new IllegalStateException("second instance");
        theInstance = this;

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

290 291 292 293
        if(slaveAgentPort!=-1)
            tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
        else
            tcpSlaveAgentListener = null;
K
kohsuke 已提交
294

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

298
        // work around to have MavenModule register itself until we either move it to a plugin
299
        // or make it a part of the core.
300
        Items.LIST.hashCode();
301

K
kohsuke 已提交
302 303 304 305
        load();
        updateComputerList();

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

K
kohsuke 已提交
307
        for (ItemListener l : itemListeners)
308
            l.onLoaded();
K
kohsuke 已提交
309 310
    }

K
kohsuke 已提交
311 312 313 314
    public TcpSlaveAgentListener getTcpSlaveAgentListener() {
        return tcpSlaveAgentListener;
    }

K
kohsuke 已提交
315
    @Exported
316 317 318 319
    public int getSlaveAgentPort() {
        return slaveAgentPort;
    }

K
kohsuke 已提交
320
    /**
J
jglick 已提交
321
     * If you are calling this on Hudson something is wrong.
K
kohsuke 已提交
322 323 324
     *
     * @deprecated
     */
J
jglick 已提交
325
    @Deprecated
K
kohsuke 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    public String getNodeName() {
        return "";
    }

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

    public String getDescription() {
        return systemMessage;
    }

    public PluginManager getPluginManager() {
        return pluginManager;
    }

    /**
     * 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 已提交
349 350 351 352 353 354 355
    /**
     * 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 已提交
356 357 358 359 360 361 362
    /**
     * 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 已提交
363 364 365 366 367 368 369
    /**
     * 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 已提交
370 371 372 373 374 375 376
    /**
     * 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 已提交
377 378 379
    /**
     * Gets the trigger descriptor by name. Primarily used for making them web-visible.
     */
380 381
    public TriggerDescriptor getTrigger(String shortClassName) {
        return (TriggerDescriptor)findDescriptor(shortClassName, Triggers.TRIGGERS);
K
kohsuke 已提交
382 383
    }

384 385 386 387
    /**
     * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
     */
    public JobPropertyDescriptor getJobProperty(String shortClassName) {
K
kohsuke 已提交
388 389 390
        // combining these two lines triggers javac bug. See issue #610.
        Descriptor d = findDescriptor(shortClassName, Jobs.PROPERTIES);
        return (JobPropertyDescriptor) d;
391 392
    }

K
kohsuke 已提交
393 394 395 396
    /**
     * Finds a descriptor that has the specified name.
     */
    private <T extends Describable<T>>
397
    Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
K
kohsuke 已提交
398 399 400 401 402 403 404 405
        String name = '.'+shortClassName;
        for (Descriptor<T> d : descriptors) {
            if(d.clazz.getName().endsWith(name))
                return d;
        }
        return null;
    }

406 407 408
    /**
     * Adds a new {@link JobListener}.
     *
409 410
     * @deprecated
     *      Use {@code getJobListners().add(l)} instead.
411 412
     */
    public void addListener(JobListener l) {
K
kohsuke 已提交
413
        itemListeners.add(new JobListenerAdapter(l));
414 415 416 417 418
    }

    /**
     * Deletes an existing {@link JobListener}.
     *
419 420
     * @deprecated
     *      Use {@code getJobListners().remove(l)} instead.
421 422
     */
    public boolean removeListener(JobListener l ) {
K
kohsuke 已提交
423
        return itemListeners.remove(new JobListenerAdapter(l));
424 425
    }

426
    /**
427
     * Gets all the installed {@link ItemListener}s.
428
     */
429
    public CopyOnWriteList<ItemListener> getJobListeners() {
K
kohsuke 已提交
430
        return itemListeners;
431 432 433 434 435 436 437 438 439
    }

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

K
kohsuke 已提交
440 441 442 443 444 445 446 447 448 449
    /**
     * 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;
450
        return p.getPlugin();
K
kohsuke 已提交
451 452 453 454 455 456 457 458 459 460
    }

    /**
     * Synonym to {@link #getNodeDescription()}.
     */
    public String getSystemMessage() {
        return systemMessage;
    }

    public Launcher createLauncher(TaskListener listener) {
K
kohsuke 已提交
461
        return new LocalLauncher(listener);
K
kohsuke 已提交
462 463 464 465 466 467 468 469 470
    }

    /**
     * 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 已提交
471
    private void updateComputerList() throws IOException {
472
        synchronized(computers) {// this synchronization is still necessary so that no two update happens concurrently
K
kohsuke 已提交
473
            Map<String,Computer> byName = new HashMap<String,Computer>();
K
kohsuke 已提交
474 475 476
            for (Computer c : computers.values()) {
                if(c.getNode()==null)
                    continue;   // this computer is gone
K
kohsuke 已提交
477
                byName.put(c.getNode().getNodeName(),c);
K
kohsuke 已提交
478
            }
K
kohsuke 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500

            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 已提交
501 502
        if (c!=null) {
            c.setNode(n); // reuse
K
kohsuke 已提交
503
        } else {
K
kohsuke 已提交
504 505
            if(n.getNumExecutors()>0)
                computers.put(n,c=n.createComputer());
K
kohsuke 已提交
506 507 508 509 510
        }
        used.add(c);
    }

    /*package*/ void removeComputer(Computer computer) {
511 512
        for (Entry<Node, Computer> e : computers.entrySet()) {
            if (e.getValue() == computer) {
K
kohsuke 已提交
513
                computers.remove(e.getKey());
514
                return;
K
kohsuke 已提交
515 516 517 518 519
            }
        }
        throw new IllegalStateException("Trying to remove unknown computer");
    }

520 521 522 523
    public String getFullName() {
        return "";
    }

524 525 526 527
    public String getFullDisplayName() {
        return "";
    }

528 529 530
    /**
     * Gets just the immediate children of {@link Hudson}.
     *
531
     * @see #getAllItems(Class)
532
     */
K
kohsuke 已提交
533
    public List<TopLevelItem> getItems() {
534
        return new ArrayList<TopLevelItem>(items.values());
535 536
    }

537 538 539 540 541 542 543 544 545 546 547 548 549 550
    /**
     * 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 已提交
551
                    r.add(type.cast(i));
552 553 554 555 556 557 558 559
                if(i instanceof ItemGroup)
                    q.push((ItemGroup)i);
            }
        }

        return r;
    }

K
kohsuke 已提交
560
    /**
K
kohsuke 已提交
561 562 563 564 565
     * 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 已提交
566
     */
K
kohsuke 已提交
567
    public List<Project> getProjects() {
K
kohsuke 已提交
568
        return Util.createSubList(items.values(),Project.class);
K
kohsuke 已提交
569 570 571 572 573
    }

    /**
     * Gets the names of all the {@link Job}s.
     */
K
kohsuke 已提交
574
    public Collection<String> getJobNames() {
575
        List<String> names = new ArrayList<String>();
K
kohsuke 已提交
576 577
        for (Job j : getAllItems(Job.class))
            names.add(j.getName());
578
        return names;
K
kohsuke 已提交
579 580
    }

581 582 583 584 585 586 587 588 589 590
    /**
     * 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 已提交
591 592 593 594 595 596
    /**
     * Every job belongs to us.
     *
     * @deprecated
     *      why are you calling a method that always return true?
     */
J
jglick 已提交
597
    @Deprecated
598
    public boolean contains(TopLevelItem view) {
K
kohsuke 已提交
599 600 601
        return true;
    }

602
    public synchronized View getView(String name) {
K
kohsuke 已提交
603
        if(views!=null) {
604
            for (ListView v : views) {
K
kohsuke 已提交
605 606 607 608 609 610 611 612 613 614 615
                if(v.getViewName().equals(name))
                    return v;
            }
        }
        if(this.getViewName().equals(name))
            return this;
        else
            return null;
    }

    /**
616
     * Gets the read-only list of all {@link View}s.
K
kohsuke 已提交
617
     */
618
    @Exported
619
    public synchronized View[] getViews() {
K
kohsuke 已提交
620
        if(views==null)
621 622
            views = new ArrayList<ListView>();
        View[] r = new View[views.size()+1];
K
kohsuke 已提交
623 624 625
        views.toArray(r);
        // sort Views and put "all" at the very beginning
        r[r.length-1] = r[0];
626
        Arrays.sort(r,1,r.length, View.SORTER);
K
kohsuke 已提交
627 628 629 630
        r[0] = this;
        return r;
    }

631
    public synchronized void deleteView(ListView view) throws IOException {
K
kohsuke 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645
        if(views!=null) {
            views.remove(view);
            save();
        }
    }

    public String getViewName() {
        return "All";
    }

    /**
     * Gets the read-only list of all {@link Computer}s.
     */
    public Computer[] getComputers() {
646 647 648 649 650
        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 已提交
651
                return lhs.getDisplayName().compareTo(rhs.getDisplayName());
652 653 654
            }
        });
        return r;
K
kohsuke 已提交
655 656 657
    }

    public Computer getComputer(String name) {
K
kohsuke 已提交
658 659 660
        if(name.equals("(master)"))
            name = "";

661 662 663
        for (Computer c : computers.values()) {
            if(c.getNode().getNodeName().equals(name))
                return c;
K
kohsuke 已提交
664 665 666 667
        }
        return null;
    }

K
kohsuke 已提交
668 669 670 671 672 673 674 675
    /**
     * @deprecated
     *      UI method. Not meant to be used programatically.
     */
    public ComputerSet getComputer() {
        return new ComputerSet();
    }

676 677 678 679 680 681
    /**
     * 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 已提交
682
        if(name==null)  return null;
683 684 685 686 687 688 689 690 691 692 693
        while(true) {
            Label l = labels.get(name);
            if(l!=null)
                return l;

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

    /**
694
     * Gets all the active labels in the current system.
695 696 697 698 699 700 701 702 703 704
     */
    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 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    public Queue getQueue() {
        return queue;
    }

    public String getDisplayName() {
        return "Hudson";
    }

    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) {
723 724 725 726 727 728
        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 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
        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);
    }

    /**
     * Gets the system default quiet period.
     */
    public int getQuietPeriod() {
        return quietPeriod!=null ? quietPeriod : 5;
    }

K
kohsuke 已提交
758 759 760 761 762
    /**
     * @deprecated
     *      Why are you calling a method that always returns ""?
     *      Perhaps you meant {@link #getRootUrl()}.
     */
K
kohsuke 已提交
763 764 765 766
    public String getUrl() {
        return "";
    }

767
    @Override
768 769
    public SearchIndexBuilder makeSearchIndex() {
        return super.makeSearchIndex()
770
            .add("configure", "config","configure")
K
kohsuke 已提交
771
            .add("manage")
K
kohsuke 已提交
772 773 774 775
            .add("log")
            .add(new CollectionSearchIndex() {// for computers
                protected Computer get(String key) { return getComputer(key); }
                protected Collection<Computer> all() { return computers.values(); }
K
kohsuke 已提交
776
            })
K
kohsuke 已提交
777
            .add(new CollectionSearchIndex() {// for users
K
kohsuke 已提交
778
                protected User get(String key) { return User.get(key,false); }
K
kohsuke 已提交
779
                protected Collection<User> all() { return User.getAll(); }
K
kohsuke 已提交
780
            })
K
kohsuke 已提交
781 782 783
            .add(new CollectionSearchIndex() {// for views
                protected View get(String key) { return getView(key); }
                protected Collection<ListView> all() { return views; }
K
kohsuke 已提交
784
            });
785 786
    }

787 788 789 790
    public String getUrlChildPrefix() {
        return "job";
    }

K
kohsuke 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
    /**
     * 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
     */
    public String getRootUrl() {
        // for compatibility. the actual data is stored in Mailer
813 814 815 816 817 818 819 820 821 822 823 824 825 826
        String url = Mailer.DESCRIPTOR.getUrl();
        if(url!=null)   return url;

        StaplerRequest req = Stapler.getCurrentRequest();
        if(req!=null) {
            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();
        }
        return null;
K
kohsuke 已提交
827 828
    }

K
kohsuke 已提交
829 830 831 832
    public File getRootDir() {
        return root;
    }

833 834 835 836
    public FilePath getWorkspaceFor(TopLevelItem item) {
        return new FilePath(new File(item.getRootDir(),"workspace"));
    }

K
kohsuke 已提交
837 838 839 840
    public FilePath getRootPath() {
        return new FilePath(getRootDir());
    }

841 842
    public ClockDifference getClockDifference() {
        return ClockDifference.ZERO;
K
kohsuke 已提交
843 844
    }

K
kohsuke 已提交
845
    /**
846 847
     * A convenience method to check if there's some security
     * restrictions in place.
K
kohsuke 已提交
848
     */
K
kohsuke 已提交
849
    public boolean isUseSecurity() {
850
        return securityRealm!=SecurityRealm.NO_AUTHENTICATION;
K
kohsuke 已提交
851 852
    }

K
kohsuke 已提交
853
    /**
854 855
     * Returns the constant that captures the three basic security modes
     * in Hudson.
K
kohsuke 已提交
856
     */
857 858 859 860 861 862 863 864 865
    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 已提交
866 867
    }

K
kohsuke 已提交
868 869 870 871 872 873 874 875
    /**
     * @return
     *      never null.
     */
    public SecurityRealm getSecurityRealm() {
        return securityRealm;
    }

876 877 878 879 880
    public void setSecurityRealm(SecurityRealm securityRealm) {
        this.securityRealm = securityRealm;
        HudsonFilter.AUTHENTICATION_MANAGER.setManager(securityRealm.createAuthenticationManager());
    }

881 882 883 884 885 886 887
    /**
     * Returns the root {@link ACL}.
     *
     * @see AuthorizationStrategy#getRootACL()
     */
    public ACL getACL() {
        return authorizationStrategy.getRootACL();
K
kohsuke 已提交
888 889
    }

890 891 892 893 894 895
    /**
     * @return
     *      never null.
     */
    public AuthorizationStrategy getAuthorizationStrategy() {
        return authorizationStrategy;
K
kohsuke 已提交
896 897
    }

K
kohsuke 已提交
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
    /**
     * 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;
    }

    /**
917 918 919
     * @deprecated
     *      Left only for the compatibility of URLs.
     *      Should not be invoked for any other purpose.
K
kohsuke 已提交
920
     */
921 922
    public TopLevelItem getJob(String name) {
        return getItem(name);
K
kohsuke 已提交
923 924
    }

925 926 927 928 929 930 931 932 933 934 935 936
    /**
     * @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()) {
            if(e.getKey().equalsIgnoreCase(name))
                return e.getValue();
        }
        return null;
    }

937
    @Override
K
kohsuke 已提交
938
    public TopLevelItem getItem(String name) {
939 940 941
        return items.get(name);
    }

942
    public File getRootDirFor(TopLevelItem child) {
943 944 945 946 947
        return getRootDirFor(child.getName());
    }

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

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
    /**
     * 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 已提交
979 980 981 982
    public Item getItemByFullName(String fullName) {
        return getItemByFullName(fullName,Item.class);
    }

K
kohsuke 已提交
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
    /**
     * 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.
     */
999
    public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
K
kohsuke 已提交
1000
        if(items.containsKey(name))
K
kohsuke 已提交
1001 1002
            throw new IllegalArgumentException();

K
kohsuke 已提交
1003
        TopLevelItem item;
K
kohsuke 已提交
1004
        try {
K
kohsuke 已提交
1005
            item = type.newInstance(name);
K
kohsuke 已提交
1006 1007 1008 1009
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }

K
kohsuke 已提交
1010 1011 1012
        item.save();
        items.put(name,item);
        return item;
K
kohsuke 已提交
1013 1014 1015 1016 1017
    }

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

1022
        items.remove(item.getName());
K
kohsuke 已提交
1023
        if(views!=null) {
1024
            for (ListView v : views) {
K
kohsuke 已提交
1025
                synchronized(v) {
1026
                    v.jobNames.remove(item.getName());
K
kohsuke 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
                }
            }
            save();
        }
    }

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

        if(views!=null) {
1042
            for (ListView v : views) {
K
kohsuke 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
                synchronized(v) {
                    if(v.jobNames.remove(oldName))
                        v.jobNames.add(newName);
                }
            }
            save();
        }
    }

    public FingerprintMap getFingerprintMap() {
        return fingerprintMap;
    }

K
kohsuke 已提交
1056
    // if no finger print matches, display "not found page".
K
kohsuke 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    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() {
        return Mode.NORMAL;
    }

1086
    public Set<Label> getAssignedLabels() {
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
        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) {
            synchronized (this) {
                Computer comp = getComputer("");
                if (dynamicLabels == null) {
                    dynamicLabels = new HashSet<Label>();
                    if (comp != null) {
                        VirtualChannel channel = comp.getChannel();
                        if (channel != null) {
                            for (DynamicLabeler labeler : LabelFinder.LABELERS) {
                                for (String label : labeler.findLabels(channel)) {
                                    dynamicLabels.add(getLabel(label));
                                }
                            }
                        }
                    }
                }
            }
        }
        return dynamicLabels;
1121 1122 1123 1124 1125 1126
    }

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

K
kohsuke 已提交
1127 1128 1129 1130
    public Computer createComputer() {
        return new MasterComputer();
    }

K
kohsuke 已提交
1131
    private synchronized void load() throws IOException {
1132
        long startTime = System.currentTimeMillis();
K
kohsuke 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
        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) {
                return child.isDirectory();
            }
        });
1148
        items.clear();
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
        if(parallelLoad) {
            // load jobs in parallel for better performance
            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 {
                        return (TopLevelItem) Items.load(Hudson.this, subdir);
                    }
                }));
            }

            for (Future<TopLevelItem> loader : loaders) {
                try {
                    TopLevelItem item = loader.get();
                    items.put(item.getName(), item);
                } catch (ExecutionException e) {
                    LOGGER.log(Level.WARNING, "Failed to loa da project",e.getCause());
                } catch (InterruptedException e) {
                    e.printStackTrace(); // this is probably not the right thing to do
                }
            }
        } else {
            for (File subdir : subdirs) {
                try {
                    TopLevelItem item = (TopLevelItem)Items.load(this,subdir);
                    items.put(item.getName(), item);
                } catch (Error e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
                }
K
kohsuke 已提交
1180 1181
            }
        }
1182
        rebuildDependencyGraph();
1183 1184

        // recompute label objects
1185 1186 1187 1188
        if (null != slaves) { // only if we have slaves
            for (Slave slave : slaves)
                slave.getAssignedLabels();
        }
K
kohsuke 已提交
1189

K
typo.  
kohsuke 已提交
1190
        // read in old data that doesn't have the security field set
1191 1192 1193 1194 1195 1196 1197 1198
        if(authorizationStrategy==null) {
            if(useSecurity==null || !useSecurity)
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
            else
                authorizationStrategy = new LegacyAuthorizationStrategy();
        }
        if(securityRealm==null) {
            if(useSecurity==null || !useSecurity)
1199
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
1200
            else
1201 1202 1203 1204
                setSecurityRealm(new LegacySecurityRealm());
        } else {
            // force the set to proxy
            setSecurityRealm(securityRealm);
1205
        }
1206

K
kohsuke 已提交
1207 1208 1209 1210
        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;
1211
            setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
K
kohsuke 已提交
1212
        }
1213
        
K
kohsuke 已提交
1214

1215
        LOGGER.info(String.format("Took %s ms to load",System.currentTimeMillis()-startTime));
K
kohsuke 已提交
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
        getConfigFile().write(this);
    }


    /**
     * Called to shut down the system.
     */
    public void cleanUp() {
        terminating = true;
1231 1232 1233
        for( Computer c : computers.values() ) {
            c.interrupt();
            c.kill();
K
kohsuke 已提交
1234 1235 1236
        }
        ExternalJob.reloadThread.interrupt();
        Trigger.timer.cancel();
1237 1238
        if(tcpSlaveAgentListener!=null)
            tcpSlaveAgentListener.shutdown();
K
kohsuke 已提交
1239 1240 1241 1242

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

1243 1244 1245 1246
        if(getRootDir().exists())
            // if we are aborting because we failed to create HUDSON_HOME,
            // don't try to save. Issue #536
            getQueue().save();
1247 1248

        threadPoolForLoad.shutdown();
K
kohsuke 已提交
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    }



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

            req.setCharacterEncoding("UTF-8");

1267 1268
            JSONObject json = StructuredForm.get(req);

1269 1270 1271
            // keep using 'useSecurity' field as the main configuration setting
            // until we get the new security implementation working
            // useSecurity = null;
1272
            if (json.has("use_security")) {
K
kohsuke 已提交
1273
                useSecurity = true;
1274 1275
                if(newSecurity) {
                    JSONObject security = json.getJSONObject("use_security");
1276
                    setSecurityRealm(SecurityRealm.LIST.newInstanceFromRadioList(security,"realm"));
1277 1278 1279
                    authorizationStrategy = AuthorizationStrategy.LIST.newInstanceFromRadioList(security,"authorization");
                } else {
                    // compatibility mode
1280
                    setSecurityRealm(new LegacySecurityRealm());
1281 1282
                    authorizationStrategy = new LegacyAuthorizationStrategy();
                }
K
kohsuke 已提交
1283
            } else {
1284
                useSecurity = null;
1285
                setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
1286
                authorizationStrategy = AuthorizationStrategy.UNSECURED;
K
kohsuke 已提交
1287
            }
K
kohsuke 已提交
1288

1289 1290
            {
                String v = req.getParameter("slaveAgentPortType");
1291
                if(!isUseSecurity() || v==null || v.equals("random"))
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
                    slaveAgentPort = 0;
                else
                if(v.equals("disable"))
                    slaveAgentPort = -1;
                else {
                    try {
                        slaveAgentPort = Integer.parseInt(req.getParameter("slaveAgentPort"));
                    } catch (NumberFormatException e) {
                        throw new FormException("Bad port number "+req.getParameter("slaveAgentPort"),"slaveAgentPort");
                    }
                }
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315

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

K
kohsuke 已提交
1318 1319 1320 1321 1322 1323 1324
            numExecutors = Integer.parseInt(req.getParameter("numExecutors"));
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));

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

            {// update slave list
                List<Slave> newSlaves = new ArrayList<Slave>();
K
kohsuke 已提交
1325 1326 1327 1328
                String[] names = req.getParameterValues("slave.name");
                if(names!=null) {
                    for(int i=0;i< names.length;i++) {
                        newSlaves.add(req.bindParameters(Slave.class,"slave.",i));
K
kohsuke 已提交
1329 1330 1331 1332
                    }
                }
                this.slaves = newSlaves;
                updateComputerList();
1333 1334 1335 1336 1337 1338 1339

                // label trim off
                for (Label l : labels.values()) {
                    l.reset();
                    if(l.getNodes().isEmpty())
                        labels.remove(l);
                }
K
kohsuke 已提交
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
            }

            {// 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 )
                result &= d.configure(req);

            for( Descriptor<Publisher> d : BuildStep.PUBLISHERS )
                result &= d.configure(req);

K
kohsuke 已提交
1362 1363 1364
            for( Descriptor<BuildWrapper> d : BuildWrappers.WRAPPERS )
                result &= d.configure(req);

1365
            for( SCMDescriptor scmd : SCMS.SCMS )
K
kohsuke 已提交
1366 1367
                result &= scmd.configure(req);

1368
            for( TriggerDescriptor d : Triggers.TRIGGERS )
K
kohsuke 已提交
1369 1370
                result &= d.configure(req);

1371 1372 1373
            for( JobPropertyDescriptor d : Jobs.PROPERTIES )
                result &= d.configure(req);

K
kohsuke 已提交
1374 1375
            save();
            if(result)
1376
                rsp.sendRedirect(req.getContextPath()+'/');  // go to the top page
K
kohsuke 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
            else
                rsp.sendRedirect("configure"); // back to config
        } catch (FormException e) {
            sendError(e,req,rsp);
        }
    }

    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1388
        checkPermission(ADMINISTER);
K
kohsuke 已提交
1389 1390 1391 1392 1393 1394 1395 1396

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

    public synchronized void doQuietDown( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
K
kohsuke 已提交
1397
        checkPermission(ADMINISTER);
K
kohsuke 已提交
1398 1399 1400 1401 1402
        isQuietingDown = true;
        rsp.sendRedirect2(".");
    }

    public synchronized void doCancelQuietDown( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
K
kohsuke 已提交
1403
        checkPermission(ADMINISTER);
K
kohsuke 已提交
1404 1405 1406 1407 1408
        isQuietingDown = false;
        getQueue().scheduleMaintenance();
        rsp.sendRedirect2(".");
    }

1409 1410 1411 1412 1413 1414 1415
    /**
     * Backward compatibility. Redirect to the thread dump.
     */
    public void doClassicThreadDump( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        rsp.sendRedirect2("threadDump");
    }

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

1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
        TopLevelItem result;

        boolean isXmlSubmission = req.getContentType().startsWith("application/xml") || req.getContentType().startsWith("text/xml");
        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");
        }
        
K
kohsuke 已提交
1430 1431 1432 1433 1434 1435
        String name = req.getParameter("name").trim();
        String mode = req.getParameter("mode");

        try {
            checkGoodName(name);
        } catch (ParseException e) {
1436
            rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
K
kohsuke 已提交
1437 1438 1439 1440
            sendError(e,req,rsp);
            return null;
        }

1441
        if(getItem(name)!=null) {
1442
            rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
K
kohsuke 已提交
1443 1444 1445 1446
            sendError("A job already exists with the name '"+name+"'",req,rsp);
            return null;
        }

1447
        if(mode!=null && mode.equals("copyJob")) {
1448
            TopLevelItem src = getItem(req.getParameter("from"));
K
kohsuke 已提交
1449 1450 1451 1452 1453
            if(src==null) {
                rsp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return null;
            }

1454
            result = createProject(src.getDescriptor(),name);
K
kohsuke 已提交
1455 1456

            // copy config
1457
            Util.copyFile(Items.getConfigFile(src).getFile(),Items.getConfigFile(result).getFile());
K
kohsuke 已提交
1458 1459

            // reload from the new config
1460
            result = (TopLevelItem)Items.load(this,result.getRootDir());
1461 1462
            result.onCopiedFrom(src);
            items.put(name,result);
1463
        } else {
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
            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) {
                    rsp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                    return null;
                }
                result = createProject(Items.getDescriptor(mode), name);
            }
K
kohsuke 已提交
1494 1495
        }

K
kohsuke 已提交
1496
        for (ItemListener l : itemListeners)
1497
            l.onCreated(result);
1498

1499 1500 1501 1502 1503 1504 1505 1506
        if(isXmlSubmission) {
            // it worked
            rsp.setStatus(HttpServletResponse.SC_OK);
        } else {
            // send the browser to the config page
            rsp.sendRedirect2(req.getContextPath()+'/'+result.getUrl()+"configure");
        }

K
kohsuke 已提交
1507 1508 1509 1510
        return result;
    }

    public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1511
        checkPermission(View.CREATE);
K
kohsuke 已提交
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523

        req.setCharacterEncoding("UTF-8");

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

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

1524
        ListView v = new ListView(this, name);
K
kohsuke 已提交
1525
        if(views==null)
1526
            views = new Vector<ListView>();
K
kohsuke 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
        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)
            throw new ParseException("No name is specified",0);

        for( int i=0; i<name.length(); i++ ) {
            char ch = name.charAt(i);
            if(Character.isISOControl(ch))
                throw new ParseException("No control code is allowed",i);
K
kohsuke 已提交
1549
            if("?*()/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
K
kohsuke 已提交
1550 1551 1552 1553 1554 1555
                throw new ParseException("'"+ch+"' is an unsafe character",i);
        }

        // looks good
    }

1556
    /**
1557 1558 1559
     * Checks if the user was successfully authenticated.
     *
     * @see BasicAuthenticationFilter
1560 1561
     */
    public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1562 1563
        if(req.getUserPrincipal()==null) {
            // authentication must have failed
1564 1565 1566 1567
            rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

1568
        // the user is now authenticated, so send him back to the target
1569 1570 1571
        String path = req.getContextPath()+req.getRestOfPath();
        String q = req.getQueryString();
        if(q!=null)
1572
            path += '?'+q;
1573

1574
        rsp.sendRedirect2(path);
1575 1576
    }

K
kohsuke 已提交
1577 1578 1579
    /**
     * Called once the user logs in. Just forward to the top page.
     */
K
kohsuke 已提交
1580
    public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
1581 1582
        if(req.getUserPrincipal()==null)
            rsp.sendRedirect2("noPrincipal");
1583 1584

        String from = req.getParameter("from");
1585
        if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
1586
            rsp.sendRedirect2(from);    // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
            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 已提交
1599 1600 1601 1602 1603
    }

    /**
     * Called once the user logs in. Just forward to the top page.
     */
K
kohsuke 已提交
1604
    public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
1605 1606 1607
        HttpSession session = req.getSession(false);
        if(session!=null)
            session.invalidate();
1608
        SecurityContextHolder.clearContext();
K
kohsuke 已提交
1609 1610 1611
        rsp.sendRedirect2(req.getContextPath()+"/");
    }

K
kohsuke 已提交
1612 1613 1614 1615
    /**
     * RSS feed for log entries.
     */
    public void doLogRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1616
        checkPermission(ADMINISTER);
1617

K
kohsuke 已提交
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
        List<LogRecord> logs = logRecords;

        // filter log records based on the log level
        String level = req.getParameter("level");
        if(level!=null) {
            Level threshold = Level.parse(level);
            List<LogRecord> filtered = new ArrayList<LogRecord>();
            for (LogRecord r : logs) {
                if(r.getLevel().intValue() >= threshold.intValue())
                    filtered.add(r);
            }
            logs = filtered;
        }

        RSS.forwardToRss("Hudson log","", logs, new FeedAdapter<LogRecord>() {
            public String getEntryTitle(LogRecord entry) {
                return entry.getMessage();
            }

            public String getEntryUrl(LogRecord entry) {
                return "log";   // TODO: one URL for one log entry?
            }

            public String getEntryID(LogRecord entry) {
                return String.valueOf(entry.getSequenceNumber());
            }

1645 1646 1647 1648
            public String getEntryDescription(LogRecord entry) {
                return Functions.printLogRecord(entry);
            }

K
kohsuke 已提交
1649 1650 1651 1652 1653 1654 1655 1656
            public Calendar getEntryTimestamp(LogRecord entry) {
                GregorianCalendar cal = new GregorianCalendar();
                cal.setTimeInMillis(entry.getMillis());
                return cal;
            }
        },req,rsp);
    }

K
kohsuke 已提交
1657 1658 1659 1660
    /**
     * Reloads the configuration.
     */
    public synchronized void doReload( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
1661
        checkPermission(ADMINISTER);
K
kohsuke 已提交
1662

1663 1664 1665 1666
        // 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 已提交
1667
        rsp.sendRedirect2(req.getContextPath()+"/");
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679

        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 已提交
1680 1681
    }

1682 1683 1684 1685
    public boolean isPluginUploaded() {
        return pluginUploaded;
    }

K
kohsuke 已提交
1686 1687 1688 1689 1690
    /**
     * Uploads a plugin.
     */
    public void doUploadPlugin( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        try {
K
kohsuke 已提交
1691
            checkPermission(ADMINISTER);
K
kohsuke 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704

            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

            // Parse the request
            FileItem fileItem = (FileItem) upload.parseRequest(req).get(0);
            String fileName = Util.getFileName(fileItem.getName());
            if(!fileName.endsWith(".hpi")) {
                sendError(fileName+" is not a Hudson plugin",req,rsp);
                return;
            }
            fileItem.write(new File(getPluginManager().rootDir, fileName));
            fileItem.delete();

1705 1706
            pluginUploaded=true;

K
kohsuke 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
            rsp.sendRedirect2("managePlugins");
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {// grrr. fileItem.write throws this
            throw new ServletException(e);
        }
    }

    /**
     * Do a finger-print check.
     */
    public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1719 1720
        // Parse the request
        MultipartFormDataParser p = new MultipartFormDataParser(req);
K
kohsuke 已提交
1721 1722
        try {
            rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
1723 1724 1725
                Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
        } finally {
            p.cleanUp();
K
kohsuke 已提交
1726 1727 1728 1729 1730 1731 1732
        }
    }

    /**
     * Serves static resources without the "Last-Modified" header to work around
     * a bug in Firefox.
     *
K
kohsuke 已提交
1733 1734
     * <p>
     * See https://bugzilla.mozilla.org/show_bug.cgi?id=89419
K
kohsuke 已提交
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
     */
    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
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        File f = new File(req.getServletContext().getRealPath("/images"),path.substring(1));
        if(!f.exists()) {
1750
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
            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 已提交
1765
        Util.copyStream(in,rsp.getOutputStream());
K
kohsuke 已提交
1766 1767 1768 1769
        in.close();
    }

    /**
K
kohsuke 已提交
1770
     * For debugging. Expose URL to perform GC.
K
kohsuke 已提交
1771 1772 1773 1774 1775 1776 1777 1778
     */
    public void doGc( StaplerRequest req, StaplerResponse rsp ) throws IOException {
        System.gc();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("GCed");
    }

K
kohsuke 已提交
1779 1780 1781 1782 1783
    /**
     * Shutdown the system.
     * @since 1.161
     */
    public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
1784
        checkPermission(ADMINISTER);
1785
        LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
K
kohsuke 已提交
1786
                getAuthentication(), req.getRemoteAddr()));
K
kohsuke 已提交
1787 1788 1789 1790 1791 1792 1793 1794 1795
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        PrintWriter w = rsp.getWriter();
        w.println("Shutting down");
        w.close();
        
        System.exit(0);
    }

K
kohsuke 已提交
1796 1797 1798 1799 1800 1801 1802 1803
    /**
     * Gets the {@link Authentication} object that represents the user
     * associated with the current request.
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

1804 1805 1806 1807
    /**
     * Configure the logging level.
     */
    public void doConfigLogger( StaplerRequest req, StaplerResponse rsp, @QueryParameter("name") String name, @QueryParameter("level") String level) throws IOException {
K
kohsuke 已提交
1808
        checkPermission(ADMINISTER);
1809 1810 1811 1812
        Logger.getLogger(name).setLevel(Level.parse(level.toUpperCase()));
        rsp.sendRedirect2("log");
    }

K
kohsuke 已提交
1813 1814
    /**
     * For system diagnostics.
K
kohsuke 已提交
1815
     * Run arbitrary Groovy script.
K
kohsuke 已提交
1816 1817
     */
    public void doScript( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1818 1819
        // ability to run arbitrary script is dangerous
        checkPermission(ADMINISTER);
K
kohsuke 已提交
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840

        String text = req.getParameter("script");
        if(text!=null) {
            GroovyShell shell = new GroovyShell();

            StringWriter out = new StringWriter();
            PrintWriter pw = new PrintWriter(out);
            shell.setVariable("out", pw);
            try {
                Object output = shell.evaluate(text);
                if(output!=null)
                pw.println("Result: "+output);
            } catch (Throwable t) {
                t.printStackTrace(pw);
            }
            req.setAttribute("output",out);
        }

        req.getView(this,"_script.jelly").forward(req,rsp);
    }

K
kohsuke 已提交
1841 1842 1843 1844 1845 1846 1847
    /**
     * 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 已提交
1848 1849 1850
    /**
     * Changes the icon size by changing the cookie
     */
K
kohsuke 已提交
1851 1852 1853 1854
    public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        String qs = req.getQueryString();
        if(!ICON_SIZE.matcher(qs).matches())
            throw new ServletException();
1855 1856 1857
        Cookie cookie = new Cookie("iconSize", qs);
        cookie.setMaxAge(/* ~4 mo. */9999999); // #762
        rsp.addCookie(cookie);
K
kohsuke 已提交
1858 1859 1860
        String ref = req.getHeader("Referer");
        if(ref==null)   ref=".";
        rsp.sendRedirect2(ref);
K
kohsuke 已提交
1861 1862
    }

K
kohsuke 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
    public void doFingerprintCleanup( StaplerRequest req, StaplerResponse rsp ) throws IOException {
        FingerprintCleanupThread.invoke();
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.setContentType("text/plain");
        rsp.getWriter().println("Invoked");
    }

    public void doWorkspaceCleanup( StaplerRequest req, StaplerResponse rsp ) throws IOException {
        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
        new FormFieldValidator(req,rsp,true) {
            public void check() throws IOException, ServletException {
                File f = getFileParameter("value");
                if(f.isDirectory()) {// OK
                    ok();
                } else {// nope
                    if(f.exists()) {
                        error(f+" is not a directory");
                    } else {
                        error("No such directory: "+f);
                    }
                }
            }
        }.process();
    }

    /**
     * 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()) {
                    error(f+" is not a directory");
                    return;
                }

                File toolsJar = new File(f,"lib/tools.jar");
1912
                File mac = new File(f,"lib/dt.jar");
K
kohsuke 已提交
1913
                if(!toolsJar.exists() && !mac.exists()) {
K
kohsuke 已提交
1914 1915 1916 1917 1918 1919 1920 1921 1922
                    error(f+" doesn't look like a JDK directory");
                    return;
                }

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

K
kohsuke 已提交
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
    /**
     * 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
                        errorWithMarkup(
                            "java is not in your PATH. Maybe you need to" +
                            "<a href='"+request.getContextPath()+"/configure'>configure JDKs</a>?");
                }
            }
        }.process();
    }

K
kohsuke 已提交
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
    /**
     * 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.
        new FormFieldValidator(req,rsp,true) {
            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
                    error("Job named "+job+" already exists");
            }
        }.process();
    }

1969 1970 1971 1972 1973 1974 1975 1976
    /**
     * 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.
     */
1977
    public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
1978
        String path = req.getRestOfPath();
1979 1980 1981 1982 1983 1984
        // 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);

1985 1986 1987
        int idx = path.lastIndexOf('.');
        String extension = path.substring(idx+1);
        if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
1988 1989 1990 1991
            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);
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
                return;
            }
        }
        rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

    /**
     * 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(
2003
        "js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
2004 2005
    ));

K
kohsuke 已提交
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021

    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 已提交
2022
        for( AbstractProject p : getAllItems(AbstractProject.class) ) {
K
kohsuke 已提交
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
            SCM scm = p.getScm();
            if (scm instanceof CVSSCM) {
                CVSSCM cvsscm = (CVSSCM) scm;
                r.add(cvsscm.getCvsRoot());
            }
        }

        return r;
    }

2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
    /**
     * Rebuilds the dependency map.
     */
    public void rebuildDependencyGraph() {
        dependencyGraph = new DependencyGraph();
    }

    public DependencyGraph getDependencyGraph() {
        return dependencyGraph;
    }

K
kohsuke 已提交
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
    /**
     * 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 已提交
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
    public Object getTarget() {
        String rest = Stapler.getCurrentRequest().getRestOfPath();
        if(rest.startsWith("/login")
        || rest.startsWith("/logout")
        || rest.startsWith("/securityRealm"))
            return this;    // URLs that are always visible without READ permission
        
        checkPermission(READ);
        return this;
    }

K
kohsuke 已提交
2066 2067 2068 2069 2070
    public static final class MasterComputer extends Computer {
        private MasterComputer() {
            super(Hudson.getInstance());
        }

K
kohsuke 已提交
2071 2072 2073 2074 2075 2076 2077
        @Override
        public String getDisplayName() {
            return "master";
        }

        @Override
        public String getCaption() {
2078
            return "Master";
K
kohsuke 已提交
2079 2080
        }

K
kohsuke 已提交
2081 2082 2083 2084
        public String getUrl() {
            return "computer/(master)/";
        }

K
kohsuke 已提交
2085 2086 2087 2088 2089
        @Override
        public VirtualChannel getChannel() {
            return localChannel;
        }

K
kohsuke 已提交
2090 2091 2092 2093
        public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
            return logRecords;
        }

K
kohsuke 已提交
2094 2095 2096
        public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            // this computer never returns null from channel, so
            // this method shall never be invoked.
2097
            rsp.sendError(SC_NOT_FOUND);
K
kohsuke 已提交
2098 2099
        }

2100 2101 2102 2103
        public void launch() {
            // noop
        }

K
kohsuke 已提交
2104 2105 2106 2107 2108 2109
        /**
         * {@link LocalChannel} instance that can be used to execute programs locally.
         */
        public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
    }

2110 2111 2112 2113
    /**
     * @deprecated
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
2114 2115 2116 2117
    public static boolean adminCheck() throws IOException {
        return adminCheck(Stapler.getCurrentRequest(), Stapler.getCurrentResponse());
    }

2118 2119 2120 2121
    /**
     * @deprecated
     *      Use {@link #checkPermission(Permission)}
     */
K
kohsuke 已提交
2122
    public static boolean adminCheck(StaplerRequest req,StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
2123 2124 2125 2126 2127 2128
        if (isAdmin(req)) return true;

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

K
kohsuke 已提交
2129 2130 2131
    /**
     * Checks if the current user (for which we are processing the current request)
     * has the admin access.
2132 2133 2134
     *
     * @deprecated
     *      Define a custom {@link Permission} and check against ACL.
K
kohsuke 已提交
2135
     */
K
kohsuke 已提交
2136
    public static boolean isAdmin() {
2137 2138
        return !getInstance().isUseSecurity()
            || Hudson.getInstance().getACL().hasPermission(Permission.FULL_CONTROL);
K
kohsuke 已提交
2139 2140
    }

2141 2142 2143 2144
    /**
     * @deprecated
     *      Define a custom {@link Permission} and check against ACL.
     */
K
kohsuke 已提交
2145
    public static boolean isAdmin(StaplerRequest req) {
2146
        return isAdmin();
K
kohsuke 已提交
2147 2148 2149 2150 2151
    }

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

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

2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
    /**
     * 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(
        0, Runtime.getRuntime().availableProcessors() * 2,
        5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory());



2170 2171 2172 2173 2174
    /**
     * Version number of this Hudson.
     */
    public static String VERSION;

2175 2176 2177 2178 2179 2180 2181
    /**
     * Prefix to static resources like images and javascripts in the war file.
     * Either "" or strings like "/static/VERSION", which avoids Hudson to pick up
     * stale cache when the user upgrades to a different version. 
     */
    public static String RESOURCE_PATH;

2182 2183 2184 2185 2186 2187 2188
    /**
     * 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.
     */
    public static String VIEW_RESOURCE_PATH;

2189 2190
    public static boolean parallelLoad = Boolean.getBoolean(Hudson.class.getName()+".parallelLoad");

2191 2192 2193 2194 2195
    /**
     * True to enable the new security implementation.
     */
    public static boolean newSecurity = Boolean.getBoolean("SECURITY");

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

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

2200
    public static final Permission ADMINISTER = new Permission(Hudson.class,"Administer", Permission.FULL_CONTROL);
K
kohsuke 已提交
2201
    public static final Permission READ = new Permission(Hudson.class,"Read", Permission.READ);
K
kohsuke 已提交
2202

K
kohsuke 已提交
2203 2204 2205 2206
    static {
        XSTREAM.alias("hudson",Hudson.class);
        XSTREAM.alias("slave",Slave.class);
        XSTREAM.alias("jdk",JDK.class);
2207 2208 2209
        // for backward compatibility with <1.75, recognize the tag name "view" as well.
        XSTREAM.alias("view", ListView.class);
        XSTREAM.alias("listView", ListView.class);
2210 2211
        // this seems to be necessary to force registration of converter early enough
        Mode.class.getEnumConstants();
K
kohsuke 已提交
2212 2213
    }
}