AbstractProject.java 75.7 KB
Newer Older
K
kohsuke 已提交
1 2 3
/*
 * The MIT License
 * 
4
 * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
5
 * Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot,
6
 * Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts,
7 8
 * id:cactusman, Yahoo! Inc., Andrew Bayer, Manufacture Francaise des Pneumatiques
 * Michelin, Romain Seguy
K
kohsuke 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 * 
 * 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.
 */
28 29
package hudson.model;

30
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
31
import hudson.Functions;
32
import antlr.ANTLRException;
K
kohsuke 已提交
33
import hudson.AbortException;
34
import hudson.CopyOnWrite;
35
import hudson.FeedAdapter;
36
import hudson.FilePath;
37
import hudson.Launcher;
38
import hudson.Util;
39
import hudson.cli.declarative.CLIMethod;
40
import hudson.cli.declarative.CLIResolver;
41
import hudson.diagnosis.OldDataMonitor;
M
mdonohue 已提交
42
import hudson.model.Cause.LegacyCodeCause;
43
import hudson.model.Cause.RemoteCause;
44
import hudson.model.Cause.UserIdCause;
45 46
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
K
kohsuke 已提交
47
import hudson.model.Queue.Executable;
48
import hudson.model.Queue.Task;
49
import hudson.model.listeners.SCMListener;
50
import hudson.model.queue.QueueTaskFuture;
51
import hudson.model.queue.SubTask;
52 53
import hudson.model.Queue.WaitingItem;
import hudson.model.RunMap.Constructor;
54 55
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
56
import hudson.model.listeners.SCMPollListener;
57
import hudson.model.queue.CauseOfBlockage;
58
import hudson.model.queue.SubTaskContributor;
K
kohsuke 已提交
59
import hudson.scm.ChangeLogSet;
K
kohsuke 已提交
60
import hudson.scm.ChangeLogSet.Entry;
61
import hudson.scm.NullSCM;
62
import hudson.scm.PollingResult;
63
import hudson.scm.SCM;
64
import hudson.scm.SCMRevisionState;
65
import hudson.scm.SCMS;
J
jbq 已提交
66
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
67
import hudson.security.Permission;
68
import hudson.slaves.WorkspaceList;
69
import hudson.tasks.BuildStep;
70
import hudson.tasks.BuildStepDescriptor;
J
jbq 已提交
71
import hudson.tasks.BuildTrigger;
72
import hudson.tasks.BuildWrapperDescriptor;
73
import hudson.tasks.Mailer;
74
import hudson.tasks.Publisher;
K
kohsuke 已提交
75
import hudson.triggers.SCMTrigger;
76
import hudson.triggers.Trigger;
77
import hudson.triggers.TriggerDescriptor;
78 79
import hudson.util.AlternativeUiTextProvider;
import hudson.util.AlternativeUiTextProvider.Message;
80
import hudson.util.DescribableList;
81
import hudson.util.EditDistance;
S
 
shinodkm 已提交
82
import hudson.util.FormValidation;
K
kohsuke 已提交
83 84
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
85
import jenkins.model.Jenkins;
86 87 88
import jenkins.scm.DefaultSCMCheckoutStrategyImpl;
import jenkins.scm.SCMCheckoutStrategy;
import jenkins.scm.SCMCheckoutStrategyDescriptor;
K
kohsuke 已提交
89
import net.sf.json.JSONObject;
90 91
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
92 93
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
94 95 96
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
97
import org.kohsuke.stapler.HttpResponses;
98
import org.kohsuke.stapler.QueryParameter;
K
kohsuke 已提交
99 100 101
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
102
import org.kohsuke.stapler.interceptor.RequirePOST;
103

K
kohsuke 已提交
104
import javax.servlet.ServletException;
105
import java.io.File;
106
import java.io.IOException;
K
kohsuke 已提交
107
import java.lang.reflect.InvocationTargetException;
K
kohsuke 已提交
108
import java.util.ArrayList;
109
import java.util.Arrays;
110
import java.util.Calendar;
111
import java.util.Collection;
J
jbq 已提交
112
import java.util.Collections;
113
import java.util.Comparator;
J
jbq 已提交
114
import java.util.HashSet;
115 116
import java.util.List;
import java.util.Map;
J
jbq 已提交
117
import java.util.Set;
118 119 120
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
K
kohsuke 已提交
121
import java.util.concurrent.Future;
122 123
import java.util.logging.Level;
import java.util.logging.Logger;
124

125 126 127
import static hudson.scm.PollingResult.*;
import static javax.servlet.http.HttpServletResponse.*;

128 129
/**
 * Base implementation of {@link Job}s that build software.
130
 *
131
 * For now this is primarily the common part of {@link Project} and MavenModule.
132
 *
133 134 135
 * @author Kohsuke Kawaguchi
 * @see AbstractBuild
 */
C
Christoph Kutzinski 已提交
136
@SuppressWarnings("rawtypes")
137
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
138

139
    /**
140 141 142
     * {@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()}.
143
     */
K
kohsuke 已提交
144
    private volatile SCM scm = new NullSCM();
145

146 147 148 149 150
    /**
     * Controls how the checkout is done.
     */
    private volatile SCMCheckoutStrategy scmCheckoutStrategy;

151 152 153 154 155
    /**
     * State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.
     */
    private volatile transient SCMRevisionState pollingBaseline = null;

156 157
    /**
     * All the builds keyed by their build number.
158 159 160
     *
     * External code should use {@link #getBuildByNumber(int)} or {@link #getLastBuild()} and traverse via
     * {@link Run#getPreviousBuild()}
161
     */
162
    @Restricted(NoExternalUse.class)
163
    protected transient /*almost final*/ RunMap<R> builds = new RunMap<R>();
164 165 166 167

    /**
     * The quiet period. Null to delegate to the system default.
     */
K
kohsuke 已提交
168
    private volatile Integer quietPeriod = null;
S
 
shinodkm 已提交
169 170
    
    /**
171
     * The retry count. Null to delegate to the system default.
S
 
shinodkm 已提交
172
     */
173
    private volatile Integer scmCheckoutRetryCount = null;
174 175

    /**
176 177 178 179 180 181 182
     * 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.
     *
183
     * @see #canRoam
184 185 186 187 188
     */
    private String assignedNode;

    /**
     * True if this project can be built on any node.
189
     *
190
     * <p>
191 192
     * This somewhat ugly flag combination is so that we can migrate
     * existing Hudson installations nicely.
193
     */
K
kohsuke 已提交
194
    private volatile boolean canRoam;
195 196 197 198

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

201 202 203 204 205 206
    /**
     * True to keep builds of this project in queue when downstream projects are
     * building. False by default to keep from breaking existing behavior.
     */
    protected volatile boolean blockBuildWhenDownstreamBuilding = false;

207 208 209 210 211 212
    /**
     * 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;

213
    /**
214 215 216
     * Identifies {@link JDK} to be used.
     * Null if no explicit configuration is required.
     *
217
     * <p>
218
     * Can't store {@link JDK} directly because {@link Jenkins} and {@link Project}
219 220
     * are saved independently.
     *
221
     * @see Jenkins#getJDK(String)
222
     */
K
kohsuke 已提交
223
    private volatile String jdk;
224

K
kohsuke 已提交
225
    private volatile BuildAuthorizationToken authToken = null;
226

227 228 229
    /**
     * List of all {@link Trigger}s for this project.
     */
230
    protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
231

232 233
    /**
     * {@link Action}s contributed from subsidiary objects associated with
234 235 236 237
     * {@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.
238
     */
239 240
    @CopyOnWrite
    protected transient volatile List<Action> transientActions = new Vector<Action>();
241

K
kohsuke 已提交
242 243
    private boolean concurrentBuild;

244 245 246
    /**
     * See {@link #setCustomWorkspace(String)}.
     *
247
     * @since 1.410
248 249 250
     */
    private String customWorkspace;
    
