Run.java 43.8 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 26 27
package hudson.model;

import com.thoughtworks.xstream.XStream;
import hudson.CloseProofOutputStream;
K
kohsuke 已提交
28
import hudson.EnvVars;
K
kohsuke 已提交
29
import hudson.ExtensionPoint;
K
kohsuke 已提交
30
import hudson.FeedAdapter;
31
import hudson.FilePath;
K
kohsuke 已提交
32
import hudson.Util;
K
kohsuke 已提交
33
import static hudson.Util.combine;
K
kohsuke 已提交
34
import hudson.XmlFile;
35
import hudson.AbortException;
36
import hudson.BulkChange;
37 38
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixRun;
39
import hudson.model.listeners.RunListener;
K
kohsuke 已提交
40
import hudson.search.SearchIndexBuilder;
41 42 43 44
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
K
kohsuke 已提交
45
import hudson.tasks.BuildStep;
K
kohsuke 已提交
46
import hudson.tasks.BuildWrapper;
47
import hudson.tasks.LogRotator;
48
import hudson.tasks.Mailer;
K
kohsuke 已提交
49 50 51
import hudson.tasks.test.AbstractTestResultAction;
import hudson.util.IOException2;
import hudson.util.XStream2;
52
import org.kohsuke.stapler.QueryParameter;
K
kohsuke 已提交
53 54
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
kohsuke 已提交
55 56
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
57
import org.kohsuke.stapler.framework.io.LargeText;
K
kohsuke 已提交
58 59 60

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
61
import java.io.BufferedReader;
K
kohsuke 已提交
62 63 64 65 66 67
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Writer;
68 69
import java.io.InputStreamReader;
import java.io.FileInputStream;
70
import java.io.UnsupportedEncodingException;
71
import java.text.DateFormat;
K
kohsuke 已提交
72 73 74 75
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
76
import java.util.Collections;
K
kohsuke 已提交
77
import java.util.Comparator;
78
import java.util.Date;
K
kohsuke 已提交
79
import java.util.GregorianCalendar;
80
import java.util.HashMap;
81
import java.util.LinkedList;
K
kohsuke 已提交
82
import java.util.List;
83
import java.util.Locale;
K
kohsuke 已提交
84
import java.util.Map;
85
import java.util.TreeMap;
86
import java.util.logging.Level;
K
kohsuke 已提交
87
import java.util.logging.Logger;
88
import java.nio.charset.Charset;
K
kohsuke 已提交
89 90 91 92 93 94 95 96 97 98

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

    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;
    /**
     * Next build. Can be null.
     */
    protected volatile transient RunT nextBuild;

    /**
     * When the build is scheduled.
     */
129
    protected transient final long timestamp;
K
kohsuke 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

    /**
     * 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 {
148 149 150
        /**
         * Build is created/queued but we haven't started building it.
         */
K
kohsuke 已提交
151
        NOT_STARTED,
152 153 154
        /**
         * Build is in progress.
         */
K
kohsuke 已提交
155
        BUILDING,
156 157 158 159 160 161 162 163
        /**
         * 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 已提交
164 165 166 167 168 169 170 171
        COMPLETED
    }

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

172 173 174 175 176 177 178 179 180 181
    /**
     * 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
     */
    private String charset;

K
kohsuke 已提交
182 183 184 185 186
    /**
     * Keeps this log entries.
     */
    private boolean keepLog;

187 188 189 190 191 192 193
    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 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207

    /**
     * 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) {
208 209 210 211
        this(job,timestamp.getTimeInMillis());
    }

    protected Run(JobT job, long timestamp) {
K
kohsuke 已提交
212 213 214 215 216 217 218 219 220
        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 {
221 222 223 224 225 226
        this(project, parseTimestampFromBuildDir(buildDir));
        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
    }

227
    /*package*/ static long parseTimestampFromBuildDir(File buildDir) throws IOException {
K
kohsuke 已提交
228
        try {
229
            return ID_FORMATTER.get().parse(buildDir.getName()).getTime();
K
kohsuke 已提交
230 231 232 233 234 235 236
        } catch (ParseException e) {
            throw new IOException2("Invalid directory name "+buildDir,e);
        } catch (NumberFormatException e) {
            throw new IOException2("Invalid directory name "+buildDir,e);
        }
    }

237 238 239 240 241 242 243
    /**
     * Ordering based on build numbers.
     */
    public int compareTo(RunT that) {
        return this.number - that.number;
    }

K
kohsuke 已提交
244 245 246 247 248 249 250
    /**
     * Returns the build result.
     *
     * <p>
     * When a build is {@link #isBuilding() in progress}, this method
     * may return null or a temporary intermediate result.
     */
K
kohsuke 已提交
251
    @Exported
K
kohsuke 已提交
252
    public Result getResult() {
K
kohsuke 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265
        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;
266
            LOGGER.fine(toString()+" : result is set to "+r+" by "+caller);
K
kohsuke 已提交
267 268
        } else {
            if(r.isWorseThan(result)) {
269
                LOGGER.fine(toString()+" : result is set to "+r+" by "+caller);
K
kohsuke 已提交
270 271 272 273 274
                result = r;
            }
        }
    }

275
    /**
276
     * Gets the subset of {@link #getActions()} that consists of {@link BuildBadgeAction}s.
277 278 279 280 281 282 283 284 285 286
     */
    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);
            }
        }
287 288 289 290 291
        if(isKeepLog()) {
            if(r==null)
                r = new ArrayList<BuildBadgeAction>();
            r.add(new KeepLogBuildBadge());
        }
292 293 294 295
        if(r==null)     return Collections.emptyList();
        else            return r;
    }

K
kohsuke 已提交
296 297 298 299 300 301 302 303 304 305 306
    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.
307
     * This includes "not started yet" state.
K
kohsuke 已提交
308
     */
K
kohsuke 已提交
309
    @Exported
K
kohsuke 已提交
310
    public boolean isBuilding() {
311 312 313 314 315 316 317 318
        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 已提交
319 320 321 322 323 324 325 326 327
    }

    /**
     * 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()) {
328
                if(e.getCurrentExecutable()==this)
K
kohsuke 已提交
329 330 331 332 333 334
                    return e;
            }
        }
        return null;
    }

335 336 337 338 339 340 341 342 343 344
    /**
     * 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 已提交
345 346 347 348 349
    /**
     * Returns true if this log file should be kept and not deleted.
     *
     * This is used as a signal to the {@link LogRotator}.
     */
K
kohsuke 已提交
350
    @Exported
351 352 353 354 355 356 357 358 359 360
    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 已提交
361
            return Messages.Run_MarkedExplicitly();
362
        return null;    // not marked at all
K
kohsuke 已提交
363 364 365 366 367 368 369 370 371 372 373 374
    }

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

    /**
     * When the build is scheduled.
     */
K
kohsuke 已提交
375
    @Exported
K
kohsuke 已提交
376
    public Calendar getTimestamp() {
377 378 379
        GregorianCalendar c = new GregorianCalendar();
        c.setTimeInMillis(timestamp);
        return c;
K
kohsuke 已提交
380 381
    }

K
kohsuke 已提交
382
    @Exported
K
kohsuke 已提交
383 384 385 386
    public String getDescription() {
        return description;
    }

387 388 389 390 391 392 393 394 395 396 397
    /**
     * 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 = "...";
398

399 400 401 402 403 404 405 406 407 408 409 410 411
        // limit the description
        String truncDescr = description.substring(
                0, maxDescrLength - ending.length());

        // truncate the description on the space
        int lastSpace = truncDescr.lastIndexOf(" ");
        if (lastSpace != -1) {
            truncDescr = truncDescr.substring(0, lastSpace);
        }

        return truncDescr + ending;
    }

K
kohsuke 已提交
412 413 414 415 416 417 418
    /**
     * Gets the string that says how long since this build has scheduled.
     *
     * @return
     *      string like "3 minutes" "1 day" etc.
     */
    public String getTimestampString() {
419
        long duration = new GregorianCalendar().getTimeInMillis()-timestamp;
K
i18n  
kohsuke 已提交
420
        return Util.getPastTimeString(duration);
K
kohsuke 已提交
421 422 423 424 425 426
    }

    /**
     * Returns the timestamp formatted in xs:dateTime.
     */
    public String getTimestampString2() {
427
        return Util.XS_DATETIME_FORMATTER.format(new Date(timestamp));
K
kohsuke 已提交
428 429 430 431 432 433
    }

    /**
     * Gets the string that says how long the build took to run.
     */
    public String getDurationString() {
434
        if(isBuilding())
435
            return Util.getTimeSpanString(System.currentTimeMillis()-timestamp)+" and counting";
K
kohsuke 已提交
436 437 438 439 440 441
        return Util.getTimeSpanString(duration);
    }

    /**
     * Gets the millisecond it took to build.
     */
K
kohsuke 已提交
442
    @Exported
K
kohsuke 已提交
443 444 445 446 447 448 449
    public long getDuration() {
        return duration;
    }

    /**
     * Gets the icon color for display.
     */
450
    public BallColor getIconColor() {
K
kohsuke 已提交
451 452
        if(!isBuilding()) {
            // already built
K
kohsuke 已提交
453
            return getResult().color;
K
kohsuke 已提交
454 455 456
        }

        // a new build is in progress
457
        BallColor baseColor;
K
kohsuke 已提交
458
        if(previousBuild==null)
459
            baseColor = BallColor.GREY;
K
kohsuke 已提交
460 461 462
        else
            baseColor = previousBuild.getIconColor();

463
        return baseColor.anime();
K
kohsuke 已提交
464 465 466 467 468 469 470 471 472 473
    }

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

    public String toString() {
K
kohsuke 已提交
474 475 476
        return getFullDisplayName();
    }

477
    @Exported
K
kohsuke 已提交
478
    public String getFullDisplayName() {
479
        return project.getFullDisplayName()+" #"+number;
K
kohsuke 已提交
480 481 482 483 484 485
    }

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

K
kohsuke 已提交
486
    @Exported(visibility=2)
K
kohsuke 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    public int getNumber() {
        return number;
    }

    public RunT getPreviousBuild() {
        return previousBuild;
    }

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

    // 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()+'/';
    }

525 526 527 528 529 530 531 532 533
    /**
     * 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 已提交
534
    @Exported(visibility=2,name="url")
535 536 537 538
    public final String getAbsoluteUrl() {
        return project.getAbsoluteUrl()+getNumber()+'/';
    }

539 540 541 542
    public final String getSearchUrl() {
        return getNumber()+"/";
    }

K
kohsuke 已提交
543 544 545 546
    /**
     * Unique ID of this build.
     */
    public String getId() {
547
        return ID_FORMATTER.get().format(new Date(timestamp));
K
kohsuke 已提交
548 549
    }

K
kohsuke 已提交
550 551 552 553 554
    /**
     * Root directory of this {@link Run} on the master.
     *
     * Files related to this {@link Run} should be stored below this directory.
     */
K
kohsuke 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    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()}.
     */
571
    @Exported
K
kohsuke 已提交
572
    public List<Artifact> getArtifacts() {
573
        ArtifactList r = new ArtifactList();
574
        addArtifacts(getArtifactsDir(),"","",r);
575
        r.computeDisplayName();
K
kohsuke 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588
        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();
    }

589
    private void addArtifacts( File dir, String path, String pathHref, List<Artifact> r ) {
K
kohsuke 已提交
590 591
        String[] children = dir.list();
        if(children==null)  return;
592
        for (String child : children) {
K
kohsuke 已提交
593 594 595 596
            if(r.size()>CUTOFF)
                return;
            File sub = new File(dir, child);
            if (sub.isDirectory()) {
597
                addArtifacts(sub, path + child + '/', pathHref + Util.rawEncode(child) + '/', r);
K
kohsuke 已提交
598
            } else {
599
                r.add(new Artifact(path + child, pathHref + Util.rawEncode(child)));
K
kohsuke 已提交
600
            }
601
        }
K
kohsuke 已提交
602 603 604 605
    }

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

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    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) {
            StringBuffer buf = new StringBuffer();
            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 已提交
677 678 679
    /**
     * A build artifact.
     */
680
    @ExportedBean
K
kohsuke 已提交
681 682 683 684
    public class Artifact {
        /**
         * Relative path name from {@link Run#getArtifactsDir()}
         */
685
    	@Exported(visibility=3)
686
        public final String relativePath;
K
kohsuke 已提交
687

688 689 690 691 692 693
        /**
         * Truncated form of {@link #relativePath} just enough
         * to disambiguate {@link Artifact}s.
         */
        /*package*/ String displayPath;

694 695 696
        private String href;

        /*package for test*/ Artifact(String relativePath, String href) {
K
kohsuke 已提交
697
            this.relativePath = relativePath;
698
            this.href = href;
K
kohsuke 已提交
699 700 701 702 703 704 705 706 707 708 709 710
        }

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

        /**
         * Returns just the file name portion, without the path.
         */
711
    	@Exported(visibility=3)
K
kohsuke 已提交
712 713 714 715
        public String getFileName() {
            return getFile().getName();
        }

716
    	@Exported(visibility=3)
717 718 719 720
        public String getDisplayPath() {
            return displayPath;
        }

721 722 723 724
        public String getHref() {
            return href;
        }

K
kohsuke 已提交
725 726 727 728 729 730 731 732 733 734 735 736
        public String toString() {
            return relativePath;
        }
    }

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

737
    protected SearchIndexBuilder makeSearchIndex() {
738 739 740 741 742 743 744 745
        SearchIndexBuilder builder = super.makeSearchIndex()
                .add("console")
                .add("changes");
        for (Action a : getActions()) {
            if(a.getIconFileName()!=null)
                builder.add(a.getUrlName());
        }
        return builder;
746 747
    }

748 749 750 751
    public Api getApi(final StaplerRequest req) {
        return new Api(this);
    }

752
    public void checkPermission(Permission p) {
753 754 755
        getACL().checkPermission(p);
    }

756 757 758 759
    public boolean hasPermission(Permission p) {
        return getACL().hasPermission(p);
    }

760
    public ACL getACL() {
761
        // for now, don't maintain ACL per run, and do it at project level
762
        return getParent().getACL();
763 764
    }

K
kohsuke 已提交
765 766 767 768 769 770 771
    /**
     * Deletes this build and its entire log
     *
     * @throws IOException
     *      if we fail to delete.
     */
    public synchronized void delete() throws IOException {
772 773 774 775
        // if we have a symlink, delete it, too
        File link = new File(project.getBuildDir(), String.valueOf(getNumber()));
        link.delete();

K
kohsuke 已提交
776 777
        File rootDir = getRootDir();
        File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName());
778 779 780
        
        boolean renamingSucceeded = rootDir.renameTo(tmp);
        Util.deleteRecursive(tmp);
781 782 783 784
        // 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 已提交
785

786
        if(!renamingSucceeded)
K
kohsuke 已提交
787 788
            throw new IOException(rootDir+" is in use");

J
jglick 已提交
789 790 791 792
        removeRunFromParent();
    }
    @SuppressWarnings("unchecked") // seems this is too clever for Java's type system?
    private void removeRunFromParent() {
K
kohsuke 已提交
793 794 795 796
        getParent().removeRun((RunT)this);
    }

    protected static interface Runner {
797 798 799 800 801 802 803
        /**
         * Performs the main build and returns the status code.
         *
         * @throws Exception
         *      exception will be recorded and the build will be considered a failure.
         */
        Result run( BuildListener listener ) throws Exception, RunnerAbortedException;
K
kohsuke 已提交
804

805 806
        /**
         * Performs the post-build action.
807
         * <p>
K
kohsuke 已提交
808 809 810 811 812
         * 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
813
         * by {@link Job#getLastSuccessfulBuild()}.
814
         */
815
        void post( BuildListener listener ) throws Exception;
816 817 818 819 820 821 822 823 824 825 826 827

        /**
         * 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.
         */
        void cleanUp(BuildListener listener) throws Exception;
K
kohsuke 已提交
828 829
    }

830 831 832 833 834 835 836
    /**
     * 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 已提交
837 838 839 840
    protected final void run(Runner job) {
        if(result!=null)
            return;     // already built.

841 842 843
        BuildListener listener=null;
        PrintStream log = null;

K
kohsuke 已提交
844 845 846 847 848 849 850 851 852
        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 已提交
853
                    log = new PrintStream(new FileOutputStream(getLogFile()));
854 855 856
                    Charset charset = Computer.currentComputer().getDefaultCharset();
                    this.charset = charset.name();
                    listener = new StreamBuildListener(new PrintStream(new CloseProofOutputStream(log)),charset);
K
kohsuke 已提交
857 858 859

                    listener.started();

K
kohsuke 已提交
860 861
                    RunListener.fireStarted(this,listener);

862 863 864
                    // create a symlink from build number to ID.
                    Util.createSymlink(getParent().getBuildDir(),getId(),String.valueOf(getNumber()),listener);

K
kohsuke 已提交
865
                    setResult(job.run(listener));
K
kohsuke 已提交
866 867 868 869

                    LOGGER.info(toString()+" main build action completed: "+result);
                } catch (ThreadDeath t) {
                    throw t;
K
kohsuke 已提交
870
                } catch( AbortException e ) {// orderly abortion
871
                    result = Result.FAILURE;
K
kohsuke 已提交
872
                } catch( RunnerAbortedException e ) {// orderly abortion.
873
                    result = Result.FAILURE;
874 875 876
                } catch( InterruptedException e) {
                    // aborted
                    result = Result.ABORTED;
K
i18n  
kohsuke 已提交
877
                    listener.getLogger().println(Messages.Run_BuildAborted());
878
                    LOGGER.log(Level.INFO,toString()+" aborted",e);
K
kohsuke 已提交
879 880 881 882 883
                } catch( Throwable e ) {
                    handleFatalBuildProblem(listener,e);
                    result = Result.FAILURE;
                }

K
kohsuke 已提交
884
                // even if the main build fails fatally, try to run post build processing
K
kohsuke 已提交
885 886 887 888 889 890 891
                job.post(listener);

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

896
                // advance the state.
897 898 899 900
                // 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.
901
                state = State.POST_PRODUCTION;
902 903 904 905 906 907 908

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

910
                RunListener.fireCompleted(this,listener);
K
kohsuke 已提交
911

912 913 914 915
                if(listener!=null)
                    listener.finished(result);
                if(log!=null)
                    log.close();
K
kohsuke 已提交
916

917 918 919
                try {
                    save();
                } catch (IOException e) {
K
kohsuke 已提交
920
                    LOGGER.log(Level.SEVERE, "Failed to save build record",e);
921
                }
K
kohsuke 已提交
922 923 924
            }

            try {
925
                getParent().logRotate();
K
kohsuke 已提交
926
            } catch (IOException e) {
K
kohsuke 已提交
927
                LOGGER.log(Level.SEVERE, "Failed to rotate log",e);
K
kohsuke 已提交
928 929 930 931 932 933 934
            }
        } finally {
            onEndBuilding();
        }
    }

    /**
K
kohsuke 已提交
935
     * Handles a fatal build problem (exception) that occurred during the build.
K
kohsuke 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
     */
    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;
    }

    /**
     * Called when a job finished building normally or abnormally.
     */
    protected void onEndBuilding() {
        state = State.COMPLETED;
        if(result==null) {
            // shouldn't happen, but be defensive until we figure out why
            result = Result.FAILURE;
            LOGGER.warning(toString()+": No build result is set, so marking as failure. This shouldn't happen");
        }
971
        RunListener.fireFinalized(this);
K
kohsuke 已提交
972 973 974 975 976 977
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
978
        if(BulkChange.contains(this))   return;
K
kohsuke 已提交
979 980 981 982 983 984 985 986 987 988
        getDataFile().write(this);
    }

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

    /**
     * Gets the log of the build as a string.
     *
989 990
     * @deprecated Use {@link #getLog(int)} instead as it avoids loading
     * the whole log into memory unnecessarily.
K
kohsuke 已提交
991
     */
992
    @Deprecated
K
kohsuke 已提交
993
    public String getLog() throws IOException {
994
        return Util.loadFile(getLogFile(),getCharset());
K
kohsuke 已提交
995 996
    }

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    /**
     * 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>();
1009
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getLogFile()),getCharset()));
K
kohsuke 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        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();
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
        }

        // 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 已提交
1034 1035 1036 1037 1038 1039
    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() {
1040
        return getIconColor().getImage();
K
kohsuke 已提交
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    }

    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)
                return new Summary(false,"stable");
            else
                return new Summary(false,"back to normal");
        }

        if(getResult()==Result.FAILURE) {
            RunT since = getPreviousNotFailedBuild();
            if(since==null)
                return new Summary(false,"broken for a long time");
            if(since==prev)
                return new Summary(true,"broken since this build");
J
jglick 已提交
1075
            return new Summary(false,"broken since "+since.getDisplayName());
K
kohsuke 已提交
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
        }

        if(getResult()==Result.ABORTED)
            return new Summary(false,"aborted");

        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)
K
kohsuke 已提交
1087
                        return new Summary(false,combine(trN.getFailCount(),"test failure"));
K
kohsuke 已提交
1088 1089 1090 1091
                    else // ???
                        return new Summary(false,"unstable");
                }
                if(trP.getFailCount()==0)
K
kohsuke 已提交
1092
                    return new Summary(true,combine(trN.getFailCount(),"test")+" started to fail");
K
kohsuke 已提交
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
                if(trP.getFailCount() < trN.getFailCount())
                    return new Summary(true,combine(trN.getFailCount()-trP.getFailCount(),"more test")
                        +" are failing ("+trN.getFailCount()+" total)");
                if(trP.getFailCount() > trN.getFailCount())
                    return new Summary(false,combine(trP.getFailCount()-trN.getFailCount(),"less test")
                        +" are failing ("+trN.getFailCount()+" total)");

                return new Summary(false,combine(trN.getFailCount(),"test")+" are still failing");
            }
        }

        return new Summary(false,"?");
    }

    /**
     * Serves the artifacts.
     */
K
kohsuke 已提交
1110
    public void doArtifact( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
K
kohsuke 已提交
1111 1112
        new DirectoryBrowserSupport(this,project.getDisplayName()+' '+getDisplayName())
            .serveFile(req, rsp, new FilePath(getArtifactsDir()), "package.gif", true);
K
kohsuke 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    }

    /**
     * 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 已提交
1125 1126 1127
    /**
     * Returns the build time stamp in the body.
     */
1128
    public void doBuildTimestamp( StaplerRequest req, StaplerResponse rsp, @QueryParameter String format) throws IOException {
K
kohsuke 已提交
1129 1130 1131
        rsp.setContentType("text/plain");
        rsp.setCharacterEncoding("US-ASCII");
        rsp.setStatus(HttpServletResponse.SC_OK);
K
kohsuke 已提交
1132 1133 1134
        DateFormat df = format==null ?
                DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.ENGLISH) :
                new SimpleDateFormat(format,req.getLocale());
K
kohsuke 已提交
1135 1136 1137
        rsp.getWriter().print(df.format(getTimestamp().getTime()));
    }

K
kohsuke 已提交
1138 1139 1140 1141
    /**
     * Handles incremental log output.
     */
    public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
1142
        new LargeText(getLogFile(),getCharset(),!isLogUpdated()).doProgressText(req,rsp);
K
kohsuke 已提交
1143 1144 1145
    }

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

K
kohsuke 已提交
1148
        keepLog(!keepLog);
K
kohsuke 已提交
1149 1150
        rsp.forwardToPreviousPage(req);
    }
K
kohsuke 已提交
1151 1152 1153 1154

    /**
     * Marks this build to keep the log.
     */
K
kohsuke 已提交
1155 1156 1157 1158 1159 1160
    public final void keepLog() throws IOException {
        keepLog(true);
    }

    public void keepLog(boolean newValue) throws IOException {
        keepLog = newValue;
K
kohsuke 已提交
1161 1162
        save();
    }
K
kohsuke 已提交
1163

1164 1165 1166 1167
    /**
     * Deletes the build when the button is pressed.
     */
    public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1168 1169
        checkPermission(DELETE);

1170 1171 1172
        // 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!
1173 1174
        String why = getWhyKeepLog();
        if (why!=null) {
K
i18n  
kohsuke 已提交
1175
            sendError(Messages.Run_UnableToDelete(toString(),why),req,rsp);
1176 1177 1178 1179 1180 1181
            return;
        }

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

K
kohsuke 已提交
1183
    public void setDescription(String description) throws IOException {
1184 1185
        checkPermission(UPDATE);
        this.description = description;
K
kohsuke 已提交
1186
        save();
1187 1188
    }
    
K
kohsuke 已提交
1189 1190 1191 1192 1193
    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");
1194
        setDescription(req.getParameter("description"));
K
kohsuke 已提交
1195 1196 1197 1198
        rsp.sendRedirect(".");  // go to the top page
    }

    /**
K
kohsuke 已提交
1199 1200
     * Returns the map that contains environmental variable overrides for this build.
     *
1201
     * <p>
K
kohsuke 已提交
1202 1203 1204 1205
     * {@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.
     *
1206 1207 1208 1209 1210 1211
     * <p>
     * On Windows systems, environment variables are case-preserving but
     * comparison/query is case insensitive (IOW, you can set 'Path' to something
     * and you get the same value by doing '%PATH%'.)  So to implement this semantics
     * the map returned from here is a {@link TreeMap} with a special comparator.
     *
K
kohsuke 已提交
1212 1213
     */
    public Map<String,String> getEnvVars() {
K
kohsuke 已提交
1214
        EnvVars env = new EnvVars();
K
kohsuke 已提交
1215 1216 1217
        env.put("BUILD_NUMBER",String.valueOf(number));
        env.put("BUILD_ID",getId());
        env.put("BUILD_TAG","hudson-"+getParent().getName()+"-"+number);
1218
        env.put("JOB_NAME",getParent().getFullName());
1219 1220 1221
        String rootUrl = Hudson.getInstance().getRootUrl();
        if(rootUrl!=null)
            env.put("HUDSON_URL", rootUrl);
K
kohsuke 已提交
1222 1223 1224 1225 1226 1227 1228

        Thread t = Thread.currentThread();
        if (t instanceof Executor) {
            Executor e = (Executor) t;
            env.put("EXECUTOR_NUMBER",String.valueOf(e.getNumber()));
        }

K
kohsuke 已提交
1229 1230 1231
        return env;
    }

H
huybrechts 已提交
1232
    public static final XStream XSTREAM = new XStream2();
K
kohsuke 已提交
1233
    static {
1234 1235 1236
        XSTREAM.alias("build",FreeStyleBuild.class);
        XSTREAM.alias("matrix-build",MatrixBuild.class);
        XSTREAM.alias("matrix-run",MatrixRun.class);
K
kohsuke 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
        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 已提交
1247 1248 1249 1250 1251
            long lt = lhs.getTimestamp().getTimeInMillis();
            long rt = rhs.getTimestamp().getTimeInMillis();
            if(lt>rt)   return -1;
            if(lt<rt)   return 1;
            return 0;
K
kohsuke 已提交
1252 1253 1254 1255 1256 1257
        }
    };

    /**
     * {@link FeedAdapter} to produce feed from the summary of this build.
     */
K
kohsuke 已提交
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
    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.
         */
        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 已提交
1285 1286
    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 已提交
1287 1288

    private static class DefaultFeedAdapter implements FeedAdapter<Run> {
K
kohsuke 已提交
1289 1290 1291 1292 1293 1294 1295 1296 1297
        public String getEntryTitle(Run entry) {
            return entry+" ("+entry.getResult()+")";
        }

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

        public String getEntryID(Run entry) {
1298 1299 1300
            return "tag:" + "hudson.dev.java.net,"
                + entry.getTimestamp().get(Calendar.YEAR) + ":"
                + entry.getParent().getName()+':'+entry.getId();
K
kohsuke 已提交
1301 1302
        }

1303 1304 1305 1306 1307
        public String getEntryDescription(Run entry) {
            // TODO: this could provide some useful details
            return null;
        }

K
kohsuke 已提交
1308 1309 1310
        public Calendar getEntryTimestamp(Run entry) {
            return entry.getTimestamp();
        }
1311 1312 1313 1314

        public String getEntryAuthor(Run entry) {
            return Mailer.DESCRIPTOR.getAdminAddress();
        }
1315
    }
1316 1317 1318 1319 1320 1321 1322

    @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 已提交
1323
            // may not have the action.. tell browsers to redirect up to the build page.
1324 1325 1326 1327 1328 1329
            result = new RedirectUp();
        return result;
    }

    public static class RedirectUp {
        public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException {
M
mindless 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
            // 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();
1342 1343
        }
    }
K
kohsuke 已提交
1344
}