Job.java 51.5 KB
Newer Older
K
kohsuke 已提交
1 2 3
/*
 * The MIT License
 * 
4
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt, Matthew R. Harrah, Red Hat, Inc., Stephen Connolly, Tom Huybrechts, CloudBees, Inc.
K
kohsuke 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * 
 * 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;

E
Emanuele Zattin 已提交
26 27
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
28
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
29
import hudson.BulkChange;
30

31
import hudson.EnvVars;
32
import hudson.Extension;
K
kohsuke 已提交
33
import hudson.ExtensionPoint;
34
import hudson.PermalinkList;
35
import hudson.Util;
36
import hudson.cli.declarative.CLIResolver;
37
import hudson.model.Descriptor.FormException;
K
kohsuke 已提交
38
import hudson.model.Fingerprint.Range;
39 40
import hudson.model.Fingerprint.RangeSet;
import hudson.model.PermalinkProjectAction.Permalink;
41
import hudson.model.listeners.ItemListener;
42
import hudson.search.QuickSilver;
K
kohsuke 已提交
43
import hudson.search.SearchIndex;
44
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
45 46
import hudson.search.SearchItem;
import hudson.search.SearchItems;
47
import hudson.security.ACL;
K
kohsuke 已提交
48
import hudson.tasks.LogRotator;
K
Kohsuke Kawaguchi 已提交
49
import hudson.util.AlternativeUiTextProvider;
K
kohsuke 已提交
50
import hudson.util.ChartUtil;
K
kohsuke 已提交
51
import hudson.util.ColorPalette;
52
import hudson.util.CopyOnWriteList;
K
kohsuke 已提交
53
import hudson.util.DataSetBuilder;
54
import hudson.util.DescribableList;
55
import hudson.util.FormApply;
56
import hudson.util.Graph;
57
import hudson.util.ProcessTree;
58
import hudson.util.QuotedStringTokenizer;
K
kohsuke 已提交
59 60
import hudson.util.RunList;
import hudson.util.ShiftedCategoryAxis;
K
kohsuke 已提交
61
import hudson.util.StackedAreaRenderer2;
K
kohsuke 已提交
62
import hudson.util.TextFile;
63
import hudson.widgets.HistoryWidget;
64
import hudson.widgets.HistoryWidget.Adapter;
65
import hudson.widgets.Widget;
K
Kohsuke Kawaguchi 已提交
66
import jenkins.model.BuildDiscarder;
67
import jenkins.model.DirectlyModifiableTopLevelItemGroup;
68
import jenkins.model.Jenkins;
69
import jenkins.model.ProjectNamingStrategy;
70
import jenkins.security.HexStringConfidentialKey;
71
import jenkins.util.io.OnMaster;
72
import net.sf.json.JSONException;
73
import net.sf.json.JSONObject;
74

75
import org.apache.commons.io.FileUtils;
K
kohsuke 已提交
76 77 78 79 80 81 82
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 已提交
83
import org.jfree.chart.renderer.category.StackedAreaRenderer;
K
kohsuke 已提交
84 85
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleInsets;
86
import org.jvnet.localizer.Localizable;
87 88
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
89
import org.kohsuke.stapler.StaplerOverridable;
K
kohsuke 已提交
90 91
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
kohsuke 已提交
92
import org.kohsuke.stapler.export.Exported;
93
import org.kohsuke.stapler.interceptor.RequirePOST;
94 95

import javax.servlet.ServletException;
96

97
import java.awt.*;
E
Emanuele Zattin 已提交
98
import java.io.*;
99
import java.net.URLEncoder;
E
Emanuele Zattin 已提交
100
import java.util.*;
101
import java.util.List;
102 103
import java.util.logging.Level;
import java.util.logging.Logger;
104 105
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
106 107

import static javax.servlet.http.HttpServletResponse.*;
108
import jenkins.model.BuildDiscarderProperty;
109
import jenkins.model.ModelObjectWithChildren;
J
Jesse Glick 已提交
110
import jenkins.model.RunIdMigrator;
J
Jesse Glick 已提交
111
import jenkins.model.lazy.LazyBuildMixIn;
J
Jesse Glick 已提交
112 113
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
K
kohsuke 已提交
114 115 116

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

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

J
jpederzolli 已提交
139 140 141 142 143 144
    /**
     * Newly copied jobs get this flag set, so that Hudson doesn't try to run the job until its configuration
     * is saved once.
     */
    private transient volatile boolean holdOffBuildUntilSave;

145 146 147 148 149 150 151
    /**
     * {@link ItemListener}s can, and do, modify the job with a corresponding save which will clear
     * {@link #holdOffBuildUntilSave} prematurely. The {@link LastItemListener} is responsible for
     * clearing this flag as the last item listener.
     */
    private transient volatile boolean holdOffBuildUntilUserSave;

152
    /** @deprecated Replaced by {@link BuildDiscarderProperty} */
K
Kohsuke Kawaguchi 已提交
153
    private volatile BuildDiscarder logRotator;
K
TAB->WS  
kohsuke 已提交
154 155 156 157 158 159 160 161 162

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

163
    boolean keepDependencies;
K
TAB->WS  
kohsuke 已提交
164 165

    /**
166
     * List of properties configured for this project.
K
TAB->WS  
kohsuke 已提交
167
     */
K
Kohsuke Kawaguchi 已提交
168
    // this should have been DescribableList but now it's too late
