AbstractProject.java 58.3 KB
Newer Older
K
kohsuke 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * The MIT License
 * 
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot, Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts, id:cactusman
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
24 25
package hudson.model;

K
kohsuke 已提交
26
import hudson.AbortException;
27
import hudson.FeedAdapter;
28
import hudson.FilePath;
29
import hudson.Launcher;
30
import hudson.Util;
31
import hudson.cli.declarative.CLIMethod;
K
kohsuke 已提交
32
import hudson.slaves.WorkspaceList;
M
mdonohue 已提交
33
import hudson.model.Cause.LegacyCodeCause;
34
import hudson.model.Cause.UserCause;
35
import hudson.model.Cause.RemoteCause;
36 37 38
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.RunMap.Constructor;
39
import hudson.model.Queue.WaitingItem;
K
kohsuke 已提交
40
import hudson.model.Queue.Executable;
41
import hudson.model.queue.CauseOfBlockage;
K
kohsuke 已提交
42
import hudson.scm.ChangeLogSet;
K
kohsuke 已提交
43
import hudson.scm.ChangeLogSet.Entry;
44
import hudson.scm.NullSCM;
45
import hudson.scm.SCM;
K
kohsuke 已提交
46
import hudson.scm.SCMS;
47 48 49 50
import hudson.scm.PollingResult;
import hudson.scm.SCMRevisionState;
import static hudson.scm.PollingResult.NO_CHANGES;
import static hudson.scm.PollingResult.BUILD_NOW;
J
jbq 已提交
51
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
52
import hudson.security.Permission;
53
import hudson.tasks.BuildStep;
J
jbq 已提交
54
import hudson.tasks.BuildTrigger;
55
import hudson.tasks.Mailer;
56
import hudson.tasks.Publisher;
57
import hudson.tasks.BuildStepDescriptor;
K
kohsuke 已提交
58
import hudson.tasks.BuildWrapperDescriptor;
K
kohsuke 已提交
59
import hudson.triggers.SCMTrigger;
60
import hudson.triggers.Trigger;
61
import hudson.triggers.TriggerDescriptor;
62
import hudson.util.DescribableList;
63
import hudson.util.EditDistance;
S
 
shinodkm 已提交
64
import hudson.util.FormValidation;
K
kohsuke 已提交
65 66 67 68 69 70
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
S
 
shinodkm 已提交
71
import org.kohsuke.stapler.QueryParameter;
72 73 74
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.ForwardToView;
75

K
kohsuke 已提交
76
import javax.servlet.ServletException;
77
import java.io.File;
78
import java.io.IOException;
K
kohsuke 已提交
79
import java.lang.reflect.InvocationTargetException;
K
kohsuke 已提交
80
import java.util.ArrayList;
81
import java.util.Arrays;
82
import java.util.Calendar;
83
import java.util.Collection;
J
jbq 已提交
84
import java.util.Collections;
85
import java.util.Comparator;
J
jbq 已提交
86
import java.util.HashSet;
87 88
import java.util.List;
import java.util.Map;
J
jbq 已提交
89
import java.util.Set;
90 91 92
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
K
kohsuke 已提交
93
import java.util.concurrent.Future;
94 95
import java.util.logging.Level;
import java.util.logging.Logger;
96 97 98

/**
 * Base implementation of {@link Job}s that build software.
99
 *
100
 * For now this is primarily the common part of {@link Project} and MavenModule.
101
 *
102 103 104
 * @author Kohsuke Kawaguchi
 * @see AbstractBuild
 */
105
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
106

107
    /**
108 109 110
     * {@link SCM} associated with the project.
     * To allow derived classes to link {@link SCM} config to elsewhere,
     * access to this variable should always go through {@link #getScm()}.
111
     */
K
kohsuke 已提交
112
    private volatile SCM scm = new NullSCM();
113

114 115 116 117 118
    /**
     * State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.
     */
    private volatile transient SCMRevisionState pollingBaseline = null;

119 120 121
    /**
     * All the builds keyed by their build number.
     */
122
    protected transient /*almost final*/ RunMap<R> builds = new RunMap<R>();
123 124 125 126

    /**
     * The quiet period. Null to delegate to the system default.
     */
K
kohsuke 已提交
127
    private volatile Integer quietPeriod = null;
S
 
shinodkm 已提交
128 129
    
    /**
130
     * The retry count. Null to delegate to the system default.
S
 
shinodkm 已提交
131
     */
132
    private volatile Integer scmCheckoutRetryCount = null;
133 134

    /**
135 136 137 138 139 140 141
     * If this project is configured to be only built on a certain label,
     * this value will be set to that label.
     *
     * For historical reasons, this is called 'assignedNode'. Also for
     * a historical reason, null to indicate the affinity
     * with the master node.
     *
142
     * @see #canRoam
143 144 145 146 147
     */
    private String assignedNode;

    /**
     * True if this project can be built on any node.
148
     *
149
     * <p>
150 151
     * This somewhat ugly flag combination is so that we can migrate
     * existing Hudson installations nicely.
152
     */
K
kohsuke 已提交
153
    private volatile boolean canRoam;
154 155 156 157

    /**
     * True to suspend new builds.
     */
K
kohsuke 已提交
158
    protected volatile boolean disabled;
159

160 161 162 163 164 165
    /**
     * True to keep builds of this project in queue when upstream projects are
     * building. False by default to keep from breaking existing behavior.
     */
    protected volatile boolean blockBuildWhenUpstreamBuilding = false;

166
    /**
167 168 169
     * Identifies {@link JDK} to be used.
     * Null if no explicit configuration is required.
     *
170
     * <p>
171 172 173
     * Can't store {@link JDK} directly because {@link Hudson} and {@link Project}
     * are saved independently.
     *
174 175
     * @see Hudson#getJDK(String)
     */
K
kohsuke 已提交
176
    private volatile String jdk;
177

178
    /**
M
mindless 已提交
179
     * @deprecated since 2007-01-29.
180 181
     */
    private transient boolean enableRemoteTrigger;
182

K
kohsuke 已提交
183
    private volatile BuildAuthorizationToken authToken = null;
184

185 186 187
    /**
     * List of all {@link Trigger}s for this project.
     */
188
    protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
189

190 191
    /**
     * {@link Action}s contributed from subsidiary objects associated with
192 193 194 195
     * {@link AbstractProject}, such as from triggers, builders, publishers, etc.
     *
     * We don't want to persist them separately, and these actions
     * come and go as configuration change, so it's kept separate.
196
     */
197
    protected transient /*final*/ List<Action> transientActions = new Vector<Action>();
198

K
kohsuke 已提交
199 200
    private boolean concurrentBuild;

201
    protected AbstractProject(ItemGroup parent, String name) {
202
        super(parent,name);
203

K
kohsuke 已提交
204
        if(!Hudson.getInstance().getNodes().isEmpty()) {
205
            // if a new job is configured with Hudson that already has slave nodes
206 207 208 209 210
            // make it roamable by default
            canRoam = true;
        }
    }

