AbstractProject.java 41.9 KB
Newer Older
K
kohsuke 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * The MIT License
 * 
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot, Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts, id:cactusman
 * 
 * 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.
 */
24 25
package hudson.model;

K
kohsuke 已提交
26
import hudson.AbortException;
27
import hudson.FeedAdapter;
28
import hudson.FilePath;
29
import hudson.Launcher;
30
import hudson.maven.MavenModule;
M
mdonohue 已提交
31 32
import hudson.model.Cause.UserCause;
import hudson.model.Cause.LegacyCodeCause;
33 34 35
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.RunMap.Constructor;
K
kohsuke 已提交
36
import hudson.model.listeners.RunListener;
37
import hudson.remoting.AsyncFutureImpl;
K
kohsuke 已提交
38
import hudson.scm.ChangeLogSet;
K
kohsuke 已提交
39
import hudson.scm.ChangeLogSet.Entry;
40
import hudson.scm.NullSCM;
41
import hudson.scm.SCM;
K
kohsuke 已提交
42
import hudson.scm.SCMS;
J
jbq 已提交
43
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
44
import hudson.security.Permission;
45
import hudson.tasks.BuildStep;
J
jbq 已提交
46
import hudson.tasks.BuildTrigger;
47
import hudson.tasks.Mailer;
48
import hudson.tasks.Publisher;
K
kohsuke 已提交
49
import hudson.triggers.SCMTrigger;
50
import hudson.triggers.Trigger;
51
import hudson.triggers.TriggerDescriptor;
52
import hudson.triggers.Triggers;
53
import hudson.util.DescribableList;
54
import hudson.util.EditDistance;
K
kohsuke 已提交
55 56 57 58 59 60
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;
61

K
kohsuke 已提交
62
import javax.servlet.ServletException;
63
import java.io.File;
64
import java.io.IOException;
K
kohsuke 已提交
65
import java.lang.reflect.InvocationTargetException;
K
kohsuke 已提交
66
import java.util.ArrayList;
67
import java.util.Arrays;
68
import java.util.Calendar;
69
import java.util.Collection;
J
jbq 已提交
70
import java.util.Collections;
71
import java.util.Comparator;
J
jbq 已提交
72
import java.util.HashSet;
73 74
import java.util.List;
import java.util.Map;
J
jbq 已提交
75
import java.util.Set;
76 77 78
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
K
kohsuke 已提交
79
import java.util.concurrent.Future;
80 81
import java.util.logging.Level;
import java.util.logging.Logger;
82 83 84

/**
 * Base implementation of {@link Job}s that build software.
85 86 87
 *
 * For now this is primarily the common part of {@link Project} and {@link MavenModule}.
 *
88 89 90
 * @author Kohsuke Kawaguchi
 * @see AbstractBuild
 */
91
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
92

93
    /**
94 95 96
     * {@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()}.
97
     */
K
kohsuke 已提交
98
    private volatile SCM scm = new NullSCM();
99

100 101 102
    /**
     * All the builds keyed by their build number.
     */
103
    protected transient /*almost final*/ RunMap<R> builds = new RunMap<R>();
104 105 106 107

    /**
     * The quiet period. Null to delegate to the system default.
     */
K
kohsuke 已提交
108
    private volatile Integer quietPeriod = null;
109 110

    /**
111 112 113 114 115 116 117
     * 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
     * with the master node.
     *
118
     * @see #canRoam
119 120 121 122 123
     */
    private String assignedNode;

    /**
     * True if this project can be built on any node.
124
     *
125
     * <p>
126 127
     * This somewhat ugly flag combination is so that we can migrate
     * existing Hudson installations nicely.
128
     */
K
kohsuke 已提交
129
    private volatile boolean canRoam;
130 131 132 133

    /**
     * True to suspend new builds.
     */
K
kohsuke 已提交
134
    protected volatile boolean disabled;
135 136

    /**
137 138 139
     * Identifies {@link JDK} to be used.
     * Null if no explicit configuration is required.
     *
140
     * <p>
141 142 143
     * Can't store {@link JDK} directly because {@link Hudson} and {@link Project}
     * are saved independently.
     *
144 145
     * @see Hudson#getJDK(String)
     */
K
kohsuke 已提交
146
    private volatile String jdk;
147

148 149 150 151
    /**
     * @deprecated
     */
    private transient boolean enableRemoteTrigger;
152

K
kohsuke 已提交
153
    private volatile BuildAuthorizationToken authToken = null;
154

155 156 157
    /**
     * List of all {@link Trigger}s for this project.
     */
158
    protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
159

160 161
    /**
     * {@link Action}s contributed from subsidiary objects associated with
162 163 164 165
     * {@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.
166
     */
167
    protected transient /*final*/ List<Action> transientActions = new Vector<Action>();
168