K
TAB->WS  
kohsuke 已提交
169 170
    protected CopyOnWriteList<JobProperty<? super JobT>> properties = new CopyOnWriteList<JobProperty<? super JobT>>();

J
Jesse Glick 已提交
171 172 173
    @Restricted(NoExternalUse.class)
    public transient RunIdMigrator runIdMigrator;

K
TAB->WS  
kohsuke 已提交
174 175 176 177
    protected Job(ItemGroup parent, String name) {
        super(parent, name);
    }

J
jpederzolli 已提交
178 179 180
    @Override
    public synchronized void save() throws IOException {
        super.save();
181
        holdOffBuildUntilSave = holdOffBuildUntilUserSave;
J
jpederzolli 已提交
182 183
    }

J
Jesse Glick 已提交
184 185 186 187 188 189
    @Override public void onCreatedFromScratch() {
        super.onCreatedFromScratch();
        runIdMigrator = new RunIdMigrator();
        runIdMigrator.created(getBuildDir());
    }

190
    @Override
K
TAB->WS  
kohsuke 已提交
191 192 193 194
    public void onLoad(ItemGroup<? extends Item> parent, String name)
            throws IOException {
        super.onLoad(parent, name);

J
Jesse Glick 已提交
195 196
        File buildDir = getBuildDir();
        runIdMigrator = new RunIdMigrator();
197
        runIdMigrator.migrate(buildDir, Jenkins.getInstance().getRootDir());
J
Jesse Glick 已提交
198

K
TAB->WS  
kohsuke 已提交
199 200 201 202 203 204
        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 已提交
205 206 207
                synchronized (this) {
                    this.nextBuildNumber = Integer.parseInt(f.readTrim());
                }
K
TAB->WS  
kohsuke 已提交
208
            } catch (NumberFormatException e) {
E
Emanuele Zattin 已提交
209
                // try to infer the value of the next build number from the existing build records. See JENKINS-11563
J
Jesse Glick 已提交
210
                File[] folders = buildDir.listFiles(new FileFilter() {
E
Emanuele Zattin 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
                    public boolean accept(File file) {
                        return file.isDirectory() && file.getName().matches("[0-9]+");
                    }
                });

                if (folders == null || folders.length == 0) {
                    this.nextBuildNumber = 1;
                } else {
                    Collection<Integer> foldersInt = Collections2.transform(Arrays.asList(folders), new Function<File, Integer>() {
                        public Integer apply(File file) {
                            return Integer.parseInt(file.getName());
                        }
                    });
                    this.nextBuildNumber = Collections.max(foldersInt) + 1;
                }
                saveNextBuildNumber();
K
TAB->WS  
kohsuke 已提交
227 228
            }
        } else {
229
            // From the old Hudson, or doCreateItem. Create this file now.
K
TAB->WS  
kohsuke 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242
            saveNextBuildNumber();
        }

        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 已提交
243 244
        synchronized (this) {
            this.nextBuildNumber = 1; // reset the next build number
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
            this.holdOffBuildUntilUserSave = true;
            this.holdOffBuildUntilSave = this.holdOffBuildUntilUserSave;
        }
    }

    @Extension(ordinal = -Double.MAX_VALUE)
    public static class LastItemListener extends ItemListener {

        @Override
        public void onCopied(Item src, Item item) {
            // If any of the other ItemListeners modify the job, they effect
            // a save, which will clear the holdOffBuildUntilUserSave and
            // causing a regression of JENKINS-2494
            if (item instanceof Job) {
                Job job = (Job) item;
                synchronized (job) {
                    job.holdOffBuildUntilUserSave = false;
                }
            }
D
dty 已提交
264
        }
K
TAB->WS  
kohsuke 已提交
265 266
    }

267
    @Override
268
    protected void performDelete() throws IOException, InterruptedException {
K
TAB->WS  
kohsuke 已提交
269 270 271 272 273 274 275 276 277 278 279 280
        // 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 已提交
281
    /*package*/ TextFile getNextBuildNumberFile() {
K
TAB->WS  
kohsuke 已提交
282 283 284
        return new TextFile(new File(this.getRootDir(), "nextBuildNumber"));
    }

285
    public synchronized boolean isHoldOffBuildUntilSave() {
J
jpederzolli 已提交
286 287 288
        return holdOffBuildUntilSave;
    }

D
dty 已提交
289
    protected synchronized void saveNextBuildNumber() throws IOException {
290 291 292
        if (nextBuildNumber == 0) { // #3361
            nextBuildNumber = 1;
        }
K
TAB->WS  
kohsuke 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
        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;
    }

309 310 311 312 313 314 315
    /**
     * Returns true if a build of this project is in progress.
     */
    public boolean isBuilding() {
        RunT b = getLastBuild();
        return b!=null && b.isBuilding();
    }
316 317 318 319 320 321 322 323
    
    /**
     * Returns true if the log file is still being updated.
     */
    public boolean isLogUpdated() {
        RunT b = getLastBuild();
        return b!=null && b.isLogUpdated();
    }    
324

325
    @Override
K
TAB->WS  
kohsuke 已提交
326
    public String getPronoun() {
K
Kohsuke Kawaguchi 已提交
327
        return AlternativeUiTextProvider.get(PRONOUN, this, Messages.Job_Pronoun());
K
TAB->WS  
kohsuke 已提交
328 329 330 331 332 333 334 335 336 337 338
    }

    /**
     * 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.
339
     * (This really only makes sense in {@link AbstractProject} but historically it was defined here.)
K
TAB->WS  
kohsuke 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
     */
    @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;
    }

