AbstractBuild.java 47.8 KB
Newer Older
K
kohsuke 已提交
1 2
/*
 * The MIT License
3
 *
4
 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., CloudBees, Inc.
5
 *
K
kohsuke 已提交
6 7 8 9 10 11
 * 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:
12
 *
K
kohsuke 已提交
13 14
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
15
 *
K
kohsuke 已提交
16 17 18 19 20 21 22 23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
24 25
package hudson.model;

K
Kohsuke Kawaguchi 已提交
26
import com.google.common.collect.ImmutableList;
27
import com.google.common.collect.ImmutableSortedSet;
28
import hudson.AbortException;
29
import hudson.EnvVars;
30
import hudson.FilePath;
31
import hudson.Functions;
32 33
import hudson.Launcher;
import hudson.Util;
34 35
import hudson.console.AnnotatedLargeText;
import hudson.console.ExpandableDetailsNote;
36
import hudson.console.ModelHyperlinkNote;
37
import hudson.matrix.MatrixConfiguration;
38 39
import hudson.model.Fingerprint.BuildPtr;
import hudson.model.Fingerprint.RangeSet;
40
import hudson.model.listeners.RunListener;
K
kohsuke 已提交
41
import hudson.model.listeners.SCMListener;
42 43 44
import hudson.scm.ChangeLogParser;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
45
import hudson.scm.NullChangeLogParser;
46 47 48 49
import hudson.scm.SCM;
import hudson.slaves.NodeProperty;
import hudson.slaves.WorkspaceList;
import hudson.slaves.WorkspaceList.Lease;
50
import hudson.tasks.BuildStep;
51 52
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.BuildTrigger;
53
import hudson.tasks.BuildWrapper;
54 55
import hudson.tasks.Builder;
import hudson.tasks.Fingerprinter.FingerprintAction;
56
import hudson.tasks.Publisher;
57
import hudson.tasks.test.AbstractTestResultAction;
58
import hudson.tasks.test.AggregatedTestResultAction;
K
kohsuke 已提交
59
import hudson.util.AdaptedIterator;
60
import hudson.util.IOException2;
K
kohsuke 已提交
61
import hudson.util.Iterators;
62
import hudson.util.LogTaskListener;
63
import hudson.util.VariableResolver;
64
import jenkins.model.Jenkins;
65
import org.kohsuke.stapler.Stapler;
66 67
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
68
import org.kohsuke.stapler.export.Exported;
69
import org.xml.sax.SAXException;
70

71
import javax.servlet.ServletException;
72 73
import java.io.File;
import java.io.IOException;
74
import java.io.InterruptedIOException;
75
import java.io.StringWriter;
76
import java.lang.ref.WeakReference;
77
import java.text.MessageFormat;
78 79 80 81 82 83 84 85 86 87 88
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
89 90
import java.util.logging.Level;
import java.util.logging.Logger;
K
kohsuke 已提交
91

92 93 94
/**
 * Base implementation of {@link Run}s that build software.
 *
95
 * For now this is primarily the common part of {@link Build} and MavenBuild.
96 97 98 99
 *
 * @author Kohsuke Kawaguchi
 * @see AbstractProject
 */
100
public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Run<P,R> implements Queue.Executable {
101

102 103 104 105 106
    /**
     * Set if we want the blame information to flow from upstream to downstream build.
     */
    private static final boolean upstreamCulprits = Boolean.getBoolean("hudson.upstreamCulprits");

107
    /**
K
kohsuke 已提交
108
     * Name of the slave this project was built on.
K
kohsuke 已提交
109
     * Null or "" if built by the master. (null happens when we read old record that didn't have this information.)
110 111 112
     */
    private String builtOn;

K
kohsuke 已提交
113 114
    /**
     * The file path on the node that performed a build. Kept as a string since {@link FilePath} is not serializable into XML.
K
kohsuke 已提交
115
     * @since 1.319
K
kohsuke 已提交
116 117 118
     */
    private String workspace;

119 120 121 122 123
    /**
     * Version of Hudson that built this.
     */
    private String hudsonVersion;

124 125 126 127 128 129 130 131 132
    /**
     * SCM used for this build.
     * Maybe null, for historical reason, in which case CVS is assumed.
     */
    private ChangeLogParser scm;

    /**
     * Changes in this build.
     */
J
John Pederzolli 已提交
133
    private volatile transient WeakReference<ChangeLogSet<? extends Entry>> changeSet;
134

135 136 137 138 139 140 141 142 143 144 145 146 147 148
    /**
     * Cumulative list of people who contributed to the build problem.
     *
     * <p>
     * This is a list of {@link User#getId() user ids} who made a change
     * since the last non-broken build. Can be null (which should be
     * treated like empty set), because of the compatibility.
     *
     * <p>
     * This field is semi-final --- once set the value will never be modified.
     *
     * @since 1.137
     */
    private volatile Set<String> culprits;
149

K
kohsuke 已提交
150 151 152 153
    /**
     * During the build this field remembers {@link BuildWrapper.Environment}s created by
     * {@link BuildWrapper}. This design is bit ugly but forced due to compatibility.
     */
154
    protected transient List<Environment> buildEnvironments;
155

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    protected AbstractBuild(P job) throws IOException {
        super(job);
    }

    protected AbstractBuild(P job, Calendar timestamp) {
        super(job, timestamp);
    }

    protected AbstractBuild(P project, File buildDir) throws IOException {
        super(project, buildDir);
    }

    public final P getProject() {
        return getParent();
    }

    /**
     * Returns a {@link Slave} on which this build was done.
K
kohsuke 已提交
174 175
     *
     * @return
M
mindless 已提交
176
     *      null, for example if the slave that this build run no longer exists.
177 178
     */
    public Node getBuiltOn() {
179
        if (builtOn==null || builtOn.equals(""))
180
            return Jenkins.getInstance();
181
        else
182
            return Jenkins.getInstance().getNode(builtOn);
183 184 185
    }

    /**
M
mindless 已提交
186 187
     * Returns the name of the slave it was built on; null or "" if built by the master.
     * (null happens when we read old record that didn't have this information.)
188
     */
K
kohsuke 已提交
189
    @Exported(name="builtOn")
190 191 192 193
    public String getBuiltOnStr() {
        return builtOn;
    }

194
    /**
195 196 197 198
     * Allows subtypes to set the value of {@link #builtOn}.
     * This is used for those implementations where an {@link AbstractBuild} is made 'built' without
     * actually running its {@link #run()} method.
     *
199 200
     * @since 1.429
     */
201
    protected void setBuiltOnStr( String builtOn ) {
202 203 204
        this.builtOn = builtOn;
    }

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    /**
     * Gets the nearest ancestor {@link AbstractBuild} that belongs to
     * {@linkplain AbstractProject#getRootProject() the root project of getProject()} that
     * dominates/governs/encompasses this build.
     *
     * <p>
     * Some projects (such as matrix projects, Maven projects, or promotion processes) form a tree of jobs,
     * and still in some of them, builds of child projects are related/tied to that of the parent project.
     * In such a case, this method returns the governing build.
     *
     * @return never null. In the worst case the build dominates itself.
     * @since 1.421
     * @see AbstractProject#getRootProject()
     */
    public AbstractBuild<?,?> getRootBuild() {
        return this;
    }

K
kohsuke 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    /**
     * Used to render the side panel "Back to project" link.
     *
     * <p>
     * In a rare situation where a build can be reached from multiple paths,
     * returning different URLs from this method based on situations might
     * be desirable.
     *
     * <p>
     * If you override this method, you'll most likely also want to override
     * {@link #getDisplayName()}.
     */
    public String getUpUrl() {
        return Functions.getNearestAncestorUrl(Stapler.getCurrentRequest(),getParent())+'/';
    }

K
kohsuke 已提交
239 240 241 242 243
    /**
     * Gets the directory where this build is being built.
     *
     * <p>
     * Note to implementors: to control where the workspace is created, override
244
     * {@link AbstractBuildExecution#decideWorkspace(Node,WorkspaceList)}.
K
kohsuke 已提交
245 246 247 248 249
     *
     * @return
     *      null if the workspace is on a slave that's not connected. Note that once the build is completed,
     *      the workspace may be used to build something else, so the value returned from this method may
     *      no longer show a workspace as it was used for this build.
K
kohsuke 已提交
250
     * @since 1.319
K
kohsuke 已提交
251 252
     */
    public final FilePath getWorkspace() {
253
        if (workspace==null) return null;
K
kohsuke 已提交
254
        Node n = getBuiltOn();
255
        if (n==null) return null;
K
kohsuke 已提交
256 257 258
        return n.createPath(workspace);
    }

259
    /**
260
     * Normally, a workspace is assigned by {@link RunExecution}, but this lets you set the workspace in case
261 262 263 264 265 266
     * {@link AbstractBuild} is created without a build.
     */
    protected void setWorkspace(FilePath ws) {
        this.workspace = ws.getRemote();
    }

K
kohsuke 已提交
267 268 269 270 271 272 273 274
    /**
     * Returns the root directory of the checked-out module.
     * <p>
     * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
     * and so on exists.
     */
    public final FilePath getModuleRoot() {
        FilePath ws = getWorkspace();
275
        if (ws==null)    return null;
276
        return getParent().getScm().getModuleRoot(ws,this);
K
kohsuke 已提交
277 278 279 280 281 282 283 284 285 286 287
    }

    /**
     * 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.
     */
    public FilePath[] getModuleRoots() {
        FilePath ws = getWorkspace();
288
        if (ws==null)    return null;
289
        return getParent().getScm().getModuleRoots(ws, this);
K
kohsuke 已提交
290 291
    }

292 293 294 295
    /**
     * List of users who committed a change since the last non-broken build till now.
     *
     * <p>
K
kohsuke 已提交
296 297
     * This list at least always include people who made changes in this build, but
     * if the previous build was a failure it also includes the culprit list from there.
298 299 300 301 302 303
     *
     * @return
     *      can be empty but never null.
     */
    @Exported
    public Set<User> getCulprits() {
304
        if (culprits==null) {
305
            Set<User> r = new HashSet<User>();
306
            R p = getPreviousCompletedBuild();
307
            if (p !=null && isBuilding()) {
K
kohsuke 已提交
308
                Result pr = p.getResult();
K
Kohsuke Kawaguchi 已提交
309
                if (pr!=null && pr.isWorseThan(Result.SUCCESS)) {
K
kohsuke 已提交
310 311 312 313 314 315
                    // we are still building, so this is just the current latest information,
                    // but we seems to be failing so far, so inherit culprits from the previous build.
                    // isBuilding() check is to avoid recursion when loading data from old Hudson, which doesn't record
                    // this information
                    r.addAll(p.getCulprits());
                }
316
            }
317
            for (Entry e : getChangeSet())
318
                r.add(e.getAuthor());
319 320 321 322

            if (upstreamCulprits) {
                // If we have dependencies since the last successful build, add their authors to our list
                if (getPreviousNotFailedBuild() != null) {
M
marco 已提交
323
                    Map <AbstractProject,AbstractBuild.DependencyChange> depmap = getDependencyChanges(getPreviousSuccessfulBuild());
324 325 326 327 328 329 330 331 332 333
                    for (AbstractBuild.DependencyChange dep : depmap.values()) {
                        for (AbstractBuild<?,?> b : dep.getBuilds()) {
                            for (Entry entry : b.getChangeSet()) {
                                r.add(entry.getAuthor());
                            }
                        }
                    }
                }
            }

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
            return r;
        }

        return new AbstractSet<User>() {
            public Iterator<User> iterator() {
                return new AdaptedIterator<String,User>(culprits.iterator()) {
                    protected User adapt(String id) {
                        return User.get(id);
                    }
                };
            }

            public int size() {
                return culprits.size();
            }
        };
    }

352 353 354 355 356 357 358
    /**
     * Returns true if this user has made a commit to this build.
     *
     * @since 1.191
     */
    public boolean hasParticipant(User user) {
        for (ChangeLogSet.Entry e : getChangeSet())
359 360 361 362 363 364 365
            try{
                if (e.getAuthor()==user)
                    return true;
            } catch (RuntimeException re) {
                // no-op, just remove exception thrown e.g. from git plugin. 
                // It there's some problem to determine committer, user probably doesn't participate in the build.
            }
366 367 368
        return false;
    }

K
kohsuke 已提交
369 370 371 372 373 374 375 376 377
    /**
     * Gets the version of Hudson that was used to build this job.
     *
     * @since 1.246
     */
    public String getHudsonVersion() {
        return hudsonVersion;
    }

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    @Override
    public synchronized void delete() throws IOException {
        // Need to check if deleting this build affects lastSuccessful/lastStable symlinks
        R lastSuccessful = getProject().getLastSuccessfulBuild(),
          lastStable = getProject().getLastStableBuild();

        super.delete();

        try {
            if (lastSuccessful == this)
                updateSymlink("lastSuccessful", getProject().getLastSuccessfulBuild());
            if (lastStable == this)
                updateSymlink("lastStable", getProject().getLastStableBuild());
        } catch (InterruptedException ex) {
            LOGGER.warning("Interrupted update of lastSuccessful/lastStable symlinks for "
                           + getProject().getDisplayName());
            // handle it later
            Thread.currentThread().interrupt();
        }
    }

    private void updateSymlink(String name, AbstractBuild<?,?> newTarget) throws InterruptedException {
        if (newTarget != null)
            newTarget.createSymlink(new LogTaskListener(LOGGER, Level.WARNING), name);
        else
            new File(getProject().getBuildDir(), "../"+name).delete();
    }

    private void createSymlink(TaskListener listener, String name) throws InterruptedException {
        Util.createSymlink(getProject().getBuildDir(),"builds/"+getId(),"../"+name,listener);
    }

410 411 412 413 414 415 416 417 418 419 420 421 422 423
    /**
     * @deprecated as of 1.467
     *      Please use {@link RunExecution}
     */
    public abstract class AbstractRunner extends AbstractBuildExecution {

    }

    public abstract class AbstractBuildExecution extends Runner {
        /*
            Some plugins might depend on this instance castable to Runner, so we need to use
            deprecated class here.
         */

424 425
        /**
         * Since configuration can be changed while a build is in progress,
426
         * create a launcher once and stick to it for the entire build duration.
427 428 429
         */
        protected Launcher launcher;

430 431 432 433 434
        /**
         * Output/progress of this build goes here.
         */
        protected BuildListener listener;

K
kohsuke 已提交
435 436 437 438 439 440 441
        /**
         * Returns the current {@link Node} on which we are buildling.
         */
        protected final Node getCurrentNode() {
            return Executor.currentExecutor().getOwner().getNode();
        }

K
kohsuke 已提交
442 443 444 445 446 447 448 449
        /**
         * Allocates the workspace from {@link WorkspaceList}.
         *
         * @param n
         *      Passed in for the convenience. The node where the build is running.
         * @param wsl
         *      Passed in for the convenience. The returned path must be registered to this object.
         */
450
        protected Lease decideWorkspace(Node n, WorkspaceList wsl) throws InterruptedException, IOException {
451 452 453 454 455
            String customWorkspace = getProject().getCustomWorkspace();
            if (customWorkspace != null) {
                // we allow custom workspaces to be concurrently used between jobs.
                return Lease.createDummyLease(n.getRootPath().child(getEnvironment(listener).expand(customWorkspace)));
            }
K
kohsuke 已提交
456
            // TODO: this cast is indicative of abstraction problem
457
            return wsl.allocate(n.getWorkspaceFor((TopLevelItem)getProject()), getBuild());
K
kohsuke 已提交
458 459
        }

460
        public Result run(BuildListener listener) throws Exception {
461
            Node node = getCurrentNode();
462 463
            assert builtOn==null;
            builtOn = node.getNodeName();
464
            hudsonVersion = Jenkins.VERSION;
465
            this.listener = listener;
466

467
            launcher = createLauncher(listener);
468
            if (!Jenkins.getInstance().getNodes().isEmpty())
469
                listener.getLogger().print(node instanceof Jenkins ? Messages.AbstractBuild_BuildingOnMaster() : 
470
                    Messages.AbstractBuild_BuildingRemotely(ModelHyperlinkNote.encodeTo("/computer/" + builtOn, builtOn)));
471 472
            else
            	listener.getLogger().print(Messages.AbstractBuild_Building());
473
            
474
            final Lease lease = decideWorkspace(node,Computer.currentComputer().getWorkspaceList());
K
kohsuke 已提交
475 476

            try {
477
                workspace = lease.path.getRemote();
478
                listener.getLogger().println(Messages.AbstractBuild_BuildingInWorkspace(workspace));
479
                node.getFileSystemProvisioner().prepareWorkspace(AbstractBuild.this,lease.path,listener);
480 481 482 483
                
                for (WorkspaceListener wl : WorkspaceListener.all()) {
                    wl.beforeUse(AbstractBuild.this, lease.path, listener);
                }
484 485 486

                getProject().getSCMCheckoutStrategy().preCheckout(AbstractBuild.this, launcher, this.listener);
                getProject().getSCMCheckoutStrategy().checkout(this);
487

488
                if (!preBuild(listener,project.getProperties()))
K
kohsuke 已提交
489
                    return Result.FAILURE;
490

K
kohsuke 已提交
491
                Result result = doRun(listener);
492

493 494
                Computer c = node.toComputer();
                if (c==null || c.isOffline()) {
495 496
                    // As can be seen in HUDSON-5073, when a build fails because of the slave connectivity problem,
                    // error message doesn't point users to the slave. So let's do it here.
497
                    listener.hyperlink("/computer/"+builtOn+"/log","Looks like the node went offline during the build. Check the slave log for the details.");
498

D
Dave Brosius 已提交
499 500 501 502 503 504 505 506 507 508
                    if (c != null) {
                        // grab the end of the log file. This might not work very well if the slave already
                        // starts reconnecting. Fixing this requires a ring buffer in slave logs.
                        AnnotatedLargeText<Computer> log = c.getLogText();
                        StringWriter w = new StringWriter();
                        log.writeHtmlTo(Math.max(0,c.getLogFile().length()-10240),w);

                        listener.getLogger().print(ExpandableDetailsNote.encodeTo("details",w.toString()));
                        listener.getLogger().println();
                    }
509 510
                }

K
kohsuke 已提交
511 512 513 514
                // kill run-away processes that are left
                // use multiple environment variables so that people can escape this massacre by overriding an environment
                // variable for some processes
                launcher.kill(getCharacteristicEnvVars());
515

K
kohsuke 已提交
516 517
                // this is ugly, but for historical reason, if non-null value is returned
                // it should become the final result.
518 519
                if (result==null)    result = getResult();
                if (result==null)    result = Result.SUCCESS;
520

K
kohsuke 已提交
521 522
                return result;
            } finally {
523
                lease.release();
524
                this.listener = null;
K
kohsuke 已提交
525
            }
526 527
        }

528 529 530 531 532
        /**
         * Creates a {@link Launcher} that this build will use. This can be overridden by derived types
         * to decorate the resulting {@link Launcher}.
         *
         * @param listener
533
         *      Always non-null. Connected to the main build output.
534 535
         */
        protected Launcher createLauncher(BuildListener listener) throws IOException, InterruptedException {
536 537 538 539
            Launcher l = getCurrentNode().createLauncher(listener);

            if (project instanceof BuildableItemWithBuildWrappers) {
                BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project;
540
                for (BuildWrapper bw : biwbw.getBuildWrappersList())
541 542 543 544 545
                    l = bw.decorateLauncher(AbstractBuild.this,l,listener);
            }

            buildEnvironments = new ArrayList<Environment>();

546 547 548 549 550 551 552
            for (RunListener rl: RunListener.all()) {
                Environment environment = rl.setUpEnvironment(AbstractBuild.this, l, listener);
                if (environment != null) {
                    buildEnvironments.add(environment);
                }
            }

553
            for (NodeProperty nodeProperty: Jenkins.getInstance().getGlobalNodeProperties()) {
554 555 556 557 558 559 560 561 562 563 564 565 566 567
                Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener);
                if (environment != null) {
                    buildEnvironments.add(environment);
                }
            }

            for (NodeProperty nodeProperty: Computer.currentComputer().getNode().getNodeProperties()) {
                Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener);
                if (environment != null) {
                    buildEnvironments.add(environment);
                }
            }

            return l;
568 569
        }

570 571 572
        public void defaultCheckout() throws IOException, InterruptedException {
            AbstractBuild<?,?> build = AbstractBuild.this;
            AbstractProject<?, ?> project = build.getProject();
573

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
            for (int retryCount=project.getScmCheckoutRetryCount(); ; retryCount--) {
                // for historical reasons, null in the scm field means CVS, so we need to explicitly set this to something
                // in case check out fails and leaves a broken changelog.xml behind.
                // see http://www.nabble.com/CVSChangeLogSet.parse-yields-SAXParseExceptions-when-parsing-bad-*AccuRev*-changelog.xml-files-td22213663.html
                build.scm = NullChangeLogParser.INSTANCE;

                try {
                    if (project.checkout(build,launcher,listener,new File(build.getRootDir(),"changelog.xml"))) {
                        // check out succeeded
                        SCM scm = project.getScm();

                        build.scm = scm.createChangeLogParser();
                        build.changeSet = new WeakReference<ChangeLogSet<? extends Entry>>(build.calcChangeSet());

                        for (SCMListener l : Jenkins.getInstance().getSCMListeners())
589 590 591 592 593
                            try {
                                l.onChangeLogParsed(build,listener,build.getChangeSet());
                            } catch (Exception e) {
                                throw new IOException2("Failed to parse changelog",e);
                            }
594 595 596 597 598 599 600 601 602
                        return;
                    }
                } catch (AbortException e) {
                    listener.error(e.getMessage());
                } catch (InterruptedIOException e) {
                    throw (InterruptedException)new InterruptedException().initCause(e);
                } catch (IOException e) {
                    // checkout error not yet reported
                    e.printStackTrace(listener.getLogger());
603
                }
604 605 606 607 608 609 610

                if (retryCount == 0)   // all attempts failed
                    throw new RunnerAbortedException();

                listener.getLogger().println("Retrying after 10 seconds");
                Thread.sleep(10000);
            }
611 612
        }

K
kohsuke 已提交
613 614 615 616 617 618 619 620 621
        /**
         * The portion of a build that is specific to a subclass of {@link AbstractBuild}
         * goes here.
         *
         * @return
         *      null to continue the build normally (that means the doRun method
         *      itself run successfully)
         *      Return a non-null value to abort the build right there with the specified result code.
         */
K
kohsuke 已提交
622
        protected abstract Result doRun(BuildListener listener) throws Exception, RunnerAbortedException;
623 624 625 626 627 628 629 630 631

        /**
         * @see #post(BuildListener)
         */
        protected abstract void post2(BuildListener listener) throws Exception;

        public final void post(BuildListener listener) throws Exception {
            try {
                post2(listener);
632 633 634 635 636 637

                if (result.isBetterOrEqualTo(Result.UNSTABLE))
                    createSymlink(listener, "lastSuccessful");

                if (result.isBetterOrEqualTo(Result.SUCCESS))
                    createSymlink(listener, "lastStable");
638 639 640 641 642
            } finally {
                // update the culprit list
                HashSet<String> r = new HashSet<String>();
                for (User u : getCulprits())
                    r.add(u.getId());
643
                culprits = ImmutableSortedSet.copyOf(r);
K
kohsuke 已提交
644
                CheckPoint.CULPRITS_DETERMINED.report();
645 646
            }
        }
647 648

        public void cleanUp(BuildListener listener) throws Exception {
649 650
            BuildTrigger.execute(AbstractBuild.this, listener);
            buildEnvironments = null;
651
        }
652

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
        /**
         * @deprecated as of 1.356
         *      Use {@link #performAllBuildSteps(BuildListener, Map, boolean)}
         */
        protected final void performAllBuildStep(BuildListener listener, Map<?,? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
            performAllBuildSteps(listener,buildSteps.values(),phase);
        }

        protected final boolean performAllBuildSteps(BuildListener listener, Map<?,? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
            return performAllBuildSteps(listener,buildSteps.values(),phase);
        }

        /**
         * @deprecated as of 1.356
         *      Use {@link #performAllBuildSteps(BuildListener, Iterable, boolean)}
         */
        protected final void performAllBuildStep(BuildListener listener, Iterable<? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
            performAllBuildSteps(listener,buildSteps,phase);
671 672 673 674 675 676 677 678
        }

        /**
         * Runs all the given build steps, even if one of them fail.
         *
         * @param phase
         *      true for the post build processing, and false for the final "run after finished" execution.
         */
679
        protected final boolean performAllBuildSteps(BuildListener listener, Iterable<? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
680
            boolean r = true;
681 682
            for (BuildStep bs : buildSteps) {
                if ((bs instanceof Publisher && ((Publisher)bs).needsToRunAfterFinalized()) ^ phase)
683
                    try {
684 685 686 687
                        if (!perform(bs,listener)) {
                            LOGGER.fine(MessageFormat.format("{0} : {1} failed", AbstractBuild.this.toString(), bs));
                            r = false;
                        }
688
                    } catch (Exception e) {
689 690 691
                        String msg = "Publisher " + bs.getClass().getName() + " aborted due to exception";
                        e.printStackTrace(listener.error(msg));
                        LOGGER.log(Level.WARNING, msg, e);
692
                        setResult(Result.FAILURE);
693
                    }
K
kohsuke 已提交
694
            }
695
            return r;
K
kohsuke 已提交
696 697 698 699 700 701 702 703 704 705 706
        }

        /**
         * Calls a build step.
         */
        protected final boolean perform(BuildStep bs, BuildListener listener) throws InterruptedException, IOException {
            BuildStepMonitor mon;
            try {
                mon = bs.getRequiredMonitorService();
            } catch (AbstractMethodError e) {
                mon = BuildStepMonitor.BUILD;
707
            }
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
            Result oldResult = AbstractBuild.this.getResult();
            boolean canContinue = mon.perform(bs, AbstractBuild.this, launcher, listener);
            Result newResult = AbstractBuild.this.getResult();
            if (newResult != oldResult) {
                String buildStepName = getBuildStepName(bs);
                listener.getLogger().format("Build step '%s' changed build result to %s%n", buildStepName, newResult);
            }
            if (!canContinue) {
                String buildStepName = getBuildStepName(bs);
                listener.getLogger().format("Build step '%s' marked build as failure%n", buildStepName);
            }
            return canContinue;
        }

        private String getBuildStepName(BuildStep bs) {
            if (bs instanceof Describable<?>) {
                return ((Describable<?>) bs).getDescriptor().getDisplayName();
            } else {
                return bs.getClass().getSimpleName();
            }
728
        }
729 730

        protected final boolean preBuild(BuildListener listener,Map<?,? extends BuildStep> steps) {
731 732 733 734
            return preBuild(listener,steps.values());
        }

        protected final boolean preBuild(BuildListener listener,Collection<? extends BuildStep> steps) {
735 736 737 738
            return preBuild(listener,(Iterable<? extends BuildStep>)steps);
        }

        protected final boolean preBuild(BuildListener listener,Iterable<? extends BuildStep> steps) {
739
            for (BuildStep bs : steps)
740 741
                if (!bs.prebuild(AbstractBuild.this,listener)) {
                    LOGGER.fine(MessageFormat.format("{0} : {1} failed", AbstractBuild.this.toString(), bs));
742
                    return false;
743
                }
744 745
            return true;
        }
746
    }
K
kohsuke 已提交
747

748 749 750 751 752 753 754 755 756 757 758 759 760 761
    /**
     * get the fingerprints associated with this build
     *
     * @return never null
     */
    @Exported(name = "fingerprint", inline = true, visibility = -1)
    public Collection<Fingerprint> getBuildFingerprints() {
        FingerprintAction fingerprintAction = getAction(FingerprintAction.class);
        if (fingerprintAction != null) {
            return fingerprintAction.getFingerprints().values();
        }
        return Collections.<Fingerprint>emptyList();
    }

762 763 764 765 766
	/*
     * No need to to lock the entire AbstractBuild on change set calculcation
     */
    private transient Object changeSetLock = new Object();
    
767 768 769 770 771
    /**
     * Gets the changes incorporated into this build.
     *
     * @return never null.
     */
K
kohsuke 已提交
772
    @Exported
773
    public ChangeLogSet<? extends Entry> getChangeSet() {
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
        synchronized (changeSetLock) {
            if (scm==null) {
                // for historical reason, null means CVS.
                try {
                    Class<?> c = Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass("hudson.scm.CVSChangeLogParser");
                    scm = (ChangeLogParser)c.newInstance();
                } catch (ClassNotFoundException e) {
                    // if CVS isn't available, fall back to something non-null.
                    scm = NullChangeLogParser.INSTANCE;
                } catch (InstantiationException e) {
                    scm = NullChangeLogParser.INSTANCE;
                    throw (Error)new InstantiationError().initCause(e);
                } catch (IllegalAccessException e) {
                    scm = NullChangeLogParser.INSTANCE;
                    throw (Error)new IllegalAccessError().initCause(e);
                }
790 791
            }
        }
792

793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
        ChangeLogSet<? extends Entry> cs = null;
        if (changeSet!=null)
            cs = changeSet.get();

        if (cs==null)
            cs = calcChangeSet();

        // defensive check. if the calculation fails (such as through an exception),
        // set a dummy value so that it'll work the next time. the exception will
        // be still reported, giving the plugin developer an opportunity to fix it.
        if (cs==null)
            cs = ChangeLogSet.createEmpty(this);

        changeSet = new WeakReference<ChangeLogSet<? extends Entry>>(cs);
        return cs;
808 809 810 811 812 813 814 815 816 817 818 819
    }

    /**
     * Returns true if the changelog is already computed.
     */
    public boolean hasChangeSetComputed() {
        File changelogFile = new File(getRootDir(), "changelog.xml");
        return changelogFile.exists();
    }

    private ChangeLogSet<? extends Entry> calcChangeSet() {
        File changelogFile = new File(getRootDir(), "changelog.xml");
820
        if (!changelogFile.exists())
821
            return ChangeLogSet.createEmpty(this);
822 823 824 825 826 827 828 829

        try {
            return scm.parse(this,changelogFile);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
830
        return ChangeLogSet.createEmpty(this);
831 832 833
    }

    @Override
K
kohsuke 已提交
834 835
    public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException {
        EnvVars env = super.getEnvironment(log);
836 837 838
        FilePath ws = getWorkspace();
        if (ws!=null)   // if this is done very early on in the build, workspace may not be decided yet. see HUDSON-3997
            env.put("WORKSPACE", ws.getRemote());
K
kohsuke 已提交
839 840 841 842
        // servlet container may have set CLASSPATH in its launch script,
        // so don't let that inherit to the new child process.
        // see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html
        env.put("CLASSPATH","");
843 844

        JDK jdk = project.getJDK();
845
        if (jdk != null) {
846 847
            Computer computer = Computer.currentComputer();
            if (computer != null) { // just in case were not in a build
K
kohsuke 已提交
848
                jdk = jdk.forNode(computer.getNode(), log);
849
            }
850
            jdk.buildEnvVars(env);
851
        }
852
        project.getScm().buildEnvVars(this,env);
853

854 855 856
        if (buildEnvironments!=null)
            for (Environment e : buildEnvironments)
                e.buildEnvVars(env);
857

858 859 860
        for (EnvironmentContributingAction a : Util.filter(getActions(),EnvironmentContributingAction.class))
            a.buildEnvVars(this,env);

861
        EnvVars.resolve(env);
862

863 864
        return env;
    }
K
kohsuke 已提交
865

K
Kohsuke Kawaguchi 已提交
866 867
    /**
     * During the build, expose the environments contributed by {@link BuildWrapper}s and others.
868 869 870 871 872 873 874
     * 
     * <p>
     * Since 1.444, executor thread that's doing the build can access mutable underlying list,
     * which allows the caller to add/remove environments. The recommended way of adding
     * environment is through {@link BuildWrapper}, but this might be handy for build steps
     * who wants to expose additional environment variables to the rest of the build.
     * 
K
Kohsuke Kawaguchi 已提交
875 876 877
     * @return can be empty list, but never null. Immutable.
     * @since 1.437
     */
878
    public EnvironmentList getEnvironments() {
879 880 881 882 883 884
        Executor e = Executor.currentExecutor();
        if (e!=null && e.getCurrentExecutable()==this) {
            if (buildEnvironments==null)    buildEnvironments = new ArrayList<Environment>();
            return new EnvironmentList(buildEnvironments); 
        }
        
885
        return new EnvironmentList(buildEnvironments==null ? Collections.<Environment>emptyList() : ImmutableList.copyOf(buildEnvironments));
K
Kohsuke Kawaguchi 已提交
886 887
    }

888
    public Calendar due() {
889
        return getTimestamp();
890
    }
891
      
892 893 894
    public List<Action> getPersistentActions(){
        return super.getActions();
    }
895

896 897
    /**
     * Builds up a set of variable names that contain sensitive values that
A
alanharder 已提交
898
     * should not be exposed. The expectation is that this set is populated with
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
     * keys returned by {@link #getBuildVariables()} that should have their
     * values masked for display purposes.
     *
     * @since 1.378
     */
    public Set<String> getSensitiveBuildVariables() {
        Set<String> s = new HashSet<String>();

        ParametersAction parameters = getAction(ParametersAction.class);
        if (parameters != null) {
            for (ParameterValue p : parameters) {
                if (p.isSensitive()) {
                    s.add(p.getName());
                }
            }
        }

        // Allow BuildWrappers to determine if any of their data is sensitive
        if (project instanceof BuildableItemWithBuildWrappers) {
            for (BuildWrapper bw : ((BuildableItemWithBuildWrappers) project).getBuildWrappersList()) {
                bw.makeSensitiveBuildVariables(this, s);
            }
        }
        
        return s;
    }

926 927 928 929 930 931 932 933 934
    /**
     * Provides additional variables and their values to {@link Builder}s.
     *
     * <p>
     * This mechanism is used by {@link MatrixConfiguration} to pass
     * the configuration values to the current build. It is up to
     * {@link Builder}s to decide whether it wants to recognize the values
     * or how to use them.
     *
935 936 937 938 939
     * <p>
     * This also includes build parameters if a build is parameterized.
     *
     * @return
     *      The returned map is mutable so that subtypes can put more values.
940 941
     */
    public Map<String,String> getBuildVariables() {
942 943 944
        Map<String,String> r = new HashMap<String, String>();

        ParametersAction parameters = getAction(ParametersAction.class);
945
        if (parameters!=null) {
946 947 948
            // this is a rather round about way of doing this...
            for (ParameterValue p : parameters) {
                String v = p.createVariableResolver(this).resolve(p.getName());
949
                if (v!=null) r.put(p.getName(),v);
950 951
            }
        }
952 953 954 955 956 957 958

        // allow the BuildWrappers to contribute additional build variables
        if (project instanceof BuildableItemWithBuildWrappers) {
            for (BuildWrapper bw : ((BuildableItemWithBuildWrappers) project).getBuildWrappersList())
                bw.makeBuildVariables(this,r);
        }

959 960 961
        for (BuildVariableContributor bvc : BuildVariableContributor.all())
            bvc.buildVariablesFor(this,r);

962
        return r;
963
    }
964 965 966 967 968 969 970 971

    /**
     * Creates {@link VariableResolver} backed by {@link #getBuildVariables()}.
     */
    public final VariableResolver<String> getBuildVariableResolver() {
        return new VariableResolver.ByMap<String>(getBuildVariables());
    }

972 973 974
    /**
     * Gets {@link AbstractTestResultAction} associated with this build if any.
     */
975 976 977
    public AbstractTestResultAction getTestResultAction() {
        return getAction(AbstractTestResultAction.class);
    }
978

979 980 981 982 983 984 985
    /**
     * Gets {@link AggregatedTestResultAction} associated with this build if any.
     */
    public AggregatedTestResultAction getAggregatedTestResultAction() {
        return getAction(AggregatedTestResultAction.class);
    }

K
kohsuke 已提交
986 987 988 989 990
    /**
     * Invoked by {@link Executor} to performs a build.
     */
    public abstract void run();

991 992 993 994 995 996 997 998 999 1000
//
//
// fingerprint related stuff
//
//

    @Override
    public String getWhyKeepLog() {
        // if any of the downstream project is configured with 'keep dependency component',
        // we need to keep this log
K
kohsuke 已提交
1001
        OUTER:
K
kohsuke 已提交
1002
        for (AbstractProject<?,?> p : getParent().getDownstreamProjects()) {
1003
            if (!p.isKeepDependencies()) continue;
K
kohsuke 已提交
1004

K
kohsuke 已提交
1005
            AbstractBuild<?,?> fb = p.getFirstBuild();
1006
            if (fb==null)        continue; // no active record
K
kohsuke 已提交
1007 1008

            // is there any active build that depends on us?
1009
            for (int i : getDownstreamRelationship(p).listNumbersReverse()) {
K
kohsuke 已提交
1010 1011 1012
                // TODO: this is essentially a "find intersection between two sparse sequences"
                // and we should be able to do much better.

1013
                if (i<fb.getNumber())
K
kohsuke 已提交
1014 1015
                    continue OUTER; // all the other records are younger than the first record, so pointless to search.

K
kohsuke 已提交
1016
                AbstractBuild<?,?> b = p.getBuildByNumber(i);
1017
                if (b!=null)
K
kohsuke 已提交
1018
                    return Messages.AbstractBuild_KeptBecause(b);
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
            }
        }

        return super.getWhyKeepLog();
    }

    /**
     * Gets the dependency relationship from this build (as the source)
     * and that project (as the sink.)
     *
     * @return
     *      range of build numbers that represent which downstream builds are using this build.
K
kohsuke 已提交
1031
     *      The range will be empty if no build of that project matches this, but it'll never be null.
1032
     */
1033 1034 1035 1036
    public RangeSet getDownstreamRelationship(AbstractProject that) {
        RangeSet rs = new RangeSet();

        FingerprintAction f = getAction(FingerprintAction.class);
1037
        if (f==null)     return rs;
1038 1039 1040

        // look for fingerprints that point to this build as the source, and merge them all
        for (Fingerprint e : f.getFingerprints().values()) {
1041 1042 1043 1044

            if (upstreamCulprits) {
                // With upstreamCulprits, we allow downstream relationships
                // from intermediate jobs
1045
                rs.add(e.getRangeSet(that));
1046 1047
            } else {
                BuildPtr o = e.getOriginal();
1048
                if (o!=null && o.is(this))
1049 1050
                    rs.add(e.getRangeSet(that));
            }
1051 1052 1053 1054
        }

        return rs;
    }
1055

K
kohsuke 已提交
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    /**
     * Works like {@link #getDownstreamRelationship(AbstractProject)} but returns
     * the actual build objects, in ascending order.
     * @since 1.150
     */
    public Iterable<AbstractBuild<?,?>> getDownstreamBuilds(final AbstractProject<?,?> that) {
        final Iterable<Integer> nums = getDownstreamRelationship(that).listNumbers();

        return new Iterable<AbstractBuild<?, ?>>() {
            public Iterator<AbstractBuild<?, ?>> iterator() {
1066 1067 1068 1069 1070 1071
                return Iterators.removeNull(
                    new AdaptedIterator<Integer,AbstractBuild<?,?>>(nums) {
                        protected AbstractBuild<?, ?> adapt(Integer item) {
                            return that.getBuildByNumber(item);
                        }
                    });
K
kohsuke 已提交
1072 1073 1074 1075
            }
        };
    }

1076 1077 1078 1079 1080 1081 1082 1083
    /**
     * Gets the dependency relationship from this build (as the sink)
     * and that project (as the source.)
     *
     * @return
     *      Build number of the upstream build that feed into this build,
     *      or -1 if no record is available.
     */
1084 1085
    public int getUpstreamRelationship(AbstractProject that) {
        FingerprintAction f = getAction(FingerprintAction.class);
1086
        if (f==null)     return -1;
1087 1088 1089 1090 1091

        int n = -1;

        // look for fingerprints that point to the given project as the source, and merge them all
        for (Fingerprint e : f.getFingerprints().values()) {
1092 1093 1094 1095
            if (upstreamCulprits) {
                // With upstreamCulprits, we allow upstream relationships
                // from intermediate jobs
                Fingerprint.RangeSet rangeset = e.getRangeSet(that);
1096
                if (!rangeset.isEmpty()) {
1097 1098 1099 1100
                    n = Math.max(n, rangeset.listNumbersReverse().iterator().next());
                }
            } else {
                BuildPtr o = e.getOriginal();
1101
                if (o!=null && o.belongsTo(that))
1102 1103
                    n = Math.max(n,o.getNumber());
            }
1104 1105 1106 1107
        }

        return n;
    }
1108

K
kohsuke 已提交
1109 1110 1111 1112 1113 1114 1115 1116
    /**
     * Works like {@link #getUpstreamRelationship(AbstractProject)} but returns the
     * actual build object.
     *
     * @return
     *      null if no such upstream build was found, or it was found but the
     *      build record is already lost.
     */
1117
    public AbstractBuild<?,?> getUpstreamRelationshipBuild(AbstractProject<?,?> that) {
K
kohsuke 已提交
1118
        int n = getUpstreamRelationship(that);
1119
        if (n==-1)   return null;
K
kohsuke 已提交
1120 1121 1122
        return that.getBuildByNumber(n);
    }

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
    /**
     * Gets the downstream builds of this build, which are the builds of the
     * downstream projects that use artifacts of this build.
     *
     * @return
     *      For each project with fingerprinting enabled, returns the range
     *      of builds (which can be empty if no build uses the artifact from this build.)
     */
    public Map<AbstractProject,RangeSet> getDownstreamBuilds() {
        Map<AbstractProject,RangeSet> r = new HashMap<AbstractProject,RangeSet>();
        for (AbstractProject p : getParent().getDownstreamProjects()) {
1134
            if (p.isFingerprintConfigured())
1135 1136 1137 1138
                r.put(p,getDownstreamRelationship(p));
        }
        return r;
    }
1139

1140 1141 1142
    /**
     * Gets the upstream builds of this build, which are the builds of the
     * upstream projects whose artifacts feed into this build.
K
kohsuke 已提交
1143 1144
     *
     * @see #getTransitiveUpstreamBuilds()
1145 1146
     */
    public Map<AbstractProject,Integer> getUpstreamBuilds() {
K
kohsuke 已提交
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
        return _getUpstreamBuilds(getParent().getUpstreamProjects());
    }

    /**
     * Works like {@link #getUpstreamBuilds()}  but also includes all the transitive
     * dependencies as well.
     */
    public Map<AbstractProject,Integer> getTransitiveUpstreamBuilds() {
        return _getUpstreamBuilds(getParent().getTransitiveUpstreamProjects());
    }

    private Map<AbstractProject, Integer> _getUpstreamBuilds(Collection<AbstractProject> projects) {
1159
        Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>();
K
kohsuke 已提交
1160
        for (AbstractProject p : projects) {
1161
            int n = getUpstreamRelationship(p);
1162
            if (n>=0)
1163 1164 1165 1166 1167
                r.put(p,n);
        }
        return r;
    }

1168 1169 1170 1171
    /**
     * Gets the changes in the dependency between the given build and this build.
     */
    public Map<AbstractProject,DependencyChange> getDependencyChanges(AbstractBuild from) {
1172
        if (from==null)             return Collections.emptyMap(); // make it easy to call this from views
1173 1174
        FingerprintAction n = this.getAction(FingerprintAction.class);
        FingerprintAction o = from.getAction(FingerprintAction.class);
1175
        if (n==null || o==null)     return Collections.emptyMap();
1176

1177 1178
        Map<AbstractProject,Integer> ndep = n.getDependencies(true);
        Map<AbstractProject,Integer> odep = o.getDependencies(true);
1179 1180 1181 1182 1183 1184 1185

        Map<AbstractProject,DependencyChange> r = new HashMap<AbstractProject,DependencyChange>();

        for (Map.Entry<AbstractProject,Integer> entry : odep.entrySet()) {
            AbstractProject p = entry.getKey();
            Integer oldNumber = entry.getValue();
            Integer newNumber = ndep.get(p);
1186
            if (newNumber!=null && oldNumber.compareTo(newNumber)<0) {
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
                r.put(p,new DependencyChange(p,oldNumber,newNumber));
            }
        }

        return r;
    }

    /**
     * Represents a change in the dependency.
     */
    public static final class DependencyChange {
        /**
         * The dependency project.
         */
        public final AbstractProject project;
        /**
         * Version of the dependency project used in the previous build.
         */
        public final int fromId;
        /**
         * {@link Build} object for {@link #fromId}. Can be null if the log is gone.
         */
        public final AbstractBuild from;
        /**
         * Version of the dependency project used in this build.
         */
        public final int toId;

        public final AbstractBuild to;

        public DependencyChange(AbstractProject<?,?> project, int fromId, int toId) {
            this.project = project;
            this.fromId = fromId;
            this.toId = toId;
            this.from = project.getBuildByNumber(fromId);
            this.to = project.getBuildByNumber(toId);
        }
1224 1225 1226 1227 1228

        /**
         * Gets the {@link AbstractBuild} objects (fromId,toId].
         * <p>
         * This method returns all such available builds in the ascending order
1229
         * of IDs, but due to log rotations, some builds may be already unavailable.
1230 1231 1232 1233 1234
         */
        public List<AbstractBuild> getBuilds() {
            List<AbstractBuild> r = new ArrayList<AbstractBuild>();

            AbstractBuild<?,?> b = (AbstractBuild)project.getNearestBuild(fromId);
1235
            if (b!=null && b.getNumber()==fromId)
1236 1237
                b = b.getNextBuild(); // fromId exclusive

1238
            while (b!=null && b.getNumber()<=toId) {
1239 1240 1241 1242 1243 1244
                r.add(b);
                b = b.getNextBuild();
            }

            return r;
        }
1245
    }
1246

1247 1248 1249 1250
    //
    // web methods
    //

K
kohsuke 已提交
1251 1252 1253 1254 1255 1256
    /**
     * Stops this build if it's still going.
     *
     * If we use this/executor/stop URL, it causes 404 if the build is already killed,
     * as {@link #getExecutor()} returns null.
     */
1257
    public synchronized void doStop(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
K
kohsuke 已提交
1258
        Executor e = getExecutor();
1259 1260
        if (e==null)
            e = getOneOffExecutor();
1261
        if (e!=null)
K
kohsuke 已提交
1262 1263 1264 1265 1266
            e.doStop(req,rsp);
        else
            // nothing is building
            rsp.forwardToPreviousPage(req);
    }
1267 1268

    private static final Logger LOGGER = Logger.getLogger(AbstractBuild.class.getName());
1269
}
1270 1271