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

26 27
import hudson.AbortException;
import hudson.BulkChange;
K
kohsuke 已提交
28
import hudson.CloseProofOutputStream;
K
kohsuke 已提交
29
import hudson.EnvVars;
K
kohsuke 已提交
30
import hudson.ExtensionPoint;
K
kohsuke 已提交
31
import hudson.FeedAdapter;
32
import hudson.FilePath;
K
kohsuke 已提交
33 34
import hudson.Util;
import hudson.XmlFile;
35
import hudson.cli.declarative.CLIMethod;
36 37
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixRun;
38
import hudson.model.listeners.RunListener;
K
kohsuke 已提交
39
import hudson.search.SearchIndexBuilder;
40 41 42 43 44
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.tasks.LogRotator;
45
import hudson.tasks.Mailer;
K
kohsuke 已提交
46 47
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildStep;
K
kohsuke 已提交
48 49
import hudson.tasks.test.AbstractTestResultAction;
import hudson.util.IOException2;
K
kohsuke 已提交
50
import hudson.util.LogTaskListener;
51
import hudson.util.XStream2;
52
import hudson.util.ProcessTree;
K
kohsuke 已提交
53

54
import java.io.BufferedReader;
K
kohsuke 已提交
55
import java.io.File;
56
import java.io.FileInputStream;
K
kohsuke 已提交
57
import java.io.FileOutputStream;
58
import java.io.FileReader;
K
kohsuke 已提交
59
import java.io.IOException;
60
import java.io.InputStreamReader;
K
kohsuke 已提交
61 62
import java.io.PrintStream;
import java.io.PrintWriter;
63
import java.io.Reader;
K
kohsuke 已提交
64
import java.io.Writer;
65
import java.nio.charset.Charset;
66
import java.text.DateFormat;
K
kohsuke 已提交
67 68 69 70
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
71
import java.util.Collections;
K
kohsuke 已提交
72
import java.util.Comparator;
73
import java.util.Date;
K
kohsuke 已提交
74
import java.util.GregorianCalendar;
75
import java.util.HashMap;
76
import java.util.LinkedList;
K
kohsuke 已提交
77
import java.util.List;
78
import java.util.Locale;
K
kohsuke 已提交
79
import java.util.Map;
K
kohsuke 已提交
80 81
import java.util.Set;
import java.util.HashSet;
82
import java.util.logging.Level;
K
kohsuke 已提交
83
import java.util.logging.Logger;
84 85 86 87 88 89 90 91 92 93 94
import java.util.zip.GZIPInputStream;

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

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 org.kohsuke.stapler.framework.io.LargeText;
95
import org.apache.commons.io.IOUtils;
96 97

import com.thoughtworks.xstream.XStream;
K
kohsuke 已提交
98 99 100 101 102 103 104 105 106 107

/**
 * 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 已提交
108
 * @see RunListener
K
kohsuke 已提交
109
 */
K
kohsuke 已提交
110
@ExportedBean
K
kohsuke 已提交
111
public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,RunT>>
112
        extends Actionable implements ExtensionPoint, Comparable<RunT>, AccessControlled, PersistenceRoot, DescriptorByNameOwner {
K
kohsuke 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

    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}.
     */
    protected volatile transient RunT previousBuild;
K
kohsuke 已提交
130

K
kohsuke 已提交
131 132 133 134 135
    /**
     * Next build. Can be null.
     */
    protected volatile transient RunT nextBuild;

K
kohsuke 已提交
136 137 138 139 140 141 142
    /**
     * 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.
     */
    private volatile transient RunT previousBuildInProgress;

K
kohsuke 已提交
143 144 145
    /**
     * When the build is scheduled.
     */
146
    protected transient final long timestamp;
K
kohsuke 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164

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

    /**
     * The current build state.
     */
    protected volatile transient State state;

    private static enum State {
165 166 167
        /**
         * Build is created/queued but we haven't started building it.
         */
K
kohsuke 已提交
168
        NOT_STARTED,
169 170 171
        /**
         * Build is in progress.
         */
K
kohsuke 已提交
172
        BUILDING,
173 174 175 176 177 178 179 180
        /**
         * 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 已提交
181 182 183 184 185 186 187 188
        COMPLETED
    }

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

189 190 191 192 193 194 195 196
    /**
     * 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
     */
197
    protected String charset;
198

K
kohsuke 已提交
199 200 201 202 203
    /**
     * Keeps this log entries.
     */
    private boolean keepLog;

K
kohsuke 已提交
204 205 206 207 208 209
    /**
     * If the build is in progress, remember {@link Runner} that's running it.
     * This field is not persisted.
     */
    private volatile transient Runner runner;

210 211 212 213 214 215 216
    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 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230

    /**
     * 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) {
231 232 233 234
        this(job,timestamp.getTimeInMillis());
    }

    protected Run(JobT job, long timestamp) {
K
kohsuke 已提交
235 236 237 238 239 240 241 242 243
        this.project = job;
        this.timestamp = timestamp;
        this.state = State.NOT_STARTED;
    }

    /**
     * Loads a run from a log file.
     */
    protected Run(JobT project, File buildDir) throws IOException {
244
        this(project, parseTimestampFromBuildDir(buildDir));
K
kohsuke 已提交
245
        this.previousBuildInProgress = _this(); // loaded builds are always completed
246 247 248 249 250
        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
    }

251
    /*package*/ static long parseTimestampFromBuildDir(File buildDir) throws IOException {
K
kohsuke 已提交
252
        try {
253
            return ID_FORMATTER.get().parse(buildDir.getName()).getTime();
K
kohsuke 已提交
254 255 256 257 258 259 260
        } catch (ParseException e) {
            throw new IOException2("Invalid directory name "+buildDir,e);
        } catch (NumberFormatException e) {
            throw new IOException2("Invalid directory name "+buildDir,e);
        }
    }

K
kohsuke 已提交
261 262 263 264 265 266 267 268
    /**
     * Obtains 'this' in a more type safe signature.
     */
    @SuppressWarnings({"unchecked"})
    private RunT _this() {
        return (RunT)this;
    }

269 270 271 272 273 274 275
    /**
     * Ordering based on build numbers.
     */
    public int compareTo(RunT that) {
        return this.number - that.number;
    }

K
kohsuke 已提交
276 277 278 279 280
    /**
     * Returns the build result.
     *
     * <p>
     * When a build is {@link #isBuilding() in progress}, this method
281
     * returns an intermediate result.
K
kohsuke 已提交
282
     */
K
kohsuke 已提交
283
    @Exported
K
kohsuke 已提交
284
    public Result getResult() {
K
kohsuke 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297
        return result;
    }

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

        StackTraceElement caller = findCaller(Thread.currentThread().getStackTrace(),"setResult");


        // result can only get worse
        if(result==null) {
            result = r;
298
            LOGGER.fine(toString()+" : result is set to "+r+" by "+caller);
K
kohsuke 已提交
299 300
        } else {
            if(r.isWorseThan(result)) {
301
                LOGGER.fine(toString()+" : result is set to "+r+" by "+caller);
K
kohsuke 已提交
302 303 304 305 306
                result = r;
            }
        }
    }

307
    /**
308
     * Gets the subset of {@link #getActions()} that consists of {@link BuildBadgeAction}s.
309 310 311 312 313 314 315 316 317 318
     */
    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);
            }
        }
319 320 321 322 323
        if(isKeepLog()) {
            if(r==null)
                r = new ArrayList<BuildBadgeAction>();
            r.add(new KeepLogBuildBadge());
        }
324 325 326 327
        if(r==null)     return Collections.emptyList();
        else            return r;
    }

K
kohsuke 已提交
328 329 330 331 332 333 334 335 336 337 338
    private StackTraceElement findCaller(StackTraceElement[] stackTrace, String callee) {
        for(int i=0; i<stackTrace.length-1; i++) {
            StackTraceElement e = stackTrace[i];
            if(e.getMethodName().equals(callee))
                return stackTrace[i+1];
        }
        return null; // not found
    }

    /**
     * Returns true if the build is not completed yet.
339
     * This includes "not started yet" state.
K
kohsuke 已提交
340
     */
K
kohsuke 已提交
341
    @Exported
K
kohsuke 已提交
342
    public boolean isBuilding() {
343 344 345 346 347 348 349 350
        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 已提交
351 352 353 354 355 356 357 358 359
    }

    /**
     * Gets the {@link Executor} building this job, if it's being built.
     * Otherwise null.
     */
    public Executor getExecutor() {
        for( Computer c : Hudson.getInstance().getComputers() ) {
            for (Executor e : c.getExecutors()) {
360
                if(e.getCurrentExecutable()==this)
K
kohsuke 已提交
361 362 363 364 365 366
                    return e;
            }
        }
        return null;
    }

367 368 369 370 371 372 373 374 375 376
    /**
     * 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 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    /**
     * 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 已提交
394 395 396 397 398
    /**
     * Returns true if this log file should be kept and not deleted.
     *
     * This is used as a signal to the {@link LogRotator}.
     */
K
kohsuke 已提交
399
    @Exported
400 401 402 403 404 405 406 407 408 409
    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 已提交
410
            return Messages.Run_MarkedExplicitly();
411
        return null;    // not marked at all
K
kohsuke 已提交
412 413 414 415 416 417 418 419 420 421 422 423
    }

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

    /**
     * When the build is scheduled.
     */
K
kohsuke 已提交
424
    @Exported
K
kohsuke 已提交
425
    public Calendar getTimestamp() {
426 427 428
        GregorianCalendar c = new GregorianCalendar();
        c.setTimeInMillis(timestamp);
        return c;
K
kohsuke 已提交
429 430
    }

K
kohsuke 已提交
431
    @Exported
K
kohsuke 已提交
432 433 434 435
    public String getDescription() {
        return description;
    }

436

437 438 439 440 441 442 443 444 445 446 447
    /**
     * 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 = "...";
448

449 450 451 452 453
        int sz = description.length();

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

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
        for (int i=0; i<sz; i++) {
            char ch = description.charAt(i);
            if(ch == '<') {
                inTag = true;
            } else if (ch == '>') {
                inTag = false;
                if (displayChars <= (maxDescrLength - ending.length())) {
                    lastTruncatablePoint = i + 1;
                }
            }
            if (!inTag) {
                displayChars++;
                if (displayChars <= (maxDescrLength - ending.length())) {
                    if (ch == ' ') {
                        lastTruncatablePoint = i;
                    }
                }
            }
473 474
        }

475 476
        String truncDesc = description;
        
477
        if (displayChars >= maxDescrLength) {
478
            truncDesc = truncDesc.substring(0, lastTruncatablePoint) + ending;
479 480
        }
        
481
        return truncDesc;
482
        
483 484
    }

K
kohsuke 已提交
485
    /**
486
     * Gets the string that says how long since this build has started.
K
kohsuke 已提交
487 488 489 490 491
     *
     * @return
     *      string like "3 minutes" "1 day" etc.
     */
    public String getTimestampString() {
492
        long duration = new GregorianCalendar().getTimeInMillis()-timestamp;
K
i18n  
kohsuke 已提交
493
        return Util.getPastTimeString(duration);
K
kohsuke 已提交
494 495 496 497 498 499
    }

    /**
     * Returns the timestamp formatted in xs:dateTime.
     */
    public String getTimestampString2() {
500
        return Util.XS_DATETIME_FORMATTER.format(new Date(timestamp));
K
kohsuke 已提交
501 502 503 504 505 506
    }

    /**
     * Gets the string that says how long the build took to run.
     */
    public String getDurationString() {
507
        if(isBuilding())
508
            return Util.getTimeSpanString(System.currentTimeMillis()-timestamp)+" and counting";
K
kohsuke 已提交
509 510 511 512 513 514
        return Util.getTimeSpanString(duration);
    }

    /**
     * Gets the millisecond it took to build.
     */
K
kohsuke 已提交
515
    @Exported
K
kohsuke 已提交
516 517 518 519 520 521 522
    public long getDuration() {
        return duration;
    }

    /**
     * Gets the icon color for display.
     */
523
    public BallColor getIconColor() {
K
kohsuke 已提交
524 525
        if(!isBuilding()) {
            // already built
K
kohsuke 已提交
526
            return getResult().color;
K
kohsuke 已提交
527 528 529
        }

        // a new build is in progress
530
        BallColor baseColor;
K
kohsuke 已提交
531
        if(previousBuild==null)
532
            baseColor = BallColor.GREY;
K
kohsuke 已提交
533 534 535
        else
            baseColor = previousBuild.getIconColor();

536
        return baseColor.anime();
K
kohsuke 已提交
537 538 539 540 541 542 543 544 545
    }

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

546
    @Override
K
kohsuke 已提交
547
    public String toString() {
K
kohsuke 已提交
548 549 550
        return getFullDisplayName();
    }

551
    @Exported
K
kohsuke 已提交
552
    public String getFullDisplayName() {
553
        return project.getFullDisplayName()+" #"+number;
K
kohsuke 已提交
554 555 556 557 558 559
    }

    public String getDisplayName() {
        return "#"+number;
    }

K
kohsuke 已提交
560
    @Exported(visibility=2)
K
kohsuke 已提交
561 562 563 564 565 566 567 568
    public int getNumber() {
        return number;
    }

    public RunT getPreviousBuild() {
        return previousBuild;
    }

569 570 571 572 573 574 575 576 577 578
    /**
     * 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 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    /**
     * 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;
    }

620 621 622 623 624 625 626 627 628 629
    /**
     * Returns the last build that was actually built - i.e., skipping any with Result.NOT_BUILT
     */
    public RunT getPreviousBuiltBuild() {
        RunT r=previousBuild;
        while( r!=null && r.getResult()==Result.NOT_BUILT )
            r=r.previousBuild;
        return r;
    }

K
kohsuke 已提交
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    /**
     * 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;
    }

    public RunT getNextBuild() {
        return nextBuild;
    }

K
kohsuke 已提交
654 655 656 657 658 659
    /**
     * 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 已提交
660 661 662 663 664 665
    // 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()+'/';
    }

666 667 668 669 670 671 672 673 674
    /**
     * Obtains the absolute URL to this build.
     *
     * @deprecated
     *      This method shall <b>NEVER</b> be used during HTML page rendering, as it won't work with
     *      network set up like Apache reverse proxy.
     *      This method is only intended for the remote API clients who cannot resolve relative references
     *      (even this won't work for the same reason, which should be fixed.)
     */
K
kohsuke 已提交
675
    @Exported(visibility=2,name="url")
676 677 678 679
    public final String getAbsoluteUrl() {
        return project.getAbsoluteUrl()+getNumber()+'/';
    }

680 681 682 683
    public final String getSearchUrl() {
        return getNumber()+"/";
    }

K
kohsuke 已提交
684 685 686
    /**
     * Unique ID of this build.
     */
K
kohsuke 已提交
687
    @Exported
K
kohsuke 已提交
688
    public String getId() {
689
        return ID_FORMATTER.get().format(new Date(timestamp));
K
kohsuke 已提交
690
    }
K
kohsuke 已提交
691 692 693 694 695 696 697 698 699
    
    /**
     * 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 已提交
700

701 702 703 704
    public Descriptor getDescriptorByName(String className) {
        return Hudson.getInstance().getDescriptorByName(className);
    }

K
kohsuke 已提交
705 706 707 708 709
    /**
     * Root directory of this {@link Run} on the master.
     *
     * Files related to this {@link Run} should be stored below this directory.
     */
K
kohsuke 已提交
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    public File getRootDir() {
        File f = new File(project.getBuildDir(),getId());
        f.mkdirs();
        return f;
    }

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

    /**
     * Gets the first {@value #CUTOFF} artifacts (relative to {@link #getArtifactsDir()}.
     */
726
    @Exported
K
kohsuke 已提交
727
    public List<Artifact> getArtifacts() {
728
        ArtifactList r = new ArtifactList();
729
        addArtifacts(getArtifactsDir(),"","",r);
730
        r.computeDisplayName();
K
kohsuke 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743
        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() {
        return !getArtifacts().isEmpty();
    }

744
    private void addArtifacts( File dir, String path, String pathHref, List<Artifact> r ) {
K
kohsuke 已提交
745 746
        String[] children = dir.list();
        if(children==null)  return;
747
        for (String child : children) {
K
kohsuke 已提交
748 749 750 751
            if(r.size()>CUTOFF)
                return;
            File sub = new File(dir, child);
            if (sub.isDirectory()) {
752
                addArtifacts(sub, path + child + '/', pathHref + Util.rawEncode(child) + '/', r);
K
kohsuke 已提交
753
            } else {
754
                r.add(new Artifact(path + child, pathHref + Util.rawEncode(child)));
K
kohsuke 已提交
755
            }
756
        }
K
kohsuke 已提交
757 758 759 760
    }

    private static final int CUTOFF = 17;   // 0, 1,... 16, and then "too many"

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    public final class ArtifactList extends ArrayList<Artifact> {
        public void computeDisplayName() {
            if(size()>CUTOFF)   return; // we are not going to display file names, so no point in computing this

            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 已提交
823
            StringBuilder buf = new StringBuilder();
824 825 826 827 828 829 830 831
            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 已提交
832 833 834
    /**
     * A build artifact.
     */
835
    @ExportedBean
K
kohsuke 已提交
836 837 838 839
    public class Artifact {
        /**
         * Relative path name from {@link Run#getArtifactsDir()}
         */
840
    	@Exported(visibility=3)
841
        public final String relativePath;
K
kohsuke 已提交
842

843 844 845 846 847 848
        /**
         * Truncated form of {@link #relativePath} just enough
         * to disambiguate {@link Artifact}s.
         */
        /*package*/ String displayPath;

849 850 851
        private String href;

        /*package for test*/ Artifact(String relativePath, String href) {
K
kohsuke 已提交
852
            this.relativePath = relativePath;
853
            this.href = href;
K
kohsuke 已提交
854 855 856 857 858 859 860 861 862 863 864 865
        }

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

        /**
         * Returns just the file name portion, without the path.
         */
866
    	@Exported(visibility=3)
K
kohsuke 已提交
867 868 869 870
        public String getFileName() {
            return getFile().getName();
        }

871
    	@Exported(visibility=3)
872 873 874 875
        public String getDisplayPath() {
            return displayPath;
        }

876 877 878 879
        public String getHref() {
            return href;
        }

880
        @Override
K
kohsuke 已提交
881 882 883 884 885 886 887 888 889 890 891 892
        public String toString() {
            return relativePath;
        }
    }

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

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
    /**
     * Returns a Reader that reads from the log file.
     * It will use a gzip-compressed log file (log.gz) if that exists.
     * @throws IOException 
     * @return a reader from the log file, or null if none exists
     */
    public Reader getLogReader() throws IOException {
    	File logFile = getLogFile();
    	if (logFile.exists() ) {
    		return new FileReader(logFile);
    	} 

    	File compressedLogFile = new File(logFile.getParentFile(), logFile.getName()+ ".gz");
    	if (compressedLogFile.exists()) {
    		return new InputStreamReader(
    				new GZIPInputStream(
    						new FileInputStream(compressedLogFile)));
    	} 
    	
    	return null;
    }
    
915
    @Override
916
    protected SearchIndexBuilder makeSearchIndex() {
917 918 919 920 921 922 923 924
        SearchIndexBuilder builder = super.makeSearchIndex()
                .add("console")
                .add("changes");
        for (Action a : getActions()) {
            if(a.getIconFileName()!=null)
                builder.add(a.getUrlName());
        }
        return builder;
925 926
    }

927
    public Api getApi() {
928 929 930
        return new Api(this);
    }

931
    public void checkPermission(Permission p) {
932 933 934
        getACL().checkPermission(p);
    }

935 936 937 938
    public boolean hasPermission(Permission p) {
        return getACL().hasPermission(p);
    }

939
    public ACL getACL() {
940
        // for now, don't maintain ACL per run, and do it at project level
941
        return getParent().getACL();
942 943
    }

K
kohsuke 已提交
944 945 946 947 948 949 950
    /**
     * Deletes this build and its entire log
     *
     * @throws IOException
     *      if we fail to delete.
     */
    public synchronized void delete() throws IOException {
951 952
        RunListener.fireDeleted(this);

953 954 955 956
        // if we have a symlink, delete it, too
        File link = new File(project.getBuildDir(), String.valueOf(getNumber()));
        link.delete();

K
kohsuke 已提交
957 958
        File rootDir = getRootDir();
        File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName());
959 960 961
        
        boolean renamingSucceeded = rootDir.renameTo(tmp);
        Util.deleteRecursive(tmp);
962 963 964 965
        // 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 已提交
966

967
        if(!renamingSucceeded)
K
kohsuke 已提交
968 969
            throw new IOException(rootDir+" is in use");

J
jglick 已提交
970 971 972 973
        removeRunFromParent();
    }
    @SuppressWarnings("unchecked") // seems this is too clever for Java's type system?
    private void removeRunFromParent() {
K
kohsuke 已提交
974 975 976
        getParent().removeRun((RunT)this);
    }

K
kohsuke 已提交
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 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

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

1048 1049 1050 1051 1052 1053
        /**
         * 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 已提交
1054
        public abstract Result run( BuildListener listener ) throws Exception, RunnerAbortedException;
K
kohsuke 已提交
1055

1056 1057
        /**
         * Performs the post-build action.
1058
         * <p>
K
kohsuke 已提交
1059 1060 1061 1062 1063
         * This method is called after the status of the build is determined.
         * 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
1064
         * by {@link Job#getLastSuccessfulBuild()}.
1065
         */
K
kohsuke 已提交
1066
        public abstract void post( BuildListener listener ) throws Exception;
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077

        /**
         * 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 已提交
1078 1079 1080 1081 1082
        public abstract void cleanUp(BuildListener listener) throws Exception;

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

1085 1086 1087 1088 1089 1090 1091
    /**
     * 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.
     */
    public static final class RunnerAbortedException extends RuntimeException {}

K
kohsuke 已提交
1092 1093 1094 1095
    protected final void run(Runner job) {
        if(result!=null)
            return;     // already built.

1096 1097 1098
        BuildListener listener=null;
        PrintStream log = null;

K
kohsuke 已提交
1099
        runner = job;
K
kohsuke 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108
        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 {
K
kohsuke 已提交
1109
                    log = new PrintStream(new FileOutputStream(getLogFile()));
1110 1111 1112
                    Charset charset = Computer.currentComputer().getDefaultCharset();
                    this.charset = charset.name();
                    listener = new StreamBuildListener(new PrintStream(new CloseProofOutputStream(log)),charset);
K
kohsuke 已提交
1113

K
kohsuke 已提交
1114
                    listener.started(getCauses());
K
kohsuke 已提交
1115

K
kohsuke 已提交
1116 1117
                    RunListener.fireStarted(this,listener);

1118 1119 1120
                    // create a symlink from build number to ID.
                    Util.createSymlink(getParent().getBuildDir(),getId(),String.valueOf(getNumber()),listener);

K
kohsuke 已提交
1121
                    setResult(job.run(listener));
K
kohsuke 已提交
1122 1123

                    LOGGER.info(toString()+" main build action completed: "+result);
K
kohsuke 已提交
1124
                    CheckPoint.MAIN_COMPLETED.report();
K
kohsuke 已提交
1125 1126
                } catch (ThreadDeath t) {
                    throw t;
1127
                } catch( AbortException e ) {// orderly abortion.
1128
                    result = Result.FAILURE;
1129
                    LOGGER.log(Level.FINE, "Build "+this+" aborted",e);
K
kohsuke 已提交
1130
                } catch( RunnerAbortedException e ) {// orderly abortion.
1131
                    result = Result.FAILURE;
1132
                    LOGGER.log(Level.FINE, "Build "+this+" aborted",e);
1133 1134 1135
                } catch( InterruptedException e) {
                    // aborted
                    result = Result.ABORTED;
K
i18n  
kohsuke 已提交
1136
                    listener.getLogger().println(Messages.Run_BuildAborted());
1137
                    LOGGER.log(Level.INFO,toString()+" aborted",e);
K
kohsuke 已提交
1138 1139 1140 1141 1142
                } catch( Throwable e ) {
                    handleFatalBuildProblem(listener,e);
                    result = Result.FAILURE;
                }

K
kohsuke 已提交
1143
                // even if the main build fails fatally, try to run post build processing
K
kohsuke 已提交
1144 1145 1146 1147 1148 1149 1150
                job.post(listener);

            } catch (ThreadDeath t) {
                throw t;
            } catch( Throwable e ) {
                handleFatalBuildProblem(listener,e);
                result = Result.FAILURE;
K
kohsuke 已提交
1151
            } finally {
1152 1153 1154
                long end = System.currentTimeMillis();
                duration = end-start;

1155
                // advance the state.
1156 1157 1158 1159
                // the significance of doing this is that Hudson
                // will now see this build as completed.
                // things like triggering other builds requires this as pre-condition.
                // see issue #980.
1160
                state = State.POST_PRODUCTION;
1161 1162 1163 1164 1165 1166 1167

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

1169
                RunListener.fireCompleted(this,listener);
K
kohsuke 已提交
1170

1171 1172 1173 1174
                if(listener!=null)
                    listener.finished(result);
                if(log!=null)
                    log.close();
K
kohsuke 已提交
1175

1176 1177 1178
                try {
                    save();
                } catch (IOException e) {
K
kohsuke 已提交
1179
                    LOGGER.log(Level.SEVERE, "Failed to save build record",e);
1180
                }
K
kohsuke 已提交
1181 1182 1183
            }

            try {
1184
                getParent().logRotate();
K
kohsuke 已提交
1185
            } catch (IOException e) {
K
kohsuke 已提交
1186
                LOGGER.log(Level.SEVERE, "Failed to rotate log",e);
1187 1188
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to rotate log",e);
K
kohsuke 已提交
1189 1190 1191 1192 1193 1194 1195
            }
        } finally {
            onEndBuilding();
        }
    }

    /**
K
kohsuke 已提交
1196
     * Handles a fatal build problem (exception) that occurred during the build.
K
kohsuke 已提交
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
     */
    private void handleFatalBuildProblem(BuildListener listener, Throwable e) {
        if(listener!=null) {
            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
                }
            }
        }
    }

    /**
     * Called when a job started building.
     */
    protected void onStartBuilding() {
        state = State.BUILDING;
K
kohsuke 已提交
1220
        RunnerStack.INSTANCE.push(runner);
K
kohsuke 已提交
1221 1222 1223 1224 1225 1226
    }

    /**
     * Called when a job finished building normally or abnormally.
     */
    protected void onEndBuilding() {
K
kohsuke 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        // signal that we've finished building.
        if (runner!=null) {
            // MavenBuilds may be created without their corresponding runners.
            state = State.COMPLETED;
            runner.checkpoints.allDone();
        } else {
            state = State.COMPLETED;
        }
        runner = null;
        RunnerStack.INSTANCE.pop();
1237 1238 1239 1240 1241
	if (result==null) {
	    result = Result.FAILURE;
	    LOGGER.warning(toString()+": No build result is set, so marking as failure. This shouldn't happen.");
        }

1242
        RunListener.fireFinalized(this);
K
kohsuke 已提交
1243 1244 1245 1246 1247 1248
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
1249
        if(BulkChange.contains(this))   return;
K
kohsuke 已提交
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        getDataFile().write(this);
    }

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

    /**
     * Gets the log of the build as a string.
     *
1260 1261
     * @deprecated Use {@link #getLog(int)} instead as it avoids loading
     * the whole log into memory unnecessarily.
K
kohsuke 已提交
1262
     */
1263
    @Deprecated
K
kohsuke 已提交
1264
    public String getLog() throws IOException {
1265
        return Util.loadFile(getLogFile(),getCharset());
K
kohsuke 已提交
1266 1267
    }

1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
    /**
     * 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>();
1280
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getLogFile()),getCharset()));
K
kohsuke 已提交
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
        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();
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        }

        // 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...]");

        return logLines;
    }

K
kohsuke 已提交
1305 1306 1307 1308 1309 1310
    public void doBuildStatus( StaplerRequest req, StaplerResponse rsp ) throws IOException {
        // see Hudson.doNocacheImages. this is a work around for a bug in Firefox
        rsp.sendRedirect2(req.getContextPath()+"/nocacheImages/48x48/"+getBuildStatusUrl());
    }

    public String getBuildStatusUrl() {
1311
        return getIconColor().getImage();
K
kohsuke 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
    }

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

    /**
     * Gets an object that computes the single line summary of this build.
     */
    public Summary getBuildStatusSummary() {
        Run prev = getPreviousBuild();

        if(getResult()==Result.SUCCESS) {
            if(prev==null || prev.getResult()== Result.SUCCESS)
1335
                return new Summary(false, Messages.Run_Summary_Stable());
K
kohsuke 已提交
1336
            else
1337
                return new Summary(false, Messages.Run_Summary_BackToNormal());
K
kohsuke 已提交
1338 1339 1340 1341 1342
        }

        if(getResult()==Result.FAILURE) {
            RunT since = getPreviousNotFailedBuild();
            if(since==null)
1343
                return new Summary(false, Messages.Run_Summary_BrokenForALongTime());
K
kohsuke 已提交
1344
            if(since==prev)
1345 1346
                return new Summary(true, Messages.Run_Summary_BrokenSinceThisBuild());
            return new Summary(false, Messages.Run_Summary_BrokenSince(since.getDisplayName()));
K
kohsuke 已提交
1347 1348 1349
        }

        if(getResult()==Result.ABORTED)
1350
            return new Summary(false, Messages.Run_Summary_Aborted());
K
kohsuke 已提交
1351 1352 1353 1354 1355 1356 1357

        if(getResult()==Result.UNSTABLE) {
            if(((Run)this) instanceof Build) {
                AbstractTestResultAction trN = ((Build)(Run)this).getTestResultAction();
                AbstractTestResultAction trP = prev==null ? null : ((Build) prev).getTestResultAction();
                if(trP==null) {
                    if(trN!=null && trN.getFailCount()>0)
1358
                        return new Summary(false, Messages.Run_Summary_TestFailures(trN.getFailCount()));
K
kohsuke 已提交
1359
                    else // ???
1360
                        return new Summary(false, Messages.Run_Summary_Unstable());
K
kohsuke 已提交
1361 1362
                }
                if(trP.getFailCount()==0)
1363
                    return new Summary(true, Messages.Run_Summary_TestsStartedToFail(trN.getFailCount()));
K
kohsuke 已提交
1364
                if(trP.getFailCount() < trN.getFailCount())
1365
                    return new Summary(true, Messages.Run_Summary_MoreTestsFailing(trN.getFailCount()-trP.getFailCount(), trN.getFailCount()));
K
kohsuke 已提交
1366
                if(trP.getFailCount() > trN.getFailCount())
1367
                    return new Summary(false, Messages.Run_Summary_LessTestsFailing(trP.getFailCount()-trN.getFailCount(), trN.getFailCount()));
K
kohsuke 已提交
1368

1369
                return new Summary(false, Messages.Run_Summary_TestsStillFailing(trN.getFailCount()));
K
kohsuke 已提交
1370 1371 1372
            }
        }

1373
        return new Summary(false, Messages.Run_Summary_Unknown());
K
kohsuke 已提交
1374 1375 1376 1377 1378
    }

    /**
     * Serves the artifacts.
     */
1379 1380
    public DirectoryBrowserSupport doArtifact() {
        return new DirectoryBrowserSupport(this,new FilePath(getArtifactsDir()), project.getDisplayName()+' '+getDisplayName(), "package.gif", true);
K
kohsuke 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    }

    /**
     * Returns the build number in the body.
     */
    public void doBuildNumber( StaplerRequest req, StaplerResponse rsp ) throws IOException {
        rsp.setContentType("text/plain");
        rsp.setCharacterEncoding("US-ASCII");
        rsp.setStatus(HttpServletResponse.SC_OK);
        rsp.getWriter().print(number);
    }

K
kohsuke 已提交
1393 1394 1395
    /**
     * Returns the build time stamp in the body.
     */
1396
    public void doBuildTimestamp( StaplerRequest req, StaplerResponse rsp, @QueryParameter String format) throws IOException {
K
kohsuke 已提交
1397 1398 1399
        rsp.setContentType("text/plain");
        rsp.setCharacterEncoding("US-ASCII");
        rsp.setStatus(HttpServletResponse.SC_OK);
K
kohsuke 已提交
1400 1401 1402
        DateFormat df = format==null ?
                DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.ENGLISH) :
                new SimpleDateFormat(format,req.getLocale());
K
kohsuke 已提交
1403 1404 1405
        rsp.getWriter().print(df.format(getTimestamp().getTime()));
    }

1406 1407 1408 1409 1410 1411 1412 1413
    /**
     * Sends out the raw console output.
     */
    public void doConsoleText(StaplerRequest req, StaplerResponse rsp) throws IOException {
        rsp.setContentType("text/plain;charset=UTF-8");
        IOUtils.copy(getLogReader(),rsp.getCompressedOutputStream(req));
    }

K
kohsuke 已提交
1414 1415 1416 1417
    /**
     * Handles incremental log output.
     */
    public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
1418
        new LargeText(getLogFile(),getCharset(),!isLogUpdated()).doProgressText(req,rsp);
K
kohsuke 已提交
1419 1420 1421
    }

    public void doToggleLogKeep( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1422
        checkPermission(UPDATE);
K
kohsuke 已提交
1423

K
kohsuke 已提交
1424
        keepLog(!keepLog);
K
kohsuke 已提交
1425 1426
        rsp.forwardToPreviousPage(req);
    }
K
kohsuke 已提交
1427 1428 1429 1430

    /**
     * Marks this build to keep the log.
     */
1431
    @CLIMethod(name="keep-build")
K
kohsuke 已提交
1432 1433 1434 1435 1436 1437
    public final void keepLog() throws IOException {
        keepLog(true);
    }

    public void keepLog(boolean newValue) throws IOException {
        keepLog = newValue;
K
kohsuke 已提交
1438 1439
        save();
    }
K
kohsuke 已提交
1440

1441 1442 1443 1444
    /**
     * Deletes the build when the button is pressed.
     */
    public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1445
        requirePOST();
1446 1447
        checkPermission(DELETE);

1448 1449 1450
        // 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!
1451 1452
        String why = getWhyKeepLog();
        if (why!=null) {
K
i18n  
kohsuke 已提交
1453
            sendError(Messages.Run_UnableToDelete(toString(),why),req,rsp);
1454 1455 1456 1457 1458 1459
            return;
        }

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

K
kohsuke 已提交
1461
    public void setDescription(String description) throws IOException {
1462 1463
        checkPermission(UPDATE);
        this.description = description;
K
kohsuke 已提交
1464
        save();
1465 1466
    }
    
K
kohsuke 已提交
1467 1468 1469 1470 1471
    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");
1472
        setDescription(req.getParameter("description"));
K
kohsuke 已提交
1473 1474 1475 1476
        rsp.sendRedirect(".");  // go to the top page
    }

    /**
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
     * @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 已提交
1490
    /**
1491
     * @deprecated as of 1.305 use {@link #getEnvironment(TaskListener)}
K
kohsuke 已提交
1492 1493 1494 1495 1496
     */
    public EnvVars getEnvironment() throws IOException, InterruptedException {
        return getEnvironment(new LogTaskListener(LOGGER, Level.INFO));
    }

1497 1498 1499
    /**
     * Returns the map that contains environmental variables to be used for launching
     * processes for this build.
K
kohsuke 已提交
1500
     *
1501
     * <p>
K
kohsuke 已提交
1502 1503 1504 1505
     * {@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.
     *
1506
     * <p>
1507 1508
     * Unlike earlier {@link #getEnvVars()}, this map contains the whole environment,
     * not just the overrides, so one can introspect values to change its behavior.
1509
     * @since 1.305
K
kohsuke 已提交
1510
     */
K
kohsuke 已提交
1511
    public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException {
1512
        EnvVars env = Computer.currentComputer().getEnvironment().overrideAll(getCharacteristicEnvVars());
1513
        String rootUrl = Hudson.getInstance().getRootUrl();
1514
        if(rootUrl!=null) {
1515
            env.put("HUDSON_URL", rootUrl);
1516 1517 1518
            env.put("BUILD_URL", rootUrl+getUrl());
            env.put("JOB_URL", rootUrl+getParent().getUrl());
        }
K
kohsuke 已提交
1519 1520
        if(!env.containsKey("HUDSON_HOME"))
            env.put("HUDSON_HOME", Hudson.getInstance().getRootDir().getPath() );
K
kohsuke 已提交
1521 1522 1523 1524 1525

        Thread t = Thread.currentThread();
        if (t instanceof Executor) {
            Executor e = (Executor) t;
            env.put("EXECUTOR_NUMBER",String.valueOf(e.getNumber()));
1526
            env.put("NODE_NAME",e.getOwner().getName());
K
kohsuke 已提交
1527 1528
        }

K
kohsuke 已提交
1529 1530 1531
        return env;
    }

1532 1533
    /**
     * Builds up the environment variable map that's sufficient to identify a process
1534
     * as ours. This is used to kill run-away processes via {@link ProcessTree#killAll(Map)}.
1535
     */
1536
    public final EnvVars getCharacteristicEnvVars() {
1537 1538 1539 1540 1541 1542 1543 1544
        EnvVars env = new EnvVars();
        env.put("BUILD_NUMBER",String.valueOf(number));
        env.put("BUILD_ID",getId());
        env.put("BUILD_TAG","hudson-"+getParent().getName()+"-"+number);
        env.put("JOB_NAME",getParent().getFullName());
        return env;
    }

H
huybrechts 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
    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));

        Job<?,?> job = (Job<?,?>) Hudson.getInstance().getItem(jobName);
        return job.getBuildByNumber(number);
    }


H
huybrechts 已提交
1562
    public static final XStream XSTREAM = new XStream2();
K
kohsuke 已提交
1563
    static {
1564 1565 1566
        XSTREAM.alias("build",FreeStyleBuild.class);
        XSTREAM.alias("matrix-build",MatrixBuild.class);
        XSTREAM.alias("matrix-run",MatrixRun.class);
K
kohsuke 已提交
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
        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 已提交
1577 1578 1579 1580 1581
            long lt = lhs.getTimestamp().getTimeInMillis();
            long rt = rhs.getTimestamp().getTimeInMillis();
            if(lt>rt)   return -1;
            if(lt<rt)   return 1;
            return 0;
K
kohsuke 已提交
1582 1583 1584 1585 1586 1587
        }
    };

    /**
     * {@link FeedAdapter} to produce feed from the summary of this build.
     */
K
kohsuke 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
    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.
         */
1598
        @Override
K
kohsuke 已提交
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
        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());
K
kohsuke 已提交
1616 1617
    public static final Permission DELETE = new Permission(PERMISSIONS,"Delete",Messages._Run_DeletePermission_Description(),Permission.DELETE);
    public static final Permission UPDATE = new Permission(PERMISSIONS,"Update",Messages._Run_UpdatePermission_Description(),Permission.UPDATE);
K
kohsuke 已提交
1618 1619

    private static class DefaultFeedAdapter implements FeedAdapter<Run> {
K
kohsuke 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628
        public String getEntryTitle(Run entry) {
            return entry+" ("+entry.getResult()+")";
        }

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

        public String getEntryID(Run entry) {
1629 1630 1631
            return "tag:" + "hudson.dev.java.net,"
                + entry.getTimestamp().get(Calendar.YEAR) + ":"
                + entry.getParent().getName()+':'+entry.getId();
K
kohsuke 已提交
1632 1633
        }

1634 1635 1636 1637 1638
        public String getEntryDescription(Run entry) {
            // TODO: this could provide some useful details
            return null;
        }

K
kohsuke 已提交
1639 1640 1641
        public Calendar getEntryTimestamp(Run entry) {
            return entry.getTimestamp();
        }
1642 1643

        public String getEntryAuthor(Run entry) {
1644
            return Mailer.descriptor().getAdminAddress();
1645
        }
1646
    }
1647 1648 1649 1650 1651 1652 1653

    @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 已提交
1654
            // may not have the action.. tell browsers to redirect up to the build page.
1655 1656 1657 1658 1659
            result = new RedirectUp();
        return result;
    }

    public static class RedirectUp {
K
kohsuke 已提交
1660
        public void doDynamic(StaplerResponse rsp) throws IOException {
M
mindless 已提交
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
            // 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();
1673 1674
        }
    }
K
kohsuke 已提交
1675
}