AbstractProject.java 29.5 KB
Newer Older
1 2
package hudson.model;

K
kohsuke 已提交
3
import hudson.AbortException;
4
import hudson.FeedAdapter;
5
import hudson.FilePath;
6
import hudson.Launcher;
7
import hudson.StructuredForm;
8
import hudson.maven.MavenModule;
9 10 11
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.RunMap.Constructor;
K
kohsuke 已提交
12
import hudson.scm.ChangeLogSet;
K
kohsuke 已提交
13
import hudson.scm.ChangeLogSet.Entry;
14
import hudson.scm.NullSCM;
15
import hudson.scm.SCM;
K
kohsuke 已提交
16
import hudson.scm.SCMS;
J
jbq 已提交
17
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
18
import hudson.security.Permission;
J
jbq 已提交
19
import hudson.tasks.BuildTrigger;
K
kohsuke 已提交
20
import hudson.triggers.SCMTrigger;
21
import hudson.triggers.Trigger;
22
import hudson.triggers.TriggerDescriptor;
23
import hudson.triggers.Triggers;
24
import hudson.util.EditDistance;
K
kohsuke 已提交
25 26 27 28 29 30
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
31

K
kohsuke 已提交
32
import javax.servlet.ServletException;
33
import java.io.File;
34
import java.io.IOException;
K
kohsuke 已提交
35
import java.lang.reflect.InvocationTargetException;
K
kohsuke 已提交
36
import java.util.ArrayList;
37
import java.util.Calendar;
38
import java.util.Collection;
J
jbq 已提交
39
import java.util.Collections;
40
import java.util.Comparator;
J
jbq 已提交
41
import java.util.HashSet;
42 43
import java.util.List;
import java.util.Map;
J
jbq 已提交
44
import java.util.Set;
45 46 47
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
48 49
import java.util.logging.Level;
import java.util.logging.Logger;
50 51 52 53

/**
 * Base implementation of {@link Job}s that build software.
 *
54
 * For now this is primarily the common part of {@link Project} and {@link MavenModule}.
55 56 57 58
 *
 * @author Kohsuke Kawaguchi
 * @see AbstractBuild
 */
59
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
60

61 62 63 64 65
    /**
     * {@link SCM} associated with the project.
     * To allow derived classes to link {@link SCM} config to elsewhere,
     * access to this variable should always go through {@link #getScm()}.
     */
66 67
    private SCM scm = new NullSCM();

68 69 70 71 72 73 74 75 76 77 78
    /**
     * All the builds keyed by their build number.
     */
    protected transient /*almost final*/ RunMap<R> builds = new RunMap<R>();

    /**
     * The quiet period. Null to delegate to the system default.
     */
    private Integer quietPeriod = null;

    /**
79 80 81 82 83
     * If this project is configured to be only built on a certain label,
     * this value will be set to that label.
     *
     * For historical reasons, this is called 'assignedNode'. Also for
     * a historical reason, null to indicate the affinity
84 85
     * with the master node.
     *
86
     * @see #canRoam
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
     */
    private String assignedNode;

    /**
     * True if this project can be built on any node.
     *
     * <p>
     * This somewhat ugly flag combination is so that we can migrate
     * existing Hudson installations nicely.
     */
    private boolean canRoam;

    /**
     * True to suspend new builds.
     */
102
    protected boolean disabled;
103 104 105 106 107 108 109 110 111 112 113 114 115

    /**
     * Identifies {@link JDK} to be used.
     * Null if no explicit configuration is required.
     *
     * <p>
     * Can't store {@link JDK} directly because {@link Hudson} and {@link Project}
     * are saved independently.
     *
     * @see Hudson#getJDK(String)
     */
    private String jdk;

116 117 118 119
    /**
     * @deprecated
     */
    private transient boolean enableRemoteTrigger;
120

121
    private BuildAuthorizationToken authToken = null;
122

123 124 125
    /**
     * List of all {@link Trigger}s for this project.
     */
126
    protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
127