363 364 365 366 367 368
    /**
     * Builds up the environment variable map that's sufficient to identify a process
     * as ours. This is used to kill run-away processes via {@link ProcessTree#killAll(Map)}.
     */
    public EnvVars getCharacteristicEnvVars() {
        EnvVars env = new EnvVars();
369 370
        env.put("JENKINS_SERVER_COOKIE",SERVER_COOKIE.get());
        env.put("HUDSON_SERVER_COOKIE",SERVER_COOKIE.get()); // Legacy compatibility
371
        env.put("JOB_NAME",getFullName());
372 373 374 375 376 377 378 379 380 381 382 383 384 385
        return env;
    }

    /**
     * Creates an environment variable override for launching processes for this project.
     *
     * <p>
     * This is for process launching outside the build execution (such as polling, tagging, deployment, etc.)
     * that happens in a context of a specific job.
     *
     * @param node
     *      Node to eventually run a process on. The implementation must cope with this parameter being null
     *      (in which case none of the node specific properties would be reflected in the resulting override.)
     */
386
    public @Nonnull EnvVars getEnvironment(@CheckForNull Node node, @Nonnull TaskListener listener) throws IOException, InterruptedException {
387 388
        EnvVars env;

389 390 391 392
        if (node!=null) {
            final Computer computer = node.toComputer();
            env = (computer != null) ? computer.buildEnvironment(listener) : new EnvVars();                
        } else {
393
            env = new EnvVars();
394
        }
395 396 397 398 399 400 401 402

        env.putAll(getCharacteristicEnvVars());

        // servlet container may have set CLASSPATH in its launch script,
        // so don't let that inherit to the new child process.
        // see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html
        env.put("CLASSPATH","");

K
Kohsuke Kawaguchi 已提交
403 404 405 406 407
        // apply them in a reverse order so that higher ordinal ones can modify values added by lower ordinal ones
        for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView())
            ec.buildEnvironmentFor(this,env,listener);


408 409 410
        return env;
    }

K
TAB->WS  
kohsuke 已提交
411 412 413 414 415 416
    /**
     * 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
417
     * {@link #getLastBuild()} returns. Otherwise it'll be no-op.
K
TAB->WS  
kohsuke 已提交
418 419 420
     * 
     * @since 1.199 (before that, this method was package private.)
     */
D
dty 已提交
421
    public synchronized void updateNextBuildNumber(int next) throws IOException {
422 423
        RunT lb = getLastBuild();
        if (lb!=null ?  next>lb.getNumber() : next>0) {
K
TAB->WS  
kohsuke 已提交
424 425 426 427 428 429
            this.nextBuildNumber = next;
            saveNextBuildNumber();
        }
    }

    /**
430
     * Returns the configured build discarder for this job, via {@link BuildDiscarderProperty}, or null if none.
K
TAB->WS  
kohsuke 已提交
431
     */
432
    public synchronized BuildDiscarder getBuildDiscarder() {
433
        BuildDiscarderProperty prop = _getProperty(BuildDiscarderProperty.class);
434
        return prop != null ? prop.getStrategy() : /* settings compatibility */ logRotator;
K
TAB->WS  
kohsuke 已提交
435 436
    }

437
    public synchronized void setBuildDiscarder(BuildDiscarder bd) throws IOException {
438 439 440 441 442 443 444 445 446 447
        BulkChange bc = new BulkChange(this);
        try {
            removeProperty(BuildDiscarderProperty.class);
            if (bd != null) {
                addProperty(new BuildDiscarderProperty(bd));
            }
            bc.commit();
        } finally {
            bc.abort();
        }
K
Kohsuke Kawaguchi 已提交
448 449 450 451 452 453 454 455 456
    }

    /**
     * Left for backward compatibility. Returns non-null if and only
     * if {@link LogRotator} is configured as {@link BuildDiscarder}.
     *
     * @deprecated as of 1.503
     *      Use {@link #getBuildDiscarder()}.
     */
457
    @Deprecated
K
Kohsuke Kawaguchi 已提交
458
    public LogRotator getLogRotator() {
459 460
        BuildDiscarder buildDiscarder = getBuildDiscarder();
        return buildDiscarder instanceof LogRotator ? (LogRotator) buildDiscarder : null;
K
Kohsuke Kawaguchi 已提交
461 462 463 464 465 466
    }

    /**
     * @deprecated as of 1.503
     *      Use {@link #setBuildDiscarder(BuildDiscarder)}
     */
467
    @Deprecated
K
Kohsuke Kawaguchi 已提交
468 469
    public void setLogRotator(LogRotator logRotator) throws IOException {
        setBuildDiscarder(logRotator);
K
TAB->WS  
kohsuke 已提交
470 471 472 473 474
    }

    /**
     * Perform log rotation.
     */
475
    public void logRotate() throws IOException, InterruptedException {
K
Kohsuke Kawaguchi 已提交
476 477 478
        BuildDiscarder bd = getBuildDiscarder();
        if (bd != null)
            bd.perform(this);
K
TAB->WS  
kohsuke 已提交
479 480 481 482 483 484 485 486 487
    }

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

488
    @Override
K
TAB->WS  
kohsuke 已提交
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
    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 已提交
520
    public void addProperty(JobProperty<? super JobT> jobProp) throws IOException {
521
        ((JobProperty)jobProp).setOwner(this);
K
TAB->WS  
kohsuke 已提交
522 523 524 525
        properties.add(jobProp);
        save();
    }