211
    @Override
212
    public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
213
        super.onLoad(parent, name);
214 215

        this.builds = new RunMap<R>();
216
        this.builds.load(this,new Constructor<R>() {
217 218 219 220 221
            public R create(File dir) throws IOException {
                return loadBuild(dir);
            }
        });

222
        if(triggers==null)
223
            // it didn't exist in < 1.28
224
            triggers = new Vector<Trigger<?>>();
225
        for (Trigger t : triggers)
226
            t.start(this,false);
227 228
        if(scm==null)
            scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
229

230 231
        if(transientActions==null)
            transientActions = new Vector<Action>();    // happens when loaded from disk
232
        updateTransientActions();
233 234
    }

235
    @Override
236
    protected void performDelete() throws IOException, InterruptedException {
K
kohsuke 已提交
237 238
        // prevent a new build while a delete operation is in progress
        makeDisabled(true);
239
        FilePath ws = getWorkspace();
240
        if(ws!=null) {
K
NPE fix  
kohsuke 已提交
241 242 243 244
            Node on = getLastBuiltOn();
            getScm().processWorkspaceBeforeDeletion(this, ws, on);
            if(on!=null)
                on.getFileSystemProvisioner().discardWorkspace(this,ws);
245
        }
K
kohsuke 已提交
246 247 248
        super.performDelete();
    }

K
kohsuke 已提交
249 250
    /**
     * Does this project perform concurrent builds?
K
kohsuke 已提交
251
     * @since 1.319
K
kohsuke 已提交
252
     */
K
kohsuke 已提交
253
    @Exported
K
kohsuke 已提交
254 255 256 257 258 259 260 261 262
    public boolean isConcurrentBuild() {
        return Hudson.CONCURRENT_BUILD && concurrentBuild;
    }

    public void setConcurrentBuild(boolean b) throws IOException {
        concurrentBuild = b;
        save();
    }

263
    /**
264 265
     * If this project is configured to be always built on this node,
     * return that {@link Node}. Otherwise null.
266
     */
267
    public Label getAssignedLabel() {
268
        if(canRoam)
269 270
            return null;

271
        if(assignedNode==null)
272 273
            return Hudson.getInstance().getSelfLabel();
        return Hudson.getInstance().getLabel(assignedNode);
274 275
    }

K
kohsuke 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    /**
     * Sets the assigned label.
     */
    public void setAssignedLabel(Label l) throws IOException {
        if(l==null) {
            canRoam = true;
            assignedNode = null;
        } else {
            canRoam = false;
            if(l==Hudson.getInstance().getSelfLabel())  assignedNode = null;
            else                                        assignedNode = l.getName();
        }
        save();
    }

291
    /**
292 293
     * Get the term used in the UI to represent this kind of {@link AbstractProject}.
     * Must start with a capital letter.
294 295 296
     */
    @Override
    public String getPronoun() {
297
        return Messages.AbstractProject_Pronoun();
298 299
    }

300 301 302 303 304
    /**
     * Returns the root project value.
     *
     * @return the root project value.
     */
305
    public AbstractProject getRootProject() {
306 307 308 309 310 311 312
        if (this.getParent() instanceof Hudson) {
            return this;
        } else {
            return ((AbstractProject) this.getParent()).getRootProject();
        }
    }

313 314
    /**
     * Gets the directory where the module is checked out.
315 316 317
     *
     * @return
     *      null if the workspace is on a slave that's not connected.
K
kohsuke 已提交
318
     * @deprecated as of 1.319
K
kohsuke 已提交
319 320 321 322 323
     *      To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.
     *      For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called
     *      from {@link Executor}, and otherwise the workspace of the last build.
     *
     *      <p>
324
     *      If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
K
kohsuke 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
     *      If you are calling this method to serve a file from the workspace, doing a form validation, etc., then
     *      use {@link #getSomeWorkspace()}
     */
    public final FilePath getWorkspace() {
        Executor e = Executor.currentExecutor();
        if(e!=null) {
            Executable exe = e.getCurrentExecutable();
            if (exe instanceof AbstractBuild) {
                AbstractBuild b = (AbstractBuild) exe;
                if(b.getProject()==this)
                    return b.getWorkspace();
            }
        }
        R lb = getLastBuild();
        if(lb!=null)    return lb.getWorkspace();
        return null;
    }

    /**
     * Gets a workspace for some build of this project.
     *
     * <p>
     * This is useful for obtaining a workspace for the purpose of form field validation, where exactly
     * which build the workspace belonged is less important. The implementation makes a cursory effort
     * to find some workspace.
     *
     * @return
     *      null if there's no available workspace.
K
kohsuke 已提交
353
     * @since 1.319
354
     */
K
kohsuke 已提交
355
    public final FilePath getSomeWorkspace() {
356 357 358 359 360 361 362 363 364 365
        R b = getSomeBuildWithWorkspace();
        return b!=null ? b.getWorkspace() : null;
    }

    /**
     * Gets some build that has a live workspace.
     *
     * @return null if no such build exists.
     */
    public final R getSomeBuildWithWorkspace() {
K
kohsuke 已提交
366 367 368
        int cnt=0;
        for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
            FilePath ws = b.getWorkspace();
369
            if (ws!=null)   return b;
K
kohsuke 已提交
370 371 372
        }
        return null;
    }
373

374 375 376
    /**
     * Returns the root directory of the checked-out module.
     * <p>
377 378
     * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
     * and so on exists.
K
kohsuke 已提交
379
     *
K
kohsuke 已提交
380
     * @deprecated as of 1.319
K
kohsuke 已提交
381
     *      See {@link #getWorkspace()} for a migration strategy.
382 383
     */
    public FilePath getModuleRoot() {
K
kohsuke 已提交
384
        FilePath ws = getWorkspace();
385
        if(ws==null)    return null;
K
kohsuke 已提交
386
        return getScm().getModuleRoot(ws);
387 388
    }

S
stephenconnolly 已提交
389 390 391 392 393 394
    /**
     * Returns the root directories of all checked-out modules.
     * <p>
     * Some SCMs support checking out multiple modules into the same workspace.
     * In these cases, the returned array will have a length greater than one.
     * @return The roots of all modules checked out from the SCM.
K
kohsuke 已提交
395
     *
K
kohsuke 已提交
396
     * @deprecated as of 1.319
K
kohsuke 已提交
397
     *      See {@link #getWorkspace()} for a migration strategy.
S
stephenconnolly 已提交
398 399 400 401 402
     */
    public FilePath[] getModuleRoots() {
        return getScm().getModuleRoots(getWorkspace());
    }

403
    public int getQuietPeriod() {
404
        return quietPeriod!=null ? quietPeriod : Hudson.getInstance().getQuietPeriod();
405
    }
S
 
shinodkm 已提交
406
    
407 408
    public int getScmCheckoutRetryCount() {
        return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Hudson.getInstance().getScmCheckoutRetryCount();
S
 
shinodkm 已提交
409
    }