128 129 130 131 132 133 134 135 136
    /**
     * {@link Action}s contributed from subsidiary objects associated with
     * {@link AbstractProject}, such as from triggers, builders, publishers, etc.
     *
     * We don't want to persist them separately, and these actions
     * come and go as configuration change, so it's kept separate.
     */
    protected transient /*final*/ List<Action> transientActions = new Vector<Action>();

137 138
    protected AbstractProject(ItemGroup parent, String name) {
        super(parent,name);
139

140
        if(!Hudson.getInstance().getSlaves().isEmpty()) {
141 142 143 144 145 146
            // if a new job is configured with Hudson that already has slave nodes
            // make it roamable by default
            canRoam = true;
        }
    }

147
    @Override
148 149
    public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
        super.onLoad(parent, name);
150 151 152 153 154 155 156 157 158 159

        this.builds = new RunMap<R>();
        this.builds.load(this,new Constructor<R>() {
            public R create(File dir) throws IOException {
                return loadBuild(dir);
            }
        });

        if(triggers==null)
            // it didn't exist in < 1.28
160
            triggers = new Vector<Trigger<?>>();
161 162
        for (Trigger t : triggers)
            t.start(this,false);
163 164 165

        if(transientActions==null)
            transientActions = new Vector<Action>();    // happens when loaded from disk
166
        updateTransientActions();
167 168
    }

169 170 171 172
    /**
     * If this project is configured to be always built on this node,
     * return that {@link Node}. Otherwise null.
     */
173
    public Label getAssignedLabel() {
174 175 176
        if(canRoam)
            return null;

177 178 179
        if(assignedNode==null)
            return Hudson.getInstance().getSelfLabel();
        return Hudson.getInstance().getLabel(assignedNode);
180 181
    }

182 183 184 185 186 187 188 189 190
    /**
     * Get the term used in the UI to represent this kind of {@link AbstractProject}.
     * Must start with a capital letter.
     */
    @Override
    public String getPronoun() {
        return "Project";
    }

191 192
    /**
     * Gets the directory where the module is checked out.
K
kohsuke 已提交
193 194 195
     *
     * @return
     *      null if the workspace is on a slave that's not connected.
196
     */
197
    public abstract FilePath getWorkspace();
198

199 200 201 202
    /**
     * Returns the root directory of the checked-out module.
     * <p>
     * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
203
     * and so on exists.
204 205 206 207 208
     */
    public FilePath getModuleRoot() {
        return getScm().getModuleRoot(getWorkspace());
    }

S
stephenconnolly 已提交
209 210 211 212 213 214 215 216 217 218 219
    /**
     * Returns the root directories of all checked-out modules.
     * <p>
     * Some SCMs support checking out multiple modules into the same workspace.
     * In these cases, the returned array will have a length greater than one.
     * @return The roots of all modules checked out from the SCM.
     */
    public FilePath[] getModuleRoots() {
        return getScm().getModuleRoots(getWorkspace());
    }

220
    public int getQuietPeriod() {
221
        return quietPeriod!=null ? quietPeriod : Hudson.getInstance().getQuietPeriod();
222 223 224 225 226 227 228 229
    }

    // ugly name because of EL
    public boolean getHasCustomQuietPeriod() {
        return quietPeriod!=null;
    }

    public final boolean isBuildable() {
K
kohsuke 已提交
230
        return !isDisabled();
231 232
    }

233 234 235 236 237 238 239 240
    /**
     * Used in <tt>sidepanel.jelly</tt> to decide whether to display
     * the config/delete/build links.
     */
    public boolean isConfigurable() {
        return true;
    }

241 242 243 244
    public boolean isDisabled() {
        return disabled;
    }

245 246 247 248
    /**
     * Marks the build as disabled.
     */
    public void makeDisabled(boolean b) throws IOException {
K
kohsuke 已提交
249
        if(disabled==b)     return; // noop
250 251 252 253
        this.disabled = b;
        save();
    }

K
kohsuke 已提交
254 255 256
    @Override
    public BallColor getIconColor() {
        if(isDisabled())
257
            return BallColor.DISABLED;
K
kohsuke 已提交
258 259 260
        else
            return super.getIconColor();
    }