K
kohsuke 已提交
526 527 528 529 530 531 532 533 534 535
    /**
     * Removes {@link JobProperty}
     *
     * @since 1.279
     */
    public void removeProperty(JobProperty<? super JobT> jobProp) throws IOException {
        properties.remove(jobProp);
        save();
    }

K
kohsuke 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    /**
     * 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 已提交
553 554 555
    /**
     * Gets all the job properties configured for this job.
     */
556
    @SuppressWarnings({"unchecked", "rawtypes"})
K
TAB->WS  
kohsuke 已提交
557
    public Map<JobPropertyDescriptor, JobProperty<? super JobT>> getProperties() {
558 559 560 561 562
        Map result = Descriptor.toMap((Iterable) properties);
        if (logRotator != null) {
            result.put(Jenkins.getActiveInstance().getDescriptorByType(BuildDiscarderProperty.DescriptorImpl.class), new BuildDiscarderProperty(logRotator));
        }
        return result;
K
TAB->WS  
kohsuke 已提交
563 564
    }

565 566 567 568 569 570 571 572 573
    /**
     * 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 已提交
574 575 576 577 578
    /**
     * Gets the specific property, or null if the propert is not configured for
     * this job.
     */
    public <T extends JobProperty> T getProperty(Class<T> clazz) {
579 580 581 582 583 584 585
        if (clazz == BuildDiscarderProperty.class && logRotator != null) {
            return clazz.cast(new BuildDiscarderProperty(logRotator));
        }
        return _getProperty(clazz);
    }

    private <T extends JobProperty> T _getProperty(Class<T> clazz) {
K
TAB->WS  
kohsuke 已提交
586 587 588 589 590 591 592
        for (JobProperty p : properties) {
            if (clazz.isInstance(p))
                return clazz.cast(p);
        }
        return null;
    }

593 594 595 596 597 598 599 600 601 602 603 604
    /**
     * Bind {@link JobProperty}s to URL spaces.
     *
     * @since 1.403
     */
    public JobProperty getProperty(String className) {
        for (JobProperty p : properties)
            if (p.getClass().getName().equals(className))
                return p;
        return null;
    }

605 606
    /**
     * Overrides from job properties.
607
     * @see JobProperty#getJobOverrides
608 609 610 611 612 613 614 615
     */
    public Collection<?> getOverrides() {
        List<Object> r = new ArrayList<Object>();
        for (JobProperty<? super JobT> p : properties)
            r.addAll(p.getJobOverrides());
        return r;
    }

K
TAB->WS  
kohsuke 已提交
616 617 618 619 620 621
    public List<Widget> getWidgets() {
        ArrayList<Widget> r = new ArrayList<Widget>();
        r.add(createHistoryWidget());
        return r;
    }

J
Jesse Glick 已提交
622 623 624
    /**
     * @see LazyBuildMixIn#createHistoryWidget
     */
K
TAB->WS  
kohsuke 已提交
625 626 627 628
    protected HistoryWidget createHistoryWidget() {
        return new HistoryWidget<Job, RunT>(this, getBuilds(), HISTORY_ADAPTER);
    }

J
Jesse Glick 已提交
629
    public static final HistoryWidget.Adapter<Run> HISTORY_ADAPTER = new Adapter<Run>() {
K
TAB->WS  
kohsuke 已提交
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
        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.
     */
K
Kohsuke Kawaguchi 已提交
660
    @Override
K
TAB->WS  
kohsuke 已提交
661
    public void renameTo(String newName) throws IOException {
662
        File oldBuildDir = getBuildDir();
663
        super.renameTo(newName);
664 665
        File newBuildDir = getBuildDir();
        if (oldBuildDir.isDirectory() && !newBuildDir.isDirectory()) {
666 667 668
            if (!newBuildDir.getParentFile().isDirectory()) {
                newBuildDir.getParentFile().mkdirs();
            }
669 670 671 672 673 674
            if (!oldBuildDir.renameTo(newBuildDir)) {
                throw new IOException("failed to rename " + oldBuildDir + " to " + newBuildDir);
            }
        }
    }

675 676 677 678 679 680
    @Override
    public void movedTo(DirectlyModifiableTopLevelItemGroup destination, AbstractItem newItem, File destDir) throws IOException {
        Job newJob = (Job) newItem; // Missing covariant parameters type here.
        File oldBuildDir = getBuildDir();
        super.movedTo(destination, newItem, destDir);
        File newBuildDir = getBuildDir();
681
        if (oldBuildDir.isDirectory()) {
682 683 684 685
            FileUtils.moveDirectory(oldBuildDir, newBuildDir);
        }
    }

686
    @Override public void delete() throws IOException, InterruptedException {
687 688
        super.delete();
        Util.deleteRecursive(getBuildDir());
K
TAB->WS  
kohsuke 已提交
689 690 691 692 693 694 695 696 697
    }

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

    /**
698
     * Gets the read-only view of all the builds.
K
TAB->WS  
kohsuke 已提交
699 700 701
     * 
     * @return never null. The first entry is the latest build.
     */
702
    @Exported(name="allBuilds",visibility=-2)
703
    @WithBridgeMethods(List.class)
704
    public RunList<RunT> getBuilds() {
705
        return RunList.fromRuns(_getRuns().values());
K
TAB->WS  
kohsuke 已提交
706 707
    }

708 709 710
    /**
     * Gets the read-only view of the recent builds.
     *
K
Kohsuke Kawaguchi 已提交
711
     * @since 1.485
712 713 714
     */
    @Exported(name="builds")
    public RunList<RunT> getNewBuilds() {
K
Kohsuke Kawaguchi 已提交
715
        return getBuilds().limit(100);
716 717
    }

K
kohsuke 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
    /**
     * 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 已提交
733 734 735 736 737 738 739 740
    /**
     * Gets all the builds in a map.
     */
    public SortedMap<Integer, RunT> getBuildsAsMap() {
        return Collections.unmodifiableSortedMap(_getRuns());
    }

    /**
741
     * Looks up a build by its ID.
J
Jesse Glick 已提交
742
     * @see LazyBuildMixIn#getBuild
K
TAB->WS  
kohsuke 已提交
743 744 745 746 747 748 749 750 751 752 753 754 755 756
     */
    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()
J
Jesse Glick 已提交
757
     * @see LazyBuildMixIn#getBuildByNumber
K
TAB->WS  
kohsuke 已提交
758 759 760 761 762
     */
    public RunT getBuildByNumber(int n) {
        return _getRuns().get(n);
    }

K
kohsuke 已提交
763 764 765 766
    /**
     * 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.
767 768
     * @deprecated
     *      as of 1.372. Should just do {@code getBuilds().byTimestamp(s,e)} to avoid code bloat in {@link Job}.
K
kohsuke 已提交
769
     */
770
    @WithBridgeMethods(List.class)
771
    @Deprecated
772
    public RunList<RunT> getBuildsByTimestamp(long start, long end) {
773
        return getBuilds().byTimestamp(start,end);
K
kohsuke 已提交
774 775
    }

776 777 778 779 780 781
    @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 已提交
782
                throw new CmdLineException(null, "No such build '#"+n+"' exists");
783 784
            return r;
        } catch (NumberFormatException e) {
M
mindless 已提交
785
            throw new CmdLineException(null, id+ "is not a number");
786 787 788
        }
    }