169
    protected AbstractProject(ItemGroup parent, String name) {
170
        super(parent,name);
171

K
kohsuke 已提交
172
        if(!Hudson.getInstance().getNodes().isEmpty()) {
173
            // if a new job is configured with Hudson that already has slave nodes
174 175 176 177 178
            // make it roamable by default
            canRoam = true;
        }
    }

179
    @Override
180
    public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
181
        super.onLoad(parent, name);
182 183

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

190
        if(triggers==null)
191
            // it didn't exist in < 1.28
192
            triggers = new Vector<Trigger<?>>();
193
        for (Trigger t : triggers)
194
            t.start(this,false);
195

196 197
        if(transientActions==null)
            transientActions = new Vector<Action>();    // happens when loaded from disk
198
        updateTransientActions();
199 200
    }

K
kohsuke 已提交
201 202 203
    protected void performDelete() throws IOException {
        // prevent a new build while a delete operation is in progress
        makeDisabled(true);
204
        FilePath ws = getWorkspace();
205 206
        if(ws!=null)
            getScm().processWorkspaceBeforeDeletion(this, ws,getLastBuiltOn());
K
kohsuke 已提交
207 208 209
        super.performDelete();
    }

210
    /**
211 212
     * If this project is configured to be always built on this node,
     * return that {@link Node}. Otherwise null.
213
     */
214
    public Label getAssignedLabel() {
215
        if(canRoam)
216 217
            return null;

218
        if(assignedNode==null)
219 220
            return Hudson.getInstance().getSelfLabel();
        return Hudson.getInstance().getLabel(assignedNode);
221 222
    }

K
kohsuke 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    /**
     * Sets the assigned label.
     */
    public void setAssignedLabel(Label l) throws IOException {
        if(l==null) {
            canRoam = true;
            assignedNode = null;
        } else {
            canRoam = false;
            if(l==Hudson.getInstance().getSelfLabel())  assignedNode = null;
            else                                        assignedNode = l.getName();
        }
        save();
    }

238
    /**
239 240
     * Get the term used in the UI to represent this kind of {@link AbstractProject}.
     * Must start with a capital letter.
241 242 243
     */
    @Override
    public String getPronoun() {
244
        return Messages.AbstractProject_Pronoun();
245 246
    }

247 248 249 250 251 252 253 254 255 256 257 258 259
    /**
     * Returns the root project value.
     *
     * @return the root project value.
     */
	public AbstractProject getRootProject() {
        if (this.getParent() instanceof Hudson) {
            return this;
        } else {
            return ((AbstractProject) this.getParent()).getRootProject();
        }
    }

260 261
    /**
     * Gets the directory where the module is checked out.
262 263 264
     *
     * @return
     *      null if the workspace is on a slave that's not connected.
265
     */
266
    public abstract FilePath getWorkspace();
267

268 269 270
    /**
     * Returns the root directory of the checked-out module.
     * <p>
271 272
     * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
     * and so on exists.
273 274
     */
    public FilePath getModuleRoot() {
K
kohsuke 已提交
275
        FilePath ws = getWorkspace();
276
        if(ws==null)    return null;
K
kohsuke 已提交
277
        return getScm().getModuleRoot(ws);
278 279
    }

S
stephenconnolly 已提交
280 281 282 283 284 285 286 287 288 289 290
    /**
     * 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());
    }

291
    public int getQuietPeriod() {
292
        return quietPeriod!=null ? quietPeriod : Hudson.getInstance().getQuietPeriod();
293 294 295 296
    }

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

    public final boolean isBuildable() {
K
kohsuke 已提交
301
        return !isDisabled();
302 303
    }

304
    /**
305 306
     * Used in <tt>sidepanel.jelly</tt> to decide whether to display
     * the config/delete/build links.
307 308 309 310 311
     */
    public boolean isConfigurable() {
        return true;
    }

312 313 314 315
    public boolean isDisabled() {
        return disabled;
    }

316 317 318 319
    /**
     * Marks the build as disabled.
     */
    public void makeDisabled(boolean b) throws IOException {
320
        if(disabled==b)     return; // noop
321
        this.disabled = b;
K
bug fix  
kohsuke 已提交
322 323
        if(b)
            Hudson.getInstance().getQueue().cancel(this);
324 325 326
        save();
    }

K
kohsuke 已提交
327 328
    @Override
    public BallColor getIconColor() {
329
        if(isDisabled())
330
            return BallColor.DISABLED;
K
kohsuke 已提交
331 332 333
        else
            return super.getIconColor();
    }
334

335
    protected void updateTransientActions() {
336
        synchronized(transientActions) {
337
            transientActions.clear();
338

339
            for (JobProperty<? super P> p : properties) {
340 341
                Action a = p.getJobAction((P)this);
                if(a!=null)
342 343 344 345 346
                    transientActions.add(a);
            }
        }
    }