261

262 263 264
    protected void updateTransientActions() {
        synchronized(transientActions) {
            transientActions.clear();
265

266 267 268 269 270 271 272 273
            for (JobProperty<? super P> p : properties) {
                Action a = p.getJobAction((P)this);
                if(a!=null)
                    transientActions.add(a);
            }
        }
    }

274 275 276 277 278 279 280 281 282 283
    public List<ProminentProjectAction> getProminentActions() {
        List<Action> a = getActions();
        List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
        for (Action action : a) {
            if(action instanceof ProminentProjectAction)
                pa.add((ProminentProjectAction) action);
        }
        return pa;
    }

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    @Override
    public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        super.doConfigSubmit(req,rsp);

        Set<AbstractProject> upstream = Collections.emptySet();
        if(req.getParameter("pseudoUpstreamTrigger")!=null) {
            upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class));
        }

        // dependency setting might have been changed by the user, so rebuild.
        Hudson.getInstance().rebuildDependencyGraph();

        // reflect the submission of the pseudo 'upstream build trriger'.
        // this needs to be done after we release the lock on 'this',
        // or otherwise we could dead-lock

        for (Project p : Hudson.getInstance().getProjects()) {
            boolean isUpstream = upstream.contains(p);
            synchronized(p) {
                List<AbstractProject> newChildProjects = new ArrayList<AbstractProject>(p.getDownstreamProjects());

                if(isUpstream) {
                    if(!newChildProjects.contains(this))
                        newChildProjects.add(this);
                } else {
                    newChildProjects.remove(this);
                }

                if(newChildProjects.isEmpty()) {
                    p.removePublisher(BuildTrigger.DESCRIPTOR);
                } else {
                    BuildTrigger existing = (BuildTrigger)p.getPublisher(BuildTrigger.DESCRIPTOR);
                    if(existing!=null && existing.hasSame(newChildProjects))
                        continue;   // no need to touch
                    p.addPublisher(new BuildTrigger(newChildProjects,
                        existing==null?Result.SUCCESS:existing.getThreshold()));
                }
            }
        }

        // notify the queue as the project might be now tied to different node
        Hudson.getInstance().getQueue().scheduleMaintenance();

        // this is to reflect the upstream build adjustments done above
        Hudson.getInstance().rebuildDependencyGraph();
    }

331 332
    /**
     * Schedules a build of this project.
333 334 335 336 337
     *
     * @return
     *      true if the project is actually added to the queue.
     *      false if the queue contained it and therefore the add()
     *      was noop
338
     */
339 340 341
    public boolean scheduleBuild() {
        if(isDisabled())    return false;
        return Hudson.getInstance().getQueue().add(this);
342 343
    }

344 345 346 347 348 349 350 351 352 353 354
    /**
     * Schedules a polling of this project.
     */
    public boolean schedulePolling() {
        if(isDisabled())    return false;
        SCMTrigger scmt = getTrigger(SCMTrigger.class);
        if(scmt==null)      return false;
        scmt.run();
        return true;
    }

355 356 357 358 359
    /**
     * Returns true if the build is in the queue.
     */
    @Override
    public boolean isInQueue() {
360
        return Hudson.getInstance().getQueue().contains(this);
361 362
    }

K
kohsuke 已提交
363 364 365 366 367
    @Override
    public Queue.Item getQueueItem() {
        return Hudson.getInstance().getQueue().getItem(this);
    }

368 369 370 371 372 373 374 375
    /**
     * Returns true if a build of this project is in progress.
     */
    public boolean isBuilding() {
        R b = getLastBuild();
        return b!=null && b.isBuilding();
    }

K
kohsuke 已提交
376 377 378
    /**
     * Gets the JDK that this project is configured with, or null.
     */
379
    public JDK getJDK() {
380
        return Hudson.getInstance().getJDK(jdk);
381 382 383 384 385 386 387 388 389 390
    }

    /**
     * Overwrites the JDK setting.
     */
    public synchronized void setJDK(JDK jdk) throws IOException {
        this.jdk = jdk.getName();
        save();
    }

