Job.java 45.0 KB
Newer Older
K
kohsuke 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * The MIT License
 * 
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt, Matthew R. Harrah, Red Hat, Inc., Stephen Connolly, Tom Huybrechts
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
K
kohsuke 已提交
24 25
package hudson.model;

26
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
27 28
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;

K
kohsuke 已提交
29
import hudson.ExtensionPoint;
30
import hudson.Util;
31
import hudson.XmlFile;
32
import hudson.PermalinkList;
33
import hudson.Extension;
34
import hudson.cli.declarative.CLIResolver;
35
import hudson.model.Descriptor.FormException;
36
import hudson.model.listeners.ItemListener;
37
import hudson.model.PermalinkProjectAction.Permalink;
K
kohsuke 已提交
38 39
import hudson.model.Fingerprint.RangeSet;
import hudson.model.Fingerprint.Range;
40
import hudson.search.QuickSilver;
K
kohsuke 已提交
41
import hudson.search.SearchIndex;
42
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
43 44
import hudson.search.SearchItem;
import hudson.search.SearchItems;
45
import hudson.security.ACL;
K
kohsuke 已提交
46
import hudson.tasks.LogRotator;
47
import hudson.util.AtomicFileWriter;
K
kohsuke 已提交
48
import hudson.util.ChartUtil;
K
kohsuke 已提交
49
import hudson.util.ColorPalette;
50
import hudson.util.CopyOnWriteList;
K
kohsuke 已提交
51 52 53 54
import hudson.util.DataSetBuilder;
import hudson.util.IOException2;
import hudson.util.RunList;
import hudson.util.ShiftedCategoryAxis;
K
kohsuke 已提交
55
import hudson.util.StackedAreaRenderer2;
K
kohsuke 已提交
56
import hudson.util.TextFile;
57
import hudson.util.Graph;
58
import hudson.widgets.HistoryWidget;
59
import hudson.widgets.Widget;
60 61 62 63 64 65
import hudson.widgets.HistoryWidget.Adapter;

import java.awt.Color;
import java.awt.Paint;
import java.io.File;
import java.io.IOException;
66 67
import java.io.StringWriter;
import java.io.PrintWriter;
68
import java.net.URLEncoder;
69
import java.text.ParseException;
K
kohsuke 已提交
70
import java.util.AbstractList;
71 72 73
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
K
kohsuke 已提交
74
import java.util.Comparator;
75
import java.util.Date;
76 77 78
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
K
kohsuke 已提交
79
import java.util.LinkedList;
80 81 82 83 84 85 86 87

import javax.servlet.ServletException;
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;

88
import net.sf.json.JSONObject;
89
import net.sf.json.JSONException;
90

K
kohsuke 已提交
91 92 93 94 95 96 97 98 99
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 已提交
100
import org.jfree.chart.renderer.category.StackedAreaRenderer;
K
kohsuke 已提交
101 102
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleInsets;
103
import org.jvnet.localizer.Localizable;
104
import org.kohsuke.stapler.QueryParameter;
K
kohsuke 已提交
105 106
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
107
import org.kohsuke.stapler.WebMethod;
K
kohsuke 已提交
108
import org.kohsuke.stapler.export.Exported;
109 110
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
K
kohsuke 已提交
111 112
import org.koshuke.stapler.simile.timeline.Event;
import org.koshuke.stapler.simile.timeline.TimelineEventList;
K
kohsuke 已提交
113 114 115

/**
 * A job is an runnable entity under the monitoring of Hudson.
116
 * 
K
kohsuke 已提交
117 118
 * <p>
 * Every time it "runs", it will be recorded as a {@link Run} object.
K
kohsuke 已提交
119 120
 *
 * <p>
K
kohsuke 已提交
121
 * To create a custom job type, extend {@link TopLevelItemDescriptor} and put {@link Extension} on it.
K
kohsuke 已提交
122
 *
K
kohsuke 已提交
123 124
 * @author Kohsuke Kawaguchi
 */
125
public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, RunT>>
K
TAB->WS  
kohsuke 已提交
126 127 128 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
        extends AbstractItem implements ExtensionPoint {

    /**
     * Next build number. 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 volatile int nextBuildNumber = 1;

    private volatile LogRotator logRotator;

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

    private boolean keepDependencies;

    /**
     * List of {@link UserProperty}s configured for this project.
     */
    protected CopyOnWriteList<JobProperty<? super JobT>> properties = new CopyOnWriteList<JobProperty<? super JobT>>();

    protected Job(ItemGroup parent, String name) {
        super(parent, name);
    }

159
    @Override
K
TAB->WS  
kohsuke 已提交
160 161 162 163 164 165 166 167 168 169
    public void onLoad(ItemGroup<? extends Item> parent, String name)
            throws IOException {
        super.onLoad(parent, name);

        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 {
D
dty 已提交
170 171 172
                synchronized (this) {
                    this.nextBuildNumber = Integer.parseInt(f.readTrim());
                }
K
TAB->WS  
kohsuke 已提交
173 174 175 176
            } catch (NumberFormatException e) {
                throw new IOException2(f + " doesn't contain a number", e);
            }
        } else {
177
            // From the old Hudson, or doCreateItem. Create this file now.
K
TAB->WS  
kohsuke 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191
            saveNextBuildNumber();
            save(); // and delete it from the config.xml
        }

        if (properties == null) // didn't exist < 1.72
            properties = new CopyOnWriteList<JobProperty<? super JobT>>();

        for (JobProperty p : properties)
            p.setOwner(this);
    }

    @Override
    public void onCopiedFrom(Item src) {
        super.onCopiedFrom(src);
D
dty 已提交
192 193 194
        synchronized (this) {
            this.nextBuildNumber = 1; // reset the next build number
        }
K
TAB->WS  
kohsuke 已提交
195 196
    }

197
    @Override
198
    protected void performDelete() throws IOException, InterruptedException {
K
TAB->WS  
kohsuke 已提交
199 200 201 202 203 204 205 206 207 208 209 210
        // if a build is in progress. Cancel it.
        RunT lb = getLastBuild();
        if (lb != null) {
            Executor e = lb.getExecutor();
            if (e != null) {
                e.interrupt();
                // should we block until the build is cancelled?
            }
        }
        super.performDelete();
    }

D
dty 已提交
211
    /*package*/ TextFile getNextBuildNumberFile() {
K
TAB->WS  
kohsuke 已提交
212 213 214
        return new TextFile(new File(this.getRootDir(), "nextBuildNumber"));
    }

D
dty 已提交
215
    protected synchronized void saveNextBuildNumber() throws IOException {
216 217 218
        if (nextBuildNumber == 0) { // #3361
            nextBuildNumber = 1;
        }
K
TAB->WS  
kohsuke 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        getNextBuildNumberFile().write(String.valueOf(nextBuildNumber) + '\n');
    }

    @Exported
    public boolean isInQueue() {
        return false;
    }

    /**
     * If this job is in the build queue, return its item.
     */
    @Exported
    public Queue.Item getQueueItem() {
        return null;
    }

235 236 237 238 239 240 241 242
    /**
     * Returns true if a build of this project is in progress.
     */
    public boolean isBuilding() {
        RunT b = getLastBuild();
        return b!=null && b.isBuilding();
    }

K
TAB->WS  
kohsuke 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 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
    /**
     * Get the term used in the UI to represent this kind of
     * {@link AbstractProject}. Must start with a capital letter.
     */
    public String getPronoun() {
        return Messages.Job_Pronoun();
    }

    /**
     * Returns whether the name of this job can be changed by user.
     */
    public boolean isNameEditable() {
        return true;
    }

    /**
     * If true, it will keep all the build logs of dependency components.
     */
    @Exported
    public boolean isKeepDependencies() {
        return keepDependencies;
    }

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

    /**
     * Peeks the next build number.
     */
    @Exported
    public int getNextBuildNumber() {
        return nextBuildNumber;
    }

    /**
     * Programatically updates the next build number.
     * 
     * <p>
     * Much of Hudson assumes that the build number is unique and monotonic, so
     * this method can only accept a new value that's bigger than
     * {@link #getNextBuildNumber()} returns. Otherwise it'll be no-op.
     * 
     * @since 1.199 (before that, this method was package private.)
     */
D
dty 已提交
293
    public synchronized void updateNextBuildNumber(int next) throws IOException {
K
TAB->WS  
kohsuke 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
        if (next > nextBuildNumber) {
            this.nextBuildNumber = next;
            saveNextBuildNumber();
        }
    }

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

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

    /**
     * Perform log rotation.
     */
314
    public void logRotate() throws IOException, InterruptedException {
K
TAB->WS  
kohsuke 已提交
315 316 317 318 319 320 321 322 323 324 325 326
        LogRotator lr = getLogRotator();
        if (lr != null)
            lr.perform(this);
    }

    /**
     * True if this instance supports log rotation configuration.
     */
    public boolean supportsLogRotator() {
        return true;
    }

327
    @Override
K
TAB->WS  
kohsuke 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    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);
            }
        }).add("configure", "config", "configure");
    }

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

    /**
     * Adds {@link JobProperty}.
     * 
     * @since 1.188
     */
K
kohsuke 已提交
359
    public void addProperty(JobProperty<? super JobT> jobProp) throws IOException {
360
        ((JobProperty)jobProp).setOwner(this);
K
TAB->WS  
kohsuke 已提交
361 362 363 364
        properties.add(jobProp);
        save();
    }

K
kohsuke 已提交
365 366 367 368 369 370 371 372 373 374
    /**
     * Removes {@link JobProperty}
     *
     * @since 1.279
     */
    public void removeProperty(JobProperty<? super JobT> jobProp) throws IOException {
        properties.remove(jobProp);
        save();
    }

K
kohsuke 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    /**
     * Removes the property of the given type.
     *
     * @return
     *      The property that was just removed.
     * @since 1.279
     */
    public <T extends JobProperty> T removeProperty(Class<T> clazz) throws IOException {
        for (JobProperty<? super JobT> p : properties) {
            if (clazz.isInstance(p)) {
                removeProperty(p);
                return clazz.cast(p);
            }
        }
        return null;
    }

K
TAB->WS  
kohsuke 已提交
392 393 394 395 396 397 398 399
    /**
     * Gets all the job properties configured for this job.
     */
    @SuppressWarnings("unchecked")
    public Map<JobPropertyDescriptor, JobProperty<? super JobT>> getProperties() {
        return Descriptor.toMap((Iterable) properties);
    }

400 401 402 403 404 405 406 407 408
    /**
     * List of all {@link JobProperty} exposed primarily for the remoting API.
     * @since 1.282
     */
    @Exported(name="property",inline=true)
    public List<JobProperty<? super JobT>> getAllProperties() {
        return properties.getView();
    }

K
TAB->WS  
kohsuke 已提交
409 410 411 412 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 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    /**
     * 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;
    }

    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) {
            try {
                int k = Integer.parseInt(key);
                return record.getNumber() - k;
            } catch (NumberFormatException nfe) {
                return String.valueOf(record.getNumber()).compareTo(key);
            }
        }

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

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

        public String getNextKey(String key) {
            try {
                int k = Integer.parseInt(key);
                return String.valueOf(k + 1);
            } catch (NumberFormatException nfe) {
                return "-unable to determine next key-";
            }
        }
    };

    /**
     * Renames a job.
     * 
     * <p>
     * This method is defined on {@link Job} but really only applicable for
     * {@link Job}s that are top-level items.
     */
    public void renameTo(String newName) throws IOException {
        // always synchronize from bigger objects first
        final Hudson parent = Hudson.getInstance();
        assert this instanceof TopLevelItem;
        synchronized (parent) {
            synchronized (this) {
                // sanity check
                if (newName == null)
                    throw new IllegalArgumentException("New name is not given");
475 476 477 478 479
                TopLevelItem existing = parent.getItem(newName);
                if (existing != null && existing!=this)
                    // the look up is case insensitive, so we need "existing!=this"
                    // to allow people to rename "Foo" to "foo", for example.
                    // see http://www.nabble.com/error-on-renaming-project-tt18061629.html
K
TAB->WS  
kohsuke 已提交
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
                    throw new IllegalArgumentException("Job " + newName
                            + " already exists");

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

                String oldName = this.name;
                File oldRoot = this.getRootDir();

                doSetName(newName);
                File newRoot = this.getRootDir();

                boolean success = false;

                try {// 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();
                        }
                    }

                    success = true;
                } finally {
                    // if failed, back out the rename.
                    if (!success)
                        doSetName(oldName);
                }

                parent.onRenamed((TopLevelItem) this, oldName, newName);

558
                for (ItemListener l : ItemListener.all())
K
TAB->WS  
kohsuke 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
                    l.onRenamed(this, oldName, newName);
            }
        }
    }

    /**
     * Returns true if we should display "build now" icon
     */
    @Exported
    public abstract boolean isBuildable();

    /**
     * Gets all the builds.
     * 
     * @return never null. The first entry is the latest build.
     */
575
    @Exported
K
TAB->WS  
kohsuke 已提交
576 577 578 579
    public List<RunT> getBuilds() {
        return new ArrayList<RunT>(_getRuns().values());
    }

K
kohsuke 已提交
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    /**
     * Obtains all the {@link Run}s whose build numbers matches the given {@link RangeSet}.
     */
    public synchronized List<RunT> getBuilds(RangeSet rs) {
        List<RunT> builds = new LinkedList<RunT>();

        for (Range r : rs.getRanges()) {
            for (RunT b = getNearestBuild(r.start); b!=null && b.getNumber()<r.end; b=b.getNextBuild()) {
                builds.add(b);
            }
        }

        return builds;
    }

K
TAB->WS  
kohsuke 已提交
595 596 597 598 599 600 601 602
    /**
     * Gets all the builds in a map.
     */
    public SortedMap<Integer, RunT> getBuildsAsMap() {
        return Collections.unmodifiableSortedMap(_getRuns());
    }

    /**
M
mindless 已提交
603 604
     * @deprecated since 2008-06-15.
     *     This is only used to support backward compatibility with old URLs.
K
TAB->WS  
kohsuke 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
     */
    @Deprecated
    public RunT getBuild(String id) {
        for (RunT r : _getRuns().values()) {
            if (r.getId().equals(id))
                return r;
        }
        return null;
    }

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

K
kohsuke 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
    /**
     * Obtains a list of builds, in the descending order, that are within the specified time range [start,end).
     *
     * @return can be empty but never null.
     */
    public List<RunT> getBuildsByTimestamp(long start, long end) {
        final List<RunT> builds = getBuilds();
        AbstractList<Long> TIMESTAMP_ADAPTER = new AbstractList<Long>() {
            public Long get(int index) {
                return builds.get(index).timestamp;
            }

            public int size() {
                return builds.size();
            }
        };
        Comparator<Long> DESCENDING_ORDER = new Comparator<Long>() {
            public int compare(Long o1, Long o2) {
                if (o1 > o2) return -1;
                if (o1 < o2) return +1;
                return 0;
            }
        };

        int s = Collections.binarySearch(TIMESTAMP_ADAPTER, start, DESCENDING_ORDER);
        if (s<0)    s=-(s+1);   // min is inclusive
        int e = Collections.binarySearch(TIMESTAMP_ADAPTER, end,   DESCENDING_ORDER);
        if (e<0)    e=-(e+1);   else e++;   // max is exclusive, so the exact match should be excluded

        return builds.subList(e,s);
    }

657 658 659 660 661 662
    @CLIResolver
    public RunT getBuildForCLI(@Argument(required=true,metaVar="BUILD#",usage="Build number") String id) throws CmdLineException {
        try {
            int n = Integer.parseInt(id);
            RunT r = getBuildByNumber(n);
            if (r==null)
M
mindless 已提交
663
                throw new CmdLineException(null, "No such build '#"+n+"' exists");
664 665
            return r;
        } catch (NumberFormatException e) {
M
mindless 已提交
666
            throw new CmdLineException(null, id+ "is not a number");
667 668 669
        }
    }

K
TAB->WS  
kohsuke 已提交
670 671 672 673 674 675 676
    /**
     * Gets the youngest build #m that satisfies <tt>n&lt;=m</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 getNearestBuild(int n) {
677 678
        SortedMap<Integer, ? extends RunT> m = _getRuns().headMap(n - 1); // the map should
                                                                          // include n, so n-1
K
TAB->WS  
kohsuke 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
        if (m.isEmpty())
            return null;
        return m.get(m.lastKey());
    }

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

697
    @Override
K
TAB->WS  
kohsuke 已提交
698 699 700 701 702 703 704 705 706 707 708 709
    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) {
            // try to map that to widgets
            for (Widget w : getWidgets()) {
                if (w.getUrlName().equals(token))
                    return w;
            }

710 711
            // is this a permalink?
            for (Permalink p : getPermalinks()) {
712
                if(p.getId().equals(token))
713 714 715
                    return p.resolve(this);
            }

K
TAB->WS  
kohsuke 已提交
716 717 718 719 720 721 722 723 724 725 726 727 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
            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() {
        return new File(getRootDir(), "builds");
    }

    /**
     * Gets all the runs.
     * 
     * The resulting map must be immutable (by employing copy-on-write
     * semantics.) The map is descending order, with newest builds at the top.
     */
    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.
     */
    @Exported
    @QuickSilver
    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.
     */
    @Exported
    @QuickSilver
    public RunT getFirstBuild() {
        SortedMap<Integer, ? extends RunT> runs = _getRuns();

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

    /**
J
jglick 已提交
776
     * Returns the last successful build, if any. Otherwise null. A successful build
K
TAB->WS  
kohsuke 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
     * would include either {@link Result#SUCCESS} or {@link Result#UNSTABLE}.
     * 
     * @see #getLastStableBuild()
     */
    @Exported
    @QuickSilver
    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.
J
jglick 已提交
795
     * @see #getLastSuccessfulBuild
K
TAB->WS  
kohsuke 已提交
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
     */
    @Exported
    @QuickSilver
    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.
     */
    @Exported
    @QuickSilver
    public RunT getLastFailedBuild() {
        RunT r = getLastBuild();
        while (r != null && (r.isBuilding() || r.getResult() != Result.FAILURE))
            r = r.getPreviousBuild();
        return r;
    }

    /**
     * Returns the last completed build, if any. Otherwise null.
     */
    @Exported
    @QuickSilver
    public RunT getLastCompletedBuild() {
        RunT r = getLastBuild();
        while (r != null && r.isBuilding())
            r = r.getPreviousBuild();
        return r;
    }

831 832
    /**
     * Gets all the {@link Permalink}s defined for this job.
833 834
     *
     * @return never null
835
     */
836
    public PermalinkList getPermalinks() {
837
        // TODO: shall we cache this?
838
        PermalinkList permalinks = new PermalinkList(Permalink.BUILTIN);
839 840 841 842 843 844 845 846 847
        for (Action a : getActions()) {
            if (a instanceof PermalinkProjectAction) {
                PermalinkProjectAction ppa = (PermalinkProjectAction) a;
                permalinks.addAll(ppa.getPermalinks());
            }
        }
        return permalinks;
    }

K
TAB->WS  
kohsuke 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 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 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
    /**
     * Used as the color of the status ball for the project.
     */
    @Exported(visibility = 2, name = "color")
    public BallColor getIconColor() {
        RunT lastBuild = getLastBuild();
        while (lastBuild != null && lastBuild.hasntStartedYet())
            lastBuild = lastBuild.getPreviousBuild();

        if (lastBuild != null)
            return lastBuild.getIconColor();
        else
            return BallColor.GREY;
    }

    /**
     * Get the current health report for a job.
     * 
     * @return the health report. Never returns null
     */
    public HealthReport getBuildHealth() {
        List<HealthReport> reports = getBuildHealthReports();
        return reports.isEmpty() ? new HealthReport() : reports.get(0);
    }

    @Exported(name = "healthReport")
    public List<HealthReport> getBuildHealthReports() {
        List<HealthReport> reports = new ArrayList<HealthReport>();
        RunT lastBuild = getLastBuild();

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

        // check the cache
        if (cachedBuildHealthReportsBuildNumber != null
                && cachedBuildHealthReports != null
                && lastBuild != null
                && cachedBuildHealthReportsBuildNumber.intValue() == lastBuild
                        .getNumber()) {
            reports.addAll(cachedBuildHealthReports);
        } else if (lastBuild != null) {
            for (HealthReportingAction healthReportingAction : lastBuild
                    .getActions(HealthReportingAction.class)) {
                final HealthReport report = healthReportingAction
                        .getBuildHealth();
                if (report != null) {
                    if (report.isAggregateReport()) {
                        reports.addAll(report.getAggregatedReports());
                    } else {
                        reports.add(report);
                    }
                }
            }
            final HealthReport report = getBuildStabilityHealthReport();
            if (report != null) {
                if (report.isAggregateReport()) {
                    reports.addAll(report.getAggregatedReports());
                } else {
                    reports.add(report);
                }
            }

            Collections.sort(reports);

            // store the cache
            cachedBuildHealthReportsBuildNumber = lastBuild.getNumber();
            cachedBuildHealthReports = new ArrayList<HealthReport>(reports);
        }

        return reports;
    }

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

949
            Localizable description;
K
TAB->WS  
kohsuke 已提交
950
            if (failCount == 0) {
951
                description = Messages._Job_NoRecentBuildFailed();
K
TAB->WS  
kohsuke 已提交
952 953 954 955
            } 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
956
                description = Messages._Job_AllRecentBuildFailed();
K
TAB->WS  
kohsuke 已提交
957
            } else {
958
                description = Messages._Job_NOfMFailed(failCount, totalCount);
K
TAB->WS  
kohsuke 已提交
959
            }
960
            return new HealthReport(score, Messages._Job_BuildStability(description));
K
TAB->WS  
kohsuke 已提交
961 962 963 964 965 966 967 968 969 970 971 972 973
        }
        return null;
    }

    //
    //
    // actions
    //
    //
    /**
     * Accepts submission from the configuration page.
     */
    public synchronized void doConfigSubmit(StaplerRequest req,
974
            StaplerResponse rsp) throws IOException, ServletException, FormException {
K
TAB->WS  
kohsuke 已提交
975 976 977 978 979 980 981 982 983 984 985
        checkPermission(CONFIGURE);

        req.setCharacterEncoding("UTF-8");

        description = req.getParameter("description");

        keepDependencies = req.getParameter("keepDependencies") != null;

        try {
            properties.clear();

986
            JSONObject json = req.getSubmittedForm();
K
TAB->WS  
kohsuke 已提交
987 988 989 990 991 992 993 994 995 996

            if (req.getParameter("logrotate") != null)
                logRotator = LogRotator.DESCRIPTOR.newInstance(req,json.getJSONObject("logrotate"));
            else
                logRotator = null;
            
            int i = 0;
            for (JobPropertyDescriptor d : JobPropertyDescriptor
                    .getPropertyDescriptors(Job.this.getClass())) {
                String name = "jobProperty" + (i++);
997 998
                JSONObject config = json.getJSONObject(name);
                JobProperty prop = d.newInstance(req, config);
K
TAB->WS  
kohsuke 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
                if (prop != null) {
                    prop.setOwner(this);
                    properties.add(prop);
                }
            }

            submit(req, rsp);

            save();

            String newName = req.getParameter("name");
            if (newName != null && !newName.equals(name)) {
                // check this error early to avoid HTTP response splitting.
                try {
                    Hudson.checkGoodName(newName);
                } catch (ParseException e) {
                    sendError(e, req, rsp);
                    return;
                }
1018
                rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8"));
K
TAB->WS  
kohsuke 已提交
1019 1020 1021 1022 1023 1024
            } else {
                rsp.sendRedirect(".");
            }
        } catch (JSONException e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
1025
            pw.println("Failed to parse form data. Please report this problem as a bug");
1026
            pw.println("JSON=" + req.getSubmittedForm());
K
TAB->WS  
kohsuke 已提交
1027 1028 1029 1030
            pw.println();
            e.printStackTrace(pw);

            rsp.setStatus(SC_BAD_REQUEST);
1031
            sendError(sw.toString(), req, rsp, true);
K
TAB->WS  
kohsuke 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
        }
    }

    /**
     * Accepts <tt>config.xml</tt> submission, as well as serve it.
     */
    @WebMethod(name = "config.xml")
    public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp)
            throws IOException {
        if (req.getMethod().equals("GET")) {
            // read
1043
            checkPermission(EXTENDED_READ);
K
TAB->WS  
kohsuke 已提交
1044 1045 1046 1047 1048 1049
            rsp.setContentType("application/xml;charset=UTF-8");
            getConfigFile().writeRawTo(rsp.getWriter());
            return;
        }
        if (req.getMethod().equals("POST")) {
            // submission
1050
            checkPermission(CONFIGURE);
K
TAB->WS  
kohsuke 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
            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
            new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this);
            onLoad(getParent(), getRootDir().getName());

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

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

    /**
     * Derived class can override this to perform additional config submission
     * work.
     */
    protected void submit(StaplerRequest req, StaplerResponse rsp)
            throws IOException, ServletException, FormException {
    }

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    /**
     * Accepts and serves the job description
     */
    public void doDescription(StaplerRequest req, StaplerResponse rsp)
            throws IOException {
        if (req.getMethod().equals("GET")) {
            //read
            rsp.setContentType("text/plain;charset=UTF-8");
            rsp.getWriter().write(this.getDescription());
            return;
        }
        if (req.getMethod().equals("POST")) {
            checkPermission(CONFIGURE);

            // submission
            if (req.getParameter("description") != null) {
                this.setDescription(req.getParameter("description"));
                rsp.sendError(SC_NO_CONTENT);
                return;
            }
        }

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

K
TAB->WS  
kohsuke 已提交
1114 1115 1116 1117 1118
    /**
     * Returns the image that shows the current buildCommand status.
     */
    public void doBuildStatus(StaplerRequest req, StaplerResponse rsp)
            throws IOException {
1119
        rsp.sendRedirect2(req.getContextPath() + "/images/48x48/" + getBuildStatusUrl());
K
TAB->WS  
kohsuke 已提交
1120 1121 1122 1123 1124 1125
    }

    public String getBuildStatusUrl() {
        return getIconColor().getImage();
    }

1126 1127 1128 1129 1130 1131
    public Graph getBuildTimeGraph() {
        return new Graph(getLastBuild().getTimestamp(),500,400) {
            @Override
            protected JFreeChart createGraph() {
                class ChartLabel implements Comparable<ChartLabel> {
                    final Run run;
K
TAB->WS  
kohsuke 已提交
1132

1133 1134 1135
                    public ChartLabel(Run r) {
                        this.run = r;
                    }
K
TAB->WS  
kohsuke 已提交
1136

1137 1138 1139
                    public int compareTo(ChartLabel that) {
                        return this.run.number - that.run.number;
                    }
K
TAB->WS  
kohsuke 已提交
1140

1141
                    @Override
1142 1143 1144 1145 1146 1147 1148 1149 1150
                    public boolean equals(Object o) {
                        // HUDSON-2682 workaround for Eclipse compilation bug
                        // on (c instanceof ChartLabel)
                        if (o == null || !ChartLabel.class.isAssignableFrom( o.getClass() ))  {
                            return false;
                        }
                        ChartLabel that = (ChartLabel) o;
                        return run == that.run;
                    }
K
TAB->WS  
kohsuke 已提交
1151

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
                    public Color getColor() {
                        // TODO: consider gradation. See
                        // http://www.javadrive.jp/java2d/shape/index9.html
                        Result r = run.getResult();
                        if (r == Result.FAILURE)
                            return ColorPalette.RED;
                        else if (r == Result.UNSTABLE)
                            return ColorPalette.YELLOW;
                        else if (r == Result.ABORTED || r == Result.NOT_BUILT)
                            return ColorPalette.GREY;
                        else
                            return ColorPalette.BLUE;
                    }
K
TAB->WS  
kohsuke 已提交
1165

1166
                    @Override
1167 1168 1169
                    public int hashCode() {
                        return run.hashCode();
                    }
K
TAB->WS  
kohsuke 已提交
1170

1171
                    @Override
1172 1173 1174 1175 1176 1177 1178 1179 1180
                    public String toString() {
                        String l = run.getDisplayName();
                        if (run instanceof Build) {
                            String s = ((Build) run).getBuiltOnStr();
                            if (s != null)
                                l += ' ' + s;
                        }
                        return l;
                    }
K
TAB->WS  
kohsuke 已提交
1181

1182
                }
K
TAB->WS  
kohsuke 已提交
1183

1184 1185 1186 1187 1188 1189
                DataSetBuilder<String, ChartLabel> data = new DataSetBuilder<String, ChartLabel>();
                for (Run r : getBuilds()) {
                    if (r.isBuilding())
                        continue;
                    data.add(((double) r.getDuration()) / (1000 * 60), "min",
                            new ChartLabel(r));
K
TAB->WS  
kohsuke 已提交
1190 1191
                }

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
                final CategoryDataset dataset = data.build();

                final JFreeChart chart = ChartFactory.createStackedAreaChart(null, // chart
                                                                                    // title
                        null, // unused
                        Messages.Job_minutes(), // 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();
                ChartUtil.adjustChebyshev(dataset, rangeAxis);
                rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

                StackedAreaRenderer ar = new StackedAreaRenderer2() {
                    @Override
                    public Paint getItemPaint(int row, int column) {
                        ChartLabel key = (ChartLabel) dataset.getColumnKey(column);
                        return key.getColor();
                    }
K
TAB->WS  
kohsuke 已提交
1235

1236 1237 1238 1239 1240 1241
                    @Override
                    public String generateURL(CategoryDataset dataset, int row,
                            int column) {
                        ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
                        return String.valueOf(label.run.number);
                    }
K
TAB->WS  
kohsuke 已提交
1242

1243 1244 1245 1246 1247 1248 1249 1250 1251
                    @Override
                    public String generateToolTip(CategoryDataset dataset, int row,
                            int column) {
                        ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
                        return label.run.getDisplayName() + " : "
                                + label.run.getDurationString();
                    }
                };
                plot.setRenderer(ar);
K
TAB->WS  
kohsuke 已提交
1252

1253 1254
                // crop extra space around the graph
                plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));
K
TAB->WS  
kohsuke 已提交
1255

1256
                return chart;
K
TAB->WS  
kohsuke 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
            }
        };
    }

    /**
     * Renames this job.
     */
    public/* not synchronized. see renameTo() */void doDoRename(
            StaplerRequest req, StaplerResponse rsp) throws IOException,
            ServletException {
1267
        requirePOST();
K
TAB->WS  
kohsuke 已提交
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
        // rename is essentially delete followed by a create
        checkPermission(CREATE);
        checkPermission(DELETE);

        String newName = req.getParameter("newName");
        try {
            Hudson.checkGoodName(newName);
        } catch (ParseException e) {
            sendError(e, req, rsp);
            return;
        }

1280 1281
        if (isBuilding()) {
            // redirect to page explaining that we can't rename now
1282
            rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8"));
1283 1284 1285
            return;
        }

K
TAB->WS  
kohsuke 已提交
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
        renameTo(newName);
        // 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());
    }

    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);
    }
1309 1310 1311 1312 1313 1314

    /**
     * Returns the {@link ACL} for this object.
     * We need to override the identical method in AbstractItem because we won't
     * call getACL(Job) otherwise (single dispatch)
     */
1315
    @Override
1316 1317 1318
    public ACL getACL() {
        return Hudson.getInstance().getAuthorizationStrategy().getACL(this);
    }
1319

K
kohsuke 已提交
1320 1321 1322
    public TimelineEventList doTimelineData(StaplerRequest req, @QueryParameter long min, @QueryParameter long max) throws IOException {
        TimelineEventList result = new TimelineEventList();
        for (RunT r : getBuildsByTimestamp(min,max)) {
1323
            Event e = new Event();
K
kohsuke 已提交
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
            e.start = r.getTime();
            e.end   = new Date(r.timestamp+r.getDuration());
            e.title = r.getFullDisplayName();
            // what to put in the description?
            // e.description = "Longish description of event "+r.getFullDisplayName();
            // e.durationEvent = true;
            e.link = req.getContextPath()+'/'+r.getUrl();
            BallColor c = r.getIconColor();
            e.color = String.format("#%06X",c.getBaseColor().darker().getRGB()&0xFFFFFF);
            e.classname = "event-"+c.noAnime().toString()+" " + (c.isAnimated()?"animated":"");
1334 1335
            result.add(e);
        }
K
kohsuke 已提交
1336
        return result;
1337
    }
K
kohsuke 已提交
1338
}