347
    /**
348 349
     * Returns the live list of all {@link Publisher}s configured for this project.
     *
350
     * <p>
351 352
     * This method couldn't be called <tt>getPublishers()</tt> because existing methods
     * in sub-classes return different inconsistent types.
353
     */
354
    public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
355

K
kohsuke 已提交
356 357 358 359 360 361
    @Override
    public void addProperty(JobProperty<? super P> jobProp) throws IOException {
        super.addProperty(jobProp);
        updateTransientActions();
    }

362 363 364 365
    public List<ProminentProjectAction> getProminentActions() {
        List<Action> a = getActions();
        List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
        for (Action action : a) {
366
            if(action instanceof ProminentProjectAction)
367 368 369 370 371
                pa.add((ProminentProjectAction) action);
        }
        return pa;
    }

372
    @Override
373 374
    public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        super.doConfigSubmit(req,rsp);
375 376

        Set<AbstractProject> upstream = Collections.emptySet();
377 378
        if(req.getParameter("pseudoUpstreamTrigger")!=null) {
            upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class));
379 380 381 382 383 384 385 386 387
        }

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

388
        for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
389
            boolean isUpstream = upstream.contains(p);
390 391 392 393 394 395 396
            synchronized(p) {
                // does 'p' include us in its BuildTrigger? 
                DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
                BuildTrigger trigger = (BuildTrigger) pl.get(BuildTrigger.DESCRIPTOR);
                List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects();
                if(isUpstream) {
                    if(!newChildProjects.contains(this))
397 398 399 400 401
                        newChildProjects.add(this);
                } else {
                    newChildProjects.remove(this);
                }

402
                if(newChildProjects.isEmpty()) {
403
                    pl.remove(BuildTrigger.DESCRIPTOR);
404
                } else {
405 406 407
                    BuildTrigger existing = (BuildTrigger)pl.get(BuildTrigger.DESCRIPTOR);
                    if(existing!=null && existing.hasSame(newChildProjects))
                        continue;   // no need to touch
408
                    pl.add(new BuildTrigger(newChildProjects,
409
                        existing==null?Result.SUCCESS:existing.getThreshold()));
410 411 412 413 414 415 416 417 418 419 420
                }
            }
        }

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

M
mdonohue 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild(Cause)}.  Since 1.283
	 */
    public boolean scheduleBuild() {
    	return scheduleBuild(new LegacyCodeCause());
    }
    
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild(int, Cause)}.  Since 1.283
	 */
    public boolean scheduleBuild(int quietPeriod) {
    	return scheduleBuild(quietPeriod, new LegacyCodeCause());
    }
    
437 438
    /**
     * Schedules a build of this project.
439 440 441 442 443
     *
     * @return
     *      true if the project is actually added to the queue.
     *      false if the queue contained it and therefore the add()
     *      was noop
444
     */
M
mdonohue 已提交
445 446
    public boolean scheduleBuild(Cause c) {
        return scheduleBuild(getQuietPeriod(), c);
K
kohsuke 已提交
447 448
    }

M
mdonohue 已提交
449
    public boolean scheduleBuild(int quietPeriod, Cause c) {
450 451 452
        if (isDisabled())
            return false;

M
mindless 已提交
453
        if (isParameterized())
454 455
        	return Hudson.getInstance().getQueue().add(
        			this, quietPeriod, new ParametersAction(getDefaultParametersValues()), new CauseAction(c));
M
mindless 已提交
456
        else
457
            return Hudson.getInstance().getQueue().add(this, quietPeriod, new CauseAction(c));
458 459 460 461 462 463
    }

    private List<ParameterValue> getDefaultParametersValues() {
        ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
        ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
        
M
mindless 已提交
464 465 466
        /*
         * This check is made ONLY if someone will call this method even if isParametrized() is false.
         */
467 468 469 470 471 472 473 474 475 476 477 478 479
        if(paramDefProp == null)
            return defValues;
        
        /* Scan for all parameter with an associated default values */
        for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
        {
           ParameterValue defaultValue  = paramDefinition.getDefaultParameterValue();
            
            if(defaultValue != null)
                defValues.add(defaultValue);           
        }
        
        return defValues;
K
kohsuke 已提交
480 481
    }

M
mdonohue 已提交
482 483 484 485 486 487 488 489
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild2(int, Cause)}.  Since 1.283
	 */
    public Future<R> scheduleBuild2(int quietPeriod) {
    	return scheduleBuild2(quietPeriod, new LegacyCodeCause());
    }
    
K
kohsuke 已提交
490
    /**
491 492
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
K
kohsuke 已提交
493
     */
M
mdonohue 已提交
494
    public Future<R> scheduleBuild2(int quietPeriod, Cause c) {
K
kohsuke 已提交
495 496
        R lastBuild = getLastBuild();
        final int n;
497 498
        if(lastBuild!=null) n = lastBuild.getNumber();
        else                n = -1;
K
kohsuke 已提交
499 500

        Future<R> f = new AsyncFutureImpl<R>() {
501
            final RunListener r = new RunListener<AbstractBuild>(AbstractBuild.class) {
502
                public void onFinalized(AbstractBuild r) {
503 504
                    if(r.getProject()==AbstractProject.this && r.getNumber()>n) {
                        set((R)r);
K
kohsuke 已提交
505 506 507 508 509
                        unregister();
                    }
                }
            };

510
            { r.register(); }
K
kohsuke 已提交
511 512
        };

M
mdonohue 已提交
513
        scheduleBuild(quietPeriod, c);
K
kohsuke 已提交
514 515

        return f;
516 517
    }

518 519 520 521
    /**
     * Schedules a polling of this project.
     */
    public boolean schedulePolling() {
522
        if(isDisabled())    return false;
523
        SCMTrigger scmt = getTrigger(SCMTrigger.class);
524
        if(scmt==null)      return false;
525 526 527 528
        scmt.run();
        return true;
    }

529 530 531 532 533
    /**
     * Returns true if the build is in the queue.
     */
    @Override
    public boolean isInQueue() {
534
        return Hudson.getInstance().getQueue().contains(this);
535 536
    }

K
kohsuke 已提交
537 538 539 540 541
    @Override
    public Queue.Item getQueueItem() {
        return Hudson.getInstance().getQueue().getItem(this);
    }

542 543 544 545 546
    /**
     * Returns true if a build of this project is in progress.
     */
    public boolean isBuilding() {
        R b = getLastBuild();
547
        return b!=null && b.isBuilding();
548 549
    }

K
kohsuke 已提交
550 551 552
    /**
     * Gets the JDK that this project is configured with, or null.
     */
553
    public JDK getJDK() {
554
        return Hudson.getInstance().getJDK(jdk);
555 556 557 558 559
    }

    /**
     * Overwrites the JDK setting.
     */
K
kohsuke 已提交
560
    public void setJDK(JDK jdk) throws IOException {
561 562 563 564
        this.jdk = jdk.getName();
        save();
    }

565 566
    public BuildAuthorizationToken getAuthToken() {
        return authToken;
567 568 569 570 571 572 573 574 575 576
    }

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

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

577 578 579 580 581
    /**
     * Determines Class&lt;R>.
     */
    protected abstract Class<R> getBuildClass();

H
huybrechts 已提交
582 583 584
    // keep track of the previous time we started a build
    private long lastBuildStartTime;
    
585 586 587
    /**
     * Creates a new build of this project for immediate execution.
     */
H
huybrechts 已提交
588 589 590 591 592 593 594 595 596 597 598
    protected synchronized R newBuild() throws IOException {
    	// make sure we don't start two builds in the same second
    	// so the build directories will be different too
    	long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
    	if (timeSinceLast < 1000) {
    		try {
				Thread.sleep(1000 - timeSinceLast);
			} catch (InterruptedException e) {
			}
    	}
    	lastBuildStartTime = System.currentTimeMillis();
599
        try {
600
            R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
601 602 603 604 605 606 607
            builds.put(lastBuild);
            return lastBuild;
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
608
            throw handleInvocationTargetException(e);
609 610 611 612
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
613

614
    private IOException handleInvocationTargetException(InvocationTargetException e) {
615
        Throwable t = e.getTargetException();
616 617 618
        if(t instanceof Error)  throw (Error)t;
        if(t instanceof RuntimeException)   throw (RuntimeException)t;
        if(t instanceof IOException)    return (IOException)t;
619 620 621
        throw new Error(t);
    }

622 623 624
    /**
     * Loads an existing build record from disk.
     */
625 626
    protected R loadBuild(File dir) throws IOException {
        try {
627
            return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
628 629 630 631 632
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
633
            throw handleInvocationTargetException(e);
634 635 636 637
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
638

K
kohsuke 已提交
639 640
    /**
     * {@inheritDoc}
641
     *
K
kohsuke 已提交
642 643
     * <p>
     * Note that this method returns a read-only view of {@link Action}s.
644 645
     * {@link BuildStep}s and others who want to add a project action
     * should do so by implementing {@link BuildStep#getProjectAction(AbstractProject)}.
K
kohsuke 已提交
646
     */
647 648 649 650
    public synchronized List<Action> getActions() {
        // add all the transient actions, too
        List<Action> actions = new Vector<Action>(super.getActions());
        actions.addAll(transientActions);
651
        // return the read only list to cause a failure on plugins who try to add an action here
K
kohsuke 已提交
652
        return Collections.unmodifiableList(actions);
653 654
    }

655 656
    /**
     * Gets the {@link Node} where this project was last built on.
657 658 659 660
     *
     * @return
     *      null if no information is available (for example,
     *      if no build was done yet.)
661 662 663 664
     */
    public Node getLastBuiltOn() {
        // where was it built on?
        AbstractBuild b = getLastBuild();
665
        if(b==null)
666 667 668 669 670
            return null;
        else
            return b.getBuiltOn();
    }

671
    /**
672
     * {@inheritDoc}
673
     *
674
     * <p>
675 676
     * A project must be blocked if its own previous build is in progress,
     * but derived classes can also check other conditions.
677
     */
678
    public boolean isBuildBlocked() {
679 680 681
        return isBuilding();
    }

682 683 684
    public String getWhyBlocked() {
        AbstractBuild<?, ?> build = getLastBuild();
        Executor e = build.getExecutor();
685 686
        String eta="";
        if(e!=null)
K
i18n  
kohsuke 已提交
687
            eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
688
        int lbn = build.getNumber();
689
        return Messages.AbstractProject_BuildInProgress(lbn,eta);
690 691 692 693
    }

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

        long duration = b.getDuration();
697
        if(duration==0) return -1;
698 699 700 701

        return duration;
    }

702
    public R createExecutable() throws IOException {
703
        if(isDisabled())    return null;
704
        return newBuild();
705 706
    }

707 708 709 710
    public void checkAbortPermission() {
        checkPermission(AbstractProject.ABORT);
    }

K
kohsuke 已提交
711 712 713 714
    public boolean hasAbortPermission() {
        return hasPermission(AbstractProject.ABORT);
    }

715 716
    /**
     * Gets the {@link Resource} that represents the workspace of this project.
717
     * Useful for locking and mutual exclusion control.
718 719
     */
    public Resource getWorkspaceResource() {
720
        return new Resource(getFullDisplayName()+" workspace");
721 722 723 724 725 726
    }

    /**
     * List of necessary resources to perform the build of this project.
     */
    public ResourceList getResourceList() {
727
        final Set<ResourceActivity> resourceActivities = getResourceActivities();
728
        final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
729 730 731 732 733 734 735 736 737 738 739
        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);
    }

    /**
740 741
     * 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.
742 743
     */
    protected Set<ResourceActivity> getResourceActivities() {
K
kohsuke 已提交
744
        return Collections.emptySet();
745 746
    }

747
    public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException {
748
        SCM scm = getScm();
749 750
        if(scm==null)
            return true;    // no SCM
751 752 753 754 755

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

756
            return scm.checkout(build, launcher, workspace, listener, changelogFile);
757
        } catch (InterruptedException e) {
K
i18n  
kohsuke 已提交
758
            listener.getLogger().println(Messages.AbstractProject_ScmAborted());
759
            LOGGER.log(Level.INFO,build.toString()+" aborted",e);
760 761 762 763 764 765
            return false;
        }
    }

    /**
     * Checks if there's any update in SCM, and returns true if any is found.
766
     *
767
     * <p>
768 769
     * The caller is responsible for coordinating the mutual exclusion between
     * a build and polling, as both touches the workspace.
770
     */
771
    public boolean pollSCMChanges( TaskListener listener ) {
772
        SCM scm = getScm();
773
        if(scm==null) {
K
i18n  
kohsuke 已提交
774
            listener.getLogger().println(Messages.AbstractProject_NoSCM());
775 776
            return false;
        }
777
        if(isDisabled()) {
K
i18n  
kohsuke 已提交
778
            listener.getLogger().println(Messages.AbstractProject_Disabled());
779
            return false;
780 781 782
        }

        try {
K
kohsuke 已提交
783
            FilePath workspace = getWorkspace();
784
            if (scm.requiresWorkspaceForPolling() && (workspace == null || !workspace.exists())) {
K
kohsuke 已提交
785
                // workspace offline. build now, or nothing will ever be built
K
kohsuke 已提交
786
                Label label = getAssignedLabel();
K
kohsuke 已提交
787
                if (label != null && label.isSelfLabel()) {
788
                    // if the build is fixed on a node, then attempting a build will do us
K
kohsuke 已提交
789
                    // no good. We should just wait for the slave to come back.
790
                    listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
K
kohsuke 已提交
791 792
                    return false;
                }
K
kohsuke 已提交
793
                if (workspace == null)
794
                    listener.getLogger().println(Messages.AbstractProject_WorkspaceOffline());
K
kohsuke 已提交
795
                else
796 797
                    listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
                listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace());
K
kohsuke 已提交
798 799
                return true;
            }
K
kohsuke 已提交
800

801
            Launcher launcher = workspace != null ? workspace.createLauncher(listener) : null;
K
kohsuke 已提交
802 803
            LOGGER.fine("Polling SCM changes of " + getName());
            return scm.pollChanges(this, launcher, workspace, listener);
804
        } catch (AbortException e) {
K
i18n  
kohsuke 已提交
805
            listener.fatalError(Messages.AbstractProject_Aborted());
806
            return false;
807 808 809 810
        } catch (IOException e) {
            e.printStackTrace(listener.fatalError(e.getMessage()));
            return false;
        } catch (InterruptedException e) {
811
            e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
812 813 814 815
            return false;
        }
    }

816 817
    /**
     * Returns true if this user has made a commit to this project.
818
     *
819 820 821
     * @since 1.191
     */
    public boolean hasParticipant(User user) {
822 823
        for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
            if(build.hasParticipant(user))
824 825 826 827
                return true;
        return false;
    }

828 829 830 831 832 833 834 835
    public SCM getScm() {
        return scm;
    }

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

836 837 838
    /**
     * Adds a new {@link Trigger} to this {@link Project} if not active yet.
     */
839
    public void addTrigger(Trigger<?> trigger) throws IOException {
840
        addToList(trigger,triggers);
841 842
    }

843
    public void removeTrigger(TriggerDescriptor trigger) throws IOException {
844
        removeFromList(trigger,triggers);
845 846
    }

847 848 849 850
    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()) {
851
                // replace
852
                collection.set(i,item);
853 854 855 856 857 858 859 860 861
                save();
                return;
            }
        }
        // add
        collection.add(item);
        save();
    }

862 863 864 865
    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) {
866 867 868 869 870 871 872 873
                // found it
                collection.remove(i);
                save();
                return;
            }
        }
    }

874 875
    public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
        return (Map)Descriptor.toMap(triggers);
876 877
    }

878
    /**
879
     * Gets the specific trigger, or null if the propert is not configured for this job.
880 881 882
     */
    public <T extends Trigger> T getTrigger(Class<T> clazz) {
        for (Trigger p : triggers) {
883
            if(clazz.isInstance(p))
884 885 886 887 888
                return clazz.cast(p);
        }
        return null;
    }

889 890 891 892 893
//
//
// fingerprint related
//
//
894 895 896 897 898 899
    /**
     * True if the builds of this project produces {@link Fingerprint} records.
     */
    public abstract boolean isFingerprintConfigured();

    /**
900 901
     * Gets the other {@link AbstractProject}s that should be built
     * when a build of this project is completed.
902
     */
K
kohsuke 已提交
903
    @Exported
904 905 906
    public final List<AbstractProject> getDownstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getDownstream(this);
    }
907

K
kohsuke 已提交
908
    @Exported
909 910
    public final List<AbstractProject> getUpstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getUpstream(this);
K
kohsuke 已提交
911 912
    }

K
kohsuke 已提交
913
    /**
914 915 916 917
     * Returns only those upstream projects that defines {@link BuildTrigger} to this project.
     * This is a subset of {@link #getUpstreamProjects()}
     *
     * @return A List of upstream projects that has a {@link BuildTrigger} to this project.
K
kohsuke 已提交
918 919 920 921
     */
    public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
        ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
        for (AbstractProject ap : getUpstreamProjects()) {
922 923 924 925
            BuildTrigger buildTrigger = (BuildTrigger)ap.getPublishersList().get(BuildTrigger.DESCRIPTOR);
            if (buildTrigger != null)
                if (buildTrigger.getChildProjects().contains(this))
                    result.add(ap);
926
        }        
K
kohsuke 已提交
927
        return result;
928 929
    }    
    
K
kohsuke 已提交
930 931
    /**
     * Gets all the upstream projects including transitive upstream projects.
932
     *
K
kohsuke 已提交
933 934 935
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveUpstreamProjects() {
936
        return Hudson.getInstance().getDependencyGraph().getTransitiveUpstream(this);
K
kohsuke 已提交
937 938 939
    }

    /**
940 941
     * Gets all the downstream projects including transitive downstream projects.
     *
K
kohsuke 已提交
942 943 944
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveDownstreamProjects() {
945
        return Hudson.getInstance().getDependencyGraph().getTransitiveDownstream(this);
946 947 948 949 950
    }

    /**
     * Gets the dependency relationship map between this project (as the source)
     * and that project (as the sink.)
951 952 953 954
     *
     * @return
     *      can be empty but not null. build number of this project to the build
     *      numbers of that project.
955 956
     */
    public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
957
        TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
958 959 960 961 962 963 964 965 966

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

        return r;
    }

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

            int n = build.getNumber();

            RangeSet value = r.get(n);
979 980
            if(value==null)
                r.put(n,rs);
981 982 983 984 985
            else
                value.add(rs);
        }
    }

986 987 988 989 990 991
    /**
     * Builds the dependency graph.
     * @see DependencyGraph
     */
    protected abstract void buildDependencyGraph(DependencyGraph graph);

K
kohsuke 已提交
992 993
    protected SearchIndexBuilder makeSearchIndex() {
        SearchIndexBuilder sib = super.makeSearchIndex();
994 995
        if(isBuildable() && Hudson.isAdmin())
            sib.add("build","build");
K
kohsuke 已提交
996 997 998
        return sib;
    }

999 1000
    @Override
    protected HistoryWidget createHistoryWidget() {
1001
        return new BuildHistoryWidget<R>(this,getBuilds(),HISTORY_ADAPTER);
1002
    }
1003
    
K
kohsuke 已提交
1004
    public boolean isParameterized() {
1005
        return getProperty(ParametersDefinitionProperty.class) != null;
K
kohsuke 已提交
1006
    }
1007

1008 1009 1010 1011 1012
//
//
// actions
//
//
1013 1014 1015
    /**
     * Schedules a new build command.
     */
1016
    public void doBuild( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1017
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
1018

K
kohsuke 已提交
1019 1020 1021
        // if a build is parameterized, let that take over
        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
1022
            pp._doBuild(req,rsp);
K
kohsuke 已提交
1023 1024 1025
            return;
        }

1026
        String delay = req.getParameter("delay");
1027
        if (delay!=null) {
M
mindless 已提交
1028 1029 1030 1031 1032
            if (!isDisabled()) {
                try {
                    // TODO: more unit handling
                    if(delay.endsWith("sec"))   delay=delay.substring(0,delay.length()-3);
                    if(delay.endsWith("secs"))  delay=delay.substring(0,delay.length()-4);
1033 1034
                    Hudson.getInstance().getQueue().add(this, Integer.parseInt(delay), 
                    		new CauseAction(new UserCause()));
M
mindless 已提交
1035 1036 1037 1038 1039
                } catch (NumberFormatException e) {
                    throw new ServletException("Invalid delay parameter value: "+delay);
                }
            }
        } else {
M
mdonohue 已提交
1040
            scheduleBuild(new UserCause());
1041
        }
1042 1043
        rsp.forwardToPreviousPage(req);
    }
M
mindless 已提交
1044
    
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    /**
     * Supports build trigger with parameters via an HTTP GET or POST.
     * Currently only String parameters are supported.
     */
    public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException {
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);

        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
            pp.buildWithParameters(req,rsp);
            return;
        } else {
        	throw new IllegalStateException("This build is not parameterized!");
        }
    	
    }
1061 1062 1063 1064

    /**
     * Schedules a new SCM polling command.
     */
1065
    public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1066 1067 1068
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
        schedulePolling();
        rsp.forwardToPreviousPage(req);
1069 1070 1071 1072 1073
    }

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

1077
        Hudson.getInstance().getQueue().cancel(this);
1078 1079 1080
        rsp.forwardToPreviousPage(req);
    }

1081
    @Override
1082 1083
    protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
        super.submit(req,rsp);
1084

1085
        makeDisabled(req.getParameter("disable")!=null);
1086 1087

        jdk = req.getParameter("jdk");
1088
        if(req.getParameter("hasCustomQuietPeriod")!=null) {
1089 1090 1091 1092 1093
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
        } else {
            quietPeriod = null;
        }

1094
        if(req.getParameter("hasSlaveAffinity")!=null) {
1095 1096
            canRoam = false;
            assignedNode = req.getParameter("slave");
1097 1098 1099
            if(assignedNode !=null) {
                if(Hudson.getInstance().getLabel(assignedNode).isEmpty())
                    assignedNode = null;   // no such label
1100 1101 1102 1103 1104 1105
            }
        } else {
            canRoam = true;
            assignedNode = null;
        }

1106
        authToken = BuildAuthorizationToken.create(req);
1107

1108 1109 1110 1111
        setScm(SCMS.parseSCM(req));

        for (Trigger t : triggers)
            t.stop();
K
kohsuke 已提交
1112
        triggers = buildDescribable(req, Triggers.getApplicableTriggers(this));
1113
        for (Trigger t : triggers)
1114
            t.start(this,true);
1115 1116

        updateTransientActions();
1117 1118
    }

K
kohsuke 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127
    /**
     * @deprecated
     *      As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
     */
    protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
        return buildDescribable(req,descriptors);
    }

    protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
1128
        throws FormException, ServletException {
1129

1130
        JSONObject data = req.getSubmittedForm();
1131
        List<T> r = new Vector<T>();
1132 1133 1134 1135
        for (Descriptor<T> d : descriptors) {
            String name = d.getJsonSafeClassName();
            if (req.getParameter(name) != null) {
                T instance = d.newInstance(req, data.getJSONObject(name));
1136
                r.add(instance);
1137 1138
            }
        }
1139
        return r;
1140 1141 1142 1143 1144
    }

    /**
     * Serves the workspace files.
     */
1145
    public void doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
1146
        checkPermission(AbstractProject.WORKSPACE);
1147
        FilePath ws = getWorkspace();
1148
        if ((ws == null) || (!ws.exists())) {
1149
            // if there's no workspace, report a nice error message
1150 1151 1152 1153
            // Would be good if when asked for *plain*, do something else!
            // (E.g. return 404, or send empty doc.)
            // Not critical; client can just check if content type is not text/plain,
            // which also serves to detect old versions of Hudson.
1154
            req.getView(this,"noWorkspace.jelly").forward(req,rsp);
1155
        } else {
1156
            new DirectoryBrowserSupport(this,getDisplayName()+" workspace").serveFile(req, rsp, ws, "folder.gif", true);
1157 1158
        }
    }
1159

1160 1161 1162
    /**
     * Wipes out the workspace.
     */
1163
    public void doDoWipeOutWorkspace(StaplerResponse rsp) throws IOException, InterruptedException {
1164
        checkPermission(BUILD);
1165 1166 1167 1168
        getWorkspace().deleteRecursive();
        rsp.sendRedirect2(".");
    }

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
    public void doDisable(StaplerResponse rsp) throws IOException, ServletException {
        requirePOST();
        checkPermission(CONFIGURE);
        makeDisabled(true);
        rsp.sendRedirect2(".");
    }

    public void doEnable(StaplerResponse rsp) throws IOException, ServletException {
        checkPermission(CONFIGURE);
        makeDisabled(false);
        rsp.sendRedirect2(".");
    }

K
kohsuke 已提交
1182 1183 1184
    /**
     * RSS feed for changes in this project.
     */
1185
    public void doRssChangelog(  StaplerRequest req, StaplerResponse rsp  ) throws IOException, ServletException {
K
kohsuke 已提交
1186 1187 1188 1189 1190 1191 1192 1193 1194
        class FeedItem {
            ChangeLogSet.Entry e;
            int idx;

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

1195
            AbstractBuild<?,?> getBuild() {
K
kohsuke 已提交
1196 1197 1198 1199 1200 1201
                return e.getParent().build;
            }
        }

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

1202 1203 1204 1205
        for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
            int idx=0;
            for( ChangeLogSet.Entry e : r.getChangeSet())
                entries.add(new FeedItem(e,idx++));
K
kohsuke 已提交
1206 1207
        }

1208 1209 1210 1211 1212 1213 1214
        RSS.forwardToRss(
            getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
            getUrl()+"changes",
            entries, new FeedAdapter<FeedItem>() {
                public String getEntryTitle(FeedItem item) {
                    return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
                }
K
kohsuke 已提交
1215

1216 1217 1218
                public String getEntryUrl(FeedItem item) {
                    return item.getBuild().getUrl()+"changes#detail"+item.idx;
                }
K
kohsuke 已提交
1219

1220 1221 1222
                public String getEntryID(FeedItem item) {
                    return getEntryUrl(item);
                }
K
kohsuke 已提交
1223

1224 1225 1226 1227 1228 1229
                public String getEntryDescription(FeedItem item) {
                    StringBuilder buf = new StringBuilder();
                    for(String path : item.e.getAffectedPaths())
                        buf.append(path).append('\n');
                    return buf.toString();
                }
1230

1231 1232 1233
                public Calendar getEntryTimestamp(FeedItem item) {
                    return item.getBuild().getTimestamp();
                }
1234

1235 1236 1237 1238 1239
                public String getEntryAuthor(FeedItem entry) {
                    return Mailer.DESCRIPTOR.getAdminAddress();
                }
            },
            req, rsp );
K
kohsuke 已提交
1240 1241
    }

1242
    /**
1243
     * Finds a {@link AbstractProject} that has the name closest to the given name.
1244 1245
     */
    public static AbstractProject findNearest(String name) {
1246
        List<AbstractProject> projects = Hudson.getInstance().getItems(AbstractProject.class);
1247
        String[] names = new String[projects.size()];
1248
        for( int i=0; i<projects.size(); i++ )
1249 1250 1251
            names[i] = projects.get(i).getName();

        String nearest = EditDistance.findNearest(name, names);
1252
        return (AbstractProject)Hudson.getInstance().getItem(nearest);
1253
    }
1254 1255 1256

    private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
1257
            return o2-o1;
1258 1259
        }
    };
1260

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

K
kohsuke 已提交
1263 1264
    public static final Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._AbstractProject_BuildPermission_Description(),  Permission.UPDATE);
    public static final Permission WORKSPACE = new Permission(PERMISSIONS, "Workspace", Messages._AbstractProject_WorkspacePermission_Description(), Permission.READ);
1265
    /**
1266
     * Permission to abort a build. For now, let's make it the same as {@link #BUILD}
1267 1268
     */
    public static final Permission ABORT = BUILD;
1269
}
1270