391 392
    public BuildAuthorizationToken getAuthToken() {
        return authToken;
393 394 395 396 397 398 399 400 401 402
    }

    public SortedMap<Integer, ? extends R> _getRuns() {
        return builds.getView();
    }

    public void removeRun(R run) {
        this.builds.remove(run);
    }

403 404 405 406 407
    /**
     * Determines Class&lt;R>.
     */
    protected abstract Class<R> getBuildClass();

408 409 410
    /**
     * Creates a new build of this project for immediate execution.
     */
411 412 413 414 415 416 417 418 419 420
    protected R newBuild() throws IOException {
        try {
            R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
            builds.put(lastBuild);
            return lastBuild;
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
421
            throw handleInvocationTargetException(e);
422 423 424 425
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
426

427 428 429 430 431 432 433 434
    private IOException handleInvocationTargetException(InvocationTargetException e) {
        Throwable t = e.getTargetException();
        if(t instanceof Error)  throw (Error)t;
        if(t instanceof RuntimeException)   throw (RuntimeException)t;
        if(t instanceof IOException)    return (IOException)t;
        throw new Error(t);
    }

435 436 437
    /**
     * Loads an existing build record from disk.
     */
438 439 440 441 442 443 444 445
    protected R loadBuild(File dir) throws IOException {
        try {
            return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
446
            throw handleInvocationTargetException(e);
447 448 449 450
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
451

452 453 454 455 456 457 458
    public synchronized List<Action> getActions() {
        // add all the transient actions, too
        List<Action> actions = new Vector<Action>(super.getActions());
        actions.addAll(transientActions);
        return actions;
    }

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    /**
     * Gets the {@link Node} where this project was last built on.
     *
     * @return
     *      null if no information is available (for example,
     *      if no build was done yet.)
     */
    public Node getLastBuiltOn() {
        // where was it built on?
        AbstractBuild b = getLastBuild();
        if(b==null)
            return null;
        else
            return b.getBuiltOn();
    }

475
    /**
476
     * {@inheritDoc}
477 478 479 480 481
     *
     * <p>
     * A project must be blocked if its own previous build is in progress,
     * but derived classes can also check other conditions.
     */
482
    public boolean isBuildBlocked() {
483 484 485
        return isBuilding();
    }

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
    public String getWhyBlocked() {
        AbstractBuild<?, ?> build = getLastBuild();
        Executor e = build.getExecutor();
        String eta="";
        if(e!=null)
            eta = " (ETA:"+e.getEstimatedRemainingTime()+")";
        int lbn = build.getNumber();
        return "Build #"+lbn+" is already in progress"+eta;
    }

    public final long getEstimatedDuration() {
        AbstractBuild b = getLastSuccessfulBuild();
        if(b==null)     return -1;

        long duration = b.getDuration();
        if(duration==0) return -1;

        return duration;
    }

506 507
    public R createExecutable() throws IOException {
        return newBuild();
508 509
    }

510 511 512 513
    public void checkAbortPermission() {
        checkPermission(AbstractProject.ABORT);
    }

514 515 516 517 518 519 520 521 522 523 524
    /**
     * Gets the {@link Resource} that represents the workspace of this project.
     */
    public Resource getWorkspaceResource() {
        return new Resource(getFullDisplayName()+" workspace");
    }

    /**
     * List of necessary resources to perform the build of this project.
     */
    public ResourceList getResourceList() {
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
        final Set<ResourceActivity> resourceActivities = getResourceActivities();
        final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
        for (ResourceActivity activity : resourceActivities) {
            if (activity != this && activity != null) {
                // defensive infinite recursion and null check
                resourceLists.add(activity.getResourceList());
            }
        }
        resourceLists.add(new ResourceList().w(getWorkspaceResource()));
        return ResourceList.union(resourceLists);
    }

    /**
     * Set of child resource activities of the build of this project (override in child projects).
     * @return The set of child resource activities of the build of this project.
     */
    protected Set<ResourceActivity> getResourceActivities() {
K
kohsuke 已提交
542
        return Collections.emptySet();
543 544
    }

545
    public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException {
546
        SCM scm = getScm();
547 548 549 550 551 552 553 554 555
        if(scm==null)
            return true;    // no SCM

        try {
            FilePath workspace = getWorkspace();
            workspace.mkdirs();

            return scm.checkout(build, launcher, workspace, listener, changelogFile);
        } catch (InterruptedException e) {
556 557
            listener.getLogger().println("SCM check out aborted");
            LOGGER.log(Level.INFO,build.toString()+" aborted",e);
558 559 560 561 562 563 564 565 566 567 568 569
            return false;
        }
    }

    /**
     * Checks if there's any update in SCM, and returns true if any is found.
     *
     * <p>
     * The caller is responsible for coordinating the mutual exclusion between
     * a build and polling, as both touches the workspace.
     */
    public boolean pollSCMChanges( TaskListener listener ) {
570
        SCM scm = getScm();
571 572
        if(scm==null) {
            listener.getLogger().println("No SCM");
573 574 575 576 577
            return false;
        }
        if(isDisabled()) {
            listener.getLogger().println("Build disabled");
            return false;
578 579 580 581
        }

        try {
            FilePath workspace = getWorkspace();
K
kohsuke 已提交
582 583 584 585 586 587
            if(workspace==null) {
                // workspace offline. build now, or nothing will ever be built
                listener.getLogger().println("Workspace is offline.");
                listener.getLogger().println("Scheduling a new build to get a workspace.");
                return true;
            }
588 589 590 591 592 593 594
            if(!workspace.exists()) {
                // no workspace. build now, or nothing will ever be built
                listener.getLogger().println("No workspace is available, so can't check for updates.");
                listener.getLogger().println("Scheduling a new build to get a workspace.");
                return true;
            }

595
            return scm.pollChanges(this, workspace.createLauncher(listener), workspace, listener );
596 597 598
        } catch (AbortException e) {
            listener.fatalError("Aborted");
            return false;
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
        } catch (IOException e) {
            e.printStackTrace(listener.fatalError(e.getMessage()));
            return false;
        } catch (InterruptedException e) {
            e.printStackTrace(listener.fatalError("SCM polling aborted"));
            return false;
        }
    }

    public SCM getScm() {
        return scm;
    }

    public void setScm(SCM scm) {
        this.scm = scm;
    }

616 617 618
    /**
     * Adds a new {@link Trigger} to this {@link Project} if not active yet.
     */
619
    public void addTrigger(Trigger<?> trigger) throws IOException {
620 621 622
        addToList(trigger,triggers);
    }

623
    public void removeTrigger(TriggerDescriptor trigger) throws IOException {
624 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
        removeFromList(trigger,triggers);
    }

    protected final synchronized <T extends Describable<T>>
    void addToList( T item, List<T> collection ) throws IOException {
        for( int i=0; i<collection.size(); i++ ) {
            if(collection.get(i).getDescriptor()==item.getDescriptor()) {
                // replace
                collection.set(i,item);
                save();
                return;
            }
        }
        // add
        collection.add(item);
        save();
    }

    protected final synchronized <T extends Describable<T>>
    void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
        for( int i=0; i< collection.size(); i++ ) {
            if(collection.get(i).getDescriptor()==item) {
                // found it
                collection.remove(i);
                save();
                return;
            }
        }
    }

654 655
    public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
        return (Map)Descriptor.toMap(triggers);
656 657
    }

658 659 660 661 662 663 664 665 666 667 668
    /**
     * Gets the specific trigger, or null if the propert is not configured for this job.
     */
    public <T extends Trigger> T getTrigger(Class<T> clazz) {
        for (Trigger p : triggers) {
            if(clazz.isInstance(p))
                return clazz.cast(p);
        }
        return null;
    }

669 670 671 672 673 674 675 676 677 678 679 680 681 682
//
//
// fingerprint related
//
//
    /**
     * True if the builds of this project produces {@link Fingerprint} records.
     */
    public abstract boolean isFingerprintConfigured();

    /**
     * Gets the other {@link AbstractProject}s that should be built
     * when a build of this project is completed.
     */
K
kohsuke 已提交
683
    @Exported
684 685 686
    public final List<AbstractProject> getDownstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getDownstream(this);
    }
687

K
kohsuke 已提交
688
    @Exported
689 690
    public final List<AbstractProject> getUpstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getUpstream(this);
K
kohsuke 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
    }

    /**
     * Gets all the upstream projects including transitive upstream projects.
     *
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveUpstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getTransitiveUpstream(this);
    }

    /**
     * Gets all the downstream projects including transitive downstream projects.
     *
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveDownstreamProjects() {
708
        return Hudson.getInstance().getDependencyGraph().getTransitiveDownstream(this);
709 710 711 712 713 714 715 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
    }

    /**
     * Gets the dependency relationship map between this project (as the source)
     * and that project (as the sink.)
     *
     * @return
     *      can be empty but not null. build number of this project to the build
     *      numbers of that project.
     */
    public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
        TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);

        checkAndRecord(that, r, this.getBuilds());
        // checkAndRecord(that, r, that.getBuilds());

        return r;
    }

    /**
     * Helper method for getDownstreamRelationship.
     *
     * For each given build, find the build number range of the given project and put that into the map.
     */
    private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
        for (R build : builds) {
            RangeSet rs = build.getDownstreamRelationship(that);
            if(rs==null || rs.isEmpty())
                continue;

            int n = build.getNumber();

            RangeSet value = r.get(n);
            if(value==null)
                r.put(n,rs);
            else
                value.add(rs);
        }
    }