410 411 412

    // ugly name because of EL
    public boolean getHasCustomQuietPeriod() {
413
        return quietPeriod!=null;
414
    }
K
kohsuke 已提交
415 416 417 418

    /**
     * Sets the custom quiet period of this project, or revert to the global default if null is given. 
     */
419
    public void setQuietPeriod(Integer seconds) throws IOException {
K
kohsuke 已提交
420 421 422
        this.quietPeriod = seconds;
        save();
    }
S
 
shinodkm 已提交
423
    
424
    public boolean hasCustomScmCheckoutRetryCount(){
425
        return scmCheckoutRetryCount != null;
S
 
shinodkm 已提交
426
    }
427

428
    public boolean isBuildable() {
K
kohsuke 已提交
429
        return !isDisabled();
430 431
    }

432
    /**
433 434
     * Used in <tt>sidepanel.jelly</tt> to decide whether to display
     * the config/delete/build links.
435 436 437 438 439
     */
    public boolean isConfigurable() {
        return true;
    }

440
    public boolean blockBuildWhenUpstreamBuilding() {
441
        return blockBuildWhenUpstreamBuilding;
442 443
    }

444
    public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
445 446
        blockBuildWhenUpstreamBuilding = b;
        save();
447 448
    }

449 450 451
    public boolean isDisabled() {
        return disabled;
    }
S
 
shinodkm 已提交
452 453 454 455 456
    
    /**
     * Validates the retry count Regex
     */
    public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
457 458 459 460 461 462 463
        // retry count is optional so this is ok
        if(value == null || value.trim().equals(""))
            return FormValidation.ok();
        if (!value.matches("[0-9]*")) {
            return FormValidation.error("Invalid retry count");
        } 
        return FormValidation.ok();
S
 
shinodkm 已提交
464
    }
465

466 467 468 469
    /**
     * Marks the build as disabled.
     */
    public void makeDisabled(boolean b) throws IOException {
470
        if(disabled==b)     return; // noop
471
        this.disabled = b;
K
bug fix  
kohsuke 已提交
472 473
        if(b)
            Hudson.getInstance().getQueue().cancel(this);
474 475 476
        save();
    }

477 478 479 480 481 482 483 484 485 486
    @CLIMethod(name="disable-job")
    public void disable() throws IOException {
        makeDisabled(true);
    }

    @CLIMethod(name="enable-job")
    public void enable() throws IOException {
        makeDisabled(false);
    }

K
kohsuke 已提交
487 488
    @Override
    public BallColor getIconColor() {
489
        if(isDisabled())
490
            return BallColor.DISABLED;
K
kohsuke 已提交
491 492 493
        else
            return super.getIconColor();
    }
494

495
    protected void updateTransientActions() {
496
        synchronized(transientActions) {
497
            transientActions.clear();
498

499
            for (JobProperty<? super P> p : properties) {
500
                transientActions.addAll(p.getJobActions((P)this));
501
            }
502 503 504

            for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
                transientActions.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
505 506 507
        }
    }

508
    /**
509 510
     * Returns the live list of all {@link Publisher}s configured for this project.
     *
511
     * <p>
512 513
     * This method couldn't be called <tt>getPublishers()</tt> because existing methods
     * in sub-classes return different inconsistent types.
514
     */
515
    public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
516

K
kohsuke 已提交
517 518 519 520 521 522
    @Override
    public void addProperty(JobProperty<? super P> jobProp) throws IOException {
        super.addProperty(jobProp);
        updateTransientActions();
    }

523 524 525 526
    public List<ProminentProjectAction> getProminentActions() {
        List<Action> a = getActions();
        List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
        for (Action action : a) {
527
            if(action instanceof ProminentProjectAction)
528 529 530 531 532
                pa.add((ProminentProjectAction) action);
        }
        return pa;
    }

533
    @Override
534
    public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
535
        super.doConfigSubmit(req,rsp);
536

537 538
        updateTransientActions();

539
        Set<AbstractProject> upstream = Collections.emptySet();
540 541
        if(req.getParameter("pseudoUpstreamTrigger")!=null) {
            upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class));
542 543 544 545 546 547 548 549 550
        }

        // dependency setting might have been changed by the user, so rebuild.
        Hudson.getInstance().rebuildDependencyGraph();

        // reflect the submission of the pseudo 'upstream build trriger'.
        // this needs to be done after we release the lock on 'this',
        // or otherwise we could dead-lock

551
        for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
552 553
            // Don't consider child projects such as MatrixConfiguration:
            if (!p.isConfigurable()) continue;
554
            boolean isUpstream = upstream.contains(p);
555 556 557
            synchronized(p) {
                // does 'p' include us in its BuildTrigger? 
                DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
558
                BuildTrigger trigger = pl.get(BuildTrigger.class);
559 560 561
                List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects();
                if(isUpstream) {
                    if(!newChildProjects.contains(this))
562 563 564 565 566
                        newChildProjects.add(this);
                } else {
                    newChildProjects.remove(this);
                }

567
                if(newChildProjects.isEmpty()) {
568
                    pl.remove(BuildTrigger.class);
569
                } else {
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
                    // here, we just need to replace the old one with the new one,
                    // but there was a regression (we don't know when it started) that put multiple BuildTriggers
                    // into the list.
                    // for us not to lose the data, we need to merge them all.
                    List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
                    BuildTrigger existing;
                    switch (existingList.size()) {
                    case 0:
                        existing = null;
                        break;
                    case 1:
                        existing = existingList.get(0);
                        break;
                    default:
                        pl.removeAll(BuildTrigger.class);
                        Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
                        for (BuildTrigger bt : existingList)
                            combinedChildren.addAll(bt.getChildProjects());
                        existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
                        pl.add(existing);
                        break;
                    }

593 594
                    if(existing!=null && existing.hasSame(newChildProjects))
                        continue;   // no need to touch
595
                    pl.replace(new BuildTrigger(newChildProjects,
596
                        existing==null?Result.SUCCESS:existing.getThreshold()));
597 598 599 600 601 602 603 604 605 606 607
                }
            }
        }

        // notify the queue as the project might be now tied to different node
        Hudson.getInstance().getQueue().scheduleMaintenance();

        // this is to reflect the upstream build adjustments done above
        Hudson.getInstance().rebuildDependencyGraph();
    }

M
mdonohue 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild(Cause)}.  Since 1.283
	 */
    public boolean scheduleBuild() {
    	return scheduleBuild(new LegacyCodeCause());
    }
    
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild(int, Cause)}.  Since 1.283
	 */
    public boolean scheduleBuild(int quietPeriod) {
    	return scheduleBuild(quietPeriod, new LegacyCodeCause());
    }
    
624 625
    /**
     * Schedules a build of this project.
626 627 628 629 630
     *
     * @return
     *      true if the project is actually added to the queue.
     *      false if the queue contained it and therefore the add()
     *      was noop
631
     */