K
TAB->WS  
kohsuke 已提交
789 790 791 792 793
    /**
     * 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.)
J
Jesse Glick 已提交
794
     * @see LazyBuildMixIn#getNearestBuild
K
TAB->WS  
kohsuke 已提交
795
     */
796
    public RunT getNearestBuild(int n) {
797 798
        SortedMap<Integer, ? extends RunT> m = _getRuns().headMap(n - 1); // the map should
                                                                          // include n, so n-1
K
TAB->WS  
kohsuke 已提交
799 800 801 802 803 804 805 806 807 808
        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.)
J
Jesse Glick 已提交
809
     * @see LazyBuildMixIn#getNearestOldBuild
K
TAB->WS  
kohsuke 已提交
810
     */
811
    public RunT getNearestOldBuild(int n) {
K
TAB->WS  
kohsuke 已提交
812 813 814 815 816 817
        SortedMap<Integer, ? extends RunT> m = _getRuns().tailMap(n);
        if (m.isEmpty())
            return null;
        return m.get(m.firstKey());
    }

818
    @Override
K
TAB->WS  
kohsuke 已提交
819 820 821 822
    public Object getDynamic(String token, StaplerRequest req,
            StaplerResponse rsp) {
        try {
            // try to interpret the token as build number
823
            return getBuildByNumber(Integer.valueOf(token));
K
TAB->WS  
kohsuke 已提交
824 825 826 827 828 829 830
        } catch (NumberFormatException e) {
            // try to map that to widgets
            for (Widget w : getWidgets()) {
                if (w.getUrlName().equals(token))
                    return w;
            }

831 832
            // is this a permalink?
            for (Permalink p : getPermalinks()) {
833
                if(p.getId().equals(token))
834 835 836
                    return p.resolve(this);
            }

K
TAB->WS  
kohsuke 已提交
837 838 839 840 841 842 843 844 845 846 847 848 849
            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
     */
850
    public File getBuildDir() {
851 852 853
        // we use the null check variant so that people can write true unit tests with a mock ItemParent
        // and without a JenkinsRule. Such tests are of limited utility as there is a high risk of hitting
        // some code that needs the singleton, but for persistence migration test cases it makes sense to permit
854
        Jenkins j = Jenkins.getInstanceOrNull();
855 856 857 858
        if (j == null) {
            return new File(getRootDir(), "builds");
        }
        return j.getBuildDirFor(this);
K
TAB->WS  
kohsuke 已提交
859 860 861 862 863
    }

    /**
     * Gets all the runs.
     * 
864
     * The resulting map must be treated immutable (by employing copy-on-write
K
TAB->WS  
kohsuke 已提交
865
     * semantics.) The map is descending order, with newest builds at the top.
J
Jesse Glick 已提交
866
     * @see LazyBuildMixIn#_getRuns
K
TAB->WS  
kohsuke 已提交
867 868 869 870 871 872 873 874
     */
    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}.
J
Jesse Glick 已提交
875
     * @see LazyBuildMixIn#removeRun
K
TAB->WS  
kohsuke 已提交
876 877 878 879 880
     */
    protected abstract void removeRun(RunT run);

    /**
     * Returns the last build.
J
Jesse Glick 已提交
881
     * @see LazyBuildMixIn#getLastBuild
K
TAB->WS  
kohsuke 已提交
882 883 884 885 886 887 888 889 890 891 892 893 894
     */
    @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.
J
Jesse Glick 已提交
895
     * @see LazyBuildMixIn#getFirstBuild
K
TAB->WS  
kohsuke 已提交
896 897 898 899 900 901 902 903 904 905 906 907
     */
    @Exported
    @QuickSilver
    public RunT getFirstBuild() {
        SortedMap<Integer, ? extends RunT> runs = _getRuns();

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

    /**
J
jglick 已提交
908
     * Returns the last successful build, if any. Otherwise null. A successful build
K
TAB->WS  
kohsuke 已提交
909 910 911 912 913 914 915
     * would include either {@link Result#SUCCESS} or {@link Result#UNSTABLE}.
     * 
     * @see #getLastStableBuild()
     */
    @Exported
    @QuickSilver
    public RunT getLastSuccessfulBuild() {
K
Kohsuke Kawaguchi 已提交
916
        return (RunT)Permalink.LAST_SUCCESSFUL_BUILD.resolve(this);
K
TAB->WS  
kohsuke 已提交
917 918
    }

919 920 921 922 923 924 925
    /**
     * Returns the last build that was anything but stable, if any. Otherwise null.
     * @see #getLastSuccessfulBuild
     */
    @Exported
    @QuickSilver
    public RunT getLastUnsuccessfulBuild() {
926
        return (RunT)Permalink.LAST_UNSUCCESSFUL_BUILD.resolve(this);
927 928 929 930 931 932 933 934 935
    }

    /**
     * Returns the last unstable build, if any. Otherwise null.
     * @see #getLastSuccessfulBuild
     */
    @Exported
    @QuickSilver
    public RunT getLastUnstableBuild() {
936
        return (RunT)Permalink.LAST_UNSTABLE_BUILD.resolve(this);
937 938
    }

K
TAB->WS  
kohsuke 已提交
939 940
    /**
     * Returns the last stable build, if any. Otherwise null.
J
jglick 已提交
941
     * @see #getLastSuccessfulBuild
K
TAB->WS  
kohsuke 已提交
942 943 944 945
     */
    @Exported
    @QuickSilver
    public RunT getLastStableBuild() {
946
        return (RunT)Permalink.LAST_STABLE_BUILD.resolve(this);
K
TAB->WS  
kohsuke 已提交
947 948 949 950 951 952 953 954
    }

    /**
     * Returns the last failed build, if any. Otherwise null.
     */
    @Exported
    @QuickSilver
    public RunT getLastFailedBuild() {
955
        return (RunT)Permalink.LAST_FAILED_BUILD.resolve(this);
K
TAB->WS  
kohsuke 已提交
956 957 958 959 960 961 962 963 964 965 966 967 968
    }

    /**
     * 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;
    }
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
    
    /**
     * Returns the last 'numberOfBuilds' builds with a build result >= 'threshold'
     * 
     * @return a list with the builds. May be smaller than 'numberOfBuilds' or even empty
     *   if not enough builds satisfying the threshold have been found. Never null.
     */
    public List<RunT> getLastBuildsOverThreshold(int numberOfBuilds, Result threshold) {
        
        List<RunT> result = new ArrayList<RunT>(numberOfBuilds);
        
        RunT r = getLastBuild();
        while (r != null && result.size() < numberOfBuilds) {
            if (!r.isBuilding() && 
                 (r.getResult() != null && r.getResult().isBetterOrEqualTo(threshold))) {
                result.add(r);
            }
            r = r.getPreviousBuild();
        }
        
        return result;
    }
    
992 993 994 995 996 997 998 999 1000
    /**
     * Returns candidate build for calculating the estimated duration of the current run.
     * 
     * Returns the 3 last successful (stable or unstable) builds, if there are any.
     * Failing to find 3 of those, it will return up to 3 last unsuccessful builds.
     * 
     * In any case it will not go more than 6 builds into the past to avoid costly build loading.
     */
    @SuppressWarnings("unchecked")
1001
    protected List<RunT> getEstimatedDurationCandidates() {
1002
        List<RunT> candidates = new ArrayList<RunT>(3);
1003
        RunT lastSuccessful = getLastSuccessfulBuild();
1004 1005 1006 1007 1008 1009 1010
        int lastSuccessfulNumber = -1;
        if (lastSuccessful != null) {
            candidates.add(lastSuccessful);
            lastSuccessfulNumber = lastSuccessful.getNumber();
        }

        int i = 0;
1011
        RunT r = getLastBuild();
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
        List<RunT> fallbackCandidates = new ArrayList<RunT>(3);
        while (r != null && candidates.size() < 3 && i < 6) {
            if (!r.isBuilding() && r.getResult() != null && r.getNumber() != lastSuccessfulNumber) {
                Result result = r.getResult();
                if (result.isBetterOrEqualTo(Result.UNSTABLE)) {
                    candidates.add(r);
                } else if (result.isCompleteBuild()) {
                    fallbackCandidates.add(r);
                }
            }
            i++;
            r = r.getPreviousBuild();
        }
        
        while (candidates.size() < 3) {
            if (fallbackCandidates.isEmpty())
                break;
            RunT run = fallbackCandidates.remove(0);
            candidates.add(run);
        }
        
        return candidates;
    }
    
1036
    public long getEstimatedDuration() {
C
Christoph Kutzinski 已提交
1037
        List<RunT> builds = getEstimatedDurationCandidates();
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
        
        if(builds.isEmpty())     return -1;

        long totalDuration = 0;
        for (RunT b : builds) {
            totalDuration += b.getDuration();
        }
        if(totalDuration==0) return -1;

        return Math.round((double)totalDuration / builds.size());
    }
K
TAB->WS  
kohsuke 已提交
1049

1050 1051
    /**
     * Gets all the {@link Permalink}s defined for this job.
1052 1053
     *
     * @return never null
1054
     */
1055
    public PermalinkList getPermalinks() {
1056
        // TODO: shall we cache this?
1057
        PermalinkList permalinks = new PermalinkList(Permalink.BUILTIN);
1058 1059
        for (PermalinkProjectAction ppa : getActions(PermalinkProjectAction.class)) {
            permalinks.addAll(ppa.getPermalinks());
1060 1061 1062
        }
        return permalinks;
    }
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    
    @Override public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
        // not sure what would be really useful here. This needs more thoughts.
        // for the time being, I'm starting with permalinks
        ContextMenu menu = new ContextMenu();
        for (Permalink p : getPermalinks()) {
            if (p.resolve(this) != null) {
                menu.add(p.getId(), p.getDisplayName());
            }
        }
        return menu;
    }
1075

K
TAB->WS  
kohsuke 已提交
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    /**
     * 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
1088
            return BallColor.NOTBUILT;
K
TAB->WS  
kohsuke 已提交
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 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
    }

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

1177
            Localizable description;
K
TAB->WS  
kohsuke 已提交
1178
            if (failCount == 0) {
1179
                description = Messages._Job_NoRecentBuildFailed();
K
TAB->WS  
kohsuke 已提交
1180 1181 1182 1183
            } 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
1184
                description = Messages._Job_AllRecentBuildFailed();
K
TAB->WS  
kohsuke 已提交
1185
            } else {
1186
                description = Messages._Job_NOfMFailed(failCount, totalCount);
K
TAB->WS  
kohsuke 已提交
1187
            }
1188
            return new HealthReport(score, Messages._Job_BuildStability(description));
K
TAB->WS  
kohsuke 已提交
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
        }
        return null;
    }

    //
    //
    // actions
    //
    //
    /**
     * Accepts submission from the configuration page.
     */
1201
    @RequirePOST
K
TAB->WS  
kohsuke 已提交
1202
    public synchronized void doConfigSubmit(StaplerRequest req,
1203
            StaplerResponse rsp) throws IOException, ServletException, FormException {
K
TAB->WS  
kohsuke 已提交
1204 1205 1206 1207
        checkPermission(CONFIGURE);

        description = req.getParameter("description");

1208
        JSONObject json = req.getSubmittedForm();
K
TAB->WS  
kohsuke 已提交
1209

1210
        try {
K
Kohsuke Kawaguchi 已提交
1211 1212
            setDisplayName(json.optString("displayNameOrNull"));

1213 1214
            logRotator = null;

1215
            DescribableList<JobProperty<?>, JobPropertyDescriptor> t = new DescribableList<JobProperty<?>, JobPropertyDescriptor>(NOOP,getAllProperties());
1216 1217 1218 1219 1220 1221
            JSONObject jsonProperties = json.optJSONObject("properties");
            if (jsonProperties != null) {
              t.rebuild(req,jsonProperties,JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass()));
            } else {
              t.clear();
            }
1222 1223 1224 1225
            properties.clear();
            for (JobProperty p : t) {
                p.setOwner(this);
                properties.add(p);
K
TAB->WS  
kohsuke 已提交
1226 1227 1228 1229 1230
            }

            submit(req, rsp);

            save();
1231
            ItemListener.fireOnUpdated(this);
K
TAB->WS  
kohsuke 已提交
1232 1233

            String newName = req.getParameter("name");
1234
            final ProjectNamingStrategy namingStrategy = Jenkins.getInstance().getProjectNamingStrategy();
1235 1236
            if (validRename(name, newName)) {
                newName = newName.trim();
K
TAB->WS  
kohsuke 已提交
1237
                // check this error early to avoid HTTP response splitting.
1238
                Jenkins.checkGoodName(newName);
1239
                namingStrategy.checkName(newName);
1240 1241 1242 1243 1244
                if (FormApply.isApply(req)) {
                    FormApply.applyResponse("notificationBar.show(" + QuotedStringTokenizer.quote(Messages.Job_you_must_use_the_save_button_if_you_wish()) + ",notificationBar.WARNING)").generateResponse(req, rsp, null);
                } else {
                    rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8"));
                }
K
TAB->WS  
kohsuke 已提交
1245
            } else {
1246 1247 1248
                if(namingStrategy.isForceExistingJobs()){
                    namingStrategy.checkName(name);
                }
1249
                FormApply.success(".").generateResponse(req, rsp, null);
K
TAB->WS  
kohsuke 已提交
1250 1251
            }
        } catch (JSONException e) {
1252 1253
            Logger.getLogger(Job.class.getName()).log(Level.WARNING, "failed to parse " + json, e);
            sendError(e, req, rsp);
K
TAB->WS  
kohsuke 已提交
1254 1255 1256
        }
    }