749 750 751 752 753 754
    /**
     * Builds the dependency graph.
     * @see DependencyGraph
     */
    protected abstract void buildDependencyGraph(DependencyGraph graph);

K
kohsuke 已提交
755 756 757 758 759 760 761
    protected SearchIndexBuilder makeSearchIndex() {
        SearchIndexBuilder sib = super.makeSearchIndex();
        if(isBuildable() && Hudson.isAdmin())
            sib.add("build","build");
        return sib;
    }

762 763 764 765 766
    @Override
    protected HistoryWidget createHistoryWidget() {
        return new BuildHistoryWidget<R>(this,getBuilds(),HISTORY_ADAPTER);
    }

767 768 769 770 771 772 773 774 775
//
//
// actions
//
//
    /**
     * Schedules a new build command.
     */
    public void doBuild( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
776
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
777 778 779 780 781 782 783 784
        scheduleBuild();
        rsp.forwardToPreviousPage(req);
    }

    /**
     * Schedules a new SCM polling command.
     */
    public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
785 786 787
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
        schedulePolling();
        rsp.forwardToPreviousPage(req);
788 789 790 791 792 793
    }

    /**
     * Cancels a scheduled build.
     */
    public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
794
        checkPermission(BUILD);
795

796
        Hudson.getInstance().getQueue().cancel(this);
