Run.java 33.1 KB
Newer Older
K
kohsuke 已提交
1 2 3 4
package hudson.model;

import com.thoughtworks.xstream.XStream;
import hudson.CloseProofOutputStream;
K
kohsuke 已提交
5
import hudson.EnvVars;
K
kohsuke 已提交
6
import hudson.ExtensionPoint;
K
kohsuke 已提交
7
import hudson.FeedAdapter;
8
import hudson.FilePath;
K
kohsuke 已提交
9
import hudson.Util;
K
kohsuke 已提交
10
import static hudson.Util.combine;
K
kohsuke 已提交
11
import hudson.XmlFile;
12
import hudson.security.Permission;
K
kohsuke 已提交
13
import hudson.security.PermissionGroup;
14 15
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixRun;
16
import hudson.model.listeners.RunListener;
K
kohsuke 已提交
17
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
18
import hudson.tasks.BuildStep;
19
import hudson.tasks.LogRotator;
K
kohsuke 已提交
20 21 22 23 24
import hudson.tasks.test.AbstractTestResultAction;
import hudson.util.IOException2;
import hudson.util.XStream2;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
kohsuke 已提交
25
import org.kohsuke.stapler.QueryParameter;
K
kohsuke 已提交
26 27
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
K
kohsuke 已提交
28 29 30

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
31
import java.io.BufferedReader;
K
kohsuke 已提交
32 33
import java.io.File;
import java.io.FileOutputStream;
34
import java.io.FileReader;
K
kohsuke 已提交
35 36 37 38 39 40
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
K
kohsuke 已提交
41
import java.text.DateFormat;
K
kohsuke 已提交
42 43
import java.util.ArrayList;
import java.util.Calendar;
44
import java.util.Collections;
K
kohsuke 已提交
45 46
import java.util.Comparator;
import java.util.GregorianCalendar;
47
import java.util.LinkedList;
K
kohsuke 已提交
48 49
import java.util.List;
import java.util.Map;
50
import java.util.TreeMap;
K
kohsuke 已提交
51
import java.util.Locale;
52
import java.util.logging.Level;
K
kohsuke 已提交
53
import java.util.logging.Logger;
K
kohsuke 已提交
54 55 56 57 58 59 60 61 62 63

/**
 * 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 已提交
64
 * @see RunListener
K
kohsuke 已提交
65
 */
K
kohsuke 已提交
66
@ExportedBean
K
kohsuke 已提交
67
public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,RunT>>
68
        extends Actionable implements ExtensionPoint, Comparable<RunT> {
K
kohsuke 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

    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.
     */
    protected transient final Calendar timestamp;

    /**
     * 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 {
113 114 115
        /**
         * Build is created/queued but we haven't started building it.
         */
K
kohsuke 已提交
116
        NOT_STARTED,
117 118 119
        /**
         * Build is in progress.
         */
K
kohsuke 已提交
120
        BUILDING,
121 122 123 124 125 126 127 128
        /**
         * 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 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        COMPLETED
    }

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

    /**
     * Keeps this log entries.
     */
    private boolean keepLog;

    protected static final SimpleDateFormat ID_FORMATTER = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");

    /**
     * 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) {
        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 {
        this(project, new GregorianCalendar());
        try {
            this.timestamp.setTime(ID_FORMATTER.parse(buildDir.getName()));
        } catch (ParseException e) {
            throw new IOException2("Invalid directory name "+buildDir,e);
        } catch (NumberFormatException e) {
            throw new IOException2("Invalid directory name "+buildDir,e);
        }
        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
    }

179 180 181 182 183 184 185 186

    /**
     * Ordering based on build numbers.
     */
    public int compareTo(RunT that) {
        return this.number - that.number;
    }

K
kohsuke 已提交
187 188 189 190 191 192 193
    /**
     * 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 已提交
194
    @Exported
K
kohsuke 已提交
195
    public Result getResult() {
K
kohsuke 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208
        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;
209
            LOGGER.fine(toString()+" : result is set to "+r+" by "+caller);
K
kohsuke 已提交
210 211
        } else {
            if(r.isWorseThan(result)) {
212
                LOGGER.fine(toString()+" : result is set to "+r+" by "+caller);
K
kohsuke 已提交
213 214 215 216 217
                result = r;
            }
        }
    }

218
    /**
219
     * Gets the subset of {@link #getActions()} that consists of {@link BuildBadgeAction}s.
220 221 222 223 224 225 226 227 228 229
     */
    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);
            }
        }
230 231 232 233 234
        if(isKeepLog()) {
            if(r==null)
                r = new ArrayList<BuildBadgeAction>();
            r.add(new KeepLogBuildBadge());
        }
235 236 237 238
        if(r==null)     return Collections.emptyList();
        else            return r;
    }

K
kohsuke 已提交
239 240 241 242 243 244 245 246 247 248 249
    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.
250
     * This includes "not started yet" state.
K
kohsuke 已提交
251
     */
K
kohsuke 已提交
252
    @Exported
K
kohsuke 已提交
253
    public boolean isBuilding() {
254 255 256 257 258 259 260 261
        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 已提交
262 263 264 265 266 267 268 269 270
    }

    /**
     * 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()) {
271
                if(e.getCurrentExecutable()==this)
K
kohsuke 已提交
272 273 274 275 276 277 278 279 280 281 282
                    return e;
            }
        }
        return null;
    }

    /**
     * Returns true if this log file should be kept and not deleted.
     *
     * This is used as a signal to the {@link LogRotator}.
     */
K
kohsuke 已提交
283
    @Exported
284 285 286 287 288 289 290 291 292 293
    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 已提交
294
            return Messages.Run_MarkedExplicitly();
295
        return null;    // not marked at all
K
kohsuke 已提交
296 297 298 299 300 301 302 303 304 305 306 307
    }

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

    /**
     * When the build is scheduled.
     */
K
kohsuke 已提交
308
    @Exported
K
kohsuke 已提交
309
    public Calendar getTimestamp() {
310
        return (Calendar)timestamp.clone();
K
kohsuke 已提交
311 312
    }

K
kohsuke 已提交
313
    @Exported
K
kohsuke 已提交
314 315 316 317
    public String getDescription() {
        return description;
    }

318 319 320 321 322 323 324 325 326 327 328
    /**
     * 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 = "...";
329

330 331 332 333 334 335 336 337 338 339 340 341 342
        // 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 已提交
343 344 345 346 347 348 349 350
    /**
     * Gets the string that says how long since this build has scheduled.
     *
     * @return
     *      string like "3 minutes" "1 day" etc.
     */
    public String getTimestampString() {
        long duration = new GregorianCalendar().getTimeInMillis()-timestamp.getTimeInMillis();
K
i18n  
kohsuke 已提交
351
        return Util.getPastTimeString(duration);
K
kohsuke 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364
    }

    /**
     * Returns the timestamp formatted in xs:dateTime.
     */
    public String getTimestampString2() {
        return Util.XS_DATETIME_FORMATTER.format(timestamp.getTime());
    }

    /**
     * Gets the string that says how long the build took to run.
     */
    public String getDurationString() {
365 366
        if(isBuilding())
            return Util.getTimeSpanString(System.currentTimeMillis()-timestamp.getTimeInMillis())+" and counting";
K
kohsuke 已提交
367 368 369 370 371 372
        return Util.getTimeSpanString(duration);
    }

    /**
     * Gets the millisecond it took to build.
     */
K
kohsuke 已提交
373
    @Exported
K
kohsuke 已提交
374 375 376 377 378 379 380
    public long getDuration() {
        return duration;
    }

    /**
     * Gets the icon color for display.
     */
381
    public BallColor getIconColor() {
K
kohsuke 已提交
382 383
        if(!isBuilding()) {
            // already built
K
kohsuke 已提交
384
            return getResult().color;
K
kohsuke 已提交
385 386 387
        }

        // a new build is in progress
388
        BallColor baseColor;
K
kohsuke 已提交
389
        if(previousBuild==null)
390
            baseColor = BallColor.GREY;
K
kohsuke 已提交
391 392 393
        else
            baseColor = previousBuild.getIconColor();

394
        return baseColor.anime();
K
kohsuke 已提交
395 396 397 398 399 400 401 402 403 404
    }

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

    public String toString() {
405
        return project.getFullDisplayName()+" #"+number;
K
kohsuke 已提交
406 407 408 409 410 411
    }

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

K
kohsuke 已提交
412
    @Exported(visibility=2)
K
kohsuke 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    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()+'/';
    }

K
kohsuke 已提交
451
    @Exported(visibility=2,name="url")
452 453 454 455
    public final String getAbsoluteUrl() {
        return project.getAbsoluteUrl()+getNumber()+'/';
    }

456 457 458 459
    public final String getSearchUrl() {
        return getNumber()+"/";
    }

K
kohsuke 已提交
460 461 462 463 464 465 466
    /**
     * Unique ID of this build.
     */
    public String getId() {
        return ID_FORMATTER.format(timestamp.getTime());
    }

K
kohsuke 已提交
467 468 469 470 471
    /**
     * Root directory of this {@link Run} on the master.
     *
     * Files related to this {@link Run} should be stored below this directory.
     */
K
kohsuke 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 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 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    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()}.
     */
    public List<Artifact> getArtifacts() {
        List<Artifact> r = new ArrayList<Artifact>();
        addArtifacts(getArtifactsDir(),"",r);
        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();
    }

    private void addArtifacts( File dir, String path, List<Artifact> r ) {
        String[] children = dir.list();
        if(children==null)  return;
        for (String child : children) {
            if(r.size()>CUTOFF)
                return;
            File sub = new File(dir, child);
            if (sub.isDirectory()) {
                addArtifacts(sub, path + child + '/', r);
            } else {
                r.add(new Artifact(path + child));
            }
        }
    }

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

    /**
     * A build artifact.
     */
    public class Artifact {
        /**
         * Relative path name from {@link Run#getArtifactsDir()}
         */
        private final String relativePath;

        private Artifact(String relativePath) {
            this.relativePath = relativePath;
        }

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

        /**
         * Returns just the file name portion, without the path.
         */
        public String getFileName() {
            return getFile().getName();
        }

        public String toString() {
            return relativePath;
        }
    }

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

560 561
    protected SearchIndexBuilder makeSearchIndex() {
        return super.makeSearchIndex()
K
kohsuke 已提交
562 563
            .add("console")
            .add("changes");
564 565
    }

566 567 568 569
    public Api getApi(final StaplerRequest req) {
        return new Api(this);
    }

570 571 572 573 574
    public void checkPermission(Permission p) {
        // for now, don't maintain ACL per run, and do it at project level
        getParent().checkPermission(p);
    }

K
kohsuke 已提交
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    /**
     * Deletes this build and its entire log
     *
     * @throws IOException
     *      if we fail to delete.
     */
    public synchronized void delete() throws IOException {
        File rootDir = getRootDir();
        File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName());

        if(!rootDir.renameTo(tmp))
            throw new IOException(rootDir+" is in use");

        Util.deleteRecursive(tmp);

J
jglick 已提交
590 591 592 593
        removeRunFromParent();
    }
    @SuppressWarnings("unchecked") // seems this is too clever for Java's type system?
    private void removeRunFromParent() {
K
kohsuke 已提交
594 595 596 597
        getParent().removeRun((RunT)this);
    }

    protected static interface Runner {
598 599 600 601 602 603 604
        /**
         * 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 已提交
605

606 607
        /**
         * Performs the post-build action.
608
         * <p>
K
kohsuke 已提交
609 610 611 612 613
         * 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
614
         * by {@link Job#getLastSuccessfulBuild()}.
615
         */
616
        void post( BuildListener listener ) throws Exception;
617 618 619 620 621 622 623 624 625 626 627 628

        /**
         * 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 已提交
629 630
    }

631 632 633 634 635 636 637
    /**
     * 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 已提交
638 639 640 641
    protected final void run(Runner job) {
        if(result!=null)
            return;     // already built.

642 643 644
        BuildListener listener=null;
        PrintStream log = null;

K
kohsuke 已提交
645 646 647 648 649 650 651 652 653
        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 已提交
654 655
                    log = new PrintStream(new FileOutputStream(getLogFile()));
                    listener = new StreamBuildListener(new CloseProofOutputStream(log));
K
kohsuke 已提交
656 657 658

                    listener.started();

K
kohsuke 已提交
659
                    setResult(job.run(listener));
K
kohsuke 已提交
660 661 662 663

                    LOGGER.info(toString()+" main build action completed: "+result);
                } catch (ThreadDeath t) {
                    throw t;
664 665
                } catch( RunnerAbortedException e ) {
                    result = Result.FAILURE;
666 667 668
                } catch( InterruptedException e) {
                    // aborted
                    result = Result.ABORTED;
K
i18n  
kohsuke 已提交
669
                    listener.getLogger().println(Messages.Run_BuildAborted());
670
                    LOGGER.log(Level.INFO,toString()+" aborted",e);
K
kohsuke 已提交
671 672 673 674 675
                } catch( Throwable e ) {
                    handleFatalBuildProblem(listener,e);
                    result = Result.FAILURE;
                }

K
kohsuke 已提交
676
                // even if the main build fails fatally, try to run post build processing
K
kohsuke 已提交
677 678 679 680 681 682 683
                job.post(listener);

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

688
                // advance the state.
689 690 691 692
                // 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.
693
                state = State.POST_PRODUCTION;
694 695 696 697 698 699 700

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

702
                RunListener.fireCompleted(this,listener);
K
kohsuke 已提交
703

704 705 706 707
                if(listener!=null)
                    listener.finished(result);
                if(log!=null)
                    log.close();
K
kohsuke 已提交
708

709 710 711 712 713
                try {
                    save();
                } catch (IOException e) {
                    e.printStackTrace();
                }
K
kohsuke 已提交
714 715 716
            }

            try {
717
                getParent().logRotate();
K
kohsuke 已提交
718 719 720 721 722 723 724 725 726
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            onEndBuilding();
        }
    }

    /**
K
kohsuke 已提交
727
     * Handles a fatal build problem (exception) that occurred during the build.
K
kohsuke 已提交
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
     */
    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");
        }
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
        getDataFile().write(this);
    }

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

    /**
     * Gets the log of the build as a string.
     *
779 780
     * @deprecated Use {@link #getLog(int)} instead as it avoids loading
     * the whole log into memory unnecessarily.
K
kohsuke 已提交
781
     */
782
    @Deprecated
K
kohsuke 已提交
783 784 785 786
    public String getLog() throws IOException {
        return Util.loadFile(getLogFile());
    }

787 788 789 790 791 792 793 794 795 796 797 798 799
    /**
     * 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>();
        BufferedReader reader = new BufferedReader(new FileReader(getLogFile()));
800
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
            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);
        }

        // 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 已提交
820 821 822 823 824 825
    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() {
826
        return getIconColor().getImage();
K
kohsuke 已提交
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
    }

    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 已提交
861
            return new Summary(false,"broken since "+since.getDisplayName());
K
kohsuke 已提交
862 863 864 865 866 867 868 869 870 871 872
        }

        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 已提交
873
                        return new Summary(false,combine(trN.getFailCount(),"test failure"));
K
kohsuke 已提交
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
                    else // ???
                        return new Summary(false,"unstable");
                }
                if(trP.getFailCount()==0)
                    return new Summary(true,combine(trP.getFailCount(),"test")+" started to fail");
                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 已提交
896
    public void doArtifact( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
K
kohsuke 已提交
897 898
        new DirectoryBrowserSupport(this,project.getDisplayName()+' '+getDisplayName())
            .serveFile(req, rsp, new FilePath(getArtifactsDir()), "package.gif", true);
K
kohsuke 已提交
899 900 901 902 903 904 905 906 907 908 909 910
    }

    /**
     * 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 已提交
911 912 913 914 915 916 917
    /**
     * Returns the build time stamp in the body.
     */
    public void doBuildTimestamp( StaplerRequest req, StaplerResponse rsp, @QueryParameter("format") String format) throws IOException {
        rsp.setContentType("text/plain");
        rsp.setCharacterEncoding("US-ASCII");
        rsp.setStatus(HttpServletResponse.SC_OK);
K
kohsuke 已提交
918 919 920
        DateFormat df = format==null ?
                DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.ENGLISH) :
                new SimpleDateFormat(format,req.getLocale());
K
kohsuke 已提交
921 922 923
        rsp.getWriter().print(df.format(getTimestamp().getTime()));
    }

K
kohsuke 已提交
924 925 926 927
    /**
     * Handles incremental log output.
     */
    public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
928
        new LargeText(getLogFile(),!isLogUpdated()).doProgressText(req,rsp);
K
kohsuke 已提交
929 930 931
    }

    public void doToggleLogKeep( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
932
        checkPermission(UPDATE);
K
kohsuke 已提交
933 934 935 936 937

        keepLog = !keepLog;
        save();
        rsp.forwardToPreviousPage(req);
    }
K
kohsuke 已提交
938 939 940 941 942 943 944 945

    /**
     * Marks this build to keep the log.
     */
    public void keepLog() throws IOException {
        keepLog = true;
        save();
    }
946 947 948 949 950
    
    /**
     * Deletes the build when the button is pressed.
     */
    public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
951 952
        checkPermission(DELETE);

953 954 955
        // 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!
956 957
        String why = getWhyKeepLog();
        if (why!=null) {
K
i18n  
kohsuke 已提交
958
            sendError(Messages.Run_UnableToDelete(toString(),why),req,rsp);
959 960 961 962 963 964
            return;
        }

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

K
kohsuke 已提交
966
    public void setDescription(String description) throws IOException {
967 968
        checkPermission(UPDATE);
        this.description = description;
K
kohsuke 已提交
969
        save();
970 971
    }
    
K
kohsuke 已提交
972 973 974 975 976
    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");
977
        setDescription(req.getParameter("description"));
K
kohsuke 已提交
978 979 980 981 982
        rsp.sendRedirect(".");  // go to the top page
    }

    /**
     * Returns the map that contains environmental variables for this build.
983
     * <p>
K
kohsuke 已提交
984
     * Used by {@link BuildStep}s that invoke external processes.
985 986 987 988 989 990
     * <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 已提交
991 992
     */
    public Map<String,String> getEnvVars() {
K
kohsuke 已提交
993
        EnvVars env = new EnvVars();
K
kohsuke 已提交
994 995 996
        env.put("BUILD_NUMBER",String.valueOf(number));
        env.put("BUILD_ID",getId());
        env.put("BUILD_TAG","hudson-"+getParent().getName()+"-"+number);
997
        env.put("JOB_NAME",getParent().getFullName());
K
kohsuke 已提交
998 999 1000 1001 1002 1003 1004

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

K
kohsuke 已提交
1005 1006 1007 1008 1009
        return env;
    }

    private static final XStream XSTREAM = new XStream2();
    static {
1010 1011 1012
        XSTREAM.alias("build",FreeStyleBuild.class);
        XSTREAM.alias("matrix-build",MatrixBuild.class);
        XSTREAM.alias("matrix-run",MatrixRun.class);
K
kohsuke 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        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 已提交
1023 1024 1025 1026 1027
            long lt = lhs.getTimestamp().getTimeInMillis();
            long rt = rhs.getTimestamp().getTimeInMillis();
            if(lt>rt)   return -1;
            if(lt<rt)   return 1;
            return 0;
K
kohsuke 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
        }
    };

    /**
     * {@link FeedAdapter} to produce feed from the summary of this build.
     */
    public static final FeedAdapter<Run> FEED_ADAPTER = new FeedAdapter<Run>() {
        public String getEntryTitle(Run entry) {
            return entry+" ("+entry.getResult()+")";
        }

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

1043
        // produces a tag URL as per RFC 4151, required by Atom 1.0
K
kohsuke 已提交
1044
        public String getEntryID(Run entry) {
1045 1046 1047
            return "tag:" + "hudson.dev.java.net,"
                + entry.getTimestamp().get(Calendar.YEAR) + ":"
                + entry.getParent().getName()+':'+entry.getId();
K
kohsuke 已提交
1048 1049
        }

1050 1051 1052 1053 1054
        public String getEntryDescription(Run entry) {
            // TODO: this could provide some useful details
            return null;
        }

K
kohsuke 已提交
1055 1056 1057 1058
        public Calendar getEntryTimestamp(Run entry) {
            return entry.getTimestamp();
        }
    };
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

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

1070
    public static final PermissionGroup PERMISSIONS = new PermissionGroup(Run.class,Messages._Run_Permissions_Title());
K
kohsuke 已提交
1071 1072
    public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Permission.DELETE);
    public static final Permission UPDATE = new Permission(PERMISSIONS,"Update", Permission.UPDATE);
K
kohsuke 已提交
1073
}