AbstractProject.java 83.5 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.EnvVars;
32
import hudson.Functions;
33
import antlr.ANTLRException;
K
kohsuke 已提交
34
import hudson.AbortException;
35
import hudson.CopyOnWrite;
36
import hudson.FeedAdapter;
37
import hudson.FilePath;
38
import hudson.Launcher;
39
import hudson.Util;
40
import hudson.cli.declarative.CLIMethod;
41
import hudson.cli.declarative.CLIResolver;
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;
47
import hudson.model.PermalinkProjectAction.Permalink;
K
kohsuke 已提交
48
import hudson.model.Queue.Executable;
49
import hudson.model.Queue.Task;
50
import hudson.model.queue.QueueTaskFuture;
K
Kohsuke Kawaguchi 已提交
51
import hudson.model.queue.ScheduleResult;
52
import hudson.model.queue.SubTask;
53
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;
59
import hudson.node_monitors.DiskSpaceMonitor;
K
kohsuke 已提交
60
import hudson.scm.ChangeLogSet;
K
kohsuke 已提交
61
import hudson.scm.ChangeLogSet.Entry;
62
import hudson.scm.NullSCM;
63
import hudson.scm.PollingResult;
64
import hudson.scm.SCM;
65
import hudson.scm.SCMRevisionState;
66
import hudson.scm.SCMS;
J
jbq 已提交
67
import hudson.search.SearchIndexBuilder;
68
import hudson.security.ACL;
K
kohsuke 已提交
69
import hudson.security.Permission;
70
import hudson.slaves.WorkspaceList;
71
import hudson.tasks.BuildStep;
72
import hudson.tasks.BuildStepDescriptor;
J
jbq 已提交
73
import hudson.tasks.BuildTrigger;
74
import hudson.tasks.BuildWrapperDescriptor;
75
import hudson.tasks.Publisher;
K
kohsuke 已提交
76
import hudson.triggers.SCMTrigger;
77
import hudson.triggers.Trigger;
78
import hudson.triggers.TriggerDescriptor;
79 80
import hudson.util.AlternativeUiTextProvider;
import hudson.util.AlternativeUiTextProvider.Message;
81
import hudson.util.DescribableList;
82
import hudson.util.EditDistance;
S
 
shinodkm 已提交
83
import hudson.util.FormValidation;
K
kohsuke 已提交
84 85
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
86
import jenkins.model.Jenkins;
87
import jenkins.model.JenkinsLocationConfiguration;
88
import jenkins.model.ModelObjectWithChildren;
89
import jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;
90 91 92
import jenkins.scm.DefaultSCMCheckoutStrategyImpl;
import jenkins.scm.SCMCheckoutStrategy;
import jenkins.scm.SCMCheckoutStrategyDescriptor;
93
import jenkins.util.TimeDuration;
K
kohsuke 已提交
94
import net.sf.json.JSONObject;
95
import org.acegisecurity.Authentication;
96 97
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
98 99
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
100 101
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
102
import org.kohsuke.stapler.Ancestor;
103 104 105
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
106
import org.kohsuke.stapler.HttpResponses;
107
import org.kohsuke.stapler.QueryParameter;
K
kohsuke 已提交
108 109 110
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
111
import org.kohsuke.stapler.interceptor.RequirePOST;
112

113
import javax.annotation.Nonnull;
K
kohsuke 已提交
114
import javax.servlet.ServletException;
115
import java.io.File;
116
import java.io.IOException;
K
kohsuke 已提交
117
import java.lang.reflect.InvocationTargetException;
K
kohsuke 已提交
118
import java.util.ArrayList;
119
import java.util.Arrays;
120
import java.util.Calendar;
121
import java.util.Collection;
J
jbq 已提交
122
import java.util.Collections;
123
import java.util.Comparator;
J
jbq 已提交
124
import java.util.HashSet;
125
import java.util.List;
126
import java.util.ListIterator;
127
import java.util.Map;
J
jbq 已提交
128
import java.util.Set;
129 130 131
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
K
kohsuke 已提交
132
import java.util.concurrent.Future;
K
Kohsuke Kawaguchi 已提交
133
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
134 135
import java.util.logging.Level;
import java.util.logging.Logger;
136

137 138 139
import static hudson.scm.PollingResult.*;
import static javax.servlet.http.HttpServletResponse.*;

140 141
/**
 * Base implementation of {@link Job}s that build software.
142
 *
143
 * For now this is primarily the common part of {@link Project} and MavenModule.
144
 *
145 146 147
 * @author Kohsuke Kawaguchi
 * @see AbstractBuild
 */
C
Christoph Kutzinski 已提交
148
@SuppressWarnings("rawtypes")
149
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem, ModelObjectWithChildren {
150

151
    /**
152 153 154
     * {@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()}.
155
     */
K
kohsuke 已提交
156
    private volatile SCM scm = new NullSCM();
157

158 159 160 161 162
    /**
     * Controls how the checkout is done.
     */
    private volatile SCMCheckoutStrategy scmCheckoutStrategy;

163 164 165 166 167
    /**
     * State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.
     */
    private volatile transient SCMRevisionState pollingBaseline = null;

168 169
    /**
     * All the builds keyed by their build number.
170 171 172
     *
     * External code should use {@link #getBuildByNumber(int)} or {@link #getLastBuild()} and traverse via
     * {@link Run#getPreviousBuild()}
173
     */
174
    @Restricted(NoExternalUse.class)
175 176
    @SuppressWarnings("deprecation") // [JENKINS-15156] builds accessed before onLoad or onCreatedFromScratch called
    protected transient RunMap<R> builds = new RunMap<R>();
177 178 179 180

    /**
     * The quiet period. Null to delegate to the system default.
     */
K
kohsuke 已提交
181
    private volatile Integer quietPeriod = null;
S
 
shinodkm 已提交
182 183
    
    /**
184
     * The retry count. Null to delegate to the system default.
S
 
shinodkm 已提交
185
     */
186
    private volatile Integer scmCheckoutRetryCount = null;
187 188

    /**
189 190 191 192 193 194 195
     * 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.
     *
196
     * @see #canRoam
197 198 199 200 201
     */
    private String assignedNode;

    /**
     * True if this project can be built on any node.
202
     *
203
     * <p>
204 205
     * This somewhat ugly flag combination is so that we can migrate
     * existing Hudson installations nicely.
206
     */
K
kohsuke 已提交
207
    private volatile boolean canRoam;
208 209 210 211

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

214 215 216 217 218 219
    /**
     * 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;

220 221 222 223 224 225
    /**
     * 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;

226
    /**
227 228 229
     * Identifies {@link JDK} to be used.
     * Null if no explicit configuration is required.
     *
230
     * <p>
231
     * Can't store {@link JDK} directly because {@link Jenkins} and {@link Project}
232 233
     * are saved independently.
     *
234
     * @see Jenkins#getJDK(String)
235
     */
K
kohsuke 已提交
236
    private volatile String jdk;
237

K
kohsuke 已提交
238
    private volatile BuildAuthorizationToken authToken = null;
239

240 241 242
    /**
     * List of all {@link Trigger}s for this project.
     */
K
Kohsuke Kawaguchi 已提交
243 244 245
    protected volatile DescribableList<Trigger<?>,TriggerDescriptor> triggers = new DescribableList<Trigger<?>,TriggerDescriptor>(this);
    private AtomicReferenceFieldUpdater<AbstractProject,List> triggersUpdater
            = AtomicReferenceFieldUpdater.newUpdater(AbstractProject.class,List.class,"triggers");
246

247 248
    /**
     * {@link Action}s contributed from subsidiary objects associated with
249 250 251 252
     * {@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.
253
     */
254 255
    @CopyOnWrite
    protected transient volatile List<Action> transientActions = new Vector<Action>();
256

K
kohsuke 已提交
257 258
    private boolean concurrentBuild;

259 260 261
    /**
     * See {@link #setCustomWorkspace(String)}.
     *
262
     * @since 1.410
263 264 265
     */
    private String customWorkspace;
    
266
    protected AbstractProject(ItemGroup parent, String name) {
267
        super(parent,name);
268

269
        if(!Jenkins.getInstance().getNodes().isEmpty()) {
270
            // if a new job is configured with Hudson that already has slave nodes
271 272 273
            // make it roamable by default
            canRoam = true;
        }
274 275
    }

276 277 278 279 280 281
    @Override
    public synchronized void save() throws IOException {
        super.save();
        updateTransientActions();
    }

282 283 284
    @Override
    public void onCreatedFromScratch() {
        super.onCreatedFromScratch();
J
Johno Crawford 已提交
285
        builds = createBuildRunMap();
286 287
        // solicit initial contributions, especially from TransientProjectActionFactory
        updateTransientActions();
288 289
    }

290
    @Override
291
    public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
292
        super.onLoad(parent, name);
293

J
Johno Crawford 已提交
294
        RunMap<R> builds = createBuildRunMap();
K
Kohsuke Kawaguchi 已提交
295 296 297

        RunMap<R> currentBuilds = this.builds;

298
        if (currentBuilds==null && parent!=null) {
K
Kohsuke Kawaguchi 已提交
299 300 301 302 303
            // are we overwriting what currently exist?
            // this is primarily when Jenkins is getting reloaded
            Item current = parent.getItem(name);
            if (current!=null && current.getClass()==getClass()) {
                currentBuilds = ((AbstractProject)current).builds;
K
Oops  
Kohsuke Kawaguchi 已提交
304
            }
K
Kohsuke Kawaguchi 已提交
305 306
        }
        if (currentBuilds !=null) {
307
            // if we are reloading, keep all those that are still building intact
K
Kohsuke Kawaguchi 已提交
308
            for (R r : currentBuilds.getLoadedBuilds().values()) {
309 310 311 312 313
                if (r.isBuilding())
                    builds.put(r);
            }
        }
        this.builds = builds;
K
Kohsuke Kawaguchi 已提交
314
        triggers().setOwner(this);
315
        for (Trigger t : triggers())
316
            t.start(this, Items.updatingByXml.get());
317 318
        if(scm==null)
            scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
319

320 321
        if(transientActions==null)
            transientActions = new Vector<Action>();    // happens when loaded from disk
322
        updateTransientActions();
323 324
    }

J
Johno Crawford 已提交
325 326 327 328 329 330 331 332
    private RunMap<R> createBuildRunMap() {
        return new RunMap<R>(getBuildDir(), new Constructor<R>() {
            public R create(File dir) throws IOException {
                return loadBuild(dir);
            }
        });
    }

K
Kohsuke Kawaguchi 已提交
333 334
    @WithBridgeMethods(List.class)
    protected DescribableList<Trigger<?>,TriggerDescriptor> triggers() {
335
        if (triggers == null) {
K
Kohsuke Kawaguchi 已提交
336
            triggersUpdater.compareAndSet(this,null,new DescribableList<Trigger<?>,TriggerDescriptor>(this));
337 338 339 340
        }
        return triggers;
    }

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    @Override
    public EnvVars getEnvironment(Node node, TaskListener listener) throws IOException, InterruptedException {
        EnvVars env =  super.getEnvironment(node, listener);

        JDK jdk = getJDK();
        if (jdk != null) {
            if (node != null) { // just in case were not in a build
                jdk = jdk.forNode(node, listener);
            }
            jdk.buildEnvVars(env);
        }

        return env;
    }

356
    @Override
357
    protected void performDelete() throws IOException, InterruptedException {
K
kohsuke 已提交
358 359
        // prevent a new build while a delete operation is in progress
        makeDisabled(true);
360
        FilePath ws = getWorkspace();
361
        if(ws!=null) {
K
NPE fix  
kohsuke 已提交
362 363 364 365
            Node on = getLastBuiltOn();
            getScm().processWorkspaceBeforeDeletion(this, ws, on);
            if(on!=null)
                on.getFileSystemProvisioner().discardWorkspace(this,ws);
366
        }
K
kohsuke 已提交
367 368 369
        super.performDelete();
    }

K
kohsuke 已提交
370 371
    /**
     * Does this project perform concurrent builds?
K
kohsuke 已提交
372
     * @since 1.319
K
kohsuke 已提交
373
     */
K
kohsuke 已提交
374
    @Exported
K
kohsuke 已提交
375
    public boolean isConcurrentBuild() {
376
        return concurrentBuild;
K
kohsuke 已提交
377 378 379 380 381 382 383
    }

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

384
    /**
385 386
     * If this project is configured to be always built on this node,
     * return that {@link Node}. Otherwise null.
387
     */
388
    public Label getAssignedLabel() {
389
        if(canRoam)
390 391
            return null;

392
        if(assignedNode==null)
393 394
            return Jenkins.getInstance().getSelfLabel();
        return Jenkins.getInstance().getLabel(assignedNode);
395 396
    }

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    /**
     * 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());
    }

412 413 414 415
    /**
     * Gets the textual representation of the assigned label as it was entered by the user.
     */
    public String getAssignedLabelString() {
416 417 418 419 420 421 422 423
        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);
        }
424 425
    }

K
kohsuke 已提交
426 427 428 429 430 431 432 433 434
    /**
     * Sets the assigned label.
     */
    public void setAssignedLabel(Label l) throws IOException {
        if(l==null) {
            canRoam = true;
            assignedNode = null;
        } else {
            canRoam = false;
435
            if(l== Jenkins.getInstance().getSelfLabel())  assignedNode = null;
436
            else                                        assignedNode = l.getExpression();
K
kohsuke 已提交
437 438 439 440
        }
        save();
    }

441 442 443 444 445 446 447
    /**
     * Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.
     */
    public void setAssignedNode(Node l) throws IOException {
        setAssignedLabel(l.getSelfLabel());
    }

448
    /**
449 450
     * Get the term used in the UI to represent this kind of {@link AbstractProject}.
     * Must start with a capital letter.
451 452 453
     */
    @Override
    public String getPronoun() {
K
Kohsuke Kawaguchi 已提交
454
        return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun());
455 456
    }

457 458 459 460 461 462
    /**
     * Gets the human readable display name to be rendered in the "Build Now" link.
     *
     * @since 1.401
     */
    public String getBuildNowText() {
463
        return AlternativeUiTextProvider.get(BUILD_NOW_TEXT, this, isParameterized() ? Messages.AbstractProject_build_with_parameters() : Messages.AbstractProject_BuildNow());
464 465
    }

466
    /**
467
     * Gets the nearest ancestor {@link TopLevelItem} that's also an {@link AbstractProject}.
468
     *
469 470 471 472 473 474 475
     * <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()
476
     */
477 478
    public AbstractProject<?,?> getRootProject() {
        if (this instanceof TopLevelItem) {
479 480
            return this;
        } else {
481 482 483 484
            ItemGroup p = this.getParent();
            if (p instanceof AbstractProject)
                return ((AbstractProject) p).getRootProject();
            return this;
485 486 487
        }
    }

488 489
    /**
     * Gets the directory where the module is checked out.
490 491 492
     *
     * @return
     *      null if the workspace is on a slave that's not connected.
K
kohsuke 已提交
493
     * @deprecated as of 1.319
K
kohsuke 已提交
494 495 496 497 498
     *      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>
499
     *      If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
K
kohsuke 已提交
500 501 502 503
     *      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() {
504 505 506 507 508 509 510 511 512 513 514 515
        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 已提交
516 517 518 519 520 521
        Executor e = Executor.currentExecutor();
        if(e!=null) {
            Executable exe = e.getCurrentExecutable();
            if (exe instanceof AbstractBuild) {
                AbstractBuild b = (AbstractBuild) exe;
                if(b.getProject()==this)
522
                    return b;
K
kohsuke 已提交
523 524 525
            }
        }
        R lb = getLastBuild();
526
        if(lb!=null)    return lb;
K
kohsuke 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539
        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 已提交
540
     * @since 1.319
541
     */
K
kohsuke 已提交
542
    public final FilePath getSomeWorkspace() {
543
        R b = getSomeBuildWithWorkspace();
544 545 546 547 548 549
        if (b!=null) return b.getWorkspace();
        for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
            FilePath f = browser.getWorkspace(this);
            if (f != null) return f;
        }
        return null;
550 551 552 553 554 555 556 557
    }

    /**
     * Gets some build that has a live workspace.
     *
     * @return null if no such build exists.
     */
    public final R getSomeBuildWithWorkspace() {
K
kohsuke 已提交
558 559 560
        int cnt=0;
        for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
            FilePath ws = b.getWorkspace();
561
            if (ws!=null)   return b;
K
kohsuke 已提交
562 563 564
        }
        return null;
    }
565

566 567 568
    /**
     * Returns the root directory of the checked-out module.
     * <p>
569 570
     * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
     * and so on exists.
K
kohsuke 已提交
571
     *
K
kohsuke 已提交
572
     * @deprecated as of 1.319
K
kohsuke 已提交
573
     *      See {@link #getWorkspace()} for a migration strategy.
574 575
     */
    public FilePath getModuleRoot() {
576 577
        AbstractBuild b = getBuildForDeprecatedMethods();
        return b != null ? b.getModuleRoot() : null;
578 579
    }

S
stephenconnolly 已提交
580 581 582 583 584 585
    /**
     * 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 已提交
586
     *
K
kohsuke 已提交
587
     * @deprecated as of 1.319
K
kohsuke 已提交
588
     *      See {@link #getWorkspace()} for a migration strategy.
S
stephenconnolly 已提交
589 590
     */
    public FilePath[] getModuleRoots() {
591 592
        AbstractBuild b = getBuildForDeprecatedMethods();
        return b != null ? b.getModuleRoots() : null;
S
stephenconnolly 已提交
593 594
    }

595
    public int getQuietPeriod() {
596
        return quietPeriod!=null ? quietPeriod : Jenkins.getInstance().getQuietPeriod();
597
    }
598

599
    public SCMCheckoutStrategy getScmCheckoutStrategy() {
600 601 602
        return scmCheckoutStrategy == null ? new DefaultSCMCheckoutStrategyImpl() : scmCheckoutStrategy;
    }

603
    public void setScmCheckoutStrategy(SCMCheckoutStrategy scmCheckoutStrategy) throws IOException {
604 605 606 607 608
        this.scmCheckoutStrategy = scmCheckoutStrategy;
        save();
    }


609
    public int getScmCheckoutRetryCount() {
610
        return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Jenkins.getInstance().getScmCheckoutRetryCount();
S
 
shinodkm 已提交
611
    }
612 613 614

    // ugly name because of EL
    public boolean getHasCustomQuietPeriod() {
615
        return quietPeriod!=null;
616
    }
K
kohsuke 已提交
617 618 619 620

    /**
     * Sets the custom quiet period of this project, or revert to the global default if null is given. 
     */
621
    public void setQuietPeriod(Integer seconds) throws IOException {
K
kohsuke 已提交
622 623 624
        this.quietPeriod = seconds;
        save();
    }
S
 
shinodkm 已提交
625
    
626
    public boolean hasCustomScmCheckoutRetryCount(){
627
        return scmCheckoutRetryCount != null;
S
 
shinodkm 已提交
628
    }
629

630
    @Override
631
    public boolean isBuildable() {
J
jpederzolli 已提交
632
        return !isDisabled() && !isHoldOffBuildUntilSave();
633 634
    }

635
    /**
636 637
     * Used in <tt>sidepanel.jelly</tt> to decide whether to display
     * the config/delete/build links.
638 639 640 641 642
     */
    public boolean isConfigurable() {
        return true;
    }

643 644 645 646 647 648 649 650 651
    public boolean blockBuildWhenDownstreamBuilding() {
        return blockBuildWhenDownstreamBuilding;
    }

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

652
    public boolean blockBuildWhenUpstreamBuilding() {
653
        return blockBuildWhenUpstreamBuilding;
654 655
    }

656
    public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
657 658
        blockBuildWhenUpstreamBuilding = b;
        save();
659 660
    }

661 662 663
    public boolean isDisabled() {
        return disabled;
    }
S
 
shinodkm 已提交
664 665 666 667 668
    
    /**
     * Validates the retry count Regex
     */
    public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
669 670 671 672 673 674 675
        // 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 已提交
676
    }
677

678 679 680 681
    /**
     * Marks the build as disabled.
     */
    public void makeDisabled(boolean b) throws IOException {
682
        if(disabled==b)     return; // noop
683
        this.disabled = b;
K
bug fix  
kohsuke 已提交
684
        if(b)
685
            Jenkins.getInstance().getQueue().cancel(this);
686 687 688
        save();
    }

689 690
    /**
     * Specifies whether this project may be disabled by the user.
691 692
     * By default, it can be only if this is a {@link TopLevelItem};
     * would be false for matrix configurations, etc.
693 694 695 696
     * @return true if the GUI should allow {@link #doDisable} and the like
     * @since 1.475
     */
    public boolean supportsMakeDisabled() {
697
        return this instanceof TopLevelItem;
698 699
    }

700 701 702 703 704 705 706 707
    public void disable() throws IOException {
        makeDisabled(true);
    }

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

K
kohsuke 已提交
708 709
    @Override
    public BallColor getIconColor() {
710
        if(isDisabled())
711
            return BallColor.DISABLED;
K
kohsuke 已提交
712 713 714
        else
            return super.getIconColor();
    }
715

716 717 718 719 720 721 722
    /**
     * effectively deprecated. Since using updateTransientActions correctly
     * under concurrent environment requires a lock that can too easily cause deadlocks.
     *
     * <p>
     * Override {@link #createTransientActions()} instead.
     */
723
    protected void updateTransientActions() {
724 725 726 727
        transientActions = createTransientActions();
    }

    protected List<Action> createTransientActions() {
728
        Vector<Action> ta = new Vector<Action>();
729

K
Kohsuke Kawaguchi 已提交
730
        for (JobProperty<? super P> p : Util.fixNull(properties))
731
            ta.addAll(p.getJobActions((P)this));
732

733 734
        for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
            ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
735
        return ta;
736 737
    }

738
    /**
739 740
     * Returns the live list of all {@link Publisher}s configured for this project.
     *
741
     * <p>
742 743
     * This method couldn't be called <tt>getPublishers()</tt> because existing methods
     * in sub-classes return different inconsistent types.
744
     */
745
    public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
746

K
kohsuke 已提交
747 748 749 750 751 752
    @Override
    public void addProperty(JobProperty<? super P> jobProp) throws IOException {
        super.addProperty(jobProp);
        updateTransientActions();
    }

753 754 755 756
    public List<ProminentProjectAction> getProminentActions() {
        List<Action> a = getActions();
        List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
        for (Action action : a) {
757
            if(action instanceof ProminentProjectAction)
758 759 760 761 762
                pa.add((ProminentProjectAction) action);
        }
        return pa;
    }

763
    @Override
764
    public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
765
        super.doConfigSubmit(req,rsp);
766

767 768
        updateTransientActions();

769
        Set<AbstractProject> upstream = Collections.emptySet();
770
        if(req.getParameter("pseudoUpstreamTrigger")!=null) {
771
            upstream = new HashSet<AbstractProject>(Items.fromNameList(getParent(),req.getParameter("upstreamProjects"),AbstractProject.class));
772 773
        }

774
        convertUpstreamBuildTrigger(upstream);
775 776

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

        // this is to reflect the upstream build adjustments done above
780
        Jenkins.getInstance().rebuildDependencyGraphAsync();
781 782
    }

783 784 785
    /**
     * Reflect the submission of the pseudo 'upstream build trigger'.
     */
786
    /* package */ void convertUpstreamBuildTrigger(Set<AbstractProject> upstream) throws IOException {
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843

        SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);
        try {
            for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
                // Don't consider child projects such as MatrixConfiguration:
                if (!p.isConfigurable()) continue;
                boolean isUpstream = upstream.contains(p);
                synchronized(p) {
                    // does 'p' include us in its BuildTrigger?
                    DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
                    BuildTrigger trigger = pl.get(BuildTrigger.class);
                    List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects(p);
                    if(isUpstream) {
                        if(!newChildProjects.contains(this))
                            newChildProjects.add(this);
                    } else {
                        newChildProjects.remove(this);
                    }

                    if(newChildProjects.isEmpty()) {
                        pl.remove(BuildTrigger.class);
                    } else {
                        // 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(p));
                            existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
                            pl.add(existing);
                            break;
                        }

                        if(existing!=null && existing.hasSame(p,newChildProjects))
                            continue;   // no need to touch
                        pl.replace(new BuildTrigger(newChildProjects,
                            existing==null? Result.SUCCESS:existing.getThreshold()));
                    }
                }
            }
        } finally {
            SecurityContextHolder.setContext(saveCtx);
        }
    }

    /**
M
mdonohue 已提交
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
	 * @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());
    }
    
859 860
    /**
     * Schedules a build of this project.
861 862
     *
     * @return
K
Kohsuke Kawaguchi 已提交
863 864
     *      true if the project is added to the queue.
     *      false if the task was rejected from the queue (such as when the system is being shut down.)
865
     */
M
mdonohue 已提交
866 867
    public boolean scheduleBuild(Cause c) {
        return scheduleBuild(getQuietPeriod(), c);
K
kohsuke 已提交
868 869
    }

M
mdonohue 已提交
870
    public boolean scheduleBuild(int quietPeriod, Cause c) {
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
        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) {
887 888 889 890 891 892
        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.
893 894 895
     *
     * @param actions
     *      For the convenience of the caller, this array can contain null, and those will be silently ignored.
896
     */
897 898
    @WithBridgeMethods(Future.class)
    public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
K
kohsuke 已提交
899 900 901 902 903 904 905 906 907 908 909
        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 已提交
910
    @SuppressWarnings("unchecked")
911 912
    @WithBridgeMethods(Future.class)
    public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {
913
        if (!isBuildable())
914
            return null;
915

K
kohsuke 已提交
916
        List<Action> queueActions = new ArrayList<Action>(actions);
917 918 919 920
        if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
            queueActions.add(new ParametersAction(getDefaultParametersValues()));
        }

S
sogabe 已提交
921 922 923 924
        if (c != null) {
            queueActions.add(new CauseAction(c));
        }

K
Kohsuke Kawaguchi 已提交
925 926 927
        ScheduleResult i = Jenkins.getInstance().getQueue().schedule2(this, quietPeriod, queueActions);
        if(i.isAccepted())
            return (QueueTaskFuture)i.getItem().getFuture();
928
        return null;
929 930 931 932 933 934
    }

    private List<ParameterValue> getDefaultParametersValues() {
        ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
        ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
        
M
mindless 已提交
935 936 937
        /*
         * This check is made ONLY if someone will call this method even if isParametrized() is false.
         */
938 939 940 941 942 943 944 945 946 947 948 949 950
        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 已提交
951 952
    }

953
    /**
954 955 956 957
     * Schedules a build, and returns a {@link Future} object
     * to wait for the completion of the build.
     *
     * <p>
958
     * Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
959
     * as deprecated.
960
     */
C
Christoph Kutzinski 已提交
961
    @SuppressWarnings("deprecation")
962 963
    @WithBridgeMethods(Future.class)
    public QueueTaskFuture<R> scheduleBuild2(int quietPeriod) {
964
        return scheduleBuild2(quietPeriod, new LegacyCodeCause());
M
mdonohue 已提交
965 966
    }
    
K
kohsuke 已提交
967
    /**
968 969
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
K
kohsuke 已提交
970
     */
971 972
    @WithBridgeMethods(Future.class)
    public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c) {
973 974 975
        return scheduleBuild2(quietPeriod, c, new Action[0]);
    }

976 977 978 979
    /**
     * Schedules a polling of this project.
     */
    public boolean schedulePolling() {
980
        if(isDisabled())    return false;
981
        SCMTrigger scmt = getTrigger(SCMTrigger.class);
982
        if(scmt==null)      return false;
983 984 985 986
        scmt.run();
        return true;
    }

987 988 989 990 991
    /**
     * Returns true if the build is in the queue.
     */
    @Override
    public boolean isInQueue() {
992
        return Jenkins.getInstance().getQueue().contains(this);
993 994
    }

K
kohsuke 已提交
995 996
    @Override
    public Queue.Item getQueueItem() {
997
        return Jenkins.getInstance().getQueue().getItem(this);
K
kohsuke 已提交
998 999
    }

K
kohsuke 已提交
1000 1001 1002
    /**
     * Gets the JDK that this project is configured with, or null.
     */
1003
    public JDK getJDK() {
1004
        return Jenkins.getInstance().getJDK(jdk);
1005 1006 1007 1008 1009
    }

    /**
     * Overwrites the JDK setting.
     */
K
kohsuke 已提交
1010
    public void setJDK(JDK jdk) throws IOException {
1011 1012 1013 1014
        this.jdk = jdk.getName();
        save();
    }

1015 1016
    public BuildAuthorizationToken getAuthToken() {
        return authToken;
1017 1018
    }

1019
    @Override
1020
    public RunMap<R> _getRuns() {
J
Jesse Glick 已提交
1021 1022 1023
        if (builds == null) {
            throw new IllegalStateException("no run map created yet for " + this);
        }
1024
        assert builds.baseDirInitialized() : "neither onCreatedFromScratch nor onLoad called on " + this + " yet";
1025
        return builds;
1026 1027
    }

1028
    @Override
1029 1030 1031 1032
    public void removeRun(R run) {
        this.builds.remove(run);
    }

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
    /**
     * {@inheritDoc}
     *
     * More efficient implementation.
     */
    @Override
    public R getBuild(String id) {
        return builds.getById(id);
    }

    /**
     * {@inheritDoc}
     *
     * More efficient implementation.
     */
    @Override
    public R getBuildByNumber(int n) {
        return builds.getByNumber(n);
    }

    /**
     * {@inheritDoc}
     *
     * More efficient implementation.
     */
    @Override
    public R getFirstBuild() {
        return builds.oldestBuild();
    }

    @Override
    public R getLastBuild() {
        return builds.newestBuild();
    }

    @Override
    public R getNearestBuild(int n) {
        return builds.search(n, Direction.ASC);
    }

    @Override
    public R getNearestOldBuild(int n) {
        return builds.search(n, Direction.DESC);
    }

1078 1079 1080 1081 1082
    /**
     * Determines Class&lt;R>.
     */
    protected abstract Class<R> getBuildClass();

H
huybrechts 已提交
1083
    // keep track of the previous time we started a build
1084
    private transient long lastBuildStartTime;
H
huybrechts 已提交
1085
    
1086 1087 1088
    /**
     * Creates a new build of this project for immediate execution.
     */
H
huybrechts 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
    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();
1100
        try {
1101
            R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
1102 1103 1104 1105 1106 1107 1108
            builds.put(lastBuild);
            return lastBuild;
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
1109
            throw handleInvocationTargetException(e);
1110 1111 1112 1113
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
1114

1115
    private IOException handleInvocationTargetException(InvocationTargetException e) {
1116
        Throwable t = e.getTargetException();
1117 1118 1119
        if(t instanceof Error)  throw (Error)t;
        if(t instanceof RuntimeException)   throw (RuntimeException)t;
        if(t instanceof IOException)    return (IOException)t;
1120 1121 1122
        throw new Error(t);
    }

1123 1124 1125
    /**
     * Loads an existing build record from disk.
     */
1126 1127
    protected R loadBuild(File dir) throws IOException {
        try {
1128
            return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
1129 1130 1131 1132 1133
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
1134
            throw handleInvocationTargetException(e);
1135 1136 1137 1138
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
1139

K
kohsuke 已提交
1140 1141
    /**
     * {@inheritDoc}
1142
     *
K
kohsuke 已提交
1143 1144
     * <p>
     * Note that this method returns a read-only view of {@link Action}s.
1145
     * {@link BuildStep}s and others who want to add a project action
1146
     * should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.
1147 1148
     *
     * @see TransientProjectActionFactory
K
kohsuke 已提交
1149
     */
1150
    @Override
1151
    public List<Action> getActions() {
1152 1153 1154
        // add all the transient actions, too
        List<Action> actions = new Vector<Action>(super.getActions());
        actions.addAll(transientActions);
1155
        // return the read only list to cause a failure on plugins who try to add an action here
K
kohsuke 已提交
1156
        return Collections.unmodifiableList(actions);
1157 1158
    }

1159 1160
    /**
     * Gets the {@link Node} where this project was last built on.
1161 1162 1163 1164
     *
     * @return
     *      null if no information is available (for example,
     *      if no build was done yet.)
1165 1166 1167 1168
     */
    public Node getLastBuiltOn() {
        // where was it built on?
        AbstractBuild b = getLastBuild();
1169
        if(b==null)
1170 1171 1172 1173 1174
            return null;
        else
            return b.getBuiltOn();
    }

1175 1176 1177 1178
    public Object getSameNodeConstraint() {
        return this; // in this way, any member that wants to run with the main guy can nominate the project itself 
    }

1179 1180 1181 1182
    public final Task getOwnerTask() {
        return this;
    }

1183 1184 1185 1186
    @Nonnull
    public Authentication getDefaultAuthentication() {
        // backward compatible behaviour.
        return ACL.SYSTEM;
1187 1188
    }

1189
    /**
1190
     * {@inheritDoc}
1191
     *
1192
     * <p>
1193
     * A project must be blocked if its own previous build is in progress,
1194 1195
     * or if the blockBuildWhenUpstreamBuilding option is true and an upstream
     * project is building, but derived classes can also check other conditions.
1196
     */
1197
    public boolean isBuildBlocked() {
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
        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;
1214 1215
        }

1216
        @Override
1217 1218 1219 1220 1221 1222 1223 1224
        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);
        }
1225
    }
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
    
    /**
     * 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());
        }
    }
1242

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
    /**
     * 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;
        }

1253
        @Override
1254 1255 1256
        public String getShortDescription() {
            return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
        }
1257 1258
    }

1259
    public CauseOfBlockage getCauseOfBlockage() {
1260 1261
        // Block builds until they are done with post-production
        if (isLogUpdated() && !isConcurrentBuild())
1262
            return new BecauseOfBuildInProgress(getLastBuild());
1263 1264 1265 1266
        if (blockBuildWhenDownstreamBuilding()) {
            AbstractProject<?,?> bup = getBuildingDownstream();
            if (bup!=null)
                return new BecauseOfDownstreamBuildInProgress(bup);
1267 1268
        }
        if (blockBuildWhenUpstreamBuilding()) {
1269 1270 1271 1272 1273 1274
            AbstractProject<?,?> bup = getBuildingUpstream();
            if (bup!=null)
                return new BecauseOfUpstreamBuildInProgress(bup);
        }
        return null;
    }
1275

1276
    /**
1277 1278
     * Returns the project if any of the downstream project is either
     * building, waiting, pending or buildable.
1279 1280 1281 1282
     * <p>
     * This means eventually there will be an automatic triggering of
     * the given project (provided that all builds went smoothly.)
     */
1283
    public AbstractProject getBuildingDownstream() {
1284
        Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
1285

1286
        for (AbstractProject tup : getTransitiveDownstreamProjects()) {
1287
			if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
1288 1289 1290 1291 1292
                return tup;
        }
        return null;
    }

1293
    /**
1294
     * Returns the project if any of the upstream project is either
1295 1296 1297 1298 1299
     * 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.)
     */
1300
    public AbstractProject getBuildingUpstream() {
1301
        Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
1302

1303
        for (AbstractProject tup : getTransitiveUpstreamProjects()) {
1304
			if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
1305 1306 1307
                return tup;
        }
        return null;
1308 1309
    }

1310 1311
    public List<SubTask> getSubTasks() {
        List<SubTask> r = new ArrayList<SubTask>();
1312
        r.add(this);
1313 1314 1315
        for (SubTaskContributor euc : SubTaskContributor.all())
            r.addAll(euc.forProject(this));
        for (JobProperty<? super P> p : properties)
1316
            r.addAll(p.getSubTasks());
1317
        return r;
1318 1319
    }

1320
    public R createExecutable() throws IOException {
1321
        if(isDisabled())    return null;
1322
        return newBuild();
1323 1324
    }

1325 1326 1327 1328
    public void checkAbortPermission() {
        checkPermission(AbstractProject.ABORT);
    }

K
kohsuke 已提交
1329 1330 1331 1332
    public boolean hasAbortPermission() {
        return hasPermission(AbstractProject.ABORT);
    }

1333 1334
    /**
     * Gets the {@link Resource} that represents the workspace of this project.
1335
     * Useful for locking and mutual exclusion control.
K
kohsuke 已提交
1336
     *
K
kohsuke 已提交
1337
     * @deprecated as of 1.319
K
kohsuke 已提交
1338 1339 1340 1341 1342 1343 1344
     *      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}.
1345 1346
     */
    public Resource getWorkspaceResource() {
1347
        return new Resource(getFullDisplayName()+" workspace");
1348 1349 1350 1351 1352 1353
    }

    /**
     * List of necessary resources to perform the build of this project.
     */
    public ResourceList getResourceList() {
1354
        final Set<ResourceActivity> resourceActivities = getResourceActivities();
1355
        final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
        for (ResourceActivity activity : resourceActivities) {
            if (activity != this && activity != null) {
                // defensive infinite recursion and null check
                resourceLists.add(activity.getResourceList());
            }
        }
        return ResourceList.union(resourceLists);
    }

    /**
1366 1367
     * 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.
1368 1369
     */
    protected Set<ResourceActivity> getResourceActivities() {
K
kohsuke 已提交
1370
        return Collections.emptySet();
1371 1372
    }

1373
    public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
1374
        SCM scm = getScm();
1375 1376
        if(scm==null)
            return true;    // no SCM
1377

1378
        FilePath workspace = build.getWorkspace();
1379 1380 1381 1382
        try {
            workspace.mkdirs();
        } catch (IOException e) {
            // Can't create workspace dir - Is slave disk full ?
1383
            new DiskSpaceMonitor().markNodeOfflineIfDiskspaceIsTooLow(build.getBuiltOn().toComputer());
1384 1385
            throw e;
        }
1386 1387
        
        boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
C
Christoph Kutzinski 已提交
1388 1389 1390
        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.
1391 1392
            calcPollingBaseline(build, launcher, listener);
        }
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
        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 {
1403
                baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);
1404 1405 1406 1407 1408 1409 1410 1411 1412
            } 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;
    }

1413 1414
    /**
     * Checks if there's any update in SCM, and returns true if any is found.
1415
     *
1416 1417
     * @deprecated as of 1.346
     *      Use {@link #poll(TaskListener)} instead.
1418
     */
1419
    public boolean pollSCMChanges( TaskListener listener ) {
1420 1421 1422 1423 1424 1425 1426
        return poll(listener).hasChanges();
    }

    /**
     * Checks if there's any update in SCM, and returns true if any is found.
     *
     * <p>
1427 1428
     * The implementation is responsible for ensuring mutual exclusion between polling and builds
     * if necessary.
1429 1430 1431 1432
     *
     * @since 1.345
     */
    public PollingResult poll( TaskListener listener ) {
1433
        SCM scm = getScm();
1434
        if (scm==null) {
K
i18n  
kohsuke 已提交
1435
            listener.getLogger().println(Messages.AbstractProject_NoSCM());
1436
            return NO_CHANGES;
1437
        }
1438
        if (!isBuildable()) {
K
i18n  
kohsuke 已提交
1439
            listener.getLogger().println(Messages.AbstractProject_Disabled());
1440 1441 1442 1443 1444
            return NO_CHANGES;
        }

        R lb = getLastBuild();
        if (lb==null) {
1445
            listener.getLogger().println(Messages.AbstractProject_NoBuilds());
1446
            return isInQueue() ? NO_CHANGES : BUILD_NOW;
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
        }

        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.
1462 1463 1464
        }

        try {
K
Kohsuke Kawaguchi 已提交
1465 1466 1467 1468
            SCMPollListener.fireBeforePolling(this, listener);
            PollingResult r = _poll(listener, scm, lb);
            SCMPollListener.firePollingSuccess(this,listener, r);
            return r;
1469
        } catch (AbortException e) {
1470
            listener.getLogger().println(e.getMessage());
K
i18n  
kohsuke 已提交
1471
            listener.fatalError(Messages.AbstractProject_Aborted());
1472
            LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
K
Kohsuke Kawaguchi 已提交
1473
            SCMPollListener.firePollingFailed(this, listener,e);
1474
            return NO_CHANGES;
1475 1476
        } catch (IOException e) {
            e.printStackTrace(listener.fatalError(e.getMessage()));
K
Kohsuke Kawaguchi 已提交
1477
            SCMPollListener.firePollingFailed(this, listener,e);
1478
            return NO_CHANGES;
1479
        } catch (InterruptedException e) {
1480
            e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
K
Kohsuke Kawaguchi 已提交
1481
            SCMPollListener.firePollingFailed(this, listener,e);
1482
            return NO_CHANGES;
K
Kohsuke Kawaguchi 已提交
1483 1484 1485 1486 1487 1488
        } catch (RuntimeException e) {
            SCMPollListener.firePollingFailed(this, listener,e);
            throw e;
        } catch (Error e) {
            SCMPollListener.firePollingFailed(this, listener,e);
            throw e;
1489 1490
        }
    }
K
Kohsuke Kawaguchi 已提交
1491 1492 1493 1494 1495 1496 1497 1498 1499

    /**
     * {@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();

1500 1501
            WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( lb );
            if ( workspaceOfflineReason != null ) {
1502 1503 1504 1505 1506 1507 1508 1509 1510
                // workspace offline
                for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
                    ws = browser.getWorkspace(this);
                    if (ws != null) {
                        return pollWithWorkspace(listener, scm, lb, ws, browser.getWorkspaceList());
                    }
                }

                // build now, or nothing will ever be built
K
Kohsuke Kawaguchi 已提交
1511 1512 1513 1514
                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.
1515 1516
                    listener.getLogger().print(Messages.AbstractProject_NoWorkspace());
                    listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
K
Kohsuke Kawaguchi 已提交
1517 1518 1519 1520 1521 1522 1523 1524 1525
                    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 {
1526 1527
                    listener.getLogger().print(Messages.AbstractProject_NewBuildForWorkspace());
                    listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
K
Kohsuke Kawaguchi 已提交
1528 1529 1530 1531
                    return BUILD_NOW;
                }
            } else {
                WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
1532 1533
                return pollWithWorkspace(listener, scm, lb, ws, l);

K
Kohsuke Kawaguchi 已提交
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
            }
        } 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;
        }
    }

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
    private PollingResult pollWithWorkspace(TaskListener listener, SCM scm, R lb, FilePath ws, WorkspaceList l) throws InterruptedException, IOException {
        // 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).decorateByEnv(getEnvironment(lb.getBuiltOn(),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();
        }
    }

1568 1569 1570 1571 1572 1573 1574
    enum WorkspaceOfflineReason {
        nonexisting_workspace,
        builton_node_gone,
        builton_node_no_executors
    }

    private WorkspaceOfflineReason workspaceOffline(R build) throws IOException, InterruptedException {
1575 1576
        FilePath ws = build.getWorkspace();
        if (ws==null || !ws.exists()) {
1577
            return WorkspaceOfflineReason.nonexisting_workspace;
1578 1579 1580 1581
        }
        
        Node builtOn = build.getBuiltOn();
        if (builtOn == null) { // node built-on doesn't exist anymore
1582
            return WorkspaceOfflineReason.builton_node_gone;
1583 1584 1585
        }
        
        if (builtOn.toComputer() == null) { // node still exists, but has 0 executors - o.s.l.t.
1586
            return WorkspaceOfflineReason.builton_node_no_executors;
1587
        }
1588 1589

        return null;
1590
    }
1591

1592 1593
    /**
     * Returns true if this user has made a commit to this project.
1594
     *
1595 1596 1597
     * @since 1.191
     */
    public boolean hasParticipant(User user) {
1598 1599
        for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
            if(build.hasParticipant(user))
1600 1601 1602 1603
                return true;
        return false;
    }

1604
    @Exported
1605 1606 1607 1608
    public SCM getScm() {
        return scm;
    }

1609
    public void setScm(SCM scm) throws IOException {
1610
        this.scm = scm;
1611
        save();
1612 1613
    }

1614 1615 1616
    /**
     * Adds a new {@link Trigger} to this {@link Project} if not active yet.
     */
1617
    public void addTrigger(Trigger<?> trigger) throws IOException {
1618
        addToList(trigger,triggers());
1619 1620
    }

1621
    public void removeTrigger(TriggerDescriptor trigger) throws IOException {
1622
        removeFromList(trigger,triggers());
1623 1624
    }

1625 1626 1627 1628
    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()) {
1629
                // replace
1630
                collection.set(i,item);
1631 1632 1633 1634 1635 1636 1637
                save();
                return;
            }
        }
        // add
        collection.add(item);
        save();
1638
        updateTransientActions();
1639 1640
    }

1641 1642 1643 1644
    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) {
1645 1646 1647
                // found it
                collection.remove(i);
                save();
1648
                updateTransientActions();
1649 1650 1651 1652 1653
                return;
            }
        }
    }

C
Christoph Kutzinski 已提交
1654
    @SuppressWarnings("unchecked")
K
Kohsuke Kawaguchi 已提交
1655 1656
    public Map<TriggerDescriptor,Trigger<?>> getTriggers() {
        return triggers().toMap();
1657 1658
    }

1659
    /**
1660
     * Gets the specific trigger, or null if the propert is not configured for this job.
1661 1662
     */
    public <T extends Trigger> T getTrigger(Class<T> clazz) {
1663
        for (Trigger p : triggers()) {
1664
            if(clazz.isInstance(p))
1665 1666 1667 1668 1669
                return clazz.cast(p);
        }
        return null;
    }

1670 1671 1672 1673 1674
//
//
// fingerprint related
//
//
1675 1676 1677 1678 1679 1680
    /**
     * True if the builds of this project produces {@link Fingerprint} records.
     */
    public abstract boolean isFingerprintConfigured();

    /**
1681 1682
     * Gets the other {@link AbstractProject}s that should be built
     * when a build of this project is completed.
1683
     */
K
kohsuke 已提交
1684
    @Exported
1685
    public final List<AbstractProject> getDownstreamProjects() {
1686
        return Jenkins.getInstance().getDependencyGraph().getDownstream(this);
1687
    }
1688

K
kohsuke 已提交
1689
    @Exported
1690
    public final List<AbstractProject> getUpstreamProjects() {
1691
        return Jenkins.getInstance().getDependencyGraph().getUpstream(this);
K
kohsuke 已提交
1692 1693
    }

K
kohsuke 已提交
1694
    /**
1695 1696 1697 1698
     * 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 已提交
1699 1700 1701
     */
    public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
        ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
1702 1703
        for (AbstractProject<?,?> ap : getUpstreamProjects()) {
            BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
1704
            if (buildTrigger != null)
1705
                if (buildTrigger.getChildProjects(ap).contains(this))
1706
                    result.add(ap);
1707
        }        
K
kohsuke 已提交
1708
        return result;
1709 1710
    }    
    
K
kohsuke 已提交
1711 1712
    /**
     * Gets all the upstream projects including transitive upstream projects.
1713
     *
K
kohsuke 已提交
1714 1715 1716
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveUpstreamProjects() {
1717
        return Jenkins.getInstance().getDependencyGraph().getTransitiveUpstream(this);
K
kohsuke 已提交
1718 1719 1720
    }

    /**
1721 1722
     * Gets all the downstream projects including transitive downstream projects.
     *
K
kohsuke 已提交
1723 1724 1725
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveDownstreamProjects() {
1726
        return Jenkins.getInstance().getDependencyGraph().getTransitiveDownstream(this);
1727 1728 1729 1730 1731
    }

    /**
     * Gets the dependency relationship map between this project (as the source)
     * and that project (as the sink.)
1732 1733 1734 1735
     *
     * @return
     *      can be empty but not null. build number of this project to the build
     *      numbers of that project.
1736 1737
     */
    public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
1738
        TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
1739 1740 1741 1742 1743 1744 1745 1746 1747

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

        return r;
    }

    /**
     * Helper method for getDownstreamRelationship.
1748 1749
     *
     * For each given build, find the build number range of the given project and put that into the map.
1750
     */
1751
    private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
1752 1753
        for (R build : builds) {
            RangeSet rs = build.getDownstreamRelationship(that);
1754
            if(rs==null || rs.isEmpty())
1755 1756 1757 1758 1759
                continue;

            int n = build.getNumber();

            RangeSet value = r.get(n);
1760 1761
            if(value==null)
                r.put(n,rs);
1762 1763 1764 1765 1766
            else
                value.add(rs);
        }
    }

1767 1768 1769 1770 1771 1772
    /**
     * Builds the dependency graph.
     * @see DependencyGraph
     */
    protected abstract void buildDependencyGraph(DependencyGraph graph);

1773
    @Override
K
kohsuke 已提交
1774 1775
    protected SearchIndexBuilder makeSearchIndex() {
        SearchIndexBuilder sib = super.makeSearchIndex();
1776
        if(isBuildable() && hasPermission(Jenkins.ADMINISTER))
1777
            sib.add("build","build");
K
kohsuke 已提交
1778 1779 1780
        return sib;
    }

1781 1782
    @Override
    protected HistoryWidget createHistoryWidget() {
1783
        return new BuildHistoryWidget<R>(this,builds,HISTORY_ADAPTER);
1784
    }
1785
    
K
kohsuke 已提交
1786
    public boolean isParameterized() {
1787
        return getProperty(ParametersDefinitionProperty.class) != null;
K
kohsuke 已提交
1788
    }
1789

1790 1791 1792 1793 1794
//
//
// actions
//
//
1795 1796 1797
    /**
     * Schedules a new build command.
     */
1798 1799
    public void doBuild( StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay ) throws IOException, ServletException {
        if (delay==null)    delay=new TimeDuration(getQuietPeriod());
1800

K
kohsuke 已提交
1801 1802
        // if a build is parameterized, let that take over
        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
J
Jesse Glick 已提交
1803 1804 1805 1806 1807 1808 1809 1810
        if (pp != null && !req.getMethod().equals("POST")) {
            // show the parameter entry form.
            req.getView(pp, "index.jelly").forward(req, rsp);
            return;
        }

        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);

K
kohsuke 已提交
1811
        if (pp != null) {
1812
            pp._doBuild(req,rsp,delay);
K
kohsuke 已提交
1813 1814 1815
            return;
        }

1816 1817 1818
        if (!isBuildable())
            throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));

K
Kohsuke Kawaguchi 已提交
1819 1820 1821
        ScheduleResult r = Jenkins.getInstance().getQueue().schedule2(this, delay.getTime(), getBuildCause(req));
        if (r.isAccepted()) {
            rsp.sendRedirect(SC_CREATED,req.getContextPath()+'/'+r.getItem().getUrl());
1822 1823
        } else
            rsp.sendRedirect(".");
1824 1825
    }

1826 1827 1828 1829 1830 1831
    /** @deprecated use {@link #doBuild(StaplerRequest, StaplerResponse, TimeDuration)} */
    @Deprecated
    public void doBuild(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        doBuild(req, rsp, TimeDuration.fromString(req.getParameter("delay")));
    }

1832 1833 1834 1835
    /**
     * Computes the build cause, using RemoteCause or UserCause as appropriate.
     */
    /*package*/ CauseAction getBuildCause(StaplerRequest req) {
1836 1837
        Cause cause;
        if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
1838 1839
            // Optional additional cause text when starting via token
            String causeText = req.getParameter("cause");
1840
            cause = new RemoteCause(req.getRemoteAddr(), causeText);
1841
        } else {
1842
            cause = new UserIdCause();
1843
        }
1844
        return new CauseAction(cause);
1845 1846 1847 1848
    }

    /**
     * Computes the delay by taking the default value and the override in the request parameter into the account.
1849
     *
1850
     * @deprecated as of 1.489
1851
     *      Inject {@link TimeDuration}.
1852 1853
     */
    public int getDelay(StaplerRequest req) throws ServletException {
1854
        String delay = req.getParameter("delay");
1855 1856 1857 1858 1859 1860 1861 1862 1863
        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);
1864
        }
1865
    }
1866

1867 1868 1869 1870
    /**
     * Supports build trigger with parameters via an HTTP GET or POST.
     * Currently only String parameters are supported.
     */
1871
    public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
1872 1873 1874 1875
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);

        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
1876
            pp.buildWithParameters(req,rsp,delay);
1877 1878 1879 1880 1881
        } else {
        	throw new IllegalStateException("This build is not parameterized!");
        }
    	
    }
1882

1883 1884 1885 1886 1887 1888
    /** @deprecated use {@link #doBuildWithParameters(StaplerRequest, StaplerResponse, TimeDuration)} */
    @Deprecated
    public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        doBuildWithParameters(req, rsp, TimeDuration.fromString(req.getParameter("delay")));
    }

1889 1890 1891
    /**
     * Schedules a new SCM polling command.
     */
1892
    public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1893 1894
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
        schedulePolling();
J
Jesse Glick 已提交
1895
        rsp.sendRedirect(".");
1896 1897 1898 1899 1900
    }

    /**
     * Cancels a scheduled build.
     */
J
Jesse Glick 已提交
1901
    @RequirePOST
1902
    public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1903
        checkPermission(ABORT);
1904

1905
        Jenkins.getInstance().getQueue().cancel(this);
1906 1907 1908
        rsp.forwardToPreviousPage(req);
    }

1909 1910 1911 1912
    /**
     * Deletes this project.
     */
    @Override
1913
    @RequirePOST
1914 1915 1916 1917
    public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
        delete();
        if (req == null || rsp == null)
            return;
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
        List<Ancestor> ancestors = req.getAncestors();
        ListIterator<Ancestor> it = ancestors.listIterator(ancestors.size());
        String url = getParent().getUrl(); // fallback but we ought to get to Jenkins.instance at the root
        while (it.hasPrevious()) {
            Object a = it.previous().getObject();
            if (a instanceof View) {
                url = ((View) a).getUrl();
                break;
            } else if (a instanceof ViewGroup) {
                url = ((ViewGroup) a).getUrl();
                break;
            }
        }
        rsp.sendRedirect2(req.getContextPath() + '/' + url);
1932 1933
    }
    
1934
    @Override
1935 1936
    protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
        super.submit(req,rsp);
1937
        JSONObject json = req.getSubmittedForm();
1938

1939
        makeDisabled(req.getParameter("disable")!=null);
1940 1941

        jdk = req.getParameter("jdk");
1942
        if(req.getParameter("hasCustomQuietPeriod")!=null) {
1943 1944 1945 1946
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
        } else {
            quietPeriod = null;
        }
1947 1948
        if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) {
            scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount"));
S
 
shinodkm 已提交
1949
        } else {
1950
            scmCheckoutRetryCount = null;
S
 
shinodkm 已提交
1951
        }
1952
        blockBuildWhenDownstreamBuilding = req.getParameter("blockBuildWhenDownstreamBuilding")!=null;
1953 1954
        blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null;

1955
        if(req.hasParameter("customWorkspace")) {
1956
            customWorkspace = Util.fixEmptyAndTrim(req.getParameter("customWorkspace.directory"));
1957 1958 1959
        } else {
            customWorkspace = null;
        }
1960 1961 1962 1963 1964 1965 1966

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

1967
        
1968
        if(req.getParameter("hasSlaveAffinity")!=null) {
1969
            assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString"));
1970 1971 1972
        } else {
            assignedNode = null;
        }
1973
        canRoam = assignedNode==null;
1974

1975
        concurrentBuild = req.getSubmittedForm().has("concurrentBuild");
K
kohsuke 已提交
1976

1977
        authToken = BuildAuthorizationToken.create(req);
1978

K
kohsuke 已提交
1979
        setScm(SCMS.parseSCM(req,this));
1980

1981
        for (Trigger t : triggers())
1982
            t.stop();
K
Kohsuke Kawaguchi 已提交
1983 1984
        triggers.replaceBy(buildDescribable(req, Trigger.for_(this)));
        for (Trigger t : triggers())
1985
            t.start(this,true);
J
Jesse Glick 已提交
1986 1987 1988 1989 1990 1991 1992

        for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, "publisher", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) {
            BuildTrigger t = (BuildTrigger) _t;
            for (AbstractProject downstream : t.getChildProjects(this)) {
                downstream.checkPermission(BUILD);
            }
        }
1993 1994
    }

K
kohsuke 已提交
1995 1996 1997 1998 1999 2000 2001 2002 2003
    /**
     * @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)
2004
        throws FormException, ServletException {
2005

2006
        JSONObject data = req.getSubmittedForm();
2007
        List<T> r = new Vector<T>();
2008
        for (Descriptor<T> d : descriptors) {
2009 2010 2011
            String safeName = d.getJsonSafeClassName();
            if (req.getParameter(safeName) != null) {
                T instance = d.newInstance(req, data.getJSONObject(safeName));
2012
                r.add(instance);
2013 2014
            }
        }
2015
        return r;
2016 2017
    }

2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
    public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
        // not sure what would be really useful here. This needs more thoughts.
        // for the time being, I'm starting with permalinks
        ContextMenu menu = new ContextMenu();
        for (Permalink p : getPermalinks()) {
            if (p.resolve(this)!=null)
                menu.add(p.getId(),p.getDisplayName());
        }
        return menu;
    }

2029 2030 2031
    /**
     * Serves the workspace files.
     */
2032
    public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
2033
        checkPermission(AbstractProject.WORKSPACE);
K
kohsuke 已提交
2034
        FilePath ws = getSomeWorkspace();
2035
        if ((ws == null) || (!ws.exists())) {
2036
            // if there's no workspace, report a nice error message
2037 2038 2039 2040
            // 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.
2041
            req.getView(this,"noWorkspace.jelly").forward(req,rsp);
2042
            return null;
2043
        } else {
2044
            return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.png", true);
2045 2046
        }
    }
2047

2048 2049 2050
    /**
     * Wipes out the workspace.
     */
2051
    public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
2052
        checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD);
2053 2054 2055 2056
        R b = getSomeBuildWithWorkspace();
        FilePath ws = b!=null ? b.getWorkspace() : null;
        if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
            ws.deleteRecursive();
2057 2058 2059
            for (WorkspaceListener wl : WorkspaceListener.all()) {
                wl.afterDelete(this);
            }
2060 2061 2062 2063
            return new HttpRedirect(".");
        } else {
            // If we get here, that means the SCM blocked the workspace deletion.
            return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
2064
        }
2065 2066
    }

2067
    @CLIMethod(name="disable-job")
2068
    @RequirePOST
2069
    public HttpResponse doDisable() throws IOException, ServletException {
2070 2071
        checkPermission(CONFIGURE);
        makeDisabled(true);
2072
        return new HttpRedirect(".");
2073 2074
    }

2075
    @CLIMethod(name="enable-job")
2076
    @RequirePOST
2077
    public HttpResponse doEnable() throws IOException, ServletException {
2078 2079
        checkPermission(CONFIGURE);
        makeDisabled(false);
2080
        return new HttpRedirect(".");
2081 2082
    }

K
kohsuke 已提交
2083 2084 2085
    /**
     * RSS feed for changes in this project.
     */
2086
    public void doRssChangelog(  StaplerRequest req, StaplerResponse rsp  ) throws IOException, ServletException {
K
kohsuke 已提交
2087 2088 2089 2090 2091 2092 2093 2094 2095
        class FeedItem {
            ChangeLogSet.Entry e;
            int idx;

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

2096
            AbstractBuild<?,?> getBuild() {
K
kohsuke 已提交
2097 2098 2099 2100 2101 2102
                return e.getParent().build;
            }
        }

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

2103 2104 2105 2106
        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 已提交
2107 2108
        }

2109 2110 2111 2112 2113 2114 2115
        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 已提交
2116

2117 2118 2119
                public String getEntryUrl(FeedItem item) {
                    return item.getBuild().getUrl()+"changes#detail"+item.idx;
                }
K
kohsuke 已提交
2120

2121 2122 2123
                public String getEntryID(FeedItem item) {
                    return getEntryUrl(item);
                }
K
kohsuke 已提交
2124

2125 2126 2127 2128 2129 2130
                public String getEntryDescription(FeedItem item) {
                    StringBuilder buf = new StringBuilder();
                    for(String path : item.e.getAffectedPaths())
                        buf.append(path).append('\n');
                    return buf.toString();
                }
2131

2132 2133 2134
                public Calendar getEntryTimestamp(FeedItem item) {
                    return item.getBuild().getTimestamp();
                }
2135

2136
                public String getEntryAuthor(FeedItem entry) {
2137
                    return JenkinsLocationConfiguration.get().getAdminAddress();
2138 2139 2140
                }
            },
            req, rsp );
K
kohsuke 已提交
2141 2142
    }

2143 2144 2145 2146 2147 2148 2149
    /**
     * {@link AbstractProject} subtypes should implement this base class as a descriptor.
     *
     * @since 1.294
     */
    public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
        /**
2150
         * {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
2151
         * from showing up on their configuration screen. This is often useful when you are building
2152 2153
         * a workflow/company specific project type, where you want to limit the number of choices
         * given to the users.
2154 2155
         *
         * <p>
2156 2157 2158 2159
         * 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}
2160 2161 2162 2163
         * to show up for the given {@link Project}.
         *
         * <p>
         * The default implementation returns true for everything.
2164 2165
         *
         * @see BuildStepDescriptor#isApplicable(Class) 
K
kohsuke 已提交
2166 2167
         * @see BuildWrapperDescriptor#isApplicable(AbstractProject) 
         * @see TriggerDescriptor#isApplicable(Item)
2168
         */
K
kohsuke 已提交
2169
        @Override
2170
        public boolean isApplicable(Descriptor descriptor) {
2171 2172
            return true;
        }
2173 2174

        public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {
2175 2176
            if (Util.fixEmpty(value)==null)
                return FormValidation.ok(); // nothing typed yet
2177 2178 2179
            try {
                Label.parseExpression(value);
            } catch (ANTLRException e) {
S
Seiji Sogabe 已提交
2180 2181
                return FormValidation.error(e,
                        Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
2182
            }
2183 2184 2185 2186 2187 2188 2189 2190
            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 已提交
2191
                return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());
2192
            }
2193 2194
            return FormValidation.ok();
        }
2195

2196
        public FormValidation doCheckCustomWorkspace(@QueryParameter(value="customWorkspace.directory") String customWorkspace){
2197
        	if(Util.fixEmptyAndTrim(customWorkspace)==null)
S
Seiji Sogabe 已提交
2198
        		return FormValidation.error(Messages.AbstractProject_CustomWorkspaceEmpty());
2199 2200 2201 2202
        	else
        		return FormValidation.ok();
        }
        
2203 2204
        public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value) {
            AutoCompletionCandidates candidates = new AutoCompletionCandidates();
2205
            List<Job> jobs = Jenkins.getInstance().getItems(Job.class);
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
            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) {
2217
            AutoCompletionCandidates c = new AutoCompletionCandidates();
2218
            Set<Label> labels = Jenkins.getInstance().getLabels();
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
            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;
        }

2231
        public List<SCMCheckoutStrategyDescriptor> getApplicableSCMCheckoutStrategyDescriptors(AbstractProject p) {
2232 2233 2234
            return SCMCheckoutStrategyDescriptor._for(p);
        }

2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
        /**
        * 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 已提交
2247
                ArrayList<String> terms = new ArrayList<String>();
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
                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;
            }
        }
2275 2276
    }

2277
    /**
2278
     * Finds a {@link AbstractProject} that has the name closest to the given name.
2279 2280
     */
    public static AbstractProject findNearest(String name) {
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
        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);
2291
        String[] names = new String[projects.size()];
2292
        for( int i=0; i<projects.size(); i++ )
2293
            names[i] = projects.get(i).getRelativeNameFrom(context);
2294 2295

        String nearest = EditDistance.findNearest(name, names);
2296
        return (AbstractProject)Jenkins.getInstance().getItem(nearest,context);
2297
    }
2298 2299 2300

    private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
2301
            return o2-o1;
2302 2303
        }
    };
2304

2305
    private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
2306

2307
    /**
2308
     * Permission to abort a build
2309
     */
2310
    public static final Permission ABORT = CANCEL;
2311

K
Kohsuke Kawaguchi 已提交
2312 2313 2314
    /**
     * Replaceable "Build Now" text.
     */
2315 2316
    public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();

2317 2318 2319 2320 2321 2322
    /**
     * Used for CLI binding.
     */
    @CLIResolver
    public static AbstractProject resolveForCLI(
            @Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException {
2323
        AbstractProject item = Jenkins.getInstance().getItemByFullName(name, AbstractProject.class);
2324 2325 2326 2327
        if (item==null)
            throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));
        return item;
    }
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346

    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. 
     *
2347
     * @since 1.410
2348 2349
     */
    public void setCustomWorkspace(String customWorkspace) throws IOException {
2350
        this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace);
2351 2352
        save();
    }
2353
    
2354
}