797 798 799
        rsp.forwardToPreviousPage(req);
    }

800 801 802
    @Override
    protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
        super.submit(req,rsp);
803 804 805 806 807 808 809 810 811 812 813 814 815 816

        disabled = req.getParameter("disable")!=null;

        jdk = req.getParameter("jdk");
        if(req.getParameter("hasCustomQuietPeriod")!=null) {
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
        } else {
            quietPeriod = null;
        }

        if(req.getParameter("hasSlaveAffinity")!=null) {
            canRoam = false;
            assignedNode = req.getParameter("slave");
            if(assignedNode !=null) {
817
                if(Hudson.getInstance().getLabel(assignedNode).isEmpty())
818
                    assignedNode = null;   // no such label
819 820 821 822 823 824
            }
        } else {
            canRoam = true;
            assignedNode = null;
        }

825
        authToken = BuildAuthorizationToken.create(req);
826

827 828 829 830
        setScm(SCMS.parseSCM(req));

        for (Trigger t : triggers)
            t.stop();
831
        triggers = buildDescribable(req, Triggers.getApplicableTriggers(this), "trigger");
832 833
        for (Trigger t : triggers)
            t.start(this,true);
834 835

        updateTransientActions();
836 837
    }

838
    protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix)
839 840
        throws FormException {

841
        JSONObject data = StructuredForm.get(req);
842
        List<T> r = new Vector<T>();
843
        for( int i=0; i< descriptors.size(); i++ ) {
844 845 846
            String name = prefix + i;
            if(req.getParameter(name)!=null) {
                T instance = descriptors.get(i).newInstance(req,data.getJSONObject(name));
847
                r.add(instance);
848 849
            }
        }
850
        return r;
851 852 853 854 855 856 857 858 859
    }

    /**
     * Serves the workspace files.
     */
    public void doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
        FilePath ws = getWorkspace();
        if(!ws.exists()) {
            // if there's no workspace, report a nice error message
860
            req.getView(this,"noWorkspace.jelly").forward(req,rsp);
861
        } else {
K
kohsuke 已提交
862
            new DirectoryBrowserSupport(this,getDisplayName()+" workspace").serveFile(req, rsp, ws, "folder.gif", true);
863 864
        }
    }