M
mdonohue 已提交
632 633
    public boolean scheduleBuild(Cause c) {
        return scheduleBuild(getQuietPeriod(), c);
K
kohsuke 已提交
634 635
    }

M
mdonohue 已提交
636
    public boolean scheduleBuild(int quietPeriod, Cause c) {
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
        return scheduleBuild(quietPeriod, c, new Action[0]);
    }

    /**
     * Schedules a build.
     *
     * Important: the actions should be persistable without outside references (e.g. don't store
     * references to this project). To provide parameters for a parameterized project, add a ParametersAction. If
     * no ParametersAction is provided for such a project, one will be created with the default parameter values.
     *
     * @param quietPeriod the quiet period to observer
     * @param c the cause for this build which should be recorded
     * @param actions a list of Actions that will be added to the build
     * @return whether the build was actually scheduled
     */
    public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {
653 654 655 656 657 658
        return scheduleBuild2(quietPeriod,c,actions)!=null;
    }

    /**
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
659 660 661
     *
     * @param actions
     *      For the convenience of the caller, this array can contain null, and those will be silently ignored.
662 663
     */
    public Future<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
664
        if (!isBuildable())
665
            return null;
666

K
kohsuke 已提交
667
        List<Action> queueActions = new ArrayList<Action>(Arrays.asList(actions));
668 669 670 671
        if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
            queueActions.add(new ParametersAction(getDefaultParametersValues()));
        }

S
sogabe 已提交
672 673 674 675
        if (c != null) {
            queueActions.add(new CauseAction(c));
        }

676 677 678 679
        WaitingItem i = Hudson.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
        if(i!=null)
            return (Future)i.getFuture();
        return null;
680 681 682 683 684 685
    }

    private List<ParameterValue> getDefaultParametersValues() {
        ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
        ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
        
M
mindless 已提交
686 687 688
        /*
         * This check is made ONLY if someone will call this method even if isParametrized() is false.
         */
689 690 691 692 693 694 695 696 697 698 699 700 701
        if(paramDefProp == null)
            return defValues;
        
        /* Scan for all parameter with an associated default values */
        for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
        {
           ParameterValue defaultValue  = paramDefinition.getDefaultParameterValue();
            
            if(defaultValue != null)
                defValues.add(defaultValue);           
        }
        
        return defValues;
K
kohsuke 已提交
702 703
    }

704
    /**
705 706 707 708
     * Schedules a build, and returns a {@link Future} object
     * to wait for the completion of the build.
     *
     * <p>
709
     * Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
710
     * as deprecated.
711
     */
M
mdonohue 已提交
712
    public Future<R> scheduleBuild2(int quietPeriod) {
713
        return scheduleBuild2(quietPeriod, new LegacyCodeCause());
M
mdonohue 已提交
714 715
    }
    
K
kohsuke 已提交
716
    /**
717 718
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
K
kohsuke 已提交
719
     */
K
kohsuke 已提交
720
    public Future<R> scheduleBuild2(int quietPeriod, Cause c) {
721 722 723
        return scheduleBuild2(quietPeriod, c, new Action[0]);
    }

724 725 726 727
    /**
     * Schedules a polling of this project.
     */
    public boolean schedulePolling() {
728
        if(isDisabled())    return false;
729
        SCMTrigger scmt = getTrigger(SCMTrigger.class);
730
        if(scmt==null)      return false;
731 732 733 734
        scmt.run();
        return true;
    }

735 736 737 738 739
    /**
     * Returns true if the build is in the queue.
     */
    @Override
    public boolean isInQueue() {
740
        return Hudson.getInstance().getQueue().contains(this);
741 742
    }

K
kohsuke 已提交
743 744 745 746 747
    @Override
    public Queue.Item getQueueItem() {
        return Hudson.getInstance().getQueue().getItem(this);
    }

K
kohsuke 已提交
748 749 750
    /**
     * Gets the JDK that this project is configured with, or null.
     */
751
    public JDK getJDK() {
752
        return Hudson.getInstance().getJDK(jdk);
753 754 755 756 757
    }

    /**
     * Overwrites the JDK setting.
     */
K
kohsuke 已提交
758
    public void setJDK(JDK jdk) throws IOException {
759 760 761 762
        this.jdk = jdk.getName();
        save();
    }

763 764
    public BuildAuthorizationToken getAuthToken() {
        return authToken;
765 766 767 768 769 770 771 772 773 774
    }

    public SortedMap<Integer, ? extends R> _getRuns() {
        return builds.getView();
    }

    public void removeRun(R run) {
        this.builds.remove(run);
    }

775 776 777 778 779
    /**
     * Determines Class&lt;R>.
     */
    protected abstract Class<R> getBuildClass();

H
huybrechts 已提交
780
    // keep track of the previous time we started a build
781
    private transient long lastBuildStartTime;
H
huybrechts 已提交
782
    
783 784 785
    /**
     * Creates a new build of this project for immediate execution.
     */