1257 1258 1259 1260 1261 1262 1263 1264 1265
    private boolean validRename(String oldName, String newName) {
        if (newName == null) {
            return false;
        }
        boolean noChange = oldName.equals(newName);
        boolean spaceAdded = oldName.equals(newName.trim());
        return !noChange && !spaceAdded;
    }

K
TAB->WS  
kohsuke 已提交
1266 1267 1268 1269 1270 1271 1272 1273
    /**
     * Derived class can override this to perform additional config submission
     * work.
     */
    protected void submit(StaplerRequest req, StaplerResponse rsp)
            throws IOException, ServletException, FormException {
    }

1274 1275 1276 1277 1278 1279 1280 1281
    /**
     * 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");
1282
            rsp.getWriter().write(Util.fixNull(this.getDescription()));
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
            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 已提交
1300 1301 1302 1303 1304
    /**
     * Returns the image that shows the current buildCommand status.
     */
    public void doBuildStatus(StaplerRequest req, StaplerResponse rsp)
            throws IOException {
1305
        rsp.sendRedirect2(req.getContextPath() + "/images/48x48/" + getBuildStatusUrl());
K
TAB->WS  
kohsuke 已提交
1306 1307 1308 1309 1310 1311
    }

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

T
tfennelly 已提交
1312 1313 1314 1315
    public String getBuildStatusIconClassName() {
        return getIconColor().getIconClassName();
    }