865

K
kohsuke 已提交
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
    /**
     * RSS feed for changes in this project.
     */
    public void doRssChangelog(  StaplerRequest req, StaplerResponse rsp  ) throws IOException, ServletException {
        class FeedItem {
            ChangeLogSet.Entry e;
            int idx;

            public FeedItem(Entry e, int idx) {
                this.e = e;
                this.idx = idx;
            }

            AbstractBuild<?,?> getBuild() {
                return e.getParent().build;
            }
        }

        List<FeedItem> entries = new ArrayList<FeedItem>();

        for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
            int idx=0;
            for( ChangeLogSet.Entry e : r.getChangeSet())
                entries.add(new FeedItem(e,idx++));
        }

        RSS.forwardToRss(
893
            getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
K
kohsuke 已提交
894 895 896
            getUrl()+"changes",
            entries, new FeedAdapter<FeedItem>() {
                public String getEntryTitle(FeedItem item) {
K
kohsuke 已提交
897
                    return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
K
kohsuke 已提交
898 899 900 901 902 903 904 905 906 907
                }

                public String getEntryUrl(FeedItem item) {
                    return item.getBuild().getUrl()+"changes#detail"+item.idx;
                }

                public String getEntryID(FeedItem item) {
                    return getEntryUrl(item);
                }

908 909 910 911 912 913 914
                public String getEntryDescription(FeedItem item) {
                    StringBuilder buf = new StringBuilder();
                    for(String path : item.e.getAffectedPaths())
                        buf.append(path).append('\n');
                    return buf.toString();
                }

K
kohsuke 已提交
915 916 917 918 919 920 921
                public Calendar getEntryTimestamp(FeedItem item) {
                    return item.getBuild().getTimestamp();
                }
            },
            req, rsp );
    }

922 923 924 925 926 927 928 929 930 931 932 933
    /**
     * Finds a {@link AbstractProject} that has the name closest to the given name.
     */
    public static AbstractProject findNearest(String name) {
        List<AbstractProject> projects = Hudson.getInstance().getAllItems(AbstractProject.class);
        String[] names = new String[projects.size()];
        for( int i=0; i<projects.size(); i++ )
            names[i] = projects.get(i).getName();

        String nearest = EditDistance.findNearest(name, names);
        return (AbstractProject)Hudson.getInstance().getItem(nearest);
    }
934 935 936 937 938 939

    private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
            return o2-o1;
        }
    };
940 941

    private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
942

K
kohsuke 已提交
943
    public static final Permission BUILD = new Permission(PERMISSIONS, "Build", Permission.UPDATE);
944 945 946 947
    /**
     * Permission to abort a build. For now, let's make it the same as {@link #BUILD}
     */
    public static final Permission ABORT = BUILD;
948
}