Run.java 70.2 KB
Newer Older
K
kohsuke 已提交
1 2 3
/*
 * The MIT License
 * 
4
 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
R
rseguy 已提交
5 6
 * Daniel Dyer, Red Hat, Inc., Tom Huybrechts, Romain Seguy, Yahoo! Inc.,
 * Darek Ostolski
K
kohsuke 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * 
 * 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.
 */
K
kohsuke 已提交
26 27
package hudson.model;

28
import hudson.console.ConsoleLogFilter;
R
rseguy 已提交
29
import hudson.Functions;
30 31
import hudson.AbortException;
import hudson.BulkChange;
K
kohsuke 已提交
32
import hudson.EnvVars;
K
kohsuke 已提交
33
import hudson.ExtensionPoint;
K
kohsuke 已提交
34
import hudson.FeedAdapter;
35
import hudson.FilePath;
K
kohsuke 已提交
36 37
import hudson.Util;
import hudson.XmlFile;
38
import hudson.cli.declarative.CLIMethod;
K
kohsuke 已提交
39
import hudson.console.AnnotatedLargeText;
40
import hudson.console.ConsoleNote;
41 42
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixRun;
43
import hudson.model.Descriptor.FormException;
44
import hudson.model.listeners.RunListener;
45
import hudson.model.listeners.SaveableListener;
46
import hudson.security.PermissionScope;
47
import jenkins.model.Jenkins.MasterComputer;
K
kohsuke 已提交
48
import hudson.search.SearchIndexBuilder;
49 50 51 52 53
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.tasks.LogRotator;
54
import hudson.tasks.Mailer;
K
kohsuke 已提交
55 56
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildStep;
K
kohsuke 已提交
57
import hudson.tasks.test.AbstractTestResultAction;
K
kohsuke 已提交
58
import hudson.util.FlushProofOutputStream;
K
kohsuke 已提交
59
import hudson.util.IOException2;
K
kohsuke 已提交
60
import hudson.util.LogTaskListener;
61
import hudson.util.XStream2;
62
import hudson.util.ProcessTree;
K
kohsuke 已提交
63

64
import java.io.BufferedReader;
K
kohsuke 已提交
65
import java.io.File;
66
import java.io.FileInputStream;
K
kohsuke 已提交
67
import java.io.IOException;
K
kohsuke 已提交
68
import java.io.InputStream;
69
import java.io.InputStreamReader;
K
kohsuke 已提交
70
import java.io.PrintWriter;
71
import java.io.Reader;
K
kohsuke 已提交
72
import java.io.Writer;
73
import java.nio.charset.Charset;
74
import java.text.DateFormat;
K
kohsuke 已提交
75 76 77
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
78
import java.util.Arrays;
K
kohsuke 已提交
79
import java.util.Calendar;
80
import java.util.Collections;
K
kohsuke 已提交
81
import java.util.Comparator;
82
import java.util.Date;
K
kohsuke 已提交
83
import java.util.GregorianCalendar;
84
import java.util.HashMap;
85
import java.util.LinkedHashMap;
86
import java.util.LinkedList;
K
kohsuke 已提交
87
import java.util.List;
88
import java.util.Locale;
K
kohsuke 已提交
89
import java.util.Map;
K
kohsuke 已提交
90 91
import java.util.Set;
import java.util.HashSet;
92
import java.util.logging.Level;
K
kohsuke 已提交
93
import java.util.logging.Logger;
94 95 96 97 98
import java.util.zip.GZIPInputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

99
import jenkins.model.Jenkins;
100
import net.sf.json.JSONObject;
K
kohsuke 已提交
101
import org.apache.commons.io.input.NullInputStream;
T
Tom Huybrechts 已提交
102
import org.apache.commons.io.IOUtils;
K
kohsuke 已提交
103
import org.apache.commons.jelly.XMLOutput;
104 105
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
106 107
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
108 109 110 111 112 113 114
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;

import com.thoughtworks.xstream.XStream;
115 116
import org.kohsuke.stapler.interceptor.RequirePOST;

117 118
import java.io.FileOutputStream;
import java.io.OutputStream;
K
kohsuke 已提交
119

120
import static java.util.logging.Level.*;
121

K
kohsuke 已提交
122 123 124 125 126 127 128 129 130
/**
 * A particular execution of {@link Job}.
 *
 * <p>
 * Custom {@link Run} type is always used in conjunction with
 * a custom {@link Job} type, so there's no separate registration
 * mechanism for custom {@link Run} types.
 *
 * @author Kohsuke Kawaguchi
K
kohsuke 已提交
131
 * @see RunListener
K
kohsuke 已提交
132
 */
K
kohsuke 已提交
133
@ExportedBean
K
kohsuke 已提交
134
public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,RunT>>
135
        extends Actionable implements ExtensionPoint, Comparable<RunT>, AccessControlled, PersistenceRoot, DescriptorByNameOwner {
K
kohsuke 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

    protected transient final JobT project;

    /**
     * Build number.
     *
     * <p>
     * In earlier versions &lt; 1.24, this number is not unique nor continuous,
     * but going forward, it will, and this really replaces the build id.
     */
    public /*final*/ int number;

    /**
     * Previous build. Can be null.
     * These two fields are maintained and updated by {@link RunMap}.
151 152
     *
     * External code should use {@link #getPreviousBuild()}
K
kohsuke 已提交
153
     */
154
    @Restricted(NoExternalUse.class)
K
kohsuke 已提交
155
    protected volatile transient RunT previousBuild;
K
kohsuke 已提交
156

K
kohsuke 已提交
157 158
    /**
     * Next build. Can be null.
159 160
     *
     * External code should use {@link #getNextBuild()}
K
kohsuke 已提交
161
     */
162
    @Restricted(NoExternalUse.class)
K
kohsuke 已提交
163 164
    protected volatile transient RunT nextBuild;

K
kohsuke 已提交
165 166 167 168 169
    /**
     * Pointer to the next younger build in progress. This data structure is lazily updated,
     * so it may point to the build that's already completed. This pointer is set to 'this'
     * if the computation determines that everything earlier than this build is already completed.
     */
170
    /* does not compile on JDK 7: private*/ volatile transient RunT previousBuildInProgress;
K
kohsuke 已提交
171

K
kohsuke 已提交
172 173 174
    /**
     * When the build is scheduled.
     */
175
    protected transient final long timestamp;
K
kohsuke 已提交
176 177 178 179 180 181 182 183 184 185 186 187

    /**
     * The build result.
     * This value may change while the state is in {@link State#BUILDING}.
     */
    protected volatile Result result;

    /**
     * Human-readable description. Can be null.
     */
    protected volatile String description;

188 189 190 191 192 193 194
    /**
     * Human-readable name of this build. Can be null.
     * If non-null, this text is displayed instead of "#NNN", which is the default.
     * @since 1.390
     */
    private volatile String displayName;

K
kohsuke 已提交
195 196 197 198 199 200
    /**
     * The current build state.
     */
    protected volatile transient State state;

    private static enum State {
201 202 203
        /**
         * Build is created/queued but we haven't started building it.
         */
K
kohsuke 已提交
204
        NOT_STARTED,
205 206 207
        /**
         * Build is in progress.
         */
K
kohsuke 已提交
208
        BUILDING,
209 210 211 212 213 214 215 216
        /**
         * Build is completed now, and the status is determined,
         * but log files are still being updated.
         */
        POST_PRODUCTION,
        /**
         * Build is completed now, and log file is closed.
         */
K
kohsuke 已提交
217 218 219 220 221 222 223 224
        COMPLETED
    }

    /**
     * Number of milli-seconds it took to run this build.
     */
    protected long duration;

225 226 227 228 229 230 231 232
    /**
     * Charset in which the log file is written.
     * For compatibility reason, this field may be null.
     * For persistence, this field is string and not {@link Charset}.
     *
     * @see #getCharset()
     * @since 1.257
     */
233
    protected String charset;
234

K
kohsuke 已提交
235 236 237 238 239
    /**
     * Keeps this log entries.
     */
    private boolean keepLog;

K
kohsuke 已提交
240 241 242 243 244 245
    /**
     * If the build is in progress, remember {@link Runner} that's running it.
     * This field is not persisted.
     */
    private volatile transient Runner runner;

246 247 248 249 250 251 252
    protected static final ThreadLocal<SimpleDateFormat> ID_FORMATTER =
            new ThreadLocal<SimpleDateFormat>() {
                @Override
                protected SimpleDateFormat initialValue() {
                    return new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
                }
            };
K
kohsuke 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266

    /**
     * Creates a new {@link Run}.
     */
    protected Run(JobT job) throws IOException {
        this(job, new GregorianCalendar());
        this.number = project.assignBuildNumber();
    }

    /**
     * Constructor for creating a {@link Run} object in
     * an arbitrary state.
     */
    protected Run(JobT job, Calendar timestamp) {
267 268 269 270
        this(job,timestamp.getTimeInMillis());
    }

    protected Run(JobT job, long timestamp) {
K
kohsuke 已提交
271 272 273
        this.project = job;
        this.timestamp = timestamp;
        this.state = State.NOT_STARTED;
274
		getRootDir().mkdirs();
K
kohsuke 已提交
275 276 277 278 279 280
    }

    /**
     * Loads a run from a log file.
     */
    protected Run(JobT project, File buildDir) throws IOException {
281
        this(project, parseTimestampFromBuildDir(buildDir));
K
kohsuke 已提交
282
        this.previousBuildInProgress = _this(); // loaded builds are always completed
283 284 285 286 287 288 289 290 291
        reload();
    }

    /**
     * Reloads the build record from disk.
     *
     * @since 1.410
     */
    public void reload() throws IOException {
292 293 294
        this.state = State.COMPLETED;
        this.result = Result.FAILURE;  // defensive measure. value should be overwritten by unmarshal, but just in case the saved data is inconsistent
        getDataFile().unmarshal(this); // load the rest of the data
295 296 297

        // not calling onLoad upon reload. partly because we don't want to call that from Run constructor,
        // and partly because some existing use of onLoad isn't assuming that it can be invoked multiple times.
298 299
    }

300 301 302 303 304 305 306 307 308
    /**
     * Called after the build is loaded and the object is added to the build list.
     */
    protected void onLoad() {
        for (Action a : getActions())
            if (a instanceof RunAction)
                ((RunAction) a).onLoad();
    }

309 310 311 312 313 314 315
    @Override
    public void addAction(Action a) {
        super.addAction(a);
        if (a instanceof RunAction)
            ((RunAction) a).onAttached(this);
    }

316
    /*package*/ static long parseTimestampFromBuildDir(File buildDir) throws IOException {
K
kohsuke 已提交
317
        try {
318
            return ID_FORMATTER.get().parse(buildDir.getName()).getTime();
K
kohsuke 已提交
319 320 321 322 323 324 325
        } catch (ParseException e) {
            throw new IOException2("Invalid directory name "+buildDir,e);
        } catch (NumberFormatException e) {
            throw new IOException2("Invalid directory name "+buildDir,e);
        }
    }

K
kohsuke 已提交
326 327 328 329 330 331 332 333
    /**
     * Obtains 'this' in a more type safe signature.
     */
    @SuppressWarnings({"unchecked"})
    private RunT _this() {
        return (RunT)this;
    }

334 335 336 337 338 339 340
    /**
     * Ordering based on build numbers.
     */
    public int compareTo(RunT that) {
        return this.number - that.number;
    }

K
kohsuke 已提交
341 342 343 344 345
    /**
     * Returns the build result.
     *
     * <p>
     * When a build is {@link #isBuilding() in progress}, this method
346
     * returns an intermediate result.
K
kohsuke 已提交
347
     */
K
kohsuke 已提交
348
    @Exported
K
kohsuke 已提交
349
    public Result getResult() {
K
kohsuke 已提交
350 351 352 353 354 355 356 357 358 359
        return result;
    }

    public void setResult(Result r) {
        // state can change only when we are building
        assert state==State.BUILDING;

        // result can only get worse
        if(result==null) {
            result = r;
360
            LOGGER.log(FINE, toString()+" : result is set to "+r,new Exception());
K
kohsuke 已提交
361 362
        } else {
            if(r.isWorseThan(result)) {
363
                LOGGER.log(FINE, toString()+" : result is set to "+r,new Exception());
K
kohsuke 已提交
364 365 366 367 368
                result = r;
            }
        }
    }

369
    /**
370
     * Gets the subset of {@link #getActions()} that consists of {@link BuildBadgeAction}s.
371 372 373 374 375 376 377 378 379 380
     */
    public List<BuildBadgeAction> getBadgeActions() {
        List<BuildBadgeAction> r = null;
        for (Action a : getActions()) {
            if(a instanceof BuildBadgeAction) {
                if(r==null)
                    r = new ArrayList<BuildBadgeAction>();
                r.add((BuildBadgeAction)a);
            }
        }
381 382 383 384 385
        if(isKeepLog()) {
            if(r==null)
                r = new ArrayList<BuildBadgeAction>();
            r.add(new KeepLogBuildBadge());
        }
386 387 388 389
        if(r==null)     return Collections.emptyList();
        else            return r;
    }

K
kohsuke 已提交
390 391
    /**
     * Returns true if the build is not completed yet.
392
     * This includes "not started yet" state.
K
kohsuke 已提交
393
     */
K
kohsuke 已提交
394
    @Exported
K
kohsuke 已提交
395
    public boolean isBuilding() {
396 397 398 399 400 401 402 403
        return state.compareTo(State.POST_PRODUCTION) < 0;
    }

    /**
     * Returns true if the log file is still being updated.
     */
    public boolean isLogUpdated() {
        return state.compareTo(State.COMPLETED) < 0;
K
kohsuke 已提交
404 405 406 407 408
    }

    /**
     * Gets the {@link Executor} building this job, if it's being built.
     * Otherwise null.
K
Kohsuke Kawaguchi 已提交
409 410 411 412 413
     * 
     * This method looks for {@link Executor} who's {@linkplain Executor#getCurrentExecutable() assigned to this build},
     * and because of that this might not be necessarily in sync with the return value of {@link #isBuilding()} &mdash;
     * an executor holds on to {@lnk Run} some more time even after the build is finished (for example to
     * perform {@linkplain State#POST_PRODUCTION post-production processing}.)
K
kohsuke 已提交
414 415
     */
    public Executor getExecutor() {
416
        for( Computer c : Jenkins.getInstance().getComputers() ) {
K
kohsuke 已提交
417
            for (Executor e : c.getExecutors()) {
418
                if(e.getCurrentExecutable()==this)
K
kohsuke 已提交
419 420 421 422 423 424
                    return e;
            }
        }
        return null;
    }

425 426 427
    /**
     * Gets the one off {@link Executor} building this job, if it's being built.
     * Otherwise null.
428
     * @since 1.433 
429 430 431 432 433 434 435 436 437 438 439
     */
    public Executor getOneOffExecutor() {
        for( Computer c : Jenkins.getInstance().getComputers() ) {
            for (Executor e : c.getOneOffExecutors()) {
                if(e.getCurrentExecutable()==this)
                    return e;
            }
        }
        return null;
    }

440 441 442 443 444 445 446 447 448 449
    /**
     * Gets the charset in which the log file is written.
     * @return never null.
     * @since 1.257
     */
    public final Charset getCharset() {
        if(charset==null)   return Charset.defaultCharset();
        return Charset.forName(charset);
    }

K
kohsuke 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    /**
     * Returns the {@link Cause}s that tirggered a build.
     *
     * <p>
     * If a build sits in the queue for a long time, multiple build requests made during this period
     * are all rolled up into one build, hence this method may return a list.
     *
     * @return
     *      can be empty but never null. read-only.
     * @since 1.321
     */
    public List<Cause> getCauses() {
        CauseAction a = getAction(CauseAction.class);
        if (a==null)    return Collections.emptyList();
        return Collections.unmodifiableList(a.getCauses());
    }

K
kohsuke 已提交
467 468 469 470 471 472 473 474 475 476 477 478
    /**
     * Returns a {@link Cause} of a particular type.
     *
     * @since 1.362
     */
    public <T extends Cause> T getCause(Class<T> type) {
        for (Cause c : getCauses())
            if (type.isInstance(c))
                return type.cast(c);
        return null;
    }

K
kohsuke 已提交
479 480 481 482 483
    /**
     * Returns true if this log file should be kept and not deleted.
     *
     * This is used as a signal to the {@link LogRotator}.
     */
K
kohsuke 已提交
484
    @Exported
485 486 487 488 489 490 491 492 493 494
    public final boolean isKeepLog() {
        return getWhyKeepLog()!=null;
    }

    /**
     * If {@link #isKeepLog()} returns true, returns a human readable
     * one-line string that explains why it's being kept.
     */
    public String getWhyKeepLog() {
        if(keepLog)
K
i18n  
kohsuke 已提交
495
            return Messages.Run_MarkedExplicitly();
496
        return null;    // not marked at all
K
kohsuke 已提交
497 498 499 500 501 502 503 504 505 506 507 508
    }

    /**
     * The project this build is for.
     */
    public JobT getParent() {
        return project;
    }

    /**
     * When the build is scheduled.
     */
K
kohsuke 已提交
509
    @Exported
K
kohsuke 已提交
510
    public Calendar getTimestamp() {
511 512 513
        GregorianCalendar c = new GregorianCalendar();
        c.setTimeInMillis(timestamp);
        return c;
K
kohsuke 已提交
514 515
    }

K
kohsuke 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529
    /**
     * Same as {@link #getTimestamp()} but in a different type.
     */
    public final Date getTime() {
        return new Date(timestamp);
    }

    /**
     * Same as {@link #getTimestamp()} but in a different type, that is since the time of the epoc.
     */
    public final long getTimeInMillis() {
        return timestamp;
    }

K
kohsuke 已提交
530
    @Exported
K
kohsuke 已提交
531 532 533 534
    public String getDescription() {
        return description;
    }

535

536 537 538 539 540 541 542 543 544 545 546
    /**
     * Returns the length-limited description.
     * @return The length-limited description.
     */
    public String getTruncatedDescription() {
        final int maxDescrLength = 100;
        if (description == null || description.length() < maxDescrLength) {
            return description;
        }

        final String ending = "...";
547
        final int sz = description.length(), maxTruncLength = maxDescrLength - ending.length();
548 549 550 551

        boolean inTag = false;
        int displayChars = 0;
        int lastTruncatablePoint = -1;
552

553 554 555 556 557 558
        for (int i=0; i<sz; i++) {
            char ch = description.charAt(i);
            if(ch == '<') {
                inTag = true;
            } else if (ch == '>') {
                inTag = false;
559
                if (displayChars <= maxTruncLength) {
560 561 562 563 564
                    lastTruncatablePoint = i + 1;
                }
            }
            if (!inTag) {
                displayChars++;
565 566
                if (displayChars <= maxTruncLength && ch == ' ') {
                    lastTruncatablePoint = i;
567 568
                }
            }
569 570
        }

571
        String truncDesc = description;
572 573 574 575 576

        // Could not find a preferred truncable index, force a trunc at maxTruncLength
        if (lastTruncatablePoint == -1)
            lastTruncatablePoint = maxTruncLength;

577
        if (displayChars >= maxDescrLength) {
578
            truncDesc = truncDesc.substring(0, lastTruncatablePoint) + ending;
579 580
        }
        
581
        return truncDesc;
582
        
583 584
    }

K
kohsuke 已提交
585
    /**
586
     * Gets the string that says how long since this build has started.
K
kohsuke 已提交
587 588 589 590 591
     *
     * @return
     *      string like "3 minutes" "1 day" etc.
     */
    public String getTimestampString() {
592
        long duration = new GregorianCalendar().getTimeInMillis()-timestamp;
K
i18n  
kohsuke 已提交
593
        return Util.getPastTimeString(duration);
K
kohsuke 已提交
594 595 596 597 598 599
    }

    /**
     * Returns the timestamp formatted in xs:dateTime.
     */
    public String getTimestampString2() {
600
        return Util.XS_DATETIME_FORMATTER.format(new Date(timestamp));
K
kohsuke 已提交
601 602 603 604 605 606
    }

    /**
     * Gets the string that says how long the build took to run.
     */
    public String getDurationString() {
607
        if(isBuilding())
608 609
            return Messages.Run_InProgressDuration(
                    Util.getTimeSpanString(System.currentTimeMillis()-timestamp));
K
kohsuke 已提交
610 611 612 613 614 615
        return Util.getTimeSpanString(duration);
    }

    /**
     * Gets the millisecond it took to build.
     */
K
kohsuke 已提交
616
    @Exported
K
kohsuke 已提交
617 618 619 620 621 622 623
    public long getDuration() {
        return duration;
    }

    /**
     * Gets the icon color for display.
     */
624
    public BallColor getIconColor() {
K
kohsuke 已提交
625 626
        if(!isBuilding()) {
            // already built
K
kohsuke 已提交
627
            return getResult().color;
K
kohsuke 已提交
628 629 630
        }

        // a new build is in progress
631
        BallColor baseColor;
K
kohsuke 已提交
632
        if(previousBuild==null)
633
            baseColor = BallColor.GREY;
K
kohsuke 已提交
634 635 636
        else
            baseColor = previousBuild.getIconColor();

637
        return baseColor.anime();
K
kohsuke 已提交
638 639 640 641 642 643 644 645 646
    }

    /**
     * Returns true if the build is still queued and hasn't started yet.
     */
    public boolean hasntStartedYet() {
        return state ==State.NOT_STARTED;
    }

647
    @Override
K
kohsuke 已提交
648
    public String toString() {
K
kohsuke 已提交
649 650 651
        return getFullDisplayName();
    }

652
    @Exported
K
kohsuke 已提交
653
    public String getFullDisplayName() {
654
        return project.getFullDisplayName()+' '+getDisplayName();
K
kohsuke 已提交
655 656 657
    }

    public String getDisplayName() {
658 659 660 661 662 663 664
        return displayName!=null ? displayName : "#"+number;
    }

    public boolean hasCustomDisplayName() {
        return displayName!=null;
    }

665 666 667 668
    /**
     * @param value
     *      Set to null to revert back to the default "#NNN".
     */
669 670 671 672
    public void setDisplayName(String value) throws IOException {
        checkPermission(UPDATE);
        this.displayName = value;
        save();
K
kohsuke 已提交
673 674
    }

K
kohsuke 已提交
675
    @Exported(visibility=2)
K
kohsuke 已提交
676 677 678 679 680 681 682 683
    public int getNumber() {
        return number;
    }

    public RunT getPreviousBuild() {
        return previousBuild;
    }

684 685 686 687 688 689 690 691 692 693
    /**
     * Gets the most recent {@linkplain #isBuilding() completed} build excluding 'this' Run itself.
     */
    public final RunT getPreviousCompletedBuild() {
        RunT r=getPreviousBuild();
        while (r!=null && r.isBuilding())
            r=r.getPreviousBuild();
        return r;
    }

K
kohsuke 已提交
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
    /**
     * Obtains the next younger build in progress. It uses a skip-pointer so that we can compute this without
     * O(n) computation time. This method also fixes up the skip list as we go, in a way that's concurrency safe.
     *
     * <p>
     * We basically follow the existing skip list, and wherever we find a non-optimal pointer, we remember them
     * in 'fixUp' and update them later.
     */
    public final RunT getPreviousBuildInProgress() {
        if(previousBuildInProgress==this)   return null;    // the most common case

        List<RunT> fixUp = new ArrayList<RunT>();
        RunT r = _this(); // 'r' is the source of the pointer (so that we can add it to fix up if we find that the target of the pointer is inefficient.)
        RunT answer;
        while (true) {
            RunT n = r.previousBuildInProgress;
            if (n==null) {// no field computed yet.
                n=r.getPreviousBuild();
                fixUp.add(r);
            }
            if (r==n || n==null) {
                // this indicates that we know there's no build in progress beyond this point
                answer = null;
                break;
            }
            if (n.isBuilding()) {
                // we now know 'n' is the target we wanted
                answer = n;
                break;
            }

            fixUp.add(r);   // r contains the stale 'previousBuildInProgress' back pointer
            r = n;
        }

        // fix up so that the next look up will run faster
        for (RunT f : fixUp)
            f.previousBuildInProgress = answer==null ? f : answer;
        return answer;
    }

735 736 737 738 739
    /**
     * Returns the last build that was actually built - i.e., skipping any with Result.NOT_BUILT
     */
    public RunT getPreviousBuiltBuild() {
        RunT r=previousBuild;
740 741
        // in certain situations (aborted m2 builds) r.getResult() can still be null, although it should theoretically never happen
        while( r!=null && (r.getResult() == null || r.getResult()==Result.NOT_BUILT) )
742 743 744 745
            r=r.previousBuild;
        return r;
    }

K
kohsuke 已提交
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
    /**
     * Returns the last build that didn't fail before this build.
     */
    public RunT getPreviousNotFailedBuild() {
        RunT r=previousBuild;
        while( r!=null && r.getResult()==Result.FAILURE )
            r=r.previousBuild;
        return r;
    }

    /**
     * Returns the last failed build before this build.
     */
    public RunT getPreviousFailedBuild() {
        RunT r=previousBuild;
        while( r!=null && r.getResult()!=Result.FAILURE )
            r=r.previousBuild;
        return r;
    }
K
kohsuke 已提交
765 766 767 768 769 770 771 772 773 774 775 776

    /**
     * Returns the last successful build before this build.
     * @since 1.383
     */
    public RunT getPreviousSuccessfulBuild() {
        RunT r=previousBuild;
        while( r!=null && r.getResult()!=Result.SUCCESS )
            r=r.previousBuild;
        return r;
    }

777
    /**
K
kutzi 已提交
778
     * Returns the last 'numberOfBuilds' builds with a build result >= 'threshold'.
779
     * 
K
kutzi 已提交
780 781
     * @param numberOfBuilds the desired number of builds
     * @param threshold the build result threshold
782 783 784 785 786 787
     * @return a list with the builds (youngest build first).
     *   May be smaller than 'numberOfBuilds' or even empty
     *   if not enough builds satisfying the threshold have been found. Never null.
     * @since 1.383
     */
    public List<RunT> getPreviousBuildsOverThreshold(int numberOfBuilds, Result threshold) {
K
kutzi 已提交
788
        List<RunT> builds = new ArrayList<RunT>(numberOfBuilds);
789 790
        
        RunT r = getPreviousBuild();
K
kutzi 已提交
791
        while (r != null && builds.size() < numberOfBuilds) {
792 793
            if (!r.isBuilding() && 
                 (r.getResult() != null && r.getResult().isBetterOrEqualTo(threshold))) {
K
kutzi 已提交
794
                builds.add(r);
795 796 797 798
            }
            r = r.getPreviousBuild();
        }
        
K
kutzi 已提交
799
        return builds;
800
    }
K
kohsuke 已提交
801 802 803 804 805

    public RunT getNextBuild() {
        return nextBuild;
    }

K
kohsuke 已提交
806 807 808 809 810 811
    /**
     * Returns the URL of this {@link Run}, relative to the context root of Hudson.
     *
     * @return
     *      String like "job/foo/32/" with trailing slash but no leading slash. 
     */
K
kohsuke 已提交
812 813 814 815 816 817
    // I really messed this up. I'm hoping to fix this some time
    // it shouldn't have trailing '/', and instead it should have leading '/'
    public String getUrl() {
        return project.getUrl()+getNumber()+'/';
    }

818 819 820 821
    /**
     * Obtains the absolute URL to this build.
     *
     * @deprecated
K
Kohsuke Kawaguchi 已提交
822 823 824
     *      This method shall <b>NEVER</b> be used during HTML page rendering, as it's too easy for
     *      misconfiguration to break this value, with network set up like Apache reverse proxy.
     *      This method is only intended for the remote API clients who cannot resolve relative references.
825
     */
K
kohsuke 已提交
826
    @Exported(visibility=2,name="url")
827 828 829 830
    public final String getAbsoluteUrl() {
        return project.getAbsoluteUrl()+getNumber()+'/';
    }

831 832 833 834
    public final String getSearchUrl() {
        return getNumber()+"/";
    }

K
kohsuke 已提交
835 836 837
    /**
     * Unique ID of this build.
     */
K
kohsuke 已提交
838
    @Exported
K
kohsuke 已提交
839
    public String getId() {
840
        return ID_FORMATTER.get().format(new Date(timestamp));
K
kohsuke 已提交
841
    }
K
kohsuke 已提交
842 843 844 845 846 847 848 849 850
    
    /**
     * Get the date formatter used to convert the directory name in to a timestamp
     * This is nasty exposure of private data, but needed all the time the directory
     * containing the build is used as it's timestamp.
     */
    public static DateFormat getIDFormatter() {
    	return ID_FORMATTER.get();
    }
K
kohsuke 已提交
851

852
    public Descriptor getDescriptorByName(String className) {
853
        return Jenkins.getInstance().getDescriptorByName(className);
854 855
    }

K
kohsuke 已提交
856 857 858 859 860
    /**
     * Root directory of this {@link Run} on the master.
     *
     * Files related to this {@link Run} should be stored below this directory.
     */
K
kohsuke 已提交
861
    public File getRootDir() {
862
        return new File(project.getBuildDir(),getId());
K
kohsuke 已提交
863 864 865 866 867 868 869 870 871 872
    }

    /**
     * Gets the directory where the artifacts are archived.
     */
    public File getArtifactsDir() {
        return new File(getRootDir(),"archive");
    }

    /**
873
     * Gets the artifacts (relative to {@link #getArtifactsDir()}.
K
kohsuke 已提交
874
     */
875
    @Exported
K
kohsuke 已提交
876
    public List<Artifact> getArtifacts() {
877 878 879 880 881 882 883
        return getArtifactsUpTo(Integer.MAX_VALUE);
    }

    /**
     * Gets the first N artifacts.
     */
    public List<Artifact> getArtifactsUpTo(int n) {
884
        ArtifactList r = new ArtifactList();
885
        addArtifacts(getArtifactsDir(),"","",r,null,n);
886
        r.computeDisplayName();
K
kohsuke 已提交
887 888 889 890 891 892 893 894 895 896
        return r;
    }

    /**
     * Returns true if this run has any artifacts.
     *
     * <p>
     * The strange method name is so that we can access it from EL.
     */
    public boolean getHasArtifacts() {
897
        return !getArtifactsUpTo(1).isEmpty();
K
kohsuke 已提交
898 899
    }

900
    private int addArtifacts( File dir, String path, String pathHref, ArtifactList r, Artifact parent, int upTo ) {
K
kohsuke 已提交
901
        String[] children = dir.list();
902
        if(children==null)  return 0;
903
        Arrays.sort(children, String.CASE_INSENSITIVE_ORDER);
904 905

        int n = 0;
906
        for (String child : children) {
907 908
            String childPath = path + child;
            String childHref = pathHref + Util.rawEncode(child);
K
kohsuke 已提交
909
            File sub = new File(dir, child);
910
            String length = sub.isFile() ? String.valueOf(sub.length()) : "";
911 912
            boolean collapsed = (children.length==1 && parent!=null);
            Artifact a;
913 914 915
            if (collapsed) {
                // Collapse single items into parent node where possible:
                a = new Artifact(parent.getFileName() + '/' + child, childPath,
S
Stephen Ware 已提交
916 917
                                 sub.isDirectory() ? null : childHref, length,
                                 parent.getTreeNodeId());
918 919 920 921
                r.tree.put(a, r.tree.remove(parent));
            } else {
                // Use null href for a directory:
                a = new Artifact(child, childPath,
S
Stephen Ware 已提交
922 923
                                 sub.isDirectory() ? null : childHref, length,
                                 "n" + ++r.idSeq);
924 925
                r.tree.put(a, parent!=null ? parent.getTreeNodeId() : null);
            }
K
kohsuke 已提交
926
            if (sub.isDirectory()) {
927
                n += addArtifacts(sub, childPath + '/', childHref + '/', r, a, upTo-n);
928
                if (n>=upTo) break;
K
kohsuke 已提交
929
            } else {
930
                // Don't store collapsed path in ArrayList (for correct data in external API)
S
Stephen Ware 已提交
931
                r.add(collapsed ? new Artifact(child, a.relativePath, a.href, length, a.treeNodeId) : a);
M
mindless 已提交
932
                if (++n>=upTo) break;
K
kohsuke 已提交
933
            }
934
        }
935
        return n;
K
kohsuke 已提交
936 937
    }

938 939 940 941 942 943 944 945 946 947 948
    /**
     * Maximum number of artifacts to list before using switching to the tree view.
     */
    public static final int LIST_CUTOFF = Integer.parseInt(System.getProperty("hudson.model.Run.ArtifactList.listCutoff", "16"));

    /**
     * Maximum number of artifacts to show in tree view before just showing a link.
     */
    public static final int TREE_CUTOFF = Integer.parseInt(System.getProperty("hudson.model.Run.ArtifactList.treeCutoff", "40"));

    // ..and then "too many"
K
kohsuke 已提交
949

950
    public final class ArtifactList extends ArrayList<Artifact> {
C
Christoph Kutzinski 已提交
951
        private static final long serialVersionUID = 1L;
952 953 954 955 956 957 958 959 960 961 962
        /**
         * Map of Artifact to treeNodeId of parent node in tree view.
         * Contains Artifact objects for directories and files (the ArrayList contains only files).
         */
        private LinkedHashMap<Artifact,String> tree = new LinkedHashMap<Artifact,String>();
        private int idSeq = 0;

        public Map<Artifact,String> getTree() {
            return tree;
        }

963
        public void computeDisplayName() {
964
            if(size()>LIST_CUTOFF)   return; // we are not going to display file names, so no point in computing this
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

            int maxDepth = 0;
            int[] len = new int[size()];
            String[][] tokens = new String[size()][];
            for( int i=0; i<tokens.length; i++ ) {
                tokens[i] = get(i).relativePath.split("[\\\\/]+");
                maxDepth = Math.max(maxDepth,tokens[i].length);
                len[i] = 1;
            }

            boolean collision;
            int depth=0;
            do {
                collision = false;
                Map<String,Integer/*index*/> names = new HashMap<String,Integer>();
                for (int i = 0; i < tokens.length; i++) {
                    String[] token = tokens[i];
                    String displayName = combineLast(token,len[i]);
                    Integer j = names.put(displayName, i);
                    if(j!=null) {
                        collision = true;
                        if(j>=0)
                            len[j]++;
                        len[i]++;
                        names.put(displayName,-1);  // occupy this name but don't let len[i] incremented with additional collisions
                    }
                }
            } while(collision && depth++<maxDepth);

            for (int i = 0; i < tokens.length; i++)
                get(i).displayPath = combineLast(tokens[i],len[i]);

//            OUTER:
//            for( int n=1; n<maxLen; n++ ) {
//                // if we just display the last n token, would it be suffice for disambiguation?
//                Set<String> names = new HashSet<String>();
//                for (String[] token : tokens) {
//                    if(!names.add(combineLast(token,n)))
//                        continue OUTER; // collision. Increase n and try again
//                }
//
//                // this n successfully diambiguates
//                for (int i = 0; i < tokens.length; i++) {
//                    String[] token = tokens[i];
//                    get(i).displayPath = combineLast(token,n);
//                }
//                return;
//            }

//            // it's impossible to get here, as that means
//            // we have the same artifacts archived twice, but be defensive
//            for (Artifact a : this)
//                a.displayPath = a.relativePath;
        }

        /**
         * Combines last N token into the "a/b/c" form.
         */
        private String combineLast(String[] token, int n) {
K
kohsuke 已提交
1024
            StringBuilder buf = new StringBuilder();
1025 1026 1027 1028 1029 1030 1031 1032
            for( int i=Math.max(0,token.length-n); i<token.length; i++ ) {
                if(buf.length()>0)  buf.append('/');
                buf.append(token[i]);
            }
            return buf.toString();
        }
    }

K
kohsuke 已提交
1033 1034 1035
    /**
     * A build artifact.
     */
1036
    @ExportedBean
K
kohsuke 已提交
1037 1038 1039 1040
    public class Artifact {
        /**
         * Relative path name from {@link Run#getArtifactsDir()}
         */
1041
    	@Exported(visibility=3)
1042
        public final String relativePath;
K
kohsuke 已提交
1043

1044 1045 1046 1047 1048 1049
        /**
         * Truncated form of {@link #relativePath} just enough
         * to disambiguate {@link Artifact}s.
         */
        /*package*/ String displayPath;

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
        /**
         * The filename of the artifact.
         * (though when directories with single items are collapsed for tree view, name may
         *  include multiple path components, like "dist/pkg/mypkg")
         */
        private String name;

        /**
         * Properly encoded relativePath for use in URLs.  This field is null for directories.
         */
1060 1061
        private String href;

1062 1063 1064 1065 1066
        /**
         * Id of this node for use in tree view.
         */
        private String treeNodeId;

S
Stephen Ware 已提交
1067 1068 1069 1070 1071 1072
        /**
         *length of this artifact for files.
         */
        private String length;

        /*package for test*/ Artifact(String name, String relativePath, String href, String len, String treeNodeId) {
1073
            this.name = name;
K
kohsuke 已提交
1074
            this.relativePath = relativePath;
1075
            this.href = href;
1076
            this.treeNodeId = treeNodeId;
S
Stephen Ware 已提交
1077
            this.length = len;
K
kohsuke 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
        }

        /**
         * Gets the artifact file.
         */
        public File getFile() {
            return new File(getArtifactsDir(),relativePath);
        }

        /**
         * Returns just the file name portion, without the path.
         */
1090
    	@Exported(visibility=3)
K
kohsuke 已提交
1091
        public String getFileName() {
1092
            return name;
K
kohsuke 已提交
1093 1094
        }

1095
    	@Exported(visibility=3)
1096 1097 1098 1099
        public String getDisplayPath() {
            return displayPath;
        }

1100 1101 1102 1103
        public String getHref() {
            return href;
        }

S
Stephen Ware 已提交
1104 1105 1106 1107
        public String getLength() {
            return length;
        }

1108 1109 1110 1111
        public String getTreeNodeId() {
            return treeNodeId;
        }

1112
        @Override
K
kohsuke 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
        public String toString() {
            return relativePath;
        }
    }

    /**
     * Returns the log file.
     */
    public File getLogFile() {
        return new File(getRootDir(),"log");
    }

1125
    /**
K
kohsuke 已提交
1126
     * Returns an input stream that reads from the log file.
1127
     * It will use a gzip-compressed log file (log.gz) if that exists.
K
kohsuke 已提交
1128
     *
1129
     * @throws IOException 
K
kohsuke 已提交
1130 1131
     * @return an input stream from the log file, or null if none exists
     * @since 1.349
1132
     */
K
kohsuke 已提交
1133
    public InputStream getLogInputStream() throws IOException {
1134 1135
    	File logFile = getLogFile();
    	if (logFile.exists() ) {
K
kohsuke 已提交
1136 1137
            return new FileInputStream(logFile);
    	}
1138 1139 1140

    	File compressedLogFile = new File(logFile.getParentFile(), logFile.getName()+ ".gz");
    	if (compressedLogFile.exists()) {
K
kohsuke 已提交
1141 1142
            return new GZIPInputStream(new FileInputStream(compressedLogFile));
    	}
1143
    	
K
kohsuke 已提交
1144
    	return new NullInputStream(0);
1145
    }
K
kohsuke 已提交
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

    public Reader getLogReader() throws IOException {
        if (charset==null)  return new InputStreamReader(getLogInputStream());
        else                return new InputStreamReader(getLogInputStream(),charset);
    }

    /**
     * Used from <tt>console.jelly</tt> to write annotated log to the given output.
     *
     * @since 1.349
     */
    public void writeLogTo(long offset, XMLOutput out) throws IOException {
T
Tom Huybrechts 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
        try {
			getLogText().writeHtmlTo(offset,out.asWriter());
		} catch (IOException e) {
			// try to fall back to the old getLogInputStream()
			// mainly to support .gz compressed files
			// In this case, console annotation handling will be turned off.
			InputStream input = getLogInputStream();
			try {
				IOUtils.copy(input, out.asWriter());
			} finally {
				IOUtils.closeQuietly(input);
			}
		}
K
kohsuke 已提交
1171 1172
    }

1173 1174 1175 1176
    /**
     * Used to URL-bind {@link AnnotatedLargeText}.
     */
    public AnnotatedLargeText getLogText() {
K
kohsuke 已提交
1177 1178 1179
        return new AnnotatedLargeText(getLogFile(),getCharset(),!isLogUpdated(),this);
    }

1180
    @Override
1181
    protected SearchIndexBuilder makeSearchIndex() {
1182 1183 1184 1185 1186 1187 1188 1189
        SearchIndexBuilder builder = super.makeSearchIndex()
                .add("console")
                .add("changes");
        for (Action a : getActions()) {
            if(a.getIconFileName()!=null)
                builder.add(a.getUrlName());
        }
        return builder;
1190 1191
    }

1192
    public Api getApi() {
1193 1194 1195
        return new Api(this);
    }

1196
    public void checkPermission(Permission p) {
1197 1198 1199
        getACL().checkPermission(p);
    }

1200 1201 1202 1203
    public boolean hasPermission(Permission p) {
        return getACL().hasPermission(p);
    }

1204
    public ACL getACL() {
1205
        // for now, don't maintain ACL per run, and do it at project level
1206
        return getParent().getACL();
1207 1208
    }

1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    /**
     * Deletes this build's artifacts. 
     *
     * @throws IOException
     *      if we fail to delete.
     *
     * @since 1.350
     */
    public synchronized void deleteArtifacts() throws IOException {
        File artifactsDir = getArtifactsDir();

        Util.deleteContentsRecursive(artifactsDir);
    }

K
kohsuke 已提交
1223 1224 1225 1226 1227 1228 1229
    /**
     * Deletes this build and its entire log
     *
     * @throws IOException
     *      if we fail to delete.
     */
    public synchronized void delete() throws IOException {
1230 1231
        RunListener.fireDeleted(this);

1232 1233 1234 1235
        // if we have a symlink, delete it, too
        File link = new File(project.getBuildDir(), String.valueOf(getNumber()));
        link.delete();

K
kohsuke 已提交
1236 1237
        File rootDir = getRootDir();
        File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName());
1238 1239 1240
        
        boolean renamingSucceeded = rootDir.renameTo(tmp);
        Util.deleteRecursive(tmp);
1241 1242 1243 1244
        // some user reported that they see some left-over .xyz files in the workspace,
        // so just to make sure we've really deleted it, schedule the deletion on VM exit, too.
        if(tmp.exists())
            tmp.deleteOnExit();
K
kohsuke 已提交
1245

1246
        if(!renamingSucceeded)
K
kohsuke 已提交
1247 1248
            throw new IOException(rootDir+" is in use");

J
jglick 已提交
1249 1250
        removeRunFromParent();
    }
1251

J
jglick 已提交
1252 1253
    @SuppressWarnings("unchecked") // seems this is too clever for Java's type system?
    private void removeRunFromParent() {
K
kohsuke 已提交
1254 1255 1256
        getParent().removeRun((RunT)this);
    }

K
kohsuke 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327

    /**
     * @see CheckPoint#report()
     */
    /*package*/ static void reportCheckpoint(CheckPoint id) {
        RunnerStack.INSTANCE.peek().checkpoints.report(id);
    }

    /**
     * @see CheckPoint#block()
     */
    /*package*/ static void waitForCheckpoint(CheckPoint id) throws InterruptedException {
        while(true) {
            Run b = RunnerStack.INSTANCE.peek().getBuild().getPreviousBuildInProgress();
            if(b==null)     return; // no pending earlier build
            Run.Runner runner = b.runner;
            if(runner==null) {
                // polled at the wrong moment. try again.
                Thread.sleep(0);
                continue;
            }
            if(runner.checkpoints.waitForCheckPoint(id))
                return; // confirmed that the previous build reached the check point

            // the previous build finished without ever reaching the check point. try again.
        }
    }

    protected abstract class Runner {
        /**
         * Keeps track of the check points attained by a build, and abstracts away the synchronization needed to 
         * maintain this data structure.
         */
        private final class CheckpointSet {
            /**
             * Stages of the builds that this runner has completed. This is used for concurrent {@link Runner}s to
             * coordinate and serialize their executions where necessary.
             */
            private final Set<CheckPoint> checkpoints = new HashSet<CheckPoint>();

            private boolean allDone;

            protected synchronized void report(CheckPoint identifier) {
                checkpoints.add(identifier);
                notifyAll();
            }

            protected synchronized boolean waitForCheckPoint(CheckPoint identifier) throws InterruptedException {
                final Thread t = Thread.currentThread();
                final String oldName = t.getName();
                t.setName(oldName+" : waiting for "+identifier+" on "+getFullDisplayName());
                try {
                    while(!allDone && !checkpoints.contains(identifier))
                        wait();
                    return checkpoints.contains(identifier);
                } finally {
                    t.setName(oldName);
                }
            }

            /**
             * Notifies that the build is fully completed and all the checkpoint locks be released.
             */
            private synchronized void allDone() {
                allDone = true;
                notifyAll();
            }
        }

        private final CheckpointSet checkpoints = new CheckpointSet();

1328 1329 1330 1331 1332 1333
        /**
         * Performs the main build and returns the status code.
         *
         * @throws Exception
         *      exception will be recorded and the build will be considered a failure.
         */
K
kohsuke 已提交
1334
        public abstract Result run( BuildListener listener ) throws Exception, RunnerAbortedException;
K
kohsuke 已提交
1335

1336 1337
        /**
         * Performs the post-build action.
1338
         * <p>
1339
         * This method is called after {@linkplain #run(BuildListener) the main portion of the build is completed.}
K
kohsuke 已提交
1340 1341 1342 1343
         * This is a good opportunity to do notifications based on the result
         * of the build. When this method is called, the build is not really
         * finalized yet, and the build is still considered in progress --- for example,
         * even if the build is successful, this build still won't be picked up
1344
         * by {@link Job#getLastSuccessfulBuild()}.
1345
         */
K
kohsuke 已提交
1346
        public abstract void post( BuildListener listener ) throws Exception;
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357

        /**
         * Performs final clean up action.
         * <p>
         * This method is called after {@link #post(BuildListener)},
         * after the build result is fully finalized. This is the point
         * where the build is already considered completed.
         * <p>
         * Among other things, this is often a necessary pre-condition
         * before invoking other builds that depend on this build.
         */
K
kohsuke 已提交
1358 1359 1360 1361 1362
        public abstract void cleanUp(BuildListener listener) throws Exception;

        protected final RunT getBuild() {
            return _this();
        }
K
kohsuke 已提交
1363 1364
    }

1365 1366 1367 1368 1369
    /**
     * Used in {@link Runner#run} to indicates that a fatal error in a build
     * is reported to {@link BuildListener} and the build should be simply aborted
     * without further recording a stack trace.
     */
C
Christoph Kutzinski 已提交
1370 1371 1372
    public static final class RunnerAbortedException extends RuntimeException {
        private static final long serialVersionUID = 1L;
    }
1373

K
kohsuke 已提交
1374 1375 1376 1377
    protected final void run(Runner job) {
        if(result!=null)
            return;     // already built.

K
kohsuke 已提交
1378
        StreamBuildListener listener=null;
1379

K
kohsuke 已提交
1380
        runner = job;
K
kohsuke 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389
        onStartBuilding();
        try {
            // to set the state to COMPLETE in the end, even if the thread dies abnormally.
            // otherwise the queue state becomes inconsistent

            long start = System.currentTimeMillis();

            try {
                try {
1390 1391
                    Charset charset = Computer.currentComputer().getDefaultCharset();
                    this.charset = charset.name();
1392 1393 1394 1395 1396 1397

                    // don't do buffering so that what's written to the listener
                    // gets reflected to the file immediately, which can then be
                    // served to the browser immediately
                    OutputStream logger = new FileOutputStream(getLogFile());
                    RunT build = job.getBuild();
1398 1399 1400 1401 1402 1403

                    // Global log filters
                    for (ConsoleLogFilter filter : ConsoleLogFilter.all()) {
                        logger = filter.decorateLogger((AbstractBuild) build, logger);
                    }

C
Christoph Kutzinski 已提交
1404
                    // Project specific log filters
1405 1406 1407 1408 1409 1410 1411 1412
                    if (project instanceof BuildableItemWithBuildWrappers && build instanceof AbstractBuild) {
                        BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project;
                        for (BuildWrapper bw : biwbw.getBuildWrappersList()) {
                            logger = bw.decorateLogger((AbstractBuild) build, logger);
                        }
                    }

                    listener = new StreamBuildListener(logger,charset);
K
kohsuke 已提交
1413

K
kohsuke 已提交
1414
                    listener.started(getCauses());
K
kohsuke 已提交
1415

K
kohsuke 已提交
1416 1417
                    RunListener.fireStarted(this,listener);

1418 1419 1420
                    // create a symlink from build number to ID.
                    Util.createSymlink(getParent().getBuildDir(),getId(),String.valueOf(getNumber()),listener);

K
kohsuke 已提交
1421
                    setResult(job.run(listener));
K
kohsuke 已提交
1422 1423

                    LOGGER.info(toString()+" main build action completed: "+result);
K
kohsuke 已提交
1424
                    CheckPoint.MAIN_COMPLETED.report();
K
kohsuke 已提交
1425 1426
                } catch (ThreadDeath t) {
                    throw t;
1427
                } catch( AbortException e ) {// orderly abortion.
1428
                    result = Result.FAILURE;
1429
                    listener.error(e.getMessage());
1430
                    LOGGER.log(FINE, "Build "+this+" aborted",e);
K
kohsuke 已提交
1431
                } catch( RunnerAbortedException e ) {// orderly abortion.
1432
                    result = Result.FAILURE;
1433
                    LOGGER.log(FINE, "Build "+this+" aborted",e);
1434 1435
                } catch( InterruptedException e) {
                    // aborted
1436
                    result = Executor.currentExecutor().abortResult();
K
i18n  
kohsuke 已提交
1437
                    listener.getLogger().println(Messages.Run_BuildAborted());
1438
                    Executor.currentExecutor().recordCauseOfInterruption(Run.this,listener);
1439
                    LOGGER.log(Level.INFO,toString()+" aborted",e);
K
kohsuke 已提交
1440 1441 1442 1443 1444
                } catch( Throwable e ) {
                    handleFatalBuildProblem(listener,e);
                    result = Result.FAILURE;
                }

K
kohsuke 已提交
1445
                // even if the main build fails fatally, try to run post build processing
K
kohsuke 已提交
1446 1447 1448 1449 1450 1451 1452
                job.post(listener);

            } catch (ThreadDeath t) {
                throw t;
            } catch( Throwable e ) {
                handleFatalBuildProblem(listener,e);
                result = Result.FAILURE;
K
kohsuke 已提交
1453
            } finally {
1454
                long end = System.currentTimeMillis();
1455
                duration = Math.max(end - start, 0);  // @see HUDSON-5844
1456

1457
                // advance the state.
1458
                // the significance of doing this is that Jenkins
1459 1460 1461
                // will now see this build as completed.
                // things like triggering other builds requires this as pre-condition.
                // see issue #980.
1462
                state = State.POST_PRODUCTION;
1463 1464 1465 1466 1467 1468 1469

                try {
                    job.cleanUp(listener);
                } catch (Exception e) {
                    handleFatalBuildProblem(listener,e);
                    // too late to update the result now
                }
K
kohsuke 已提交
1470

1471
                RunListener.fireCompleted(this,listener);
K
kohsuke 已提交
1472

1473 1474
                if(listener!=null)
                    listener.finished(result);
K
kohsuke 已提交
1475 1476
                if(listener!=null)
                    listener.closeQuietly();
K
kohsuke 已提交
1477

1478 1479 1480
                try {
                    save();
                } catch (IOException e) {
K
kohsuke 已提交
1481
                    LOGGER.log(Level.SEVERE, "Failed to save build record",e);
1482
                }
K
kohsuke 已提交
1483 1484 1485
            }

            try {
1486
                getParent().logRotate();
K
kohsuke 已提交
1487
            } catch (IOException e) {
K
kohsuke 已提交
1488
                LOGGER.log(Level.SEVERE, "Failed to rotate log",e);
1489 1490
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to rotate log",e);
K
kohsuke 已提交
1491 1492 1493 1494 1495 1496 1497
            }
        } finally {
            onEndBuilding();
        }
    }

    /**
K
kohsuke 已提交
1498
     * Handles a fatal build problem (exception) that occurred during the build.
K
kohsuke 已提交
1499 1500 1501
     */
    private void handleFatalBuildProblem(BuildListener listener, Throwable e) {
        if(listener!=null) {
1502 1503
            LOGGER.log(FINE, getDisplayName()+" failed to build",e);

K
kohsuke 已提交
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
            if(e instanceof IOException)
                Util.displayIOException((IOException)e,listener);

            Writer w = listener.fatalError(e.getMessage());
            if(w!=null) {
                try {
                    e.printStackTrace(new PrintWriter(w));
                    w.close();
                } catch (IOException e1) {
                    // ignore
                }
            }
1516 1517
        } else {
            LOGGER.log(SEVERE, getDisplayName()+" failed to build and we don't even have a listener",e);
K
kohsuke 已提交
1518 1519 1520 1521 1522 1523 1524 1525
        }
    }

    /**
     * Called when a job started building.
     */
    protected void onStartBuilding() {
        state = State.BUILDING;
K
kohsuke 已提交
1526 1527
        if (runner!=null)
            RunnerStack.INSTANCE.push(runner);
K
kohsuke 已提交
1528 1529 1530 1531 1532 1533
    }

    /**
     * Called when a job finished building normally or abnormally.
     */
    protected void onEndBuilding() {
K
kohsuke 已提交
1534 1535 1536 1537 1538
        // signal that we've finished building.
        if (runner!=null) {
            // MavenBuilds may be created without their corresponding runners.
            state = State.COMPLETED;
            runner.checkpoints.allDone();
K
kohsuke 已提交
1539 1540
            runner = null;
            RunnerStack.INSTANCE.pop();
K
kohsuke 已提交
1541 1542 1543
        } else {
            state = State.COMPLETED;
        }
K
kohsuke 已提交
1544 1545 1546
        if (result == null) {
            result = Result.FAILURE;
            LOGGER.warning(toString() + ": No build result is set, so marking as failure. This shouldn't happen.");
1547 1548
        }

1549
        RunListener.fireFinalized(this);
K
kohsuke 已提交
1550 1551 1552 1553 1554 1555
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
1556
        if(BulkChange.contains(this))   return;
K
kohsuke 已提交
1557
        getDataFile().write(this);
1558
        SaveableListener.fireOnChange(this, getDataFile());
K
kohsuke 已提交
1559 1560 1561 1562 1563 1564 1565 1566 1567
    }

    private XmlFile getDataFile() {
        return new XmlFile(XSTREAM,new File(getRootDir(),"build.xml"));
    }

    /**
     * Gets the log of the build as a string.
     *
M
mindless 已提交
1568 1569 1570
     * @deprecated since 2007-11-11.
     *     Use {@link #getLog(int)} instead as it avoids loading
     *     the whole log into memory unnecessarily.
K
kohsuke 已提交
1571
     */
1572
    @Deprecated
K
kohsuke 已提交
1573
    public String getLog() throws IOException {
1574
        return Util.loadFile(getLogFile(),getCharset());
K
kohsuke 已提交
1575 1576
    }

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
    /**
     * Gets the log of the build as a list of strings (one per log line).
     * The number of lines returned is constrained by the maxLines parameter.
     *
     * @param maxLines The maximum number of log lines to return.  If the log
     * is bigger than this, only the most recent lines are returned.
     * @return A list of log lines.  Will have no more than maxLines elements.
     * @throws IOException If there is a problem reading the log file.
     */
    public List<String> getLog(int maxLines) throws IOException {
        int lineCount = 0;
        List<String> logLines = new LinkedList<String>();
1589
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getLogFile()),getCharset()));
K
kohsuke 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
        try {
            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                logLines.add(line);
                ++lineCount;
                // If we have too many lines, remove the oldest line.  This way we
                // never have to hold the full contents of a huge log file in memory.
                // Adding to and removing from the ends of a linked list are cheap
                // operations.
                if (lineCount > maxLines)
                    logLines.remove(0);
            }
        } finally {
            reader.close();
1603 1604 1605 1606 1607 1608 1609 1610
        }

        // If the log has been truncated, include that information.
        // Use set (replaces the first element) rather than add so that
        // the list doesn't grow beyond the specified maximum number of lines.
        if (lineCount > maxLines)
            logLines.set(0, "[...truncated " + (lineCount - (maxLines - 1)) + " lines...]");

1611
        return ConsoleNote.removeNotes(logLines);
1612 1613
    }

K
kohsuke 已提交
1614
    public void doBuildStatus( StaplerRequest req, StaplerResponse rsp ) throws IOException {
1615
        rsp.sendRedirect2(req.getContextPath()+"/images/48x48/"+getBuildStatusUrl());
K
kohsuke 已提交
1616 1617 1618
    }

    public String getBuildStatusUrl() {
1619
        return getIconColor().getImage();
K
kohsuke 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
    }

    public static class Summary {
        /**
         * Is this build worse or better, compared to the previous build?
         */
        public boolean isWorse;
        public String message;

        public Summary(boolean worse, String message) {
            this.isWorse = worse;
            this.message = message;
        }
    }

    /**
K
Kohsuke Kawaguchi 已提交
1636 1637
     * Gets an object which represents the single line summary of the status of this build
     * (especially in comparison with the previous build.)
K
kohsuke 已提交
1638 1639
     */
    public Summary getBuildStatusSummary() {
1640 1641 1642 1643
        if (isBuilding()) {
            return new Summary(false, Messages.Run_Summary_Unknown());
        }
        
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
        ResultTrend trend = ResultTrend.getResultTrend(this);
        
        switch (trend) {
            case ABORTED : return new Summary(false, Messages.Run_Summary_Aborted());
            
            case NOT_BUILT : return new Summary(false, Messages.Run_Summary_NotBuilt());
            
            case FAILURE : return new Summary(true, Messages.Run_Summary_BrokenSinceThisBuild());
            
            case STILL_FAILING : 
                RunT since = getPreviousNotFailedBuild();
                if(since==null)
                    return new Summary(false, Messages.Run_Summary_BrokenForALongTime());
                RunT failedBuild = since.getNextBuild();
                return new Summary(false, Messages.Run_Summary_BrokenSince(failedBuild.getDisplayName()));
           
            case NOW_UNSTABLE:
                return determineDetailedUnstableSummary(Boolean.FALSE);
            case UNSTABLE :
                return determineDetailedUnstableSummary(Boolean.TRUE);
            case STILL_UNSTABLE :
                return determineDetailedUnstableSummary(null);
                
            case SUCCESS :
1668
                return new Summary(false, Messages.Run_Summary_Stable());
1669 1670
            
            case FIXED :
1671
                return new Summary(false, Messages.Run_Summary_BackToNormal());
1672
                
K
kohsuke 已提交
1673
        }
1674 1675 1676
        
        return new Summary(false, Messages.Run_Summary_Unknown());
    }
K
kohsuke 已提交
1677

1678 1679 1680 1681 1682 1683 1684
    /**
     * @param worseOverride override the 'worse' parameter to this value.
     *   May be null in which case 'worse' is calculated based on the number of failed tests.
     */
    private Summary determineDetailedUnstableSummary(Boolean worseOverride) {
        if(((Run)this) instanceof AbstractBuild) {
            AbstractTestResultAction trN = ((AbstractBuild)(Run)this).getTestResultAction();
C
Christoph Kutzinski 已提交
1685
            Run prev = getPreviousBuild();
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
            AbstractTestResultAction trP = prev==null ? null : ((AbstractBuild) prev).getTestResultAction();
            if(trP==null) {
                if(trN!=null && trN.getFailCount()>0)
                    return new Summary(worseOverride != null ? worseOverride : true,
                            Messages.Run_Summary_TestFailures(trN.getFailCount()));
            } else {
                if(trN.getFailCount()!= 0) {
                    if(trP.getFailCount()==0)
                        return new Summary(worseOverride != null ? worseOverride : true,
                                Messages.Run_Summary_TestsStartedToFail(trN.getFailCount()));
                    if(trP.getFailCount() < trN.getFailCount())
                        return new Summary(worseOverride != null ? worseOverride : true,
                                Messages.Run_Summary_MoreTestsFailing(trN.getFailCount()-trP.getFailCount(), trN.getFailCount()));
                    if(trP.getFailCount() > trN.getFailCount())
                        return new Summary(worseOverride != null ? worseOverride : false,
                                Messages.Run_Summary_LessTestsFailing(trP.getFailCount()-trN.getFailCount(), trN.getFailCount()));
                    
                    return new Summary(worseOverride != null ? worseOverride : false,
                            Messages.Run_Summary_TestsStillFailing(trN.getFailCount()));
K
kohsuke 已提交
1705 1706 1707
                }
            }
        }
1708 1709 1710
        
        return new Summary(worseOverride != null ? worseOverride : false,
                Messages.Run_Summary_Unstable());
K
kohsuke 已提交
1711 1712 1713 1714 1715
    }

    /**
     * Serves the artifacts.
     */
1716
    public DirectoryBrowserSupport doArtifact() {
R
rseguy 已提交
1717 1718 1719
        if(Functions.isArtifactsPermissionEnabled()) {
          checkPermission(ARTIFACTS);
        }
1720
        return new DirectoryBrowserSupport(this,new FilePath(getArtifactsDir()), project.getDisplayName()+' '+getDisplayName(), "package.png", true);
K
kohsuke 已提交
1721 1722 1723 1724 1725
    }

    /**
     * Returns the build number in the body.
     */
1726
    public void doBuildNumber(StaplerResponse rsp) throws IOException {
K
kohsuke 已提交
1727 1728 1729 1730 1731 1732
        rsp.setContentType("text/plain");
        rsp.setCharacterEncoding("US-ASCII");
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.getWriter().print(number);
    }

K
kohsuke 已提交
1733 1734 1735
    /**
     * Returns the build time stamp in the body.
     */
1736
    public void doBuildTimestamp( StaplerRequest req, StaplerResponse rsp, @QueryParameter String format) throws IOException {
K
kohsuke 已提交
1737 1738 1739
        rsp.setContentType("text/plain");
        rsp.setCharacterEncoding("US-ASCII");
        rsp.setStatus(HttpServletResponse.SC_OK);
K
kohsuke 已提交
1740 1741 1742
        DateFormat df = format==null ?
                DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.ENGLISH) :
                new SimpleDateFormat(format,req.getLocale());
K
kohsuke 已提交
1743
        rsp.getWriter().print(df.format(getTime()));
K
kohsuke 已提交
1744 1745
    }

1746 1747 1748 1749 1750
    /**
     * Sends out the raw console output.
     */
    public void doConsoleText(StaplerRequest req, StaplerResponse rsp) throws IOException {
        rsp.setContentType("text/plain;charset=UTF-8");
1751
        // Prevent jelly from flushing stream so Content-Length header can be added afterwards
K
kohsuke 已提交
1752
        FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req));
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
        try{
        	getLogText().writeLogTo(0,out);
        } catch (IOException e) {
			// see comment in writeLogTo() method
			InputStream input = getLogInputStream();
			try {
				IOUtils.copy(input, out);
			} finally {
				IOUtils.closeQuietly(input);
			}
		}
1764
        out.close();
1765 1766
    }

K
kohsuke 已提交
1767 1768
    /**
     * Handles incremental log output.
1769 1770
     * @deprecated as of 1.352
     *      Use {@code getLogText().doProgressiveText(req,rsp)}
K
kohsuke 已提交
1771 1772
     */
    public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
1773
        getLogText().doProgressText(req,rsp);
K
kohsuke 已提交
1774 1775 1776
    }

    public void doToggleLogKeep( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
K
kohsuke 已提交
1777
        keepLog(!keepLog);
K
kohsuke 已提交
1778 1779
        rsp.forwardToPreviousPage(req);
    }
K
kohsuke 已提交
1780 1781 1782 1783

    /**
     * Marks this build to keep the log.
     */
1784
    @CLIMethod(name="keep-build")
K
kohsuke 已提交
1785 1786 1787 1788 1789
    public final void keepLog() throws IOException {
        keepLog(true);
    }

    public void keepLog(boolean newValue) throws IOException {
1790
        checkPermission(UPDATE);
K
kohsuke 已提交
1791
        keepLog = newValue;
K
kohsuke 已提交
1792 1793
        save();
    }
K
kohsuke 已提交
1794

1795 1796 1797
    /**
     * Deletes the build when the button is pressed.
     */
1798
    @RequirePOST
1799
    public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1800 1801
        checkPermission(DELETE);

1802 1803 1804
        // We should not simply delete the build if it has been explicitly
        // marked to be preserved, or if the build should not be deleted
        // due to dependencies!
1805 1806
        String why = getWhyKeepLog();
        if (why!=null) {
K
i18n  
kohsuke 已提交
1807
            sendError(Messages.Run_UnableToDelete(toString(),why),req,rsp);
1808 1809 1810 1811 1812 1813
            return;
        }

        delete();
        rsp.sendRedirect2(req.getContextPath()+'/' + getParent().getUrl());
    }
K
kohsuke 已提交
1814

K
kohsuke 已提交
1815
    public void setDescription(String description) throws IOException {
1816 1817
        checkPermission(UPDATE);
        this.description = description;
K
kohsuke 已提交
1818
        save();
1819 1820
    }
    
K
kohsuke 已提交
1821 1822 1823 1824
    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1825
        setDescription(req.getParameter("description"));
K
kohsuke 已提交
1826 1827 1828 1829
        rsp.sendRedirect(".");  // go to the top page
    }

    /**
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
     * @deprecated as of 1.292
     *      Use {@link #getEnvironment()} instead.
     */
    public Map<String,String> getEnvVars() {
        try {
            return getEnvironment();
        } catch (IOException e) {
            return new EnvVars();
        } catch (InterruptedException e) {
            return new EnvVars();
        }
    }

K
kohsuke 已提交
1843
    /**
1844
     * @deprecated as of 1.305 use {@link #getEnvironment(TaskListener)}
K
kohsuke 已提交
1845 1846 1847 1848 1849
     */
    public EnvVars getEnvironment() throws IOException, InterruptedException {
        return getEnvironment(new LogTaskListener(LOGGER, Level.INFO));
    }

1850 1851 1852
    /**
     * Returns the map that contains environmental variables to be used for launching
     * processes for this build.
K
kohsuke 已提交
1853
     *
1854
     * <p>
K
kohsuke 已提交
1855 1856 1857 1858
     * {@link BuildStep}s that invoke external processes should use this.
     * This allows {@link BuildWrapper}s and other project configurations (such as JDK selection)
     * to take effect.
     *
1859
     * <p>
1860 1861
     * Unlike earlier {@link #getEnvVars()}, this map contains the whole environment,
     * not just the overrides, so one can introspect values to change its behavior.
1862 1863
     * 
     * @return the map with the environmental variables. Never <code>null</code>.
1864
     * @since 1.305
K
kohsuke 已提交
1865
     */
K
kohsuke 已提交
1866
    public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException {
K
kohsuke 已提交
1867 1868 1869 1870
        EnvVars env = getCharacteristicEnvVars();
        Computer c = Computer.currentComputer();
        if (c!=null)
            env = c.getEnvironment().overrideAll(env);
1871
        String rootUrl = Jenkins.getInstance().getRootUrl();
1872
        if(rootUrl!=null) {
1873 1874
            env.put("JENKINS_URL", rootUrl);
            env.put("HUDSON_URL", rootUrl); // Legacy compatibility
1875 1876 1877
            env.put("BUILD_URL", rootUrl+getUrl());
            env.put("JOB_URL", rootUrl+getParent().getUrl());
        }
1878
        
1879 1880
        env.put("JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath() );
        env.put("HUDSON_HOME", Jenkins.getInstance().getRootDir().getPath() );   // legacy compatibility
K
kohsuke 已提交
1881 1882 1883 1884 1885

        Thread t = Thread.currentThread();
        if (t instanceof Executor) {
            Executor e = (Executor) t;
            env.put("EXECUTOR_NUMBER",String.valueOf(e.getNumber()));
1886 1887 1888 1889 1890
	    if(e.getOwner() instanceof MasterComputer) {
		env.put("NODE_NAME", "master");
	    } else {
	    	env.put("NODE_NAME",e.getOwner().getName());
	    }
K
kohsuke 已提交
1891 1892 1893
            Node n = e.getOwner().getNode();
            if (n!=null)
                env.put("NODE_LABELS",Util.join(n.getAssignedLabels()," "));
K
kohsuke 已提交
1894 1895
        }

1896 1897 1898
        for (EnvironmentContributor ec : EnvironmentContributor.all())
            ec.buildEnvironmentFor(this,env,log);

K
kohsuke 已提交
1899 1900 1901
        return env;
    }

1902 1903
    /**
     * Builds up the environment variable map that's sufficient to identify a process
1904
     * as ours. This is used to kill run-away processes via {@link ProcessTree#killAll(Map)}.
1905
     */
1906
    public final EnvVars getCharacteristicEnvVars() {
1907
        EnvVars env = new EnvVars();
1908 1909
        env.put("JENKINS_SERVER_COOKIE",Util.getDigestOf("ServerID:"+ Jenkins.getInstance().getSecretKey()));
        env.put("HUDSON_SERVER_COOKIE",Util.getDigestOf("ServerID:"+ Jenkins.getInstance().getSecretKey())); // Legacy compatibility
1910 1911
        env.put("BUILD_NUMBER",String.valueOf(number));
        env.put("BUILD_ID",getId());
1912
        env.put("BUILD_TAG","jenkins-"+getParent().getFullName().replace('/', '-')+"-"+number);
1913 1914 1915 1916
        env.put("JOB_NAME",getParent().getFullName());
        return env;
    }

H
huybrechts 已提交
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
    public String getExternalizableId() {
        return project.getName() + "#" + getNumber();
    }

    public static Run<?,?> fromExternalizableId(String id) {
        int hash = id.lastIndexOf('#');
        if (hash <= 0) {
            throw new IllegalArgumentException("Invalid id");
        }
        String jobName = id.substring(0, hash);
        int number = Integer.parseInt(id.substring(hash + 1));

1929
        Job<?,?> job = (Job<?,?>) Jenkins.getInstance().getItem(jobName);
H
huybrechts 已提交
1930 1931 1932
        return job.getBuildByNumber(number);
    }

1933 1934 1935 1936 1937 1938 1939 1940
    /**
     * Returns the estimated duration for this run if it is currently running.
     * Default to {@link Job#getEstimatedDuration()}, may be overridden in subclasses
     * if duration may depend on run specific parameters (like incremental Maven builds).
     * 
     * @return the estimated duration in milliseconds
     * @since 1.383
     */
1941
    @Exported
1942 1943 1944
    public long getEstimatedDuration() {
        return project.getEstimatedDuration();
    }
H
huybrechts 已提交
1945

1946
    @RequirePOST
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
    public HttpResponse doConfigSubmit( StaplerRequest req ) throws IOException, ServletException, FormException {
        checkPermission(UPDATE);
        BulkChange bc = new BulkChange(this);
        try {
            JSONObject json = req.getSubmittedForm();
            submit(json);
            bc.commit();
        } finally {
            bc.abort();
        }
        return HttpResponses.redirectToDot();
    }

    protected void submit(JSONObject json) throws IOException {
1961
        setDisplayName(Util.fixEmptyAndTrim(json.getString("displayName")));
1962 1963 1964
        setDescription(json.getString("description"));
    }

H
huybrechts 已提交
1965
    public static final XStream XSTREAM = new XStream2();
1966 1967 1968 1969 1970 1971

    /**
     * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
     */
    public static final XStream2 XSTREAM2 = (XStream2)XSTREAM;

K
kohsuke 已提交
1972
    static {
1973 1974 1975
        XSTREAM.alias("build",FreeStyleBuild.class);
        XSTREAM.alias("matrix-build",MatrixBuild.class);
        XSTREAM.alias("matrix-run",MatrixRun.class);
K
kohsuke 已提交
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
        XSTREAM.registerConverter(Result.conv);
    }

    private static final Logger LOGGER = Logger.getLogger(Run.class.getName());

    /**
     * Sort by date. Newer ones first. 
     */
    public static final Comparator<Run> ORDER_BY_DATE = new Comparator<Run>() {
        public int compare(Run lhs, Run rhs) {
K
kohsuke 已提交
1986 1987
            long lt = lhs.getTimeInMillis();
            long rt = rhs.getTimeInMillis();
K
kohsuke 已提交
1988 1989 1990
            if(lt>rt)   return -1;
            if(lt<rt)   return 1;
            return 0;
K
kohsuke 已提交
1991 1992 1993 1994 1995 1996
        }
    };

    /**
     * {@link FeedAdapter} to produce feed from the summary of this build.
     */
K
kohsuke 已提交
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
    public static final FeedAdapter<Run> FEED_ADAPTER = new DefaultFeedAdapter();

    /**
     * {@link FeedAdapter} to produce feeds to show one build per project.
     */
    public static final FeedAdapter<Run> FEED_ADAPTER_LATEST = new DefaultFeedAdapter() {
        /**
         * The entry unique ID needs to be tied to a project, so that
         * new builds will replace the old result.
         */
2007
        @Override
K
kohsuke 已提交
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
        public String getEntryID(Run e) {
            // can't use a meaningful year field unless we remember when the job was created.
            return "tag:hudson.dev.java.net,2008:"+e.getParent().getAbsoluteUrl();
        }
    };

    /**
     * {@link BuildBadgeAction} that shows the logs are being kept.
     */
    public final class KeepLogBuildBadge implements BuildBadgeAction {
        public String getIconFileName() { return null; }
        public String getDisplayName() { return null; }
        public String getUrlName() { return null; }
        public String getWhyKeepLog() { return Run.this.getWhyKeepLog(); }
    }

    public static final PermissionGroup PERMISSIONS = new PermissionGroup(Run.class,Messages._Run_Permissions_Title());
2025 2026
    public static final Permission DELETE = new Permission(PERMISSIONS,"Delete",Messages._Run_DeletePermission_Description(),Permission.DELETE, PermissionScope.RUN);
    public static final Permission UPDATE = new Permission(PERMISSIONS,"Update",Messages._Run_UpdatePermission_Description(),Permission.UPDATE, PermissionScope.RUN);
R
rseguy 已提交
2027 2028
    /** See {@link hudson.Functions#isArtifactsPermissionEnabled} */
    public static final Permission ARTIFACTS = new Permission(PERMISSIONS,"Artifacts",Messages._Run_ArtifactsPermission_Description(), null,
2029
                                                              Functions.isArtifactsPermissionEnabled(), new PermissionScope[]{PermissionScope.RUN});
K
kohsuke 已提交
2030 2031

    private static class DefaultFeedAdapter implements FeedAdapter<Run> {
K
kohsuke 已提交
2032
        public String getEntryTitle(Run entry) {
2033
            return entry+" ("+entry.getBuildStatusSummary().message+")";
K
kohsuke 已提交
2034 2035 2036 2037 2038 2039 2040
        }

        public String getEntryUrl(Run entry) {
            return entry.getUrl();
        }

        public String getEntryID(Run entry) {
2041 2042 2043
            return "tag:" + "hudson.dev.java.net,"
                + entry.getTimestamp().get(Calendar.YEAR) + ":"
                + entry.getParent().getName()+':'+entry.getId();
K
kohsuke 已提交
2044 2045
        }

2046
        public String getEntryDescription(Run entry) {
2047
            return entry.getDescription();
2048 2049
        }

K
kohsuke 已提交
2050 2051 2052
        public Calendar getEntryTimestamp(Run entry) {
            return entry.getTimestamp();
        }
2053 2054

        public String getEntryAuthor(Run entry) {
2055
            return Mailer.descriptor().getAdminAddress();
2056
        }
2057
    }
2058 2059 2060 2061 2062 2063 2064

    @Override
    public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
        Object result = super.getDynamic(token, req, rsp);
        if (result == null)
            // Next/Previous Build links on an action page (like /job/Abc/123/testReport)
            // will also point to same action (/job/Abc/124/testReport), but other builds
M
mindless 已提交
2065
            // may not have the action.. tell browsers to redirect up to the build page.
2066 2067 2068 2069 2070
            result = new RedirectUp();
        return result;
    }

    public static class RedirectUp {
K
kohsuke 已提交
2071
        public void doDynamic(StaplerResponse rsp) throws IOException {
M
mindless 已提交
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
            // Compromise to handle both browsers (auto-redirect) and programmatic access
            // (want accurate 404 response).. send 404 with javscript to redirect browsers.
            rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            rsp.setContentType("text/html;charset=UTF-8");
            PrintWriter out = rsp.getWriter();
            out.println("<html><head>" +
                "<meta http-equiv='refresh' content='1;url=..'/>" +
                "<script>window.location.replace('..');</script>" +
                "</head>" +
                "<body style='background-color:white; color:white;'>" +
                "Not found</body></html>");
            out.flush();
2084 2085
        }
    }
2086
}