1316
    public Graph getBuildTimeGraph() {
1317
        return new Graph(getLastBuildTime(),500,400) {
1318 1319 1320 1321
            @Override
            protected JFreeChart createGraph() {
                class ChartLabel implements Comparable<ChartLabel> {
                    final Run run;
K
TAB->WS  
kohsuke 已提交
1322

1323 1324 1325
                    public ChartLabel(Run r) {
                        this.run = r;
                    }
K
TAB->WS  
kohsuke 已提交
1326

1327 1328 1329
                    public int compareTo(ChartLabel that) {
                        return this.run.number - that.run.number;
                    }
K
TAB->WS  
kohsuke 已提交
1330

1331
                    @Override
1332 1333 1334 1335 1336 1337 1338 1339 1340
                    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 已提交
1341

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
                    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 已提交
1355

1356
                    @Override
1357 1358 1359
                    public int hashCode() {
                        return run.hashCode();
                    }
K
TAB->WS  
kohsuke 已提交
1360

1361
                    @Override
1362 1363 1364 1365 1366 1367 1368 1369 1370
                    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 已提交
1371

1372
                }
K
TAB->WS  
kohsuke 已提交
1373

1374
                DataSetBuilder<String, ChartLabel> data = new DataSetBuilder<String, ChartLabel>();
1375
                for (Run r : getNewBuilds()) {
1376 1377 1378 1379
                    if (r.isBuilding())
                        continue;
                    data.add(((double) r.getDuration()) / (1000 * 60), "min",
                            new ChartLabel(r));
K
TAB->WS  
kohsuke 已提交
1380 1381
                }

1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
                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 已提交
1425

1426 1427 1428 1429 1430 1431
                    @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 已提交
1432

1433 1434 1435 1436 1437 1438 1439 1440 1441
                    @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 已提交
1442

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

1446
                return chart;
K
TAB->WS  
kohsuke 已提交
1447 1448 1449 1450
            }
        };
    }

