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

3
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
K
kohsuke 已提交
4
import hudson.ExtensionPoint;
5
import hudson.StructuredForm;
6
import hudson.Util;
7
import hudson.XmlFile;
8
import hudson.model.Descriptor.FormException;
9
import hudson.model.listeners.ItemListener;
10
import hudson.search.QuickSilver;
K
kohsuke 已提交
11
import hudson.search.SearchIndex;
12
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
13 14
import hudson.search.SearchItem;
import hudson.search.SearchItems;
K
kohsuke 已提交
15
import hudson.tasks.LogRotator;
16
import hudson.util.AtomicFileWriter;
K
kohsuke 已提交
17
import hudson.util.ChartUtil;
K
kohsuke 已提交
18
import hudson.util.ColorPalette;
19
import hudson.util.CopyOnWriteList;
K
kohsuke 已提交
20 21 22 23
import hudson.util.DataSetBuilder;
import hudson.util.IOException2;
import hudson.util.RunList;
import hudson.util.ShiftedCategoryAxis;
K
kohsuke 已提交
24
import hudson.util.StackedAreaRenderer2;
K
kohsuke 已提交
25
import hudson.util.TextFile;
26
import hudson.widgets.HistoryWidget;
27
import hudson.widgets.Widget;
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
import hudson.widgets.HistoryWidget.Adapter;

import java.awt.Color;
import java.awt.Paint;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

50
import net.sf.json.JSONObject;
51

K
kohsuke 已提交
52 53 54 55 56 57 58 59 60
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 已提交
61
import org.jfree.chart.renderer.category.StackedAreaRenderer;
K
kohsuke 已提交
62 63 64 65
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleInsets;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
66
import org.kohsuke.stapler.WebMethod;
K
kohsuke 已提交
67
import org.kohsuke.stapler.export.Exported;
K
kohsuke 已提交
68 69 70 71 72 73 74 75 76 77

/**
 * 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>>
78
        extends AbstractItem implements ExtensionPoint {
K
kohsuke 已提交
79 80

    /**
K
kohsuke 已提交
81
     * Next build number.
K
kohsuke 已提交
82 83 84 85 86 87 88 89 90 91
     * 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;
92 93 94 95 96 97 98
    
    /**
     * Not all plugins are good at calculating their health report quickly.
     * These fields are used to cache the health reports to speed up rendering the main page.
     */
    private transient Integer cachedBuildHealthReportsBuildNumber = null;
    private transient List<HealthReport> cachedBuildHealthReports = null;
K
kohsuke 已提交
99 100 101

    private boolean keepDependencies;

102 103 104
    /**
     * List of {@link UserProperty}s configured for this project.
     */
K
kohsuke 已提交
105
    protected CopyOnWriteList<JobProperty<? super JobT>> properties = new CopyOnWriteList<JobProperty<? super JobT>>();
106

107 108
    protected Job(ItemGroup parent,String name) {
        super(parent,name);
K
kohsuke 已提交
109 110
    }

111 112
    public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
        super.onLoad(parent, name);
K
kohsuke 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

        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
        }
129 130 131

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

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

137 138 139 140 141 142
    @Override
    public void onCopiedFrom(Item src) {
        super.onCopiedFrom(src);
        this.nextBuildNumber = 1;     // reset the next build number
    }

K
kohsuke 已提交
143
    private TextFile getNextBuildNumberFile() {
144
        return new TextFile(new File(this.getRootDir(),"nextBuildNumber"));
K
kohsuke 已提交
145 146
    }

147
    protected void saveNextBuildNumber() throws IOException {
K
kohsuke 已提交
148 149 150
        getNextBuildNumberFile().write(String.valueOf(nextBuildNumber)+'\n');
    }

K
kohsuke 已提交
151
    @Exported
K
kohsuke 已提交
152 153 154 155
    public boolean isInQueue() {
        return false;
    }

K
kohsuke 已提交
156 157 158
    /**
     * If this job is in the build queue, return its item.
     */
K
kohsuke 已提交
159
    @Exported
K
kohsuke 已提交
160 161 162 163
    public Queue.Item getQueueItem() {
        return null;
    }

164 165 166 167 168
    /**
     * Get the term used in the UI to represent this kind of {@link AbstractProject}.
     * Must start with a capital letter.
     */
    public String getPronoun() {
K
i18n  
kohsuke 已提交
169
        return Messages.Job_Pronoun();
170 171
    }

172 173 174 175 176 177 178
    /**
     * Returns whether the name of this job can be changed by user.
     */
    public boolean isNameEditable() {
        return true;
    }

K
kohsuke 已提交
179 180 181
    /**
     * If true, it will keep all the build logs of dependency components.
     */
K
kohsuke 已提交
182
    @Exported
K
kohsuke 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195
    public boolean isKeepDependencies() {
        return keepDependencies;
    }

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

196 197 198
    /**
     * Peeks the next build number.
     */
K
kohsuke 已提交
199
    @Exported
K
kohsuke 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    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;
    }

215 216 217 218 219 220 221 222 223
    /**
     * Perform log rotation.
     */
    public void logRotate() throws IOException {
        LogRotator lr = getLogRotator();
        if(lr!=null)
            lr.perform(this);
    }

K
kohsuke 已提交
224 225 226 227 228 229 230
    /**
     * True if this instance supports log rotation configuration.
     */
    public boolean supportsLogRotator() {
        return true;
    }

K
kohsuke 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    protected SearchIndexBuilder makeSearchIndex() {
        return super.makeSearchIndex()
            .add(new SearchIndex() {
                public void find(String token, List<SearchItem> result) {
                    try {
                        if(token.startsWith("#"))   token=token.substring(1);   // ignore leading '#'
                        int n = Integer.parseInt(token);
                        Run b = getBuildByNumber(n);
                        if(b==null) return; // no such build
                        result.add(SearchItems.create("#"+n,""+n,b));
                    } catch (NumberFormatException e) {
                        // not a number.
                    }
                }

                public void suggest(String token, List<SearchItem> result) {
                    find(token,result);
                }
K
kohsuke 已提交
249
            }).add("configure","config","configure");
K
kohsuke 已提交
250 251
    }

252
    public Collection<? extends Job> getAllJobs() {
253 254 255
        return Collections.<Job>singleton(this);
    }

256 257 258 259 260 261 262 263
    /**
     * Adds {@link JobProperty}.
     * @since 1.188
     */
    public void addProperty(JobProperty<? super JobT> jobProp) throws IOException {
        properties.add(jobProp);
        save();
    }
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    /**
     * 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;
    }

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    public List<Widget> getWidgets() {
        ArrayList<Widget> r = new ArrayList<Widget>();
        r.add(createHistoryWidget());
        return r;
    }

    protected HistoryWidget createHistoryWidget() {
        return new HistoryWidget<Job,RunT>(this,getBuilds(),HISTORY_ADAPTER);
    }

    protected static final HistoryWidget.Adapter<Run> HISTORY_ADAPTER = new Adapter<Run>() {
        public int compare(Run record, String key) {
            return record.getNumber()-Integer.parseInt(key);
        }

        public String getKey(Run record) {
            return String.valueOf(record.getNumber());
        }

        public boolean isBuilding(Run record) {
            return record.isBuilding();
        }

        public String getNextKey(String key) {
            return String.valueOf(Integer.parseInt(key)+1);
        }
    };

K
kohsuke 已提交
311 312
    /**
     * Renames a job.
K
kohsuke 已提交
313 314 315 316
     *
     * <p>
     * This method is defined on {@link Job} but really only applicable
     * for {@link Job}s that are top-level items.
K
kohsuke 已提交
317 318 319
     */
    public void renameTo(String newName) throws IOException {
        // always synchronize from bigger objects first
320
        final Hudson parent = Hudson.getInstance();
K
kohsuke 已提交
321
        assert this instanceof TopLevelItem;
K
kohsuke 已提交
322 323 324 325 326
        synchronized(parent) {
            synchronized(this) {
                // sanity check
                if(newName==null)
                    throw new IllegalArgumentException("New name is not given");
327
                if(parent.getItem(newName)!=null)
K
kohsuke 已提交
328 329 330 331 332 333 334 335
                    throw new IllegalArgumentException("Job "+newName+" already exists");

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


                String oldName = this.name;
336
                File oldRoot = this.getRootDir();
K
kohsuke 已提交
337 338

                doSetName(newName);
339
                File newRoot = this.getRootDir();
K
kohsuke 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

                {// 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 已提交
390
                parent.onRenamed((TopLevelItem)this,oldName,newName);
K
kohsuke 已提交
391

392 393
                for (ItemListener l : Hudson.getInstance().getJobListeners())
                    l.onRenamed(this,oldName,newName);
K
kohsuke 已提交
394 395 396 397 398 399 400
            }
        }
    }

    /**
     * Returns true if we should display "build now" icon
     */
K
kohsuke 已提交
401
    @Exported
K
kohsuke 已提交
402 403 404 405 406 407
    public abstract boolean isBuildable();

    /**
     * Gets all the builds.
     *
     * @return
K
kohsuke 已提交
408
     *      never null. The first entry is the latest build.
K
kohsuke 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
     */
    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 已提交
426
    @Deprecated
K
kohsuke 已提交
427 428 429 430 431 432 433 434 435 436 437
    public RunT getBuild(String id) {
        for (RunT r : _getRuns().values()) {
            if(r.getId().equals(id))
                return r;
        }
        return null;
    }

    /**
     * @param n
     *      The build number.
K
kohsuke 已提交
438 439
     * @return
     *      null if no such build exists.
K
kohsuke 已提交
440 441 442 443 444 445
     * @see Run#getNumber()
     */
    public RunT getBuildByNumber(int n) {
        return _getRuns().get(n);
    }

K
kohsuke 已提交
446
    /**
K
kohsuke 已提交
447
     * Gets the youngest build #m that satisfies <tt>n&lt;=m</tt>.
K
kohsuke 已提交
448 449 450 451
     *
     * This is useful when you'd like to fetch a build but the exact build might be already
     * gone (deleted, rotated, etc.)
     */
K
kohsuke 已提交
452
    public final RunT getNearestBuild(int n) {
K
kohsuke 已提交
453
        SortedMap<Integer, ? extends RunT> m = _getRuns().headMap(n-1); // the map should include n, so n-1
K
kohsuke 已提交
454
        if(m.isEmpty()) return null;
455
        return m.get(m.lastKey());
K
kohsuke 已提交
456 457
    }

K
kohsuke 已提交
458 459 460 461 462 463 464 465 466 467 468 469
    /**
     * 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 已提交
470 471 472 473 474
    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) {
475 476 477 478 479 480
            // try to map that to widgets
            for (Widget w : getWidgets()) {
                if(w.getUrlName().equals(token))
                    return w;
            }
            
K
kohsuke 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494
            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() {
495
        return new File(getRootDir(),"builds");
K
kohsuke 已提交
496 497 498 499 500 501
    }

    /**
     * Gets all the runs.
     *
     * The resulting map must be immutable (by employing copy-on-write semantics.)
502
     * The map is descending order, with newest builds at the top.
K
kohsuke 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516
     */
    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.
     */
517
    @Exported @QuickSilver
K
kohsuke 已提交
518 519 520 521 522 523 524 525 526 527
    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.
     */
528
    @Exported @QuickSilver
K
kohsuke 已提交
529 530 531 532 533 534 535 536 537
    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 已提交
538
     * A stable build would include either {@link Result#SUCCESS} or {@link Result#UNSTABLE}.
539
     * @see #getLastStableBuild()
K
kohsuke 已提交
540
     */
541
    @Exported @QuickSilver
K
kohsuke 已提交
542 543 544 545 546 547 548 549 550 551 552
    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.
     */
553
    @Exported @QuickSilver
K
kohsuke 已提交
554 555 556 557 558 559 560 561 562 563
    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.
     */
564
    @Exported @QuickSilver
K
kohsuke 已提交
565 566 567 568 569 570 571 572 573 574
    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 已提交
575
    @Exported(visibility=2,name="color")
576
    public BallColor getIconColor() {
K
kohsuke 已提交
577 578 579 580 581 582 583
        RunT lastBuild = getLastBuild();
        while(lastBuild!=null && lastBuild.hasntStartedYet())
            lastBuild = lastBuild.getPreviousBuild();

        if(lastBuild!=null)
            return lastBuild.getIconColor();
        else
584
            return BallColor.GREY;
K
kohsuke 已提交
585 586
    }

S
stephenconnolly 已提交
587 588 589 590 591
    /**
     * Get the current health report for a job.
     * @return
     *     the health report.  Never returns null
     */
592
    public HealthReport getBuildHealth() {
593 594 595
        List<HealthReport> reports = getBuildHealthReports();
        return reports.isEmpty() ? new HealthReport() : reports.get(0);
    }
S
stephenconnolly 已提交
596

597
    @Exported(name="healthReport")
598 599
    public List<HealthReport> getBuildHealthReports() {
        List<HealthReport> reports = new ArrayList<HealthReport>();
S
stephenconnolly 已提交
600
        RunT lastBuild = getLastBuild();
601 602

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

607 608 609 610 611 612 613
        // check the cache
        if (cachedBuildHealthReportsBuildNumber != null && 
                cachedBuildHealthReports != null &&
                lastBuild != null &&
                cachedBuildHealthReportsBuildNumber.intValue() == lastBuild.getNumber()) {
            reports.addAll(cachedBuildHealthReports);
        } else if (lastBuild != null) {
S
stephenconnolly 已提交
614
            for (HealthReportingAction healthReportingAction : lastBuild.getActions(HealthReportingAction.class)) {
615 616
                final HealthReport report = healthReportingAction.getBuildHealth();
                if (report != null) {
617 618 619 620 621
                    if (report.isAggregateReport()) {
                        reports.addAll(report.getAggregatedReports());
                    } else {
                        reports.add(report);
                    }
622 623 624 625
                }
            }
            final HealthReport report = getBuildStabilityHealthReport();
            if (report != null) {
626 627 628 629 630
                if (report.isAggregateReport()) {
                    reports.addAll(report.getAggregatedReports());
                } else {
                    reports.add(report);
                }
631
            }
632 633 634 635 636 637

            Collections.sort(reports);
    
            // store the cache
            cachedBuildHealthReportsBuildNumber = lastBuild.getNumber();
            cachedBuildHealthReports = new ArrayList<HealthReport>(reports);
638
        }
S
stephenconnolly 已提交
639

640
        return reports;
S
stephenconnolly 已提交
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
    }

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

K
i18n  
kohsuke 已提交
674
            String description;
S
stephenconnolly 已提交
675
            if (failCount == 0) {
K
i18n  
kohsuke 已提交
676
                description = Messages.Job_NoRecentBuildFailed();
S
stephenconnolly 已提交
677 678 679 680
            } 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
K
i18n  
kohsuke 已提交
681
                description = Messages.Job_AllRecentBuildFailed();
S
stephenconnolly 已提交
682
            } else {
K
i18n  
kohsuke 已提交
683
                description = Messages.Job_NOfMFailed(failCount,totalCount);
S
stephenconnolly 已提交
684
            }
K
i18n  
kohsuke 已提交
685
            return new HealthReport(score, Messages.Job_BuildStability(description));
S
stephenconnolly 已提交
686 687
        }
        return null;
688
    }
K
kohsuke 已提交
689 690 691 692 693 694 695 696 697

//
//
// actions
//
//
    /**
     * Accepts submission from the configuration page.
     */
698
    public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
699
        checkPermission(CONFIGURE);
K
kohsuke 已提交
700 701 702 703 704

        req.setCharacterEncoding("UTF-8");

        description = req.getParameter("description");

705
        if (req.getParameter("logrotate") != null)
K
kohsuke 已提交
706 707 708 709
            logRotator = LogRotator.DESCRIPTOR.newInstance(req);
        else
            logRotator = null;

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

712 713
        try {
            properties.clear();
714 715 716 717

            JSONObject json = StructuredForm.get(req);

            int i=0;
K
kohsuke 已提交
718
            for (JobPropertyDescriptor d : JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass())) {
719 720
                String name = "jobProperty"+(i++);
                JobProperty prop = d.newInstance(req,json.getJSONObject(name));
K
kohsuke 已提交
721 722
                if (prop != null) {
                    prop.setOwner(this);
723
                    properties.add(prop);
K
kohsuke 已提交
724
                }
725
            }
726 727 728 729 730 731 732

            submit(req,rsp);

            save();

            String newName = req.getParameter("name");
            if(newName!=null && !newName.equals(name)) {
K
kohsuke 已提交
733 734 735 736 737 738 739
                // check this error early to avoid HTTP response splitting.
                try {
                    Hudson.checkGoodName(newName);
                } catch (ParseException e) {
                    sendError(e,req,rsp);
                    return;
                }
740 741 742 743
                rsp.sendRedirect("rename?newName="+newName);
            } else {
                rsp.sendRedirect(".");
            }
744
        } catch (FormException e) {
745
            sendError(e,req,rsp);
746
        }
747
    }
K
kohsuke 已提交
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
    /**
     * Accepts <tt>config.xml</tt> submission, as well as serve it.
     */
    @WebMethod(name="config.xml")
    public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException {
        checkPermission(CONFIGURE);

        if(req.getMethod().equals("GET")) {
            // read
            rsp.setContentType("application/xml;charset=UTF-8");
            getConfigFile().writeRawTo(rsp.getWriter());
            return;
        }
        if(req.getMethod().equals("POST")) {
            // submission
            XmlFile configXmlFile = getConfigFile();
            AtomicFileWriter out = new AtomicFileWriter(configXmlFile.getFile());

            try {
                // this allows us to use UTF-8 for storing data,
                // plus it checks any well-formedness issue in the submitted data
                Transformer t = TransformerFactory.newInstance().newTransformer();
                t.transform(new StreamSource(req.getReader()),new StreamResult(out));
                out.close();
            } catch (TransformerException e) {
                throw new IOException2("Failed to persist configuration.xml",e);
            }

            // try to reflect the changes by reloading
778
            new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this);
779 780 781 782 783 784 785 786 787 788 789
            onLoad(getParent(),getName());

            // if everything went well, commit this new version
            out.commit();
            return;
        }

        // huh?
        rsp.sendError(SC_BAD_REQUEST);
    }

790 791 792 793
    /**
     * Derived class can override this to perform additional config submission work.
     */
    protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
K
kohsuke 已提交
794 795 796 797 798 799 800 801 802 803
    }

    /**
     * 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() {
804
        return getIconColor().getImage();
K
kohsuke 已提交
805 806 807 808 809 810
    }

    /**
     * Returns the graph that shows how long each build took.
     */
    public void doBuildTimeGraph( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
811 812 813 814
        if(getLastBuild()==null) {
            rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
K
kohsuke 已提交
815 816
        if(req.checkIfModified(getLastBuild().getTimestamp(),rsp))
            return;
K
kohsuke 已提交
817 818 819
        ChartUtil.generateGraph(req,rsp, createBuildTimeTrendChart(),500,400);
    }

K
kohsuke 已提交
820 821 822 823
    /**
     * Returns the clickable map for the build time graph.
     * Loaded lazily by AJAX.
     */
K
kohsuke 已提交
824
    public void doBuildTimeGraphMap( StaplerRequest req, StaplerResponse rsp ) throws IOException {
K
kohsuke 已提交
825 826 827 828
        if(getLastBuild()==null) {
            rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
K
kohsuke 已提交
829 830
        if(req.checkIfModified(getLastBuild().getTimestamp(),rsp))
            return;
K
kohsuke 已提交
831 832 833 834
        ChartUtil.generateClickableMap(req,rsp, createBuildTimeTrendChart(),500,400);
    }

    private JFreeChart createBuildTimeTrendChart() {
835
        class ChartLabel implements Comparable<ChartLabel> {
K
kohsuke 已提交
836
            final Run run;
K
kohsuke 已提交
837

838
            public ChartLabel(Run r) {
K
kohsuke 已提交
839 840 841
                this.run = r;
            }

842
            public int compareTo(ChartLabel that) {
K
kohsuke 已提交
843 844 845 846
                return this.run.number-that.run.number;
            }

            public boolean equals(Object o) {
847
                ChartLabel that = (ChartLabel) o;
K
kohsuke 已提交
848 849 850
                return run ==that.run;
            }

K
kohsuke 已提交
851
            public Color getColor() {
K
kohsuke 已提交
852
                // TODO: consider gradation. See http://www.javadrive.jp/java2d/shape/index9.html
K
kohsuke 已提交
853 854 855 856 857 858 859
                Result r = run.getResult();
                if(r ==Result.FAILURE || r== Result.ABORTED)
                    return ColorPalette.RED;
                else
                    return ColorPalette.BLUE;
            }

K
kohsuke 已提交
860 861 862 863 864 865 866 867 868 869 870 871 872
            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 已提交
873

K
kohsuke 已提交
874 875
        }

876
        DataSetBuilder<String,ChartLabel> data = new DataSetBuilder<String, ChartLabel>();
K
kohsuke 已提交
877 878
        for( Run r : getBuilds() ) {
            if(r.isBuilding())  continue;
K
i18n  
kohsuke 已提交
879
            data.add( ((double)r.getDuration())/(1000*60), "min", new ChartLabel(r));
K
kohsuke 已提交
880
        }
K
kohsuke 已提交
881

K
kohsuke 已提交
882
        final CategoryDataset dataset = data.build();
K
kohsuke 已提交
883 884 885 886

        final JFreeChart chart = ChartFactory.createStackedAreaChart(
            null,                   // chart title
            null,                   // unused
K
i18n  
kohsuke 已提交
887
            Messages.Job_minutes(),   // range axis label
K
kohsuke 已提交
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
            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();
916
        ChartUtil.adjustChebyshev(dataset,rangeAxis);
K
kohsuke 已提交
917 918
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

K
kohsuke 已提交
919 920
        StackedAreaRenderer ar = new StackedAreaRenderer2() {
            @Override
K
kohsuke 已提交
921
            public Paint getItemPaint(int row, int column) {
922
                ChartLabel key = (ChartLabel) dataset.getColumnKey(column);
K
kohsuke 已提交
923 924
                return key.getColor();
            }
K
kohsuke 已提交
925 926 927

            @Override
            public String generateURL(CategoryDataset dataset, int row, int column) {
928
                ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
K
kohsuke 已提交
929
                return String.valueOf(label.run.number);
K
kohsuke 已提交
930
            }
K
kohsuke 已提交
931 932

            @Override
K
kohsuke 已提交
933
            public String generateToolTip(CategoryDataset dataset, int row, int column) {
934
                ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
K
kohsuke 已提交
935
                return label.run.getDisplayName() + " : " + label.run.getDurationString();
K
kohsuke 已提交
936
            }
K
kohsuke 已提交
937
        };
K
kohsuke 已提交
938
        plot.setRenderer(ar);
K
kohsuke 已提交
939 940 941 942

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

K
kohsuke 已提交
943
        return chart;
K
kohsuke 已提交
944 945 946 947 948
    }

    /**
     * Renames this job.
     */
949
    public /*not synchronized. see renameTo()*/ void doDoRename( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
950 951 952
        // rename is essentially delete followed by a create
        checkPermission(CREATE);
        checkPermission(DELETE);
K
kohsuke 已提交
953 954

        String newName = req.getParameter("newName");
955 956 957 958 959 960
        try {
            Hudson.checkGoodName(newName);
        } catch (ParseException e) {
            sendError(e,req,rsp);
            return;
        }
K
kohsuke 已提交
961 962

        renameTo(newName);
K
kohsuke 已提交
963 964 965
        // send to the new job page
        // note we can't use getUrl() because that would pick up old name in the Ancestor.getUrl()
        rsp.sendRedirect2(req.getContextPath()+'/'+getParent().getUrl()+getShortUrl());
K
kohsuke 已提交
966 967 968 969 970 971 972 973 974 975 976 977 978 979
    }

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