H
huybrechts 已提交
786 787 788 789 790 791 792 793 794 795 796
    protected synchronized R newBuild() throws IOException {
    	// make sure we don't start two builds in the same second
    	// so the build directories will be different too
    	long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
    	if (timeSinceLast < 1000) {
    		try {
				Thread.sleep(1000 - timeSinceLast);
			} catch (InterruptedException e) {
			}
    	}
    	lastBuildStartTime = System.currentTimeMillis();
797
        try {
798
            R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
799 800 801 802 803 804 805
            builds.put(lastBuild);
            return lastBuild;
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
806
            throw handleInvocationTargetException(e);
807 808 809 810
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
811

812
    private IOException handleInvocationTargetException(InvocationTargetException e) {
813
        Throwable t = e.getTargetException();
814 815 816
        if(t instanceof Error)  throw (Error)t;
        if(t instanceof RuntimeException)   throw (RuntimeException)t;
        if(t instanceof IOException)    return (IOException)t;
817 818 819
        throw new Error(t);
    }

820 821 822
    /**
     * Loads an existing build record from disk.
     */
823 824
    protected R loadBuild(File dir) throws IOException {
        try {
825
            return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
826 827 828 829 830
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
831
            throw handleInvocationTargetException(e);
832 833 834 835
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
836

K
kohsuke 已提交
837 838
    /**
     * {@inheritDoc}
839
     *
K
kohsuke 已提交
840 841
     * <p>
     * Note that this method returns a read-only view of {@link Action}s.
842
     * {@link BuildStep}s and others who want to add a project action
843
     * should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.
844 845
     *
     * @see TransientProjectActionFactory
K
kohsuke 已提交
846
     */
847
    @Override
848 849 850 851
    public synchronized List<Action> getActions() {
        // add all the transient actions, too
        List<Action> actions = new Vector<Action>(super.getActions());
        actions.addAll(transientActions);
852
        // return the read only list to cause a failure on plugins who try to add an action here
K
kohsuke 已提交
853
        return Collections.unmodifiableList(actions);
854 855
    }

856 857
    /**
     * Gets the {@link Node} where this project was last built on.
858 859 860 861
     *
     * @return
     *      null if no information is available (for example,
     *      if no build was done yet.)
862 863 864 865
     */
    public Node getLastBuiltOn() {
        // where was it built on?
        AbstractBuild b = getLastBuild();
866
        if(b==null)
867 868 869 870 871
            return null;
        else
            return b.getBuiltOn();
    }

872
    /**
873
     * {@inheritDoc}
874
     *
875
     * <p>
876
     * A project must be blocked if its own previous build is in progress,
877 878
     * or if the blockBuildWhenUpstreamBuilding option is true and an upstream
     * project is building, but derived classes can also check other conditions.
879
     */
880
    public boolean isBuildBlocked() {
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
        return getCauseOfBlockage()!=null;
    }

    public String getWhyBlocked() {
        CauseOfBlockage cb = getCauseOfBlockage();
        return cb!=null ? cb.getShortDescription() : null;
    }

    /**
     * Blocked because the previous build is already in progress.
     */
    public static class BecauseOfBuildInProgress extends CauseOfBlockage {
        private final AbstractBuild<?,?> build;

        public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {
            this.build = build;
897 898
        }

899 900 901 902 903 904 905 906
        public String getShortDescription() {
            Executor e = build.getExecutor();
            String eta = "";
            if (e != null)
                eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
            int lbn = build.getNumber();
            return Messages.AbstractProject_BuildInProgress(lbn, eta);
        }
907 908
    }

909 910 911 912 913 914 915 916 917 918 919 920 921
    /**
     * Because the upstream build is in progress, and we are configured to wait for that.
     */
    public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {
        public final AbstractProject<?,?> up;

        public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {
            this.up = up;
        }

        public String getShortDescription() {
            return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
        }
922 923
    }

924 925 926 927 928 929 930 931 932 933
    public CauseOfBlockage getCauseOfBlockage() {
        if (isBuilding() && !isConcurrentBuild())
            return new BecauseOfBuildInProgress(getLastBuild());
        if (blockBuildWhenUpstreamBuilding()) {
            AbstractProject<?,?> bup = getBuildingUpstream();
            if (bup!=null)
                return new BecauseOfUpstreamBuildInProgress(bup);
        }
        return null;
    }
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950

    /**
     * Returns the project if any of the upstream project (or itself) is either
     * building or is in the queue.
     * <p>
     * This means eventually there will be an automatic triggering of
     * the given project (provided that all builds went smoothly.)
     */
    protected AbstractProject getBuildingUpstream() {
    	DependencyGraph graph = Hudson.getInstance().getDependencyGraph();
        Set<AbstractProject> tups = graph.getTransitiveUpstream(this);
        tups.add(this);
        for (AbstractProject tup : tups) {
            if(tup!=this && (tup.isBuilding() || tup.isInQueue()))
                return tup;
        }
        return null;
951 952 953 954
    }

    public final long getEstimatedDuration() {
        AbstractBuild b = getLastSuccessfulBuild();
955
        if(b==null)     return -1;
956 957

        long duration = b.getDuration();
958
        if(duration==0) return -1;
959 960 961 962

        return duration;
    }

963
    public R createExecutable() throws IOException {
964
        if(isDisabled())    return null;
965
        return newBuild();
966 967
    }

968 969 970 971
    public void checkAbortPermission() {
        checkPermission(AbstractProject.ABORT);
    }

K
kohsuke 已提交
972 973 974 975
    public boolean hasAbortPermission() {
        return hasPermission(AbstractProject.ABORT);
    }

976 977
    /**
     * Gets the {@link Resource} that represents the workspace of this project.
978
     * Useful for locking and mutual exclusion control.
K
kohsuke 已提交
979
     *
K
kohsuke 已提交
980
     * @deprecated as of 1.319
K
kohsuke 已提交
981 982 983 984 985 986 987
     *      Projects no longer have a fixed workspace, ands builds will find an available workspace via
     *      {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)
     *      So a {@link Resource} representation for a workspace at the project level no longer makes sense.
     *
     *      <p>
     *      If you need to lock a workspace while you do some computation, see the source code of
     *      {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.
988 989
     */
    public Resource getWorkspaceResource() {
990
        return new Resource(getFullDisplayName()+" workspace");
991 992 993 994 995 996
    }

    /**
     * List of necessary resources to perform the build of this project.
     */
    public ResourceList getResourceList() {
997
        final Set<ResourceActivity> resourceActivities = getResourceActivities();
998
        final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
999 1000 1001 1002 1003 1004 1005 1006 1007 1008
        for (ResourceActivity activity : resourceActivities) {
            if (activity != this && activity != null) {
                // defensive infinite recursion and null check
                resourceLists.add(activity.getResourceList());
            }
        }
        return ResourceList.union(resourceLists);
    }

    /**
1009 1010
     * Set of child resource activities of the build of this project (override in child projects).
     * @return The set of child resource activities of the build of this project.
1011 1012
     */
    protected Set<ResourceActivity> getResourceActivities() {
K
kohsuke 已提交
1013
        return Collections.emptySet();
1014 1015
    }

1016
    public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
1017
        SCM scm = getScm();
1018 1019
        if(scm==null)
            return true;    // no SCM
1020

1021 1022
        FilePath workspace = build.getWorkspace();
        workspace.mkdirs();
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        
        boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
        calcPollingBaseline(build, launcher, listener);
        return r;
    }

    /**
     * Pushes the baseline up to the newly checked out revision.
     */
    private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
        SCMRevisionState baseline = build.getAction(SCMRevisionState.class);
        if (baseline==null) {
            try {
                baseline = safeCalcRevisionsFromBuild(build, launcher, listener);
            } catch (AbstractMethodError e) {
                baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling
            }
            if (baseline!=null)
                build.addAction(baseline);
        }
        pollingBaseline = baseline;
    }

    /**
     * For reasons I don't understand, if I inline this method, AbstractMethodError escapes try/catch block.
     */
    private SCMRevisionState safeCalcRevisionsFromBuild(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
        return getScm().calcRevisionsFromBuild(build, launcher, listener);
1051 1052 1053 1054
    }

    /**
     * Checks if there's any update in SCM, and returns true if any is found.
1055
     *
1056 1057
     * @deprecated as of 1.346
     *      Use {@link #poll(TaskListener)} instead.
1058
     */
1059
    public boolean pollSCMChanges( TaskListener listener ) {
1060 1061 1062 1063 1064 1065 1066
        return poll(listener).hasChanges();
    }

    /**
     * Checks if there's any update in SCM, and returns true if any is found.
     *
     * <p>
1067 1068
     * The implementation is responsible for ensuring mutual exclusion between polling and builds
     * if necessary.
1069 1070 1071 1072
     *
     * @since 1.345
     */
    public PollingResult poll( TaskListener listener ) {
1073
        SCM scm = getScm();
1074
        if(scm==null) {
K
i18n  
kohsuke 已提交
1075
            listener.getLogger().println(Messages.AbstractProject_NoSCM());
1076
            return NO_CHANGES;
1077
        }
1078
        if(isDisabled()) {
K
i18n  
kohsuke 已提交
1079
            listener.getLogger().println(Messages.AbstractProject_Disabled());
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
            return NO_CHANGES;
        }

        R lb = getLastBuild();
        if (lb==null) {
            listener.getLogger().println("No builds have done yet. Scheduling a new one");
            return BUILD_NOW;
        }

        if (pollingBaseline==null) {
            R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this
            for (R r=lb; r!=null; r=r.getPreviousBuild()) {
                SCMRevisionState s = r.getAction(SCMRevisionState.class);
                if (s!=null) {
                    pollingBaseline = s;
                    break;
                }
                if (r==success) break;  // searched far enough
            }
            // NOTE-NO-BASELINE:
            // if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline
            // as action, so we need to compute it. This happens later.
1102 1103 1104
        }

        try {
K
kohsuke 已提交
1105 1106
            if(scm.requiresWorkspaceForPolling()) {
                // lock the workspace of the last build
1107
                FilePath ws=lb.getWorkspace();
K
kohsuke 已提交
1108 1109 1110 1111 1112 1113 1114 1115

                if (ws==null || !ws.exists()) {
                    // workspace offline. build now, or nothing will ever be built
                    Label label = getAssignedLabel();
                    if (label != null && label.isSelfLabel()) {
                        // if the build is fixed on a node, then attempting a build will do us
                        // no good. We should just wait for the slave to come back.
                        listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
1116
                        return NO_CHANGES;
K
kohsuke 已提交
1117
                    }
1118 1119 1120
                    listener.getLogger().println( ws==null
                        ? Messages.AbstractProject_WorkspaceOffline()
                        : Messages.AbstractProject_NoWorkspace());
K
kohsuke 已提交
1121
                    listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace());
1122
                    return BUILD_NOW;
K
kohsuke 已提交
1123 1124
                } else {
                    WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
1125
                    // if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
1126 1127 1128 1129 1130
                    // this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
                    //
                    // OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
                    // so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
                    // by having multiple workspaces
1131
                    WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
1132
                    Launcher launcher = ws.createLauncher(listener);
K
kohsuke 已提交
1133 1134
                    try {
                        LOGGER.fine("Polling SCM changes of " + getName());
1135 1136 1137 1138 1139
                        if (pollingBaseline==null) // see NOTE-NO-BASELINE above
                            calcPollingBaseline(lb,launcher,listener);
                        PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);
                        pollingBaseline = r.remote;
                        return r;
K
kohsuke 已提交
1140
                    } finally {
1141
                        lease.release();
K
kohsuke 已提交
1142
                    }
K
kohsuke 已提交
1143
                }
K
kohsuke 已提交
1144 1145 1146
            } else {
                // polling without workspace
                LOGGER.fine("Polling SCM changes of " + getName());
1147 1148 1149 1150 1151 1152

                if (pollingBaseline==null) // see NOTE-NO-BASELINE above
                    calcPollingBaseline(lb,null,listener);
                PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
                pollingBaseline = r.remote;
                return r;
K
kohsuke 已提交
1153
            }
1154
        } catch (AbortException e) {
K
i18n  
kohsuke 已提交
1155
            listener.fatalError(Messages.AbstractProject_Aborted());
1156
            LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
1157
            return NO_CHANGES;
1158 1159
        } catch (IOException e) {
            e.printStackTrace(listener.fatalError(e.getMessage()));
1160
            return NO_CHANGES;
1161
        } catch (InterruptedException e) {
1162
            e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
1163
            return NO_CHANGES;
1164 1165 1166
        }
    }

1167 1168
    /**
     * Returns true if this user has made a commit to this project.
1169
     *
1170 1171 1172
     * @since 1.191
     */
    public boolean hasParticipant(User user) {
1173 1174
        for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
            if(build.hasParticipant(user))
1175 1176 1177 1178
                return true;
        return false;
    }

1179
    @Exported
1180 1181 1182 1183 1184 1185 1186 1187
    public SCM getScm() {
        return scm;
    }

    public void setScm(SCM scm) {
        this.scm = scm;
    }

1188 1189 1190
    /**
     * Adds a new {@link Trigger} to this {@link Project} if not active yet.
     */
1191
    public void addTrigger(Trigger<?> trigger) throws IOException {
1192
        addToList(trigger,triggers);
1193 1194
    }

1195
    public void removeTrigger(TriggerDescriptor trigger) throws IOException {
1196
        removeFromList(trigger,triggers);
1197 1198
    }

1199 1200 1201 1202
    protected final synchronized <T extends Describable<T>>
    void addToList( T item, List<T> collection ) throws IOException {
        for( int i=0; i<collection.size(); i++ ) {
            if(collection.get(i).getDescriptor()==item.getDescriptor()) {
1203
                // replace
1204
                collection.set(i,item);
1205 1206 1207 1208 1209 1210 1211 1212 1213
                save();
                return;
            }
        }
        // add
        collection.add(item);
        save();
    }

1214 1215 1216 1217
    protected final synchronized <T extends Describable<T>>
    void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
        for( int i=0; i< collection.size(); i++ ) {
            if(collection.get(i).getDescriptor()==item) {
1218 1219 1220 1221 1222 1223 1224 1225
                // found it
                collection.remove(i);
                save();
                return;
            }
        }
    }

1226 1227
    public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
        return (Map)Descriptor.toMap(triggers);
1228 1229
    }

1230
    /**
1231
     * Gets the specific trigger, or null if the propert is not configured for this job.
1232 1233 1234
     */
    public <T extends Trigger> T getTrigger(Class<T> clazz) {
        for (Trigger p : triggers) {
1235
            if(clazz.isInstance(p))
1236 1237 1238 1239 1240
                return clazz.cast(p);
        }
        return null;
    }

1241 1242 1243 1244 1245
//
//
// fingerprint related
//
//
1246 1247 1248 1249 1250 1251
    /**
     * True if the builds of this project produces {@link Fingerprint} records.
     */
    public abstract boolean isFingerprintConfigured();

    /**
1252 1253
     * Gets the other {@link AbstractProject}s that should be built
     * when a build of this project is completed.
1254
     */
K
kohsuke 已提交
1255
    @Exported
1256 1257 1258
    public final List<AbstractProject> getDownstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getDownstream(this);
    }
1259

K
kohsuke 已提交
1260
    @Exported
1261 1262
    public final List<AbstractProject> getUpstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getUpstream(this);
K
kohsuke 已提交
1263 1264
    }

K
kohsuke 已提交
1265
    /**
1266 1267 1268 1269
     * Returns only those upstream projects that defines {@link BuildTrigger} to this project.
     * This is a subset of {@link #getUpstreamProjects()}
     *
     * @return A List of upstream projects that has a {@link BuildTrigger} to this project.
K
kohsuke 已提交
1270 1271 1272
     */
    public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
        ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
1273 1274
        for (AbstractProject<?,?> ap : getUpstreamProjects()) {
            BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
1275 1276 1277
            if (buildTrigger != null)
                if (buildTrigger.getChildProjects().contains(this))
                    result.add(ap);
1278
        }        
K
kohsuke 已提交
1279
        return result;
1280 1281
    }    
    
K
kohsuke 已提交
1282 1283
    /**
     * Gets all the upstream projects including transitive upstream projects.
1284
     *
K
kohsuke 已提交
1285 1286 1287
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveUpstreamProjects() {
1288
        return Hudson.getInstance().getDependencyGraph().getTransitiveUpstream(this);
K
kohsuke 已提交
1289 1290 1291
    }

    /**
1292 1293
     * Gets all the downstream projects including transitive downstream projects.
     *
K
kohsuke 已提交
1294 1295 1296
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveDownstreamProjects() {
1297
        return Hudson.getInstance().getDependencyGraph().getTransitiveDownstream(this);
1298 1299 1300 1301 1302
    }

    /**
     * Gets the dependency relationship map between this project (as the source)
     * and that project (as the sink.)
1303 1304 1305 1306
     *
     * @return
     *      can be empty but not null. build number of this project to the build
     *      numbers of that project.
1307 1308
     */
    public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
1309
        TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
1310 1311 1312 1313 1314 1315 1316 1317 1318

        checkAndRecord(that, r, this.getBuilds());
        // checkAndRecord(that, r, that.getBuilds());

        return r;
    }

    /**
     * Helper method for getDownstreamRelationship.
1319 1320
     *
     * For each given build, find the build number range of the given project and put that into the map.
1321
     */
1322
    private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
1323 1324
        for (R build : builds) {
            RangeSet rs = build.getDownstreamRelationship(that);
1325
            if(rs==null || rs.isEmpty())
1326 1327 1328 1329 1330
                continue;

            int n = build.getNumber();

            RangeSet value = r.get(n);
1331 1332
            if(value==null)
                r.put(n,rs);
1333 1334 1335 1336 1337
            else
                value.add(rs);
        }
    }

1338 1339 1340 1341 1342 1343
    /**
     * Builds the dependency graph.
     * @see DependencyGraph
     */
    protected abstract void buildDependencyGraph(DependencyGraph graph);

1344
    @Override
K
kohsuke 已提交
1345 1346
    protected SearchIndexBuilder makeSearchIndex() {
        SearchIndexBuilder sib = super.makeSearchIndex();
1347
        if(isBuildable() && hasPermission(Hudson.ADMINISTER))
1348
            sib.add("build","build");
K
kohsuke 已提交
1349 1350 1351
        return sib;
    }

1352 1353
    @Override
    protected HistoryWidget createHistoryWidget() {
1354
        return new BuildHistoryWidget<R>(this,getBuilds(),HISTORY_ADAPTER);
1355
    }
1356
    
K
kohsuke 已提交
1357
    public boolean isParameterized() {
1358
        return getProperty(ParametersDefinitionProperty.class) != null;
K
kohsuke 已提交
1359
    }
1360

1361 1362 1363 1364 1365
//
//
// actions
//
//
1366 1367 1368
    /**
     * Schedules a new build command.
     */
1369
    public void doBuild( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1370
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
1371

K
kohsuke 已提交
1372 1373 1374
        // if a build is parameterized, let that take over
        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
1375
            pp._doBuild(req,rsp);
K
kohsuke 已提交
1376 1377 1378
            return;
        }

1379 1380
        Cause cause;
        if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
1381 1382
            // Optional additional cause text when starting via token
            String causeText = req.getParameter("cause");
1383
            cause = new RemoteCause(req.getRemoteAddr(), causeText);
1384 1385 1386 1387
        } else {
            cause = new UserCause();
        }

1388
        String delay = req.getParameter("delay");
1389
        if (delay!=null) {
1390
            if (isBuildable()) {
M
mindless 已提交
1391 1392 1393 1394
                try {
                    // TODO: more unit handling
                    if(delay.endsWith("sec"))   delay=delay.substring(0,delay.length()-3);
                    if(delay.endsWith("secs"))  delay=delay.substring(0,delay.length()-4);
1395
                    Hudson.getInstance().getQueue().schedule(this, Integer.parseInt(delay),
1396
                    		new CauseAction(cause));
M
mindless 已提交
1397 1398 1399 1400 1401
                } catch (NumberFormatException e) {
                    throw new ServletException("Invalid delay parameter value: "+delay);
                }
            }
        } else {
1402
            scheduleBuild(cause);
1403
        }
1404 1405
        rsp.forwardToPreviousPage(req);
    }
1406

1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
    /**
     * Supports build trigger with parameters via an HTTP GET or POST.
     * Currently only String parameters are supported.
     */
    public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException {
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);

        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
            pp.buildWithParameters(req,rsp);
        } else {
        	throw new IllegalStateException("This build is not parameterized!");
        }
    	
    }
1422 1423 1424 1425

    /**
     * Schedules a new SCM polling command.
     */
1426
    public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1427 1428 1429
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
        schedulePolling();
        rsp.forwardToPreviousPage(req);
1430 1431 1432 1433 1434
    }

    /**
     * Cancels a scheduled build.
     */
1435
    public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1436
        checkPermission(BUILD);
1437

1438
        Hudson.getInstance().getQueue().cancel(this);
1439 1440 1441
        rsp.forwardToPreviousPage(req);
    }

1442
    @Override
1443 1444
    protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
        super.submit(req,rsp);
1445

1446
        makeDisabled(req.getParameter("disable")!=null);
1447 1448

        jdk = req.getParameter("jdk");
1449
        if(req.getParameter("hasCustomQuietPeriod")!=null) {
1450 1451 1452 1453
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
        } else {
            quietPeriod = null;
        }
1454 1455
        if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) {
            scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount"));
S
 
shinodkm 已提交
1456
        } else {
1457
            scmCheckoutRetryCount = null;
S
 
shinodkm 已提交
1458
        }
1459 1460
        blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null;

1461
        if(req.getParameter("hasSlaveAffinity")!=null) {
1462 1463
            canRoam = false;
            assignedNode = req.getParameter("slave");
1464 1465 1466
            if(assignedNode !=null) {
                if(Hudson.getInstance().getLabel(assignedNode).isEmpty())
                    assignedNode = null;   // no such label
1467 1468 1469 1470 1471 1472
            }
        } else {
            canRoam = true;
            assignedNode = null;
        }

1473
        concurrentBuild = req.getSubmittedForm().has("concurrentBuild");
K
kohsuke 已提交
1474

1475
        authToken = BuildAuthorizationToken.create(req);
1476

K
kohsuke 已提交
1477
        setScm(SCMS.parseSCM(req,this));
1478 1479 1480

        for (Trigger t : triggers)
            t.stop();
1481
        triggers = buildDescribable(req, Trigger.for_(this));
1482
        for (Trigger t : triggers)
1483
            t.start(this,true);
1484 1485
    }

K
kohsuke 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494
    /**
     * @deprecated
     *      As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
     */
    protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
        return buildDescribable(req,descriptors);
    }

    protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
1495
        throws FormException, ServletException {
1496

1497
        JSONObject data = req.getSubmittedForm();
1498
        List<T> r = new Vector<T>();
1499 1500 1501 1502
        for (Descriptor<T> d : descriptors) {
            String name = d.getJsonSafeClassName();
            if (req.getParameter(name) != null) {
                T instance = d.newInstance(req, data.getJSONObject(name));
1503
                r.add(instance);
1504 1505
            }
        }
1506
        return r;
1507 1508 1509 1510 1511
    }

    /**
     * Serves the workspace files.
     */
1512
    public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
1513
        checkPermission(AbstractProject.WORKSPACE);
K
kohsuke 已提交
1514
        FilePath ws = getSomeWorkspace();
1515
        if ((ws == null) || (!ws.exists())) {
1516
            // if there's no workspace, report a nice error message
1517 1518 1519 1520
            // Would be good if when asked for *plain*, do something else!
            // (E.g. return 404, or send empty doc.)
            // Not critical; client can just check if content type is not text/plain,
            // which also serves to detect old versions of Hudson.
1521
            req.getView(this,"noWorkspace.jelly").forward(req,rsp);
1522
            return null;
1523
        } else {
1524
            return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.gif", true);
1525 1526
        }
    }
1527

1528 1529 1530
    /**
     * Wipes out the workspace.
     */
1531
    public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
1532
        checkPermission(BUILD);
1533 1534 1535 1536
        R b = getSomeBuildWithWorkspace();
        FilePath ws = b!=null ? b.getWorkspace() : null;
        if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
            ws.deleteRecursive();
1537 1538 1539 1540
            return new HttpRedirect(".");
        } else {
            // If we get here, that means the SCM blocked the workspace deletion.
            return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
1541
        }
1542 1543
    }

1544
    public HttpResponse doDisable() throws IOException, ServletException {
1545 1546 1547
        requirePOST();
        checkPermission(CONFIGURE);
        makeDisabled(true);
1548
        return new HttpRedirect(".");
1549 1550
    }

1551
    public HttpResponse doEnable() throws IOException, ServletException {
1552
        requirePOST();
1553 1554
        checkPermission(CONFIGURE);
        makeDisabled(false);
1555
        return new HttpRedirect(".");
1556 1557
    }

K
kohsuke 已提交
1558 1559 1560
    /**
     * RSS feed for changes in this project.
     */
1561
    public void doRssChangelog(  StaplerRequest req, StaplerResponse rsp  ) throws IOException, ServletException {
K
kohsuke 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570
        class FeedItem {
            ChangeLogSet.Entry e;
            int idx;

            public FeedItem(Entry e, int idx) {
                this.e = e;
                this.idx = idx;
            }

1571
            AbstractBuild<?,?> getBuild() {
K
kohsuke 已提交
1572 1573 1574 1575 1576 1577
                return e.getParent().build;
            }
        }

        List<FeedItem> entries = new ArrayList<FeedItem>();

1578 1579 1580 1581
        for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
            int idx=0;
            for( ChangeLogSet.Entry e : r.getChangeSet())
                entries.add(new FeedItem(e,idx++));
K
kohsuke 已提交
1582 1583
        }

1584 1585 1586 1587 1588 1589 1590
        RSS.forwardToRss(
            getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
            getUrl()+"changes",
            entries, new FeedAdapter<FeedItem>() {
                public String getEntryTitle(FeedItem item) {
                    return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
                }
K
kohsuke 已提交
1591

1592 1593 1594
                public String getEntryUrl(FeedItem item) {
                    return item.getBuild().getUrl()+"changes#detail"+item.idx;
                }
K
kohsuke 已提交
1595

1596 1597 1598
                public String getEntryID(FeedItem item) {
                    return getEntryUrl(item);
                }
K
kohsuke 已提交
1599

1600 1601 1602 1603 1604 1605
                public String getEntryDescription(FeedItem item) {
                    StringBuilder buf = new StringBuilder();
                    for(String path : item.e.getAffectedPaths())
                        buf.append(path).append('\n');
                    return buf.toString();
                }
1606

1607 1608 1609
                public Calendar getEntryTimestamp(FeedItem item) {
                    return item.getBuild().getTimestamp();
                }
1610

1611
                public String getEntryAuthor(FeedItem entry) {
1612
                    return Mailer.descriptor().getAdminAddress();
1613 1614 1615
                }
            },
            req, rsp );
K
kohsuke 已提交
1616 1617
    }

1618 1619 1620 1621 1622 1623 1624
    /**
     * {@link AbstractProject} subtypes should implement this base class as a descriptor.
     *
     * @since 1.294
     */
    public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
        /**
1625
         * {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
1626
         * from showing up on their configuration screen. This is often useful when you are building
1627 1628
         * a workflow/company specific project type, where you want to limit the number of choices
         * given to the users.
1629 1630
         *
         * <p>
1631 1632 1633 1634
         * Some {@link Descriptor}s define their own schemes for controlling applicability
         * (such as {@link BuildStepDescriptor#isApplicable(Class)}),
         * This method works like AND in conjunction with them;
         * Both this method and that method need to return true in order for a given {@link Descriptor}
1635 1636 1637 1638
         * to show up for the given {@link Project}.
         *
         * <p>
         * The default implementation returns true for everything.
1639 1640
         *
         * @see BuildStepDescriptor#isApplicable(Class) 
K
kohsuke 已提交
1641 1642
         * @see BuildWrapperDescriptor#isApplicable(AbstractProject) 
         * @see TriggerDescriptor#isApplicable(Item)
1643
         */
K
kohsuke 已提交
1644
        @Override
1645
        public boolean isApplicable(Descriptor descriptor) {
1646 1647 1648 1649
            return true;
        }
    }

1650
    /**
1651
     * Finds a {@link AbstractProject} that has the name closest to the given name.
1652 1653
     */
    public static AbstractProject findNearest(String name) {
1654
        List<AbstractProject> projects = Hudson.getInstance().getItems(AbstractProject.class);
1655
        String[] names = new String[projects.size()];
1656
        for( int i=0; i<projects.size(); i++ )
1657 1658 1659
            names[i] = projects.get(i).getName();

        String nearest = EditDistance.findNearest(name, names);
1660
        return (AbstractProject)Hudson.getInstance().getItem(nearest);
1661
    }
1662 1663 1664

    private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
1665
            return o2-o1;
1666 1667
        }
    };
1668

1669
    private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
1670

1671
    /**
1672
     * Permission to abort a build. For now, let's make it the same as {@link #BUILD}
1673 1674
     */
    public static final Permission ABORT = BUILD;
1675
}
1676