251
    protected AbstractProject(ItemGroup parent, String name) {
252
        super(parent,name);
253

254
        if(!Jenkins.getInstance().getNodes().isEmpty()) {
255
            // if a new job is configured with Hudson that already has slave nodes
256 257 258
            // make it roamable by default
            canRoam = true;
        }
259 260 261 262 263 264 265
    }

    @Override
    public void onCreatedFromScratch() {
        super.onCreatedFromScratch();
        // solicit initial contributions, especially from TransientProjectActionFactory
        updateTransientActions();
266 267
    }

268
    @Override
269
    public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
270
        super.onLoad(parent, name);
271

K
Kohsuke Kawaguchi 已提交
272 273
        if (this.builds==null)
            this.builds = new RunMap<R>();
274
        this.builds.load(this,new Constructor<R>() {
275 276 277 278 279
            public R create(File dir) throws IOException {
                return loadBuild(dir);
            }
        });

280
        if(triggers==null) {
281
            // it didn't exist in < 1.28
282
            triggers = new Vector<Trigger<?>>();
283 284
            OldDataMonitor.report(this, "1.28");
        }
285
        for (Trigger t : triggers)
286
            t.start(this, Items.updatingByXml.get());
287 288
        if(scm==null)
            scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
289

290 291
        if(transientActions==null)
            transientActions = new Vector<Action>();    // happens when loaded from disk
292
        updateTransientActions();
293 294
    }

295
    @Override
296
    protected void performDelete() throws IOException, InterruptedException {
K
kohsuke 已提交
297 298
        // prevent a new build while a delete operation is in progress
        makeDisabled(true);
299
        FilePath ws = getWorkspace();
300
        if(ws!=null) {
K
NPE fix  
kohsuke 已提交
301 302 303 304
            Node on = getLastBuiltOn();
            getScm().processWorkspaceBeforeDeletion(this, ws, on);
            if(on!=null)
                on.getFileSystemProvisioner().discardWorkspace(this,ws);
305
        }
K
kohsuke 已提交
306 307 308
        super.performDelete();
    }

K
kohsuke 已提交
309 310
    /**
     * Does this project perform concurrent builds?
K
kohsuke 已提交
311
     * @since 1.319
K
kohsuke 已提交
312
     */
K
kohsuke 已提交
313
    @Exported
K
kohsuke 已提交
314
    public boolean isConcurrentBuild() {
315
        return concurrentBuild;
K
kohsuke 已提交
316 317 318 319 320 321 322
    }

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

323
    /**
324 325
     * If this project is configured to be always built on this node,
     * return that {@link Node}. Otherwise null.
326
     */
327
    public Label getAssignedLabel() {
328
        if(canRoam)
329 330
            return null;

331
        if(assignedNode==null)
332 333
            return Jenkins.getInstance().getSelfLabel();
        return Jenkins.getInstance().getLabel(assignedNode);
334 335
    }

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    /**
     * Set of labels relevant to this job.
     *
     * This method is used to determine what slaves are relevant to jobs, for example by {@link View}s.
     * It does not affect the scheduling. This information is informational and the best-effort basis.
     *
     * @since 1.456
     * @return
     *      Minimally it should contain {@link #getAssignedLabel()}. The set can contain null element
     *      to correspond to the null return value from {@link #getAssignedLabel()}.
     */
    public Set<Label> getRelevantLabels() {
        return Collections.singleton(getAssignedLabel());
    }

351 352 353 354
    /**
     * Gets the textual representation of the assigned label as it was entered by the user.
     */
    public String getAssignedLabelString() {
355 356 357 358 359 360 361 362
        if (canRoam || assignedNode==null)    return null;
        try {
            LabelExpression.parseExpression(assignedNode);
            return assignedNode;
        } catch (ANTLRException e) {
            // must be old label or host name that includes whitespace or other unsafe chars
            return LabelAtom.escape(assignedNode);
        }
363 364
    }

K
kohsuke 已提交
365 366 367 368 369 370 371 372 373
    /**
     * Sets the assigned label.
     */
    public void setAssignedLabel(Label l) throws IOException {
        if(l==null) {
            canRoam = true;
            assignedNode = null;
        } else {
            canRoam = false;
374
            if(l== Jenkins.getInstance().getSelfLabel())  assignedNode = null;
375
            else                                        assignedNode = l.getExpression();
K
kohsuke 已提交
376 377 378 379
        }
        save();
    }

380 381 382 383 384 385 386
    /**
     * Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.
     */
    public void setAssignedNode(Node l) throws IOException {
        setAssignedLabel(l.getSelfLabel());
    }

387
    /**
388 389
     * Get the term used in the UI to represent this kind of {@link AbstractProject}.
     * Must start with a capital letter.
390 391 392
     */
    @Override
    public String getPronoun() {
K
Kohsuke Kawaguchi 已提交
393
        return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun());
394 395
    }

396 397 398 399 400 401 402 403 404
    /**
     * Gets the human readable display name to be rendered in the "Build Now" link.
     *
     * @since 1.401
     */
    public String getBuildNowText() {
        return AlternativeUiTextProvider.get(BUILD_NOW_TEXT,this,Messages.AbstractProject_BuildNow());
    }

405
    /**
406
     * Gets the nearest ancestor {@link TopLevelItem} that's also an {@link AbstractProject}.
407
     *
408 409 410 411 412 413 414
     * <p>
     * Some projects (such as matrix projects, Maven projects, or promotion processes) form a tree of jobs
     * that acts as a single unit. This method can be used to find the top most dominating job that
     * covers such a tree.
     *
     * @return never null.
     * @see AbstractBuild#getRootBuild()
415
     */
416 417
    public AbstractProject<?,?> getRootProject() {
        if (this instanceof TopLevelItem) {
418 419
            return this;
        } else {
420 421 422 423
            ItemGroup p = this.getParent();
            if (p instanceof AbstractProject)
                return ((AbstractProject) p).getRootProject();
            return this;
424 425 426
        }
    }

427 428
    /**
     * Gets the directory where the module is checked out.
429 430 431
     *
     * @return
     *      null if the workspace is on a slave that's not connected.
K
kohsuke 已提交
432
     * @deprecated as of 1.319
K
kohsuke 已提交
433 434 435 436 437
     *      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>
438
     *      If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
K
kohsuke 已提交
439 440 441 442
     *      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() {
443 444 445 446 447 448 449 450 451 452 453 454
        AbstractBuild b = getBuildForDeprecatedMethods();
        return b != null ? b.getWorkspace() : null;

    }
    
    /**
     * Various deprecated methods in this class all need the 'current' build.  This method returns
     * the build suitable for that purpose.
     * 
     * @return An AbstractBuild for deprecated methods to use.
     */
    private AbstractBuild getBuildForDeprecatedMethods() {
K
kohsuke 已提交
455 456 457 458 459 460
        Executor e = Executor.currentExecutor();
        if(e!=null) {
            Executable exe = e.getCurrentExecutable();
            if (exe instanceof AbstractBuild) {
                AbstractBuild b = (AbstractBuild) exe;
                if(b.getProject()==this)
461
                    return b;
K
kohsuke 已提交
462 463 464
            }
        }
        R lb = getLastBuild();
465
        if(lb!=null)    return lb;
K
kohsuke 已提交
466 467 468 469 470 471 472 473 474 475 476 477 478
        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 已提交
479
     * @since 1.319
480
     */
K
kohsuke 已提交
481
    public final FilePath getSomeWorkspace() {
482 483 484 485 486 487 488 489 490 491
        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 已提交
492 493 494
        int cnt=0;
        for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
            FilePath ws = b.getWorkspace();
495
            if (ws!=null)   return b;
K
kohsuke 已提交
496 497 498
        }
        return null;
    }
499

500 501 502
    /**
     * Returns the root directory of the checked-out module.
     * <p>
503 504
     * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
     * and so on exists.
K
kohsuke 已提交
505
     *
K
kohsuke 已提交
506
     * @deprecated as of 1.319
K
kohsuke 已提交
507
     *      See {@link #getWorkspace()} for a migration strategy.
508 509
     */
    public FilePath getModuleRoot() {
510 511
        AbstractBuild b = getBuildForDeprecatedMethods();
        return b != null ? b.getModuleRoot() : null;
512 513
    }

S
stephenconnolly 已提交
514 515 516 517 518 519
    /**
     * 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 已提交
520
     *
K
kohsuke 已提交
521
     * @deprecated as of 1.319
K
kohsuke 已提交
522
     *      See {@link #getWorkspace()} for a migration strategy.
S
stephenconnolly 已提交
523 524
     */
    public FilePath[] getModuleRoots() {
525 526
        AbstractBuild b = getBuildForDeprecatedMethods();
        return b != null ? b.getModuleRoots() : null;
S
stephenconnolly 已提交
527 528
    }

529
    public int getQuietPeriod() {
530
        return quietPeriod!=null ? quietPeriod : Jenkins.getInstance().getQuietPeriod();
531
    }
532

533
    public SCMCheckoutStrategy getScmCheckoutStrategy() {
534 535 536
        return scmCheckoutStrategy == null ? new DefaultSCMCheckoutStrategyImpl() : scmCheckoutStrategy;
    }

537
    public void setScmCheckoutStrategy(SCMCheckoutStrategy scmCheckoutStrategy) throws IOException {
538 539 540 541 542
        this.scmCheckoutStrategy = scmCheckoutStrategy;
        save();
    }


543
    public int getScmCheckoutRetryCount() {
544
        return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Jenkins.getInstance().getScmCheckoutRetryCount();
S
 
shinodkm 已提交
545
    }
546 547 548

    // ugly name because of EL
    public boolean getHasCustomQuietPeriod() {
549
        return quietPeriod!=null;
550
    }
K
kohsuke 已提交
551 552 553 554

    /**
     * Sets the custom quiet period of this project, or revert to the global default if null is given. 
     */
555
    public void setQuietPeriod(Integer seconds) throws IOException {
K
kohsuke 已提交
556 557 558
        this.quietPeriod = seconds;
        save();
    }
S
 
shinodkm 已提交
559
    
560
    public boolean hasCustomScmCheckoutRetryCount(){
561
        return scmCheckoutRetryCount != null;
S
 
shinodkm 已提交
562
    }
563

564
    @Override
565
    public boolean isBuildable() {
J
jpederzolli 已提交
566
        return !isDisabled() && !isHoldOffBuildUntilSave();
567 568
    }

569
    /**
570 571
     * Used in <tt>sidepanel.jelly</tt> to decide whether to display
     * the config/delete/build links.
572 573 574 575 576
     */
    public boolean isConfigurable() {
        return true;
    }

577 578 579 580 581 582 583 584 585
    public boolean blockBuildWhenDownstreamBuilding() {
        return blockBuildWhenDownstreamBuilding;
    }

    public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException {
        blockBuildWhenDownstreamBuilding = b;
        save();
    }

586
    public boolean blockBuildWhenUpstreamBuilding() {
587
        return blockBuildWhenUpstreamBuilding;
588 589
    }

590
    public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
591 592
        blockBuildWhenUpstreamBuilding = b;
        save();
593 594
    }

595 596 597
    public boolean isDisabled() {
        return disabled;
    }
S
 
shinodkm 已提交
598 599 600 601 602
    
    /**
     * Validates the retry count Regex
     */
    public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
603 604 605 606 607 608 609
        // 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 已提交
610
    }
611

612 613 614 615
    /**
     * Marks the build as disabled.
     */
    public void makeDisabled(boolean b) throws IOException {
616
        if(disabled==b)     return; // noop
617
        this.disabled = b;
K
bug fix  
kohsuke 已提交
618
        if(b)
619
            Jenkins.getInstance().getQueue().cancel(this);
620 621 622
        save();
    }

623 624
    /**
     * Specifies whether this project may be disabled by the user.
625 626
     * By default, it can be only if this is a {@link TopLevelItem};
     * would be false for matrix configurations, etc.
627 628 629 630
     * @return true if the GUI should allow {@link #doDisable} and the like
     * @since 1.475
     */
    public boolean supportsMakeDisabled() {
631
        return this instanceof TopLevelItem;
632 633
    }

634 635 636 637 638 639 640 641
    public void disable() throws IOException {
        makeDisabled(true);
    }

    public void enable() throws IOException {
        makeDisabled(false);
    }

K
kohsuke 已提交
642 643
    @Override
    public BallColor getIconColor() {
644
        if(isDisabled())
645
            return BallColor.DISABLED;
K
kohsuke 已提交
646 647 648
        else
            return super.getIconColor();
    }
649

650 651 652 653 654 655 656
    /**
     * effectively deprecated. Since using updateTransientActions correctly
     * under concurrent environment requires a lock that can too easily cause deadlocks.
     *
     * <p>
     * Override {@link #createTransientActions()} instead.
     */
657
    protected void updateTransientActions() {
658 659 660 661
        transientActions = createTransientActions();
    }

    protected List<Action> createTransientActions() {
662
        Vector<Action> ta = new Vector<Action>();
663

664 665
        for (JobProperty<? super P> p : properties)
            ta.addAll(p.getJobActions((P)this));
666

667 668
        for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
            ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
669
        return ta;
670 671
    }

672
    /**
673 674
     * Returns the live list of all {@link Publisher}s configured for this project.
     *
675
     * <p>
676 677
     * This method couldn't be called <tt>getPublishers()</tt> because existing methods
     * in sub-classes return different inconsistent types.
678
     */
679
    public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
680

K
kohsuke 已提交
681 682 683 684 685 686
    @Override
    public void addProperty(JobProperty<? super P> jobProp) throws IOException {
        super.addProperty(jobProp);
        updateTransientActions();
    }

687 688 689 690
    public List<ProminentProjectAction> getProminentActions() {
        List<Action> a = getActions();
        List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
        for (Action action : a) {
691
            if(action instanceof ProminentProjectAction)
692 693 694 695 696
                pa.add((ProminentProjectAction) action);
        }
        return pa;
    }

697
    @Override
698
    public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
699
        super.doConfigSubmit(req,rsp);
700

701 702
        updateTransientActions();

703
        Set<AbstractProject> upstream = Collections.emptySet();
704
        if(req.getParameter("pseudoUpstreamTrigger")!=null) {
705
            upstream = new HashSet<AbstractProject>(Items.fromNameList(getParent(),req.getParameter("upstreamProjects"),AbstractProject.class));
706 707 708
        }

        // dependency setting might have been changed by the user, so rebuild.
709
        Jenkins.getInstance().rebuildDependencyGraph();
710 711 712 713 714

        // 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

715
        for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
716 717
            // Don't consider child projects such as MatrixConfiguration:
            if (!p.isConfigurable()) continue;
718
            boolean isUpstream = upstream.contains(p);
719 720 721
            synchronized(p) {
                // does 'p' include us in its BuildTrigger? 
                DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
722
                BuildTrigger trigger = pl.get(BuildTrigger.class);
723
                List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects(p);
724 725
                if(isUpstream) {
                    if(!newChildProjects.contains(this))
726 727 728 729 730
                        newChildProjects.add(this);
                } else {
                    newChildProjects.remove(this);
                }

731
                if(newChildProjects.isEmpty()) {
732
                    pl.remove(BuildTrigger.class);
733
                } else {
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
                    // 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)
751
                            combinedChildren.addAll(bt.getChildProjects(p));
752 753 754 755 756
                        existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
                        pl.add(existing);
                        break;
                    }

757
                    if(existing!=null && existing.hasSame(p,newChildProjects))
758
                        continue;   // no need to touch
759
                    pl.replace(new BuildTrigger(newChildProjects,
760
                        existing==null?Result.SUCCESS:existing.getThreshold()));
761 762 763 764 765
                }
            }
        }

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

        // this is to reflect the upstream build adjustments done above
769
        Jenkins.getInstance().rebuildDependencyGraph();
770 771
    }

M
mdonohue 已提交
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
	/**
	 * @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());
    }
    
788 789
    /**
     * Schedules a build of this project.
790 791 792 793 794
     *
     * @return
     *      true if the project is actually added to the queue.
     *      false if the queue contained it and therefore the add()
     *      was noop
795
     */
M
mdonohue 已提交
796 797
    public boolean scheduleBuild(Cause c) {
        return scheduleBuild(getQuietPeriod(), c);
K
kohsuke 已提交
798 799
    }

M
mdonohue 已提交
800
    public boolean scheduleBuild(int quietPeriod, Cause c) {
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
        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) {
817 818 819 820 821 822
        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.
823 824 825
     *
     * @param actions
     *      For the convenience of the caller, this array can contain null, and those will be silently ignored.
826
     */
827 828
    @WithBridgeMethods(Future.class)
    public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
K
kohsuke 已提交
829 830 831 832 833 834 835 836 837 838 839
        return scheduleBuild2(quietPeriod,c,Arrays.asList(actions));
    }

    /**
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
     *
     * @param actions
     *      For the convenience of the caller, this collection can contain null, and those will be silently ignored.
     * @since 1.383
     */
C
Christoph Kutzinski 已提交
840
    @SuppressWarnings("unchecked")
841 842
    @WithBridgeMethods(Future.class)
    public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {
843
        if (!isBuildable())
844
            return null;
845

K
kohsuke 已提交
846
        List<Action> queueActions = new ArrayList<Action>(actions);
847 848 849 850
        if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
            queueActions.add(new ParametersAction(getDefaultParametersValues()));
        }

S
sogabe 已提交
851 852 853 854
        if (c != null) {
            queueActions.add(new CauseAction(c));
        }

855
        WaitingItem i = Jenkins.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
856
        if(i!=null)
857
            return (QueueTaskFuture)i.getFuture();
858
        return null;
859 860 861 862 863 864
    }

    private List<ParameterValue> getDefaultParametersValues() {
        ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
        ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
        
M
mindless 已提交
865 866 867
        /*
         * This check is made ONLY if someone will call this method even if isParametrized() is false.
         */
868 869 870 871 872 873 874 875 876 877 878 879 880
        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 已提交
881 882
    }

883
    /**
884 885 886 887
     * Schedules a build, and returns a {@link Future} object
     * to wait for the completion of the build.
     *
     * <p>
888
     * Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
889
     * as deprecated.
890
     */
C
Christoph Kutzinski 已提交
891
    @SuppressWarnings("deprecation")
892 893
    @WithBridgeMethods(Future.class)
    public QueueTaskFuture<R> scheduleBuild2(int quietPeriod) {
894
        return scheduleBuild2(quietPeriod, new LegacyCodeCause());
M
mdonohue 已提交
895 896
    }
    
K
kohsuke 已提交
897
    /**
898 899
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
K
kohsuke 已提交
900
     */
901 902
    @WithBridgeMethods(Future.class)
    public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c) {
903 904 905
        return scheduleBuild2(quietPeriod, c, new Action[0]);
    }

906 907 908 909
    /**
     * Schedules a polling of this project.
     */
    public boolean schedulePolling() {
910
        if(isDisabled())    return false;
911
        SCMTrigger scmt = getTrigger(SCMTrigger.class);
912
        if(scmt==null)      return false;
913 914 915 916
        scmt.run();
        return true;
    }

917 918 919 920 921
    /**
     * Returns true if the build is in the queue.
     */
    @Override
    public boolean isInQueue() {
922
        return Jenkins.getInstance().getQueue().contains(this);
923 924
    }

K
kohsuke 已提交
925 926
    @Override
    public Queue.Item getQueueItem() {
927
        return Jenkins.getInstance().getQueue().getItem(this);
K
kohsuke 已提交
928 929
    }

K
kohsuke 已提交
930 931 932
    /**
     * Gets the JDK that this project is configured with, or null.
     */
933
    public JDK getJDK() {
934
        return Jenkins.getInstance().getJDK(jdk);
935 936 937 938 939
    }

    /**
     * Overwrites the JDK setting.
     */
K
kohsuke 已提交
940
    public void setJDK(JDK jdk) throws IOException {
941 942 943 944
        this.jdk = jdk.getName();
        save();
    }

945 946
    public BuildAuthorizationToken getAuthToken() {
        return authToken;
947 948
    }

949
    @Override
950 951 952 953
    public SortedMap<Integer, ? extends R> _getRuns() {
        return builds.getView();
    }

954
    @Override
955 956 957 958
    public void removeRun(R run) {
        this.builds.remove(run);
    }

959 960 961 962 963
    /**
     * Determines Class&lt;R>.
     */
    protected abstract Class<R> getBuildClass();

H
huybrechts 已提交
964
    // keep track of the previous time we started a build
965
    private transient long lastBuildStartTime;
H
huybrechts 已提交
966
    
967 968 969
    /**
     * Creates a new build of this project for immediate execution.
     */
H
huybrechts 已提交
970 971 972 973 974 975 976 977 978 979 980
    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();
981
        try {
982
            R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
983 984 985 986 987 988 989
            builds.put(lastBuild);
            return lastBuild;
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
990
            throw handleInvocationTargetException(e);
991 992 993 994
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
995

996
    private IOException handleInvocationTargetException(InvocationTargetException e) {
997
        Throwable t = e.getTargetException();
998 999 1000
        if(t instanceof Error)  throw (Error)t;
        if(t instanceof RuntimeException)   throw (RuntimeException)t;
        if(t instanceof IOException)    return (IOException)t;
1001 1002 1003
        throw new Error(t);
    }

1004 1005 1006
    /**
     * Loads an existing build record from disk.
     */
1007 1008
    protected R loadBuild(File dir) throws IOException {
        try {
1009
            return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
1010 1011 1012 1013 1014
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
1015
            throw handleInvocationTargetException(e);
1016 1017 1018 1019
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
1020

K
kohsuke 已提交
1021 1022
    /**
     * {@inheritDoc}
1023
     *
K
kohsuke 已提交
1024 1025
     * <p>
     * Note that this method returns a read-only view of {@link Action}s.
1026
     * {@link BuildStep}s and others who want to add a project action
1027
     * should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.
1028 1029
     *
     * @see TransientProjectActionFactory
K
kohsuke 已提交
1030
     */
1031
    @Override
1032 1033 1034 1035
    public synchronized List<Action> getActions() {
        // add all the transient actions, too
        List<Action> actions = new Vector<Action>(super.getActions());
        actions.addAll(transientActions);
1036
        // return the read only list to cause a failure on plugins who try to add an action here
K
kohsuke 已提交
1037
        return Collections.unmodifiableList(actions);
1038 1039
    }

1040 1041
    /**
     * Gets the {@link Node} where this project was last built on.
1042 1043 1044 1045
     *
     * @return
     *      null if no information is available (for example,
     *      if no build was done yet.)
1046 1047 1048 1049
     */
    public Node getLastBuiltOn() {
        // where was it built on?
        AbstractBuild b = getLastBuild();
1050
        if(b==null)
1051 1052 1053 1054 1055
            return null;
        else
            return b.getBuiltOn();
    }

1056 1057 1058 1059
    public Object getSameNodeConstraint() {
        return this; // in this way, any member that wants to run with the main guy can nominate the project itself 
    }

1060 1061 1062 1063
    public final Task getOwnerTask() {
        return this;
    }

1064
    /**
1065
     * {@inheritDoc}
1066
     *
1067
     * <p>
1068
     * A project must be blocked if its own previous build is in progress,
1069 1070
     * or if the blockBuildWhenUpstreamBuilding option is true and an upstream
     * project is building, but derived classes can also check other conditions.
1071
     */
1072
    public boolean isBuildBlocked() {
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        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;
1089 1090
        }

1091
        @Override
1092 1093 1094 1095 1096 1097 1098 1099
        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);
        }
1100
    }
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    
    /**
     * Because the downstream build is in progress, and we are configured to wait for that.
     */
    public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage {
        public final AbstractProject<?,?> up;

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

        @Override
        public String getShortDescription() {
            return Messages.AbstractProject_DownstreamBuildInProgress(up.getName());
        }
    }
1117

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    /**
     * 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;
        }

1128
        @Override
1129 1130 1131
        public String getShortDescription() {
            return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
        }
1132 1133
    }

1134
    public CauseOfBlockage getCauseOfBlockage() {
1135 1136
        // Block builds until they are done with post-production
        if (isLogUpdated() && !isConcurrentBuild())
1137
            return new BecauseOfBuildInProgress(getLastBuild());
1138 1139 1140 1141
        if (blockBuildWhenDownstreamBuilding()) {
            AbstractProject<?,?> bup = getBuildingDownstream();
            if (bup!=null)
                return new BecauseOfDownstreamBuildInProgress(bup);
1142 1143
        }
        if (blockBuildWhenUpstreamBuilding()) {
1144 1145 1146 1147 1148 1149
            AbstractProject<?,?> bup = getBuildingUpstream();
            if (bup!=null)
                return new BecauseOfUpstreamBuildInProgress(bup);
        }
        return null;
    }
1150

1151
    /**
1152 1153
     * Returns the project if any of the downstream project is either
     * building, waiting, pending or buildable.
1154 1155 1156 1157
     * <p>
     * This means eventually there will be an automatic triggering of
     * the given project (provided that all builds went smoothly.)
     */
1158
    public AbstractProject getBuildingDownstream() {
1159
        Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
1160

1161
        for (AbstractProject tup : getTransitiveDownstreamProjects()) {
1162
			if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
1163 1164 1165 1166 1167
                return tup;
        }
        return null;
    }

1168
    /**
1169
     * Returns the project if any of the upstream project is either
1170 1171 1172 1173 1174
     * 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.)
     */
1175
    public AbstractProject getBuildingUpstream() {
1176
        Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
1177

1178
        for (AbstractProject tup : getTransitiveUpstreamProjects()) {
1179
			if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
1180 1181 1182
                return tup;
        }
        return null;
1183 1184
    }

1185 1186
    public List<SubTask> getSubTasks() {
        List<SubTask> r = new ArrayList<SubTask>();
1187
        r.add(this);
1188 1189 1190
        for (SubTaskContributor euc : SubTaskContributor.all())
            r.addAll(euc.forProject(this));
        for (JobProperty<? super P> p : properties)
1191
            r.addAll(p.getSubTasks());
1192
        return r;
1193 1194
    }

1195
    public R createExecutable() throws IOException {
1196
        if(isDisabled())    return null;
1197
        return newBuild();
1198 1199
    }

1200 1201 1202 1203
    public void checkAbortPermission() {
        checkPermission(AbstractProject.ABORT);
    }

K
kohsuke 已提交
1204 1205 1206 1207
    public boolean hasAbortPermission() {
        return hasPermission(AbstractProject.ABORT);
    }

1208 1209
    /**
     * Gets the {@link Resource} that represents the workspace of this project.
1210
     * Useful for locking and mutual exclusion control.
K
kohsuke 已提交
1211
     *
K
kohsuke 已提交
1212
     * @deprecated as of 1.319
K
kohsuke 已提交
1213 1214 1215 1216 1217 1218 1219
     *      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}.
1220 1221
     */
    public Resource getWorkspaceResource() {
1222
        return new Resource(getFullDisplayName()+" workspace");
1223 1224 1225 1226 1227 1228
    }

    /**
     * List of necessary resources to perform the build of this project.
     */
    public ResourceList getResourceList() {
1229
        final Set<ResourceActivity> resourceActivities = getResourceActivities();
1230
        final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        for (ResourceActivity activity : resourceActivities) {
            if (activity != this && activity != null) {
                // defensive infinite recursion and null check
                resourceLists.add(activity.getResourceList());
            }
        }
        return ResourceList.union(resourceLists);
    }

    /**
1241 1242
     * 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.
1243 1244
     */
    protected Set<ResourceActivity> getResourceActivities() {
K
kohsuke 已提交
1245
        return Collections.emptySet();
1246 1247
    }

1248
    public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
1249
        SCM scm = getScm();
1250 1251
        if(scm==null)
            return true;    // no SCM
1252

1253 1254
        FilePath workspace = build.getWorkspace();
        workspace.mkdirs();
1255 1256
        
        boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
C
Christoph Kutzinski 已提交
1257 1258 1259
        if (r) {
            // Only calcRevisionsFromBuild if checkout was successful. Note that modern SCM implementations
            // won't reach this line anyway, as they throw AbortExceptions on checkout failure.
1260 1261
            calcPollingBaseline(build, launcher, listener);
        }
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
        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 {
1272
                baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);
1273 1274 1275 1276 1277 1278 1279 1280 1281
            } 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;
    }

1282 1283
    /**
     * Checks if there's any update in SCM, and returns true if any is found.
1284
     *
1285 1286
     * @deprecated as of 1.346
     *      Use {@link #poll(TaskListener)} instead.
1287
     */
1288
    public boolean pollSCMChanges( TaskListener listener ) {
1289 1290 1291 1292 1293 1294 1295
        return poll(listener).hasChanges();
    }

    /**
     * Checks if there's any update in SCM, and returns true if any is found.
     *
     * <p>
1296 1297
     * The implementation is responsible for ensuring mutual exclusion between polling and builds
     * if necessary.
1298 1299 1300 1301
     *
     * @since 1.345
     */
    public PollingResult poll( TaskListener listener ) {
1302
        SCM scm = getScm();
1303
        if (scm==null) {
K
i18n  
kohsuke 已提交
1304
            listener.getLogger().println(Messages.AbstractProject_NoSCM());
1305
            return NO_CHANGES;
1306
        }
1307
        if (isDisabled()) {
K
i18n  
kohsuke 已提交
1308
            listener.getLogger().println(Messages.AbstractProject_Disabled());
1309 1310 1311 1312 1313
            return NO_CHANGES;
        }

        R lb = getLastBuild();
        if (lb==null) {
1314
            listener.getLogger().println(Messages.AbstractProject_NoBuilds());
1315
            return isInQueue() ? NO_CHANGES : BUILD_NOW;
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
        }

        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.
1331 1332 1333
        }

        try {
K
Kohsuke Kawaguchi 已提交
1334 1335 1336 1337
            SCMPollListener.fireBeforePolling(this, listener);
            PollingResult r = _poll(listener, scm, lb);
            SCMPollListener.firePollingSuccess(this,listener, r);
            return r;
1338
        } catch (AbortException e) {
1339
            listener.getLogger().println(e.getMessage());
K
i18n  
kohsuke 已提交
1340
            listener.fatalError(Messages.AbstractProject_Aborted());
1341
            LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
K
Kohsuke Kawaguchi 已提交
1342
            SCMPollListener.firePollingFailed(this, listener,e);
1343
            return NO_CHANGES;
1344 1345
        } catch (IOException e) {
            e.printStackTrace(listener.fatalError(e.getMessage()));
K
Kohsuke Kawaguchi 已提交
1346
            SCMPollListener.firePollingFailed(this, listener,e);
1347
            return NO_CHANGES;
1348
        } catch (InterruptedException e) {
1349
            e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
K
Kohsuke Kawaguchi 已提交
1350
            SCMPollListener.firePollingFailed(this, listener,e);
1351
            return NO_CHANGES;
K
Kohsuke Kawaguchi 已提交
1352 1353 1354 1355 1356 1357
        } catch (RuntimeException e) {
            SCMPollListener.firePollingFailed(this, listener,e);
            throw e;
        } catch (Error e) {
            SCMPollListener.firePollingFailed(this, listener,e);
            throw e;
1358 1359
        }
    }
K
Kohsuke Kawaguchi 已提交
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420

    /**
     * {@link #poll(TaskListener)} method without the try/catch block that does listener notification and .
     */
    private PollingResult _poll(TaskListener listener, SCM scm, R lb) throws IOException, InterruptedException {
        if (scm.requiresWorkspaceForPolling()) {
            // lock the workspace of the last build
            FilePath ws=lb.getWorkspace();

            if (workspaceOffline(lb)) {
                // 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());
                    return NO_CHANGES;
                }
                listener.getLogger().println( ws==null
                    ? Messages.AbstractProject_WorkspaceOffline()
                    : Messages.AbstractProject_NoWorkspace());
                if (isInQueue()) {
                    listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());
                    return NO_CHANGES;
                } else {
                    listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace());
                    return BUILD_NOW;
                }
            } else {
                WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
                // if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
                // 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
                WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
                Launcher launcher = ws.createLauncher(listener);
                try {
                    LOGGER.fine("Polling SCM changes of " + getName());
                    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;
                } finally {
                    lease.release();
                }
            }
        } else {
            // polling without workspace
            LOGGER.fine("Polling SCM changes of " + getName());

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

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    private boolean workspaceOffline(R build) throws IOException, InterruptedException {
        FilePath ws = build.getWorkspace();
        if (ws==null || !ws.exists()) {
            return true;
        }
        
        Node builtOn = build.getBuiltOn();
        if (builtOn == null) { // node built-on doesn't exist anymore
            return true;
        }
        
        if (builtOn.toComputer() == null) { // node still exists, but has 0 executors - o.s.l.t.
            return true;
        }
        
        return false;
    }
1438

1439 1440
    /**
     * Returns true if this user has made a commit to this project.
1441
     *
1442 1443 1444
     * @since 1.191
     */
    public boolean hasParticipant(User user) {
1445 1446
        for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
            if(build.hasParticipant(user))
1447 1448 1449 1450
                return true;
        return false;
    }

1451
    @Exported
1452 1453 1454 1455
    public SCM getScm() {
        return scm;
    }

1456
    public void setScm(SCM scm) throws IOException {
1457
        this.scm = scm;
1458
        save();
1459 1460
    }

1461 1462 1463
    /**
     * Adds a new {@link Trigger} to this {@link Project} if not active yet.
     */
1464
    public void addTrigger(Trigger<?> trigger) throws IOException {
1465
        addToList(trigger,triggers);
1466 1467
    }

1468
    public void removeTrigger(TriggerDescriptor trigger) throws IOException {
1469
        removeFromList(trigger,triggers);
1470 1471
    }

1472 1473 1474 1475
    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()) {
1476
                // replace
1477
                collection.set(i,item);
1478 1479 1480 1481 1482 1483 1484
                save();
                return;
            }
        }
        // add
        collection.add(item);
        save();
1485
        updateTransientActions();
1486 1487
    }

1488 1489 1490 1491
    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) {
1492 1493 1494
                // found it
                collection.remove(i);
                save();
1495
                updateTransientActions();
1496 1497 1498 1499 1500
                return;
            }
        }
    }

C
Christoph Kutzinski 已提交
1501
    @SuppressWarnings("unchecked")
1502 1503
    public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
        return (Map)Descriptor.toMap(triggers);
1504 1505
    }

1506
    /**
1507
     * Gets the specific trigger, or null if the propert is not configured for this job.
1508 1509 1510
     */
    public <T extends Trigger> T getTrigger(Class<T> clazz) {
        for (Trigger p : triggers) {
1511
            if(clazz.isInstance(p))
1512 1513 1514 1515 1516
                return clazz.cast(p);
        }
        return null;
    }

1517 1518 1519 1520 1521
//
//
// fingerprint related
//
//
1522 1523 1524 1525 1526 1527
    /**
     * True if the builds of this project produces {@link Fingerprint} records.
     */
    public abstract boolean isFingerprintConfigured();

    /**
1528 1529
     * Gets the other {@link AbstractProject}s that should be built
     * when a build of this project is completed.
1530
     */
K
kohsuke 已提交
1531
    @Exported
1532
    public final List<AbstractProject> getDownstreamProjects() {
1533
        return Jenkins.getInstance().getDependencyGraph().getDownstream(this);
1534
    }
1535

K
kohsuke 已提交
1536
    @Exported
1537
    public final List<AbstractProject> getUpstreamProjects() {
1538
        return Jenkins.getInstance().getDependencyGraph().getUpstream(this);
K
kohsuke 已提交
1539 1540
    }

K
kohsuke 已提交
1541
    /**
1542 1543 1544 1545
     * 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 已提交
1546 1547 1548
     */
    public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
        ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
1549 1550
        for (AbstractProject<?,?> ap : getUpstreamProjects()) {
            BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
1551
            if (buildTrigger != null)
1552
                if (buildTrigger.getChildProjects(ap).contains(this))
1553
                    result.add(ap);
1554
        }        
K
kohsuke 已提交
1555
        return result;
1556 1557
    }    
    
K
kohsuke 已提交
1558 1559
    /**
     * Gets all the upstream projects including transitive upstream projects.
1560
     *
K
kohsuke 已提交
1561 1562 1563
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveUpstreamProjects() {
1564
        return Jenkins.getInstance().getDependencyGraph().getTransitiveUpstream(this);
K
kohsuke 已提交
1565 1566 1567
    }

    /**
1568 1569
     * Gets all the downstream projects including transitive downstream projects.
     *
K
kohsuke 已提交
1570 1571 1572
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveDownstreamProjects() {
1573
        return Jenkins.getInstance().getDependencyGraph().getTransitiveDownstream(this);
1574 1575 1576 1577 1578
    }

    /**
     * Gets the dependency relationship map between this project (as the source)
     * and that project (as the sink.)
1579 1580 1581 1582
     *
     * @return
     *      can be empty but not null. build number of this project to the build
     *      numbers of that project.
1583 1584
     */
    public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
1585
        TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
1586 1587 1588 1589 1590 1591 1592 1593 1594

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

        return r;
    }

    /**
     * Helper method for getDownstreamRelationship.
1595 1596
     *
     * For each given build, find the build number range of the given project and put that into the map.
1597
     */
1598
    private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
1599 1600
        for (R build : builds) {
            RangeSet rs = build.getDownstreamRelationship(that);
1601
            if(rs==null || rs.isEmpty())
1602 1603 1604 1605 1606
                continue;

            int n = build.getNumber();

            RangeSet value = r.get(n);
1607 1608
            if(value==null)
                r.put(n,rs);
1609 1610 1611 1612 1613
            else
                value.add(rs);
        }
    }

1614 1615 1616 1617 1618 1619
    /**
     * Builds the dependency graph.
     * @see DependencyGraph
     */
    protected abstract void buildDependencyGraph(DependencyGraph graph);

1620
    @Override
K
kohsuke 已提交
1621 1622
    protected SearchIndexBuilder makeSearchIndex() {
        SearchIndexBuilder sib = super.makeSearchIndex();
1623
        if(isBuildable() && hasPermission(Jenkins.ADMINISTER))
1624
            sib.add("build","build");
K
kohsuke 已提交
1625 1626 1627
        return sib;
    }

1628 1629
    @Override
    protected HistoryWidget createHistoryWidget() {
1630
        return new BuildHistoryWidget<R>(this,getBuilds(),HISTORY_ADAPTER);
1631
    }
1632
    
K
kohsuke 已提交
1633
    public boolean isParameterized() {
1634
        return getProperty(ParametersDefinitionProperty.class) != null;
K
kohsuke 已提交
1635
    }
1636

1637 1638 1639 1640 1641
//
//
// actions
//
//
1642 1643 1644
    /**
     * Schedules a new build command.
     */
1645
    public void doBuild( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1646
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
1647

K
kohsuke 已提交
1648 1649 1650
        // if a build is parameterized, let that take over
        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
1651
            pp._doBuild(req,rsp);
K
kohsuke 已提交
1652 1653 1654
            return;
        }

1655 1656 1657
        if (!isBuildable())
            throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));

1658
        Jenkins.getInstance().getQueue().schedule(this, getDelay(req), getBuildCause(req));
1659 1660 1661 1662 1663 1664 1665
        rsp.forwardToPreviousPage(req);
    }

    /**
     * Computes the build cause, using RemoteCause or UserCause as appropriate.
     */
    /*package*/ CauseAction getBuildCause(StaplerRequest req) {
1666 1667
        Cause cause;
        if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
1668 1669
            // Optional additional cause text when starting via token
            String causeText = req.getParameter("cause");
1670
            cause = new RemoteCause(req.getRemoteAddr(), causeText);
1671
        } else {
1672
            cause = new UserIdCause();
1673
        }
1674
        return new CauseAction(cause);
1675 1676 1677 1678 1679 1680
    }

    /**
     * Computes the delay by taking the default value and the override in the request parameter into the account.
     */
    public int getDelay(StaplerRequest req) throws ServletException {
1681
        String delay = req.getParameter("delay");
1682 1683 1684 1685 1686 1687 1688 1689 1690
        if (delay==null)    return getQuietPeriod();

        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);
            return Integer.parseInt(delay);
        } catch (NumberFormatException e) {
            throw new ServletException("Invalid delay parameter value: "+delay);
1691
        }
1692
    }
1693

1694 1695 1696 1697
    /**
     * Supports build trigger with parameters via an HTTP GET or POST.
     * Currently only String parameters are supported.
     */
1698
    public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
        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!");
        }
    	
    }
1709 1710 1711 1712

    /**
     * Schedules a new SCM polling command.
     */
1713
    public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1714 1715 1716
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
        schedulePolling();
        rsp.forwardToPreviousPage(req);
1717 1718 1719 1720 1721
    }

    /**
     * Cancels a scheduled build.
     */
1722
    public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1723
        checkPermission(ABORT);
1724

1725
        Jenkins.getInstance().getQueue().cancel(this);
1726 1727 1728
        rsp.forwardToPreviousPage(req);
    }

1729 1730 1731 1732
    /**
     * Deletes this project.
     */
    @Override
1733
    @RequirePOST
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
    public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
        delete();
        if (req == null || rsp == null)
            return;
        View view = req.findAncestorObject(View.class);
        if (view == null)
            rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl());
        else 
            rsp.sendRedirect2(req.getContextPath() + '/' + view.getUrl());
    }
    
1745
    @Override
1746 1747
    protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
        super.submit(req,rsp);
1748
        JSONObject json = req.getSubmittedForm();
1749

1750
        makeDisabled(req.getParameter("disable")!=null);
1751 1752

        jdk = req.getParameter("jdk");
1753
        if(req.getParameter("hasCustomQuietPeriod")!=null) {
1754 1755 1756 1757
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
        } else {
            quietPeriod = null;
        }
1758 1759
        if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) {
            scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount"));
S
 
shinodkm 已提交
1760
        } else {
1761
            scmCheckoutRetryCount = null;
S
 
shinodkm 已提交
1762
        }
1763
        blockBuildWhenDownstreamBuilding = req.getParameter("blockBuildWhenDownstreamBuilding")!=null;
1764 1765
        blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null;

1766
        if(req.hasParameter("customWorkspace")) {
1767
            customWorkspace = Util.fixEmptyAndTrim(req.getParameter("customWorkspace.directory"));
1768 1769 1770
        } else {
            customWorkspace = null;
        }
1771 1772 1773 1774 1775 1776 1777

        if (json.has("scmCheckoutStrategy"))
            scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class,
                json.getJSONObject("scmCheckoutStrategy"));
        else
            scmCheckoutStrategy = null;

1778
        
1779
        if(req.getParameter("hasSlaveAffinity")!=null) {
1780
            assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString"));
1781 1782 1783
        } else {
            assignedNode = null;
        }
1784
        canRoam = assignedNode==null;
1785

1786
        concurrentBuild = req.getSubmittedForm().has("concurrentBuild");
K
kohsuke 已提交
1787

1788
        authToken = BuildAuthorizationToken.create(req);
1789

K
kohsuke 已提交
1790
        setScm(SCMS.parseSCM(req,this));
1791 1792 1793

        for (Trigger t : triggers)
            t.stop();
1794
        triggers = buildDescribable(req, Trigger.for_(this));
1795
        for (Trigger t : triggers)
1796
            t.start(this,true);
1797 1798
    }

K
kohsuke 已提交
1799 1800 1801 1802 1803 1804 1805 1806 1807
    /**
     * @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)
1808
        throws FormException, ServletException {
1809

1810
        JSONObject data = req.getSubmittedForm();
1811
        List<T> r = new Vector<T>();
1812
        for (Descriptor<T> d : descriptors) {
1813 1814 1815
            String safeName = d.getJsonSafeClassName();
            if (req.getParameter(safeName) != null) {
                T instance = d.newInstance(req, data.getJSONObject(safeName));
1816
                r.add(instance);
1817 1818
            }
        }
1819
        return r;
1820 1821 1822 1823 1824
    }

    /**
     * Serves the workspace files.
     */
1825
    public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
1826
        checkPermission(AbstractProject.WORKSPACE);
K
kohsuke 已提交
1827
        FilePath ws = getSomeWorkspace();
1828
        if ((ws == null) || (!ws.exists())) {
1829
            // if there's no workspace, report a nice error message
1830 1831 1832 1833
            // 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.
1834
            req.getView(this,"noWorkspace.jelly").forward(req,rsp);
1835
            return null;
1836
        } else {
1837
            return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.png", true);
1838 1839
        }
    }
1840

1841 1842 1843
    /**
     * Wipes out the workspace.
     */
1844
    public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
1845
        checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD);
1846 1847 1848 1849
        R b = getSomeBuildWithWorkspace();
        FilePath ws = b!=null ? b.getWorkspace() : null;
        if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
            ws.deleteRecursive();
1850 1851 1852
            for (WorkspaceListener wl : WorkspaceListener.all()) {
                wl.afterDelete(this);
            }
1853 1854 1855 1856
            return new HttpRedirect(".");
        } else {
            // If we get here, that means the SCM blocked the workspace deletion.
            return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
1857
        }
1858 1859
    }

1860
    @CLIMethod(name="disable-job")
1861
    @RequirePOST
1862
    public HttpResponse doDisable() throws IOException, ServletException {
1863 1864
        checkPermission(CONFIGURE);
        makeDisabled(true);
1865
        return new HttpRedirect(".");
1866 1867
    }

1868
    @CLIMethod(name="enable-job")
1869
    @RequirePOST
1870
    public HttpResponse doEnable() throws IOException, ServletException {
1871 1872
        checkPermission(CONFIGURE);
        makeDisabled(false);
1873
        return new HttpRedirect(".");
1874 1875
    }

K
kohsuke 已提交
1876 1877 1878
    /**
     * RSS feed for changes in this project.
     */
1879
    public void doRssChangelog(  StaplerRequest req, StaplerResponse rsp  ) throws IOException, ServletException {
K
kohsuke 已提交
1880 1881 1882 1883 1884 1885 1886 1887 1888
        class FeedItem {
            ChangeLogSet.Entry e;
            int idx;

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

1889
            AbstractBuild<?,?> getBuild() {
K
kohsuke 已提交
1890 1891 1892 1893 1894 1895
                return e.getParent().build;
            }
        }

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

1896 1897 1898 1899
        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 已提交
1900 1901
        }

1902 1903 1904 1905 1906 1907 1908
        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 已提交
1909

1910 1911 1912
                public String getEntryUrl(FeedItem item) {
                    return item.getBuild().getUrl()+"changes#detail"+item.idx;
                }
K
kohsuke 已提交
1913

1914 1915 1916
                public String getEntryID(FeedItem item) {
                    return getEntryUrl(item);
                }
K
kohsuke 已提交
1917

1918 1919 1920 1921 1922 1923
                public String getEntryDescription(FeedItem item) {
                    StringBuilder buf = new StringBuilder();
                    for(String path : item.e.getAffectedPaths())
                        buf.append(path).append('\n');
                    return buf.toString();
                }
1924

1925 1926 1927
                public Calendar getEntryTimestamp(FeedItem item) {
                    return item.getBuild().getTimestamp();
                }
1928

1929
                public String getEntryAuthor(FeedItem entry) {
1930
                    return Mailer.descriptor().getAdminAddress();
1931 1932 1933
                }
            },
            req, rsp );
K
kohsuke 已提交
1934 1935
    }

1936 1937 1938 1939 1940 1941 1942
    /**
     * {@link AbstractProject} subtypes should implement this base class as a descriptor.
     *
     * @since 1.294
     */
    public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
        /**
1943
         * {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
1944
         * from showing up on their configuration screen. This is often useful when you are building
1945 1946
         * a workflow/company specific project type, where you want to limit the number of choices
         * given to the users.
1947 1948
         *
         * <p>
1949 1950 1951 1952
         * 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}
1953 1954 1955 1956
         * to show up for the given {@link Project}.
         *
         * <p>
         * The default implementation returns true for everything.
1957 1958
         *
         * @see BuildStepDescriptor#isApplicable(Class) 
K
kohsuke 已提交
1959 1960
         * @see BuildWrapperDescriptor#isApplicable(AbstractProject) 
         * @see TriggerDescriptor#isApplicable(Item)
1961
         */
K
kohsuke 已提交
1962
        @Override
1963
        public boolean isApplicable(Descriptor descriptor) {
1964 1965
            return true;
        }
1966 1967

        public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {
1968 1969
            if (Util.fixEmpty(value)==null)
                return FormValidation.ok(); // nothing typed yet
1970 1971 1972
            try {
                Label.parseExpression(value);
            } catch (ANTLRException e) {
S
Seiji Sogabe 已提交
1973 1974
                return FormValidation.error(e,
                        Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
1975
            }
1976 1977 1978 1979 1980 1981 1982 1983
            Label l = Jenkins.getInstance().getLabel(value);
            if (l.isEmpty()) {
                for (LabelAtom a : l.listAtoms()) {
                    if (a.isEmpty()) {
                        LabelAtom nearest = LabelAtom.findNearest(a.getName());
                        return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch_DidYouMean(a.getName(),nearest.getDisplayName()));
                    }
                }
S
Seiji Sogabe 已提交
1984
                return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());
1985
            }
1986 1987
            return FormValidation.ok();
        }
1988

1989
        public FormValidation doCheckCustomWorkspace(@QueryParameter(value="customWorkspace.directory") String customWorkspace){
1990
        	if(Util.fixEmptyAndTrim(customWorkspace)==null)
S
Seiji Sogabe 已提交
1991
        		return FormValidation.error(Messages.AbstractProject_CustomWorkspaceEmpty());
1992 1993 1994 1995
        	else
        		return FormValidation.ok();
        }
        
1996 1997
        public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value) {
            AutoCompletionCandidates candidates = new AutoCompletionCandidates();
1998
            List<Job> jobs = Jenkins.getInstance().getItems(Job.class);
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
            for (Job job: jobs) {
                if (job.getFullName().startsWith(value)) {
                    if (job.hasPermission(Item.READ)) {
                        candidates.add(job.getFullName());
                    }
                }
            }
            return candidates;
        }

        public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) {
2010
            AutoCompletionCandidates c = new AutoCompletionCandidates();
2011
            Set<Label> labels = Jenkins.getInstance().getLabels();
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
            List<String> queries = new AutoCompleteSeeder(value).getSeeds();

            for (String term : queries) {
                for (Label l : labels) {
                    if (l.getName().startsWith(term)) {
                        c.add(l.getName());
                    }
                }
            }
            return c;
        }

2024
        public List<SCMCheckoutStrategyDescriptor> getApplicableSCMCheckoutStrategyDescriptors(AbstractProject p) {
2025 2026 2027
            return SCMCheckoutStrategyDescriptor._for(p);
        }

2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
        /**
        * Utility class for taking the current input value and computing a list
        * of potential terms to match against the list of defined labels.
         */
        static class AutoCompleteSeeder {
            private String source;

            AutoCompleteSeeder(String source) {
                this.source = source;
            }

            List<String> getSeeds() {
C
Christoph Kutzinski 已提交
2040
                ArrayList<String> terms = new ArrayList<String>();
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
                boolean trailingQuote = source.endsWith("\"");
                boolean leadingQuote = source.startsWith("\"");
                boolean trailingSpace = source.endsWith(" ");

                if (trailingQuote || (trailingSpace && !leadingQuote)) {
                    terms.add("");
                } else {
                    if (leadingQuote) {
                        int quote = source.lastIndexOf('"');
                        if (quote == 0) {
                            terms.add(source.substring(1));
                        } else {
                            terms.add("");
                        }
                    } else {
                        int space = source.lastIndexOf(' ');
                        if (space > -1) {
                            terms.add(source.substring(space+1));
                        } else {
                            terms.add(source);
                        }
                    }
                }

                return terms;
            }
        }
2068 2069
    }

2070
    /**
2071
     * Finds a {@link AbstractProject} that has the name closest to the given name.
2072 2073
     */
    public static AbstractProject findNearest(String name) {
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
        return findNearest(name,Hudson.getInstance());
    }

    /**
     * Finds a {@link AbstractProject} whose name (when referenced from the specified context) is closest to the given name.
     *
     * @since 1.419
     */
    public static AbstractProject findNearest(String name, ItemGroup context) {
        List<AbstractProject> projects = Hudson.getInstance().getAllItems(AbstractProject.class);
2084
        String[] names = new String[projects.size()];
2085
        for( int i=0; i<projects.size(); i++ )
2086
            names[i] = projects.get(i).getRelativeNameFrom(context);
2087 2088

        String nearest = EditDistance.findNearest(name, names);
2089
        return (AbstractProject)Jenkins.getInstance().getItem(nearest,context);
2090
    }
2091 2092 2093

    private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
2094
            return o2-o1;
2095 2096
        }
    };
2097

2098
    private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
2099

2100
    /**
2101
     * Permission to abort a build
2102
     */
2103
    public static final Permission ABORT = CANCEL;
2104

K
Kohsuke Kawaguchi 已提交
2105 2106 2107
    /**
     * Replaceable "Build Now" text.
     */
2108 2109
    public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();

2110 2111 2112 2113 2114 2115
    /**
     * Used for CLI binding.
     */
    @CLIResolver
    public static AbstractProject resolveForCLI(
            @Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException {
2116
        AbstractProject item = Jenkins.getInstance().getItemByFullName(name, AbstractProject.class);
2117 2118 2119 2120
        if (item==null)
            throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));
        return item;
    }
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139

    public String getCustomWorkspace() {
        return customWorkspace;
    }

    /**
     * User-specified workspace directory, or null if it's up to Jenkins.
     *
     * <p>
     * Normally a project uses the workspace location assigned by its parent container,
     * but sometimes people have builds that have hard-coded paths.
     *
     * <p>
     * This is not {@link File} because it may have to hold a path representation on another OS.
     *
     * <p>
     * If this path is relative, it's resolved against {@link Node#getRootPath()} on the node where this workspace
     * is prepared. 
     *
2140
     * @since 1.410
2141 2142
     */
    public void setCustomWorkspace(String customWorkspace) throws IOException {
2143
        this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace);
2144 2145
        save();
    }
2146
    
2147
}