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

import hudson.ExtensionPoint;
import hudson.Util;
K
kohsuke 已提交
5
import org.kohsuke.stapler.export.Exported;
6
import hudson.model.Descriptor.FormException;
K
kohsuke 已提交
7 8 9
import hudson.tasks.BuildTrigger;
import hudson.tasks.LogRotator;
import hudson.util.ChartUtil;
K
kohsuke 已提交
10
import hudson.util.ColorPalette;
11
import hudson.util.CopyOnWriteList;
K
kohsuke 已提交
12 13 14 15
import hudson.util.DataSetBuilder;
import hudson.util.IOException2;
import hudson.util.RunList;
import hudson.util.ShiftedCategoryAxis;
K
kohsuke 已提交
16
import hudson.util.StackedAreaRenderer2;
K
kohsuke 已提交
17 18 19 20 21 22 23 24 25 26
import hudson.util.TextFile;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
K
kohsuke 已提交
27
import org.jfree.chart.renderer.category.StackedAreaRenderer;
K
kohsuke 已提交
28 29
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleInsets;
K
kohsuke 已提交
30
import org.kohsuke.stapler.Header;
K
kohsuke 已提交
31 32 33 34
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

import javax.servlet.ServletException;
K
kohsuke 已提交
35
import javax.servlet.http.HttpServletResponse;
K
kohsuke 已提交
36
import java.awt.Color;
K
kohsuke 已提交
37
import java.awt.Paint;
K
kohsuke 已提交
38 39 40
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
41
import java.util.Collection;
K
kohsuke 已提交
42
import java.util.Collections;
K
kohsuke 已提交
43
import java.util.List;
44
import java.util.Map;
45
import java.util.SortedMap;
46
import java.text.ParseException;
K
kohsuke 已提交
47 48 49 50 51 52 53 54 55 56

/**
 * A job is an runnable entity under the monitoring of Hudson.
 *
 * <p>
 * Every time it "runs", it will be recorded as a {@link Run} object.
 *
 * @author Kohsuke Kawaguchi
 */
public abstract class Job<JobT extends Job<JobT,RunT>, RunT extends Run<JobT,RunT>>
57
        extends AbstractItem implements ExtensionPoint {
K
kohsuke 已提交
58 59

    /**
K
kohsuke 已提交
60
     * Next build number.
K
kohsuke 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73
     * Kept in a separate file because this is the only information
     * that gets updated often. This allows the rest of the configuration
     * to be in the VCS.
     * <p>
     * In 1.28 and earlier, this field was stored in the project configuration file,
     * so even though this is marked as transient, don't move it around.
     */
    protected transient int nextBuildNumber = 1;

    private LogRotator logRotator;

    private boolean keepDependencies;

74 75 76
    /**
     * List of {@link UserProperty}s configured for this project.
     */
K
kohsuke 已提交
77
    protected CopyOnWriteList<JobProperty<? super JobT>> properties = new CopyOnWriteList<JobProperty<? super JobT>>();
78

79 80
    protected Job(ItemGroup parent,String name) {
        super(parent,name);
K
kohsuke 已提交
81 82 83
        getBuildDir().mkdirs();
    }

84 85
    public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
        super.onLoad(parent, name);
K
kohsuke 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

        TextFile f = getNextBuildNumberFile();
        if(f.exists()) {
            // starting 1.28, we store nextBuildNumber in a separate file.
            // but old Hudson didn't do it, so if the file doesn't exist,
            // assume that nextBuildNumber was read from config.xml
            try {
                this.nextBuildNumber = Integer.parseInt(f.readTrim());
            } catch (NumberFormatException e) {
                throw new IOException2(f+" doesn't contain a number",e);
            }
        } else {
            // this must be the old Hudson. create this file now.
            saveNextBuildNumber();
            save(); // and delete it from the config.xml
        }
102 103 104

        if(properties==null) // didn't exist < 1.72
            properties = new CopyOnWriteList<JobProperty<? super JobT>>();
K
kohsuke 已提交
105 106 107

        for (JobProperty p : properties)
            p.setOwner(this);
K
kohsuke 已提交
108 109
    }

110 111 112 113 114 115
    @Override
    public void onCopiedFrom(Item src) {
        super.onCopiedFrom(src);
        this.nextBuildNumber = 1;     // reset the next build number
    }

K
kohsuke 已提交
116
    private TextFile getNextBuildNumberFile() {
117
        return new TextFile(new File(this.getRootDir(),"nextBuildNumber"));
K
kohsuke 已提交
118 119
    }

120
    protected void saveNextBuildNumber() throws IOException {
K
kohsuke 已提交
121 122 123
        getNextBuildNumberFile().write(String.valueOf(nextBuildNumber)+'\n');
    }

K
kohsuke 已提交
124
    @Exported
K
kohsuke 已提交
125 126 127 128
    public boolean isInQueue() {
        return false;
    }

K
kohsuke 已提交
129 130 131
    /**
     * If this job is in the build queue, return its item.
     */
K
kohsuke 已提交
132
    @Exported
K
kohsuke 已提交
133 134 135 136
    public Queue.Item getQueueItem() {
        return null;
    }

137 138 139 140 141 142 143 144
    /**
     * Get the term used in the UI to represent this kind of {@link AbstractProject}.
     * Must start with a capital letter.
     */
    public String getPronoun() {
        return "Project";
    }

145 146 147 148 149 150 151
    /**
     * Returns whether the name of this job can be changed by user.
     */
    public boolean isNameEditable() {
        return true;
    }

K
kohsuke 已提交
152 153 154
    /**
     * If true, it will keep all the build logs of dependency components.
     */
K
kohsuke 已提交
155
    @Exported
K
kohsuke 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168
    public boolean isKeepDependencies() {
        return keepDependencies;
    }

    /**
     * Allocates a new buildCommand number.
     */
    public synchronized int assignBuildNumber() throws IOException {
        int r = nextBuildNumber++;
        saveNextBuildNumber();
        return r;
    }

169 170 171
    /**
     * Peeks the next build number.
     */
K
kohsuke 已提交
172
    @Exported
K
kohsuke 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    public int getNextBuildNumber() {
        return nextBuildNumber;
    }

    /**
     * Returns the log rotator for this job, or null if none.
     */
    public LogRotator getLogRotator() {
        return logRotator;
    }

    public void setLogRotator(LogRotator logRotator) {
        this.logRotator = logRotator;
    }

188 189 190 191 192 193 194 195 196
    /**
     * Perform log rotation.
     */
    public void logRotate() throws IOException {
        LogRotator lr = getLogRotator();
        if(lr!=null)
            lr.perform(this);
    }

K
kohsuke 已提交
197 198 199 200 201 202 203
    /**
     * True if this instance supports log rotation configuration.
     */
    public boolean supportsLogRotator() {
        return true;
    }

204
    public Collection<? extends Job> getAllJobs() {
205 206 207
        return Collections.<Job>singleton(this);
    }

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    /**
     * Gets all the job properties configured for this job.
     */
    @SuppressWarnings("unchecked")
    public Map<JobPropertyDescriptor,JobProperty<? super JobT>> getProperties() {
        return Descriptor.toMap((Iterable)properties);
    }

    /**
     * Gets the specific property, or null if the propert is not configured for this job.
     */
    public <T extends JobProperty> T getProperty(Class<T> clazz) {
        for (JobProperty p : properties) {
            if(clazz.isInstance(p))
                return clazz.cast(p);
        }
        return null;
    }

K
kohsuke 已提交
227 228
    /**
     * Renames a job.
K
kohsuke 已提交
229 230 231 232
     *
     * <p>
     * This method is defined on {@link Job} but really only applicable
     * for {@link Job}s that are top-level items.
K
kohsuke 已提交
233 234 235
     */
    public void renameTo(String newName) throws IOException {
        // always synchronize from bigger objects first
236
        final Hudson parent = Hudson.getInstance();
K
kohsuke 已提交
237
        assert this instanceof TopLevelItem;
K
kohsuke 已提交
238 239 240 241 242
        synchronized(parent) {
            synchronized(this) {
                // sanity check
                if(newName==null)
                    throw new IllegalArgumentException("New name is not given");
243
                if(parent.getItem(newName)!=null)
K
kohsuke 已提交
244 245 246 247 248 249 250 251
                    throw new IllegalArgumentException("Job "+newName+" already exists");

                // noop?
                if(this.name.equals(newName))
                    return;


                String oldName = this.name;
252
                File oldRoot = this.getRootDir();
K
kohsuke 已提交
253 254

                doSetName(newName);
255
                File newRoot = this.getRootDir();
K
kohsuke 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

                {// rename data files
                    boolean interrupted=false;
                    boolean renamed = false;

                    // try to rename the job directory.
                    // this may fail on Windows due to some other processes accessing a file.
                    // so retry few times before we fall back to copy.
                    for( int retry=0; retry<5; retry++ ) {
                        if(oldRoot.renameTo(newRoot)) {
                            renamed = true;
                            break; // succeeded
                        }
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            // process the interruption later
                            interrupted = true;
                        }
                    }

                    if(interrupted)
                        Thread.currentThread().interrupt();

                    if(!renamed) {
                        // failed to rename. it must be that some lengthy process is going on
                        // to prevent a rename operation. So do a copy. Ideally we'd like to
                        // later delete the old copy, but we can't reliably do so, as before the VM
                        // shuts down there might be a new job created under the old name.
                        Copy cp = new Copy();
                        cp.setProject(new org.apache.tools.ant.Project());
                        cp.setTodir(newRoot);
                        FileSet src = new FileSet();
                        src.setDir(getRootDir());
                        cp.addFileset(src);
                        cp.setOverwrite(true);
                        cp.setPreserveLastModified(true);
                        cp.setFailOnError(false);   // keep going even if there's an error
                        cp.execute();

                        // try to delete as much as possible
                        try {
                            Util.deleteRecursive(oldRoot);
                        } catch (IOException e) {
                            // but ignore the error, since we expect that
                            e.printStackTrace();
                        }
                    }
                }

K
kohsuke 已提交
306
                parent.onRenamed((TopLevelItem)this,oldName,newName);
K
kohsuke 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

                // update BuildTrigger of other projects that point to this object.
                // can't we generalize this?
                for( Project p : parent.getProjects() ) {
                    BuildTrigger t = (BuildTrigger) p.getPublishers().get(BuildTrigger.DESCRIPTOR);
                    if(t!=null) {
                        if(t.onJobRenamed(oldName,newName))
                            p.save();
                    }
                }
            }
        }
    }

    /**
     * Returns true if we should display "build now" icon
     */
K
kohsuke 已提交
324
    @Exported
K
kohsuke 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    public abstract boolean isBuildable();

    /**
     * Gets all the builds.
     *
     * @return
     *      never null. The first entry is the latest buildCommand.
     */
    public List<RunT> getBuilds() {
        return new ArrayList<RunT>(_getRuns().values());
    }

    /**
     * Gets all the builds in a map.
     */
    public SortedMap<Integer,RunT> getBuildsAsMap() {
        return Collections.unmodifiableSortedMap(_getRuns());
    }

    /**
     * @deprecated
     *      This is only used to support backward compatibility with
     *      old URLs.
     */
J
jglick 已提交
349
    @Deprecated
K
kohsuke 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    public RunT getBuild(String id) {
        for (RunT r : _getRuns().values()) {
            if(r.getId().equals(id))
                return r;
        }
        return null;
    }

    /**
     * @param n
     *      The build number.
     * @see Run#getNumber()
     */
    public RunT getBuildByNumber(int n) {
        return _getRuns().get(n);
    }

K
kohsuke 已提交
367
    /**
K
kohsuke 已提交
368
     * Gets the youngest build #m that satisfies <tt>n&lt;=m</tt>.
K
kohsuke 已提交
369 370 371 372
     *
     * This is useful when you'd like to fetch a build but the exact build might be already
     * gone (deleted, rotated, etc.)
     */
K
kohsuke 已提交
373
    public final RunT getNearestBuild(int n) {
K
kohsuke 已提交
374
        SortedMap<Integer, ? extends RunT> m = _getRuns().headMap(n-1); // the map should include n, so n-1
K
kohsuke 已提交
375
        if(m.isEmpty()) return null;
376
        return m.get(m.lastKey());
K
kohsuke 已提交
377 378
    }

K
kohsuke 已提交
379 380 381 382 383 384 385 386 387 388 389 390
    /**
     * Gets the latest build #m that satisfies <tt>m&lt;=n</tt>.
     *
     * This is useful when you'd like to fetch a build but the exact build might be already
     * gone (deleted, rotated, etc.)
     */
    public final RunT getNearestOldBuild(int n) {
        SortedMap<Integer, ? extends RunT> m = _getRuns().tailMap(n);
        if(m.isEmpty()) return null;
        return m.get(m.firstKey());
    }

K
kohsuke 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
        try {
            // try to interpret the token as build number
            return _getRuns().get(Integer.valueOf(token));
        } catch (NumberFormatException e) {
            return super.getDynamic(token,req,rsp);
        }
    }

    /**
     * Directory for storing {@link Run} records.
     * <p>
     * Some {@link Job}s may not have backing data store for {@link Run}s,
     * but those {@link Job}s that use file system for storing data
     * should use this directory for consistency.
     *
     * @see RunMap
     */
    protected File getBuildDir() {
410
        return new File(getRootDir(),"builds");
K
kohsuke 已提交
411 412 413 414 415 416
    }

    /**
     * Gets all the runs.
     *
     * The resulting map must be immutable (by employing copy-on-write semantics.)
417
     * The map is descending order, with newest builds at the top.
K
kohsuke 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431
     */
    protected abstract SortedMap<Integer,? extends RunT> _getRuns();

    /**
     * Called from {@link Run} to remove it from this job.
     *
     * The files are deleted already. So all the callee needs to do
     * is to remove a reference from this {@link Job}.
     */
    protected abstract void removeRun(RunT run);

    /**
     * Returns the last build.
     */
K
kohsuke 已提交
432
    @Exported
K
kohsuke 已提交
433 434 435 436 437 438 439 440 441 442
    public RunT getLastBuild() {
        SortedMap<Integer,? extends RunT> runs = _getRuns();

        if(runs.isEmpty())    return null;
        return runs.get(runs.firstKey());
    }

    /**
     * Returns the oldest build in the record.
     */
K
kohsuke 已提交
443
    @Exported
K
kohsuke 已提交
444 445 446 447 448 449 450 451 452
    public RunT getFirstBuild() {
        SortedMap<Integer,? extends RunT> runs = _getRuns();

        if(runs.isEmpty())    return null;
        return runs.get(runs.lastKey());
    }

    /**
     * Returns the last successful build, if any. Otherwise null.
K
kohsuke 已提交
453
     * A stable build would include either {@link Result#SUCCESS} or {@link Result#UNSTABLE}.
454
     * @see #getLastStableBuild()
K
kohsuke 已提交
455
     */
K
kohsuke 已提交
456
    @Exported
K
kohsuke 已提交
457 458 459 460 461 462 463 464 465 466 467
    public RunT getLastSuccessfulBuild() {
        RunT r = getLastBuild();
        // temporary hack till we figure out what's causing this bug
        while(r!=null && (r.isBuilding() || r.getResult()==null || r.getResult().isWorseThan(Result.UNSTABLE)))
            r=r.getPreviousBuild();
        return r;
    }

    /**
     * Returns the last stable build, if any. Otherwise null.
     */
K
kohsuke 已提交
468
    @Exported
K
kohsuke 已提交
469 470 471 472 473 474 475 476 477 478
    public RunT getLastStableBuild() {
        RunT r = getLastBuild();
        while(r!=null && (r.isBuilding() || r.getResult().isWorseThan(Result.SUCCESS)))
            r=r.getPreviousBuild();
        return r;
    }

    /**
     * Returns the last failed build, if any. Otherwise null.
     */
K
kohsuke 已提交
479
    @Exported
K
kohsuke 已提交
480 481 482 483 484 485 486 487 488 489
    public RunT getLastFailedBuild() {
        RunT r = getLastBuild();
        while(r!=null && (r.isBuilding() || r.getResult()!=Result.FAILURE))
            r=r.getPreviousBuild();
        return r;
    }

    /**
     * Used as the color of the status ball for the project.
     */
K
kohsuke 已提交
490
    @Exported(visibility=2,name="color")
491
    public BallColor getIconColor() {
K
kohsuke 已提交
492 493 494 495 496 497 498
        RunT lastBuild = getLastBuild();
        while(lastBuild!=null && lastBuild.hasntStartedYet())
            lastBuild = lastBuild.getPreviousBuild();

        if(lastBuild!=null)
            return lastBuild.getIconColor();
        else
499
            return BallColor.GREY;
K
kohsuke 已提交
500 501
    }

S
stephenconnolly 已提交
502 503 504 505 506
    /**
     * Get the current health report for a job.
     * @return
     *     the health report.  Never returns null
     */
507
    public HealthReport getBuildHealth() {
S
stephenconnolly 已提交
508 509 510
        HealthReport buildHealth = null;

        RunT lastBuild = getLastBuild();
511 512 513 514 515 516

        if (lastBuild != null && lastBuild.isBuilding()) {
            // show the previous build's report until the current one is finished building.            
            lastBuild = lastBuild.getPreviousBuild();
        }

S
stephenconnolly 已提交
517 518 519
        if (lastBuild != null) {

            for (HealthReportingAction healthReportingAction : lastBuild.getActions(HealthReportingAction.class)) {
520
                buildHealth = HealthReport.min(buildHealth, healthReportingAction.getBuildHealth());
521
            }
S
stephenconnolly 已提交
522 523

            // if all else fails, use the stability health report.
524
            buildHealth = HealthReport.min(buildHealth, getBuildStabilityHealthReport());
525
        }
S
stephenconnolly 已提交
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 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

        if (buildHealth == null)
            buildHealth = new HealthReport();
        return buildHealth;
    }

    private HealthReport getBuildStabilityHealthReport() {
        // we can give a simple view of build health from the last five builds
        int failCount = 0;
        int totalCount = 0;
        RunT i = getLastBuild();
        while (totalCount < 5 && i != null) {
            switch (i.getIconColor()) {
                case BLUE:
                case YELLOW:
                    //failCount stays the same
                    totalCount++;
                    break;
                case RED:
                    failCount++;
                    totalCount++;
                    break;

                default:
                    // do nothing as these are inconclusive statuses
                    break;
            }
            i = i.getPreviousBuild();
        }
        if (totalCount > 0) {
            int score = (int) ((100.0 * (totalCount - failCount)) / totalCount);
            if (score < 100 && score > 0) {
                // HACK
                // force e.g. 4/5 to be in the 60-79 range
                score--;
            }

            StringBuilder description = new StringBuilder("Build stability: ");
            if (failCount == 0) {
                description.append("No recent builds failed.");
            } else if (totalCount == failCount) {
                // this should catch the case where totalCount == 1
                // as failCount must be between 0 and totalCount
                // and we can't get here if failCount == 0
                description.append("All recent builds failed.");
            } else {
                description.append(failCount);
                description.append(" out of the last ");
                description.append(totalCount);
                description.append(" builds failed.");
            }
            return new HealthReport(score,  description.toString());
        }
        return null;
580
    }
K
kohsuke 已提交
581 582 583 584 585 586 587 588 589

//
//
// actions
//
//
    /**
     * Accepts submission from the configuration page.
     */
590 591
    public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        if (!Hudson.adminCheck(req, rsp))
K
kohsuke 已提交
592 593 594 595 596 597
            return;

        req.setCharacterEncoding("UTF-8");

        description = req.getParameter("description");

598
        if (req.getParameter("logrotate") != null)
K
kohsuke 已提交
599 600 601 602
            logRotator = LogRotator.DESCRIPTOR.newInstance(req);
        else
            logRotator = null;

603
        keepDependencies = req.getParameter("keepDependencies") != null;
K
kohsuke 已提交
604

605 606
        try {
            properties.clear();
K
kohsuke 已提交
607
            for (JobPropertyDescriptor d : JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass())) {
608
                JobProperty prop = d.newInstance(req);
K
kohsuke 已提交
609 610
                if (prop != null) {
                    prop.setOwner(this);
611
                    properties.add(prop);
K
kohsuke 已提交
612
                }
613
            }
614 615 616 617 618 619 620

            submit(req,rsp);

            save();

            String newName = req.getParameter("name");
            if(newName!=null && !newName.equals(name)) {
K
kohsuke 已提交
621 622 623 624 625 626 627
                // check this error early to avoid HTTP response splitting.
                try {
                    Hudson.checkGoodName(newName);
                } catch (ParseException e) {
                    sendError(e,req,rsp);
                    return;
                }
628 629 630 631
                rsp.sendRedirect("rename?newName="+newName);
            } else {
                rsp.sendRedirect(".");
            }
632
        } catch (FormException e) {
633
            sendError(e,req,rsp);
634
        }
635
    }
K
kohsuke 已提交
636

637 638 639 640
    /**
     * Derived class can override this to perform additional config submission work.
     */
    protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
K
kohsuke 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
    }

    /**
     * Returns the image that shows the current buildCommand status.
     */
    public void doBuildStatus( StaplerRequest req, StaplerResponse rsp ) throws IOException {
        rsp.sendRedirect2(req.getContextPath()+"/nocacheImages/48x48/"+getBuildStatusUrl());
    }

    public String getBuildStatusUrl() {
        return getIconColor()+".gif";
    }

    /**
     * Returns the graph that shows how long each build took.
     */
    public void doBuildTimeGraph( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
658 659 660 661
        if(getLastBuild()==null) {
            rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
K
kohsuke 已提交
662 663
        if(req.checkIfModified(getLastBuild().getTimestamp(),rsp))
            return;
K
kohsuke 已提交
664 665 666
        ChartUtil.generateGraph(req,rsp, createBuildTimeTrendChart(),500,400);
    }

K
kohsuke 已提交
667 668 669 670
    /**
     * Returns the clickable map for the build time graph.
     * Loaded lazily by AJAX.
     */
K
kohsuke 已提交
671
    public void doBuildTimeGraphMap( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
672 673 674 675
        if(getLastBuild()==null) {
            rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
K
kohsuke 已提交
676 677
        if(req.checkIfModified(getLastBuild().getTimestamp(),rsp))
            return;
K
kohsuke 已提交
678 679 680 681
        ChartUtil.generateClickableMap(req,rsp, createBuildTimeTrendChart(),500,400);
    }

    private JFreeChart createBuildTimeTrendChart() {
682
        class ChartLabel implements Comparable<ChartLabel> {
K
kohsuke 已提交
683
            final Run run;
K
kohsuke 已提交
684

685
            public ChartLabel(Run r) {
K
kohsuke 已提交
686 687 688
                this.run = r;
            }

689
            public int compareTo(ChartLabel that) {
K
kohsuke 已提交
690 691 692 693
                return this.run.number-that.run.number;
            }

            public boolean equals(Object o) {
694
                ChartLabel that = (ChartLabel) o;
K
kohsuke 已提交
695 696 697
                return run ==that.run;
            }

K
kohsuke 已提交
698
            public Color getColor() {
K
kohsuke 已提交
699
                // TODO: consider gradation. See http://www.javadrive.jp/java2d/shape/index9.html
K
kohsuke 已提交
700 701 702 703 704 705 706
                Result r = run.getResult();
                if(r ==Result.FAILURE || r== Result.ABORTED)
                    return ColorPalette.RED;
                else
                    return ColorPalette.BLUE;
            }

K
kohsuke 已提交
707 708 709 710 711 712 713 714 715 716 717 718 719
            public int hashCode() {
                return run.hashCode();
            }

            public String toString() {
                String l = run.getDisplayName();
                if(run instanceof Build) {
                    String s = ((Build)run).getBuiltOnStr();
                    if(s!=null)
                        l += ' '+s;
                }
                return l;
            }
K
kohsuke 已提交
720

K
kohsuke 已提交
721 722
        }

723
        DataSetBuilder<String,ChartLabel> data = new DataSetBuilder<String, ChartLabel>();
K
kohsuke 已提交
724 725
        for( Run r : getBuilds() ) {
            if(r.isBuilding())  continue;
726
            data.add( ((double)r.getDuration())/(1000*60), "mins", new ChartLabel(r));
K
kohsuke 已提交
727
        }
K
kohsuke 已提交
728

K
kohsuke 已提交
729
        final CategoryDataset dataset = data.build();
K
kohsuke 已提交
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

        final JFreeChart chart = ChartFactory.createStackedAreaChart(
            null,                   // chart title
            null,                   // unused
            "min",                  // range axis label
            dataset,                  // data
            PlotOrientation.VERTICAL, // orientation
            false,                     // include legend
            true,                     // tooltips
            false                     // urls
        );

        chart.setBackgroundPaint(Color.white);

        final CategoryPlot plot = chart.getCategoryPlot();

        // plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
        plot.setBackgroundPaint(Color.WHITE);
        plot.setOutlinePaint(null);
        plot.setForegroundAlpha(0.8f);
//        plot.setDomainGridlinesVisible(true);
//        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.black);

        CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
        plot.setDomainAxis(domainAxis);
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        domainAxis.setLowerMargin(0.0);
        domainAxis.setUpperMargin(0.0);
        domainAxis.setCategoryMargin(0.0);

        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

K
kohsuke 已提交
765 766
        StackedAreaRenderer ar = new StackedAreaRenderer2() {
            @Override
K
kohsuke 已提交
767
            public Paint getItemPaint(int row, int column) {
768
                ChartLabel key = (ChartLabel) dataset.getColumnKey(column);
K
kohsuke 已提交
769 770
                return key.getColor();
            }
K
kohsuke 已提交
771 772 773

            @Override
            public String generateURL(CategoryDataset dataset, int row, int column) {
774
                ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
K
kohsuke 已提交
775
                return String.valueOf(label.run.number);
K
kohsuke 已提交
776
            }
K
kohsuke 已提交
777 778

            @Override
K
kohsuke 已提交
779
            public String generateToolTip(CategoryDataset dataset, int row, int column) {
780
                ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
K
kohsuke 已提交
781
                return label.run.getDisplayName() + " : " + label.run.getDurationString();
K
kohsuke 已提交
782
            }
K
kohsuke 已提交
783
        };
K
kohsuke 已提交
784
        plot.setRenderer(ar);
K
kohsuke 已提交
785 786 787 788

        // crop extra space around the graph
        plot.setInsets(new RectangleInsets(0,0,0,5.0));

K
kohsuke 已提交
789
        return chart;
K
kohsuke 已提交
790 791 792 793 794
    }

    /**
     * Renames this job.
     */
795
    public /*not synchronized. see renameTo()*/ void doDoRename( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
K
kohsuke 已提交
796 797 798 799
        if(!Hudson.adminCheck(req,rsp))
            return;

        String newName = req.getParameter("newName");
800 801 802 803 804 805
        try {
            Hudson.checkGoodName(newName);
        } catch (ParseException e) {
            sendError(e,req,rsp);
            return;
        }
K
kohsuke 已提交
806 807 808 809 810

        renameTo(newName);
        rsp.sendRedirect2(req.getContextPath()+'/'+getUrl()); // send to the new job page
    }

811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
    /**
     * Handles AJAX requests from browsers to update build history.
     *
     * @param n
     *      The build number to fetch
     */
    public void doAjaxBuildHistoryUpdate( StaplerRequest req, StaplerResponse rsp,
                  @Header("n") int n ) throws IOException, ServletException {

        rsp.setContentType("text/html;charset=UTF-8");

        // pick up builds to send back
        Collection<? extends RunT> builds = _getRuns().headMap(n-1).values();

        req.setAttribute("builds",builds);

        int next = getNextBuildNumber();
        if(!builds.isEmpty()) {
            RunT b = builds.iterator().next();
            next = b.getNumber();
            if(!b.isBuilding())  next++;
        }
        rsp.setHeader("n",String.valueOf(next));

        req.getView(this,"ajaxBuildHistory.jelly").forward(req,rsp);
    }

K
kohsuke 已提交
838 839 840 841 842 843 844 845 846 847 848 849
    public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        rss(req, rsp, " all builds", new RunList(this));
    }
    public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        rss(req, rsp, " failed builds", new RunList(this).failureOnly());
    }

    private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
        RSS.forwardToRss(getDisplayName()+ suffix, getUrl(),
            runs.newBuilds(), Run.FEED_ADAPTER, req, rsp );
    }
}