1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    private Calendar getLastBuildTime() {
        final RunT lastBuild = getLastBuild();
        if (lastBuild ==null) {
            final GregorianCalendar neverBuiltCalendar = new GregorianCalendar();
            neverBuiltCalendar.setTimeInMillis(0);
            return neverBuiltCalendar;
        }
        return lastBuild.getTimestamp();
    }

K
TAB->WS  
kohsuke 已提交
1461 1462 1463
    /**
     * Renames this job.
     */
1464
    @RequirePOST
K
TAB->WS  
kohsuke 已提交
1465 1466 1467
    public/* not synchronized. see renameTo() */void doDoRename(
            StaplerRequest req, StaplerResponse rsp) throws IOException,
            ServletException {
1468 1469 1470 1471 1472 1473

        if (!hasPermission(CONFIGURE)) {
            // rename is essentially delete followed by a create
            checkPermission(CREATE);
            checkPermission(DELETE);
        }
K
TAB->WS  
kohsuke 已提交
1474 1475

        String newName = req.getParameter("newName");
1476
        Jenkins.checkGoodName(newName);
K
TAB->WS  
kohsuke 已提交
1477

1478 1479
        if (isBuilding()) {
            // redirect to page explaining that we can't rename now
1480
            rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8"));
1481 1482 1483
            return;
        }

K
TAB->WS  
kohsuke 已提交
1484 1485 1486 1487
        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()
L
lvotypko 已提交
1488
        rsp.sendRedirect2("../" + newName);
K
TAB->WS  
kohsuke 已提交
1489 1490 1491 1492
    }

    public void doRssAll(StaplerRequest req, StaplerResponse rsp)
            throws IOException, ServletException {
1493
        rss(req, rsp, " all builds", getBuilds());
K
TAB->WS  
kohsuke 已提交
1494 1495 1496 1497
    }

    public void doRssFailed(StaplerRequest req, StaplerResponse rsp)
            throws IOException, ServletException {
1498
        rss(req, rsp, " failed builds", getBuilds().failureOnly());
K
TAB->WS  
kohsuke 已提交
1499 1500 1501 1502 1503 1504 1505
    }

    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);
    }
1506 1507 1508 1509 1510 1511

    /**
     * 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)
     */
1512
    @Override
1513
    public ACL getACL() {
1514
        return Jenkins.getInstance().getAuthorizationStrategy().getACL(this);
1515
    }
1516

1517 1518
    public BuildTimelineWidget getTimeline() {
        return new BuildTimelineWidget(getBuilds());
1519
    }
1520 1521

    private final static HexStringConfidentialKey SERVER_COOKIE = new HexStringConfidentialKey(Job.class,"serverCookie",16);
K
kohsuke 已提交
1522
}