AbstractBuild.java 18.2 KB
Newer Older
1 2 3 4 5
package hudson.model;

import hudson.Launcher;
import hudson.Proc.LocalProc;
import hudson.Util;
6
import hudson.util.AdaptedIterator;
7
import hudson.matrix.MatrixConfiguration;
8
import hudson.maven.MavenBuild;
9 10
import hudson.model.Fingerprint.BuildPtr;
import hudson.model.Fingerprint.RangeSet;
11
import static hudson.model.Hudson.isWindows;
K
kohsuke 已提交
12
import hudson.model.listeners.SCMListener;
K
kohsuke 已提交
13
import hudson.model.listeners.RunListener;
14 15 16 17 18
import hudson.scm.CVSChangeLogParser;
import hudson.scm.ChangeLogParser;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.SCM;
19 20 21
import hudson.tasks.Builder;
import hudson.tasks.Fingerprinter.FingerprintAction;
import hudson.tasks.test.AbstractTestResultAction;
22 23
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
24
import org.kohsuke.stapler.export.Exported;
25
import org.xml.sax.SAXException;
26

27
import javax.servlet.ServletException;
28 29 30
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
31
import java.util.*;
K
kohsuke 已提交
32

33 34 35 36 37 38 39 40
/**
 * Base implementation of {@link Run}s that build software.
 *
 * For now this is primarily the common part of {@link Build} and {@link MavenBuild}.
 *
 * @author Kohsuke Kawaguchi
 * @see AbstractProject
 */
41
public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Run<P,R> implements Queue.Executable {
42 43

    /**
K
kohsuke 已提交
44
     * Name of the slave this project was built on.
K
kohsuke 已提交
45
     * Null or "" if built by the master. (null happens when we read old record that didn't have this information.)
46 47 48
     */
    private String builtOn;

49 50 51 52 53
    /**
     * Version of Hudson that built this.
     */
    private String hudsonVersion;

54 55 56 57 58 59 60 61 62 63 64
    /**
     * SCM used for this build.
     * Maybe null, for historical reason, in which case CVS is assumed.
     */
    private ChangeLogParser scm;

    /**
     * Changes in this build.
     */
    private volatile transient ChangeLogSet<? extends Entry> changeSet;

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    /**
     * Cumulative list of people who contributed to the build problem.
     *
     * <p>
     * This is a list of {@link User#getId() user ids} who made a change
     * since the last non-broken build. Can be null (which should be
     * treated like empty set), because of the compatibility.
     *
     * <p>
     * This field is semi-final --- once set the value will never be modified.
     *
     * @since 1.137
     */
    private volatile Set<String> culprits;

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    protected AbstractBuild(P job) throws IOException {
        super(job);
    }

    protected AbstractBuild(P job, Calendar timestamp) {
        super(job, timestamp);
    }

    protected AbstractBuild(P project, File buildDir) throws IOException {
        super(project, buildDir);
    }

    public final P getProject() {
        return getParent();
    }

    /**
     * Returns a {@link Slave} on which this build was done.
     */
    public Node getBuiltOn() {
K
kohsuke 已提交
100
        if(builtOn==null || builtOn.equals(""))
101 102 103 104 105 106 107 108
            return Hudson.getInstance();
        else
            return Hudson.getInstance().getSlave(builtOn);
    }

    /**
     * Returns the name of the slave it was built on, or null if it was the master.
     */
K
kohsuke 已提交
109
    @Exported(name="builtOn")
110 111 112 113
    public String getBuiltOnStr() {
        return builtOn;
    }

114 115 116 117
    /**
     * List of users who committed a change since the last non-broken build till now.
     *
     * <p>
K
kohsuke 已提交
118 119
     * This list at least always include people who made changes in this build, but
     * if the previous build was a failure it also includes the culprit list from there.
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
     *
     * @return
     *      can be empty but never null.
     */
    @Exported
    public Set<User> getCulprits() {
        if(culprits==null) {
            Set<User> r = new HashSet<User>();
            if(getPreviousBuild()!=null && isBuilding() && getPreviousBuild().getResult().isWorseThan(Result.UNSTABLE)) {
                // we are still building, so this is just the current latest information,
                // but we seems to be failing so far, so inherit culprits from the previous build.
                // isBuilding() check is to avoid recursion when loading data from old Hudson, which doesn't record
                // this information
                r.addAll(getPreviousBuild().getCulprits());
            }
            for( Entry e : getChangeSet() )
                r.add(e.getAuthor());
            return r;
        }

        return new AbstractSet<User>() {
            public Iterator<User> iterator() {
                return new AdaptedIterator<String,User>(culprits.iterator()) {
                    protected User adapt(String id) {
                        return User.get(id);
                    }
                };
            }

            public int size() {
                return culprits.size();
            }
        };
    }

155 156 157 158 159 160 161
    protected abstract class AbstractRunner implements Runner {
        /**
         * Since configuration can be changed while a build is in progress,
         * stick to one launcher and use it.
         */
        protected Launcher launcher;

K
kohsuke 已提交
162 163 164 165 166 167 168
        /**
         * Returns the current {@link Node} on which we are buildling.
         */
        protected final Node getCurrentNode() {
            return Executor.currentExecutor().getOwner().getNode();
        }

169
        public Result run(BuildListener listener) throws Exception {
170
            Node node = getCurrentNode();
171 172
            assert builtOn==null;
            builtOn = node.getNodeName();
173
            hudsonVersion = Hudson.VERSION;
174 175 176 177 178

            launcher = node.createLauncher(listener);
            if(node instanceof Slave)
                listener.getLogger().println("Building remotely on "+node.getNodeName());

179
            if(checkout(listener))
180 181
                return Result.FAILURE;

182 183 184 185
            Result result = doRun(listener);
            if(result!=null)
                return result;  // abort here

K
kohsuke 已提交
186 187
            if(getResult()==null || getResult()==Result.SUCCESS)
                createLastSuccessfulLink(listener);
188 189 190 191

            return Result.SUCCESS;
        }

192
        private void createLastSuccessfulLink(BuildListener listener) throws InterruptedException {
193 194 195
            if(!isWindows()) {
                try {
                    // ignore a failure.
196
                    new LocalProc(new String[]{"rm","-rf","../lastSuccessful"},new String[0],listener.getLogger(),getProject().getBuildDir()).join();
197 198 199 200 201 202 203 204 205 206 207 208 209

                    int r = new LocalProc(new String[]{
                        "ln","-s","builds/"+getId()/*ugly*/,"../lastSuccessful"},
                        new String[0],listener.getLogger(),getProject().getBuildDir()).join();
                    if(r!=0)
                        listener.getLogger().println("ln failed: "+r);
                } catch (IOException e) {
                    PrintStream log = listener.getLogger();
                    log.println("ln failed");
                    Util.displayIOException(e,listener);
                    e.printStackTrace( log );
                }
            }
210
        }
211

212 213 214 215 216 217 218 219 220 221 222 223
        private boolean checkout(BuildListener listener) throws Exception {
            if(!project.checkout(AbstractBuild.this,launcher,listener,new File(getRootDir(),"changelog.xml")))
                return true;

            SCM scm = project.getScm();

            AbstractBuild.this.scm = scm.createChangeLogParser();
            AbstractBuild.this.changeSet = AbstractBuild.this.calcChangeSet();

            for (SCMListener l : Hudson.getInstance().getSCMListeners())
                l.onChangeLogParsed(AbstractBuild.this,listener,changeSet);
            return false;
224 225
        }

K
kohsuke 已提交
226 227 228 229 230 231 232 233 234
        /**
         * The portion of a build that is specific to a subclass of {@link AbstractBuild}
         * goes here.
         *
         * @return
         *      null to continue the build normally (that means the doRun method
         *      itself run successfully)
         *      Return a non-null value to abort the build right there with the specified result code.
         */
235
        protected abstract Result doRun(BuildListener listener) throws Exception;
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

        /**
         * @see #post(BuildListener)
         */
        protected abstract void post2(BuildListener listener) throws Exception;

        public final void post(BuildListener listener) throws Exception {
            try {
                post2(listener);
            } finally {
                // update the culprit list
                HashSet<String> r = new HashSet<String>();
                for (User u : getCulprits())
                    r.add(u.getId());
                culprits = r;
            }
        }
253
    }
K
kohsuke 已提交
254

255 256 257 258 259
    /**
     * Gets the changes incorporated into this build.
     *
     * @return never null.
     */
K
kohsuke 已提交
260
    @Exported
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    public ChangeLogSet<? extends Entry> getChangeSet() {
        if(scm==null)
            scm = new CVSChangeLogParser();

        if(changeSet==null) // cached value
            changeSet = calcChangeSet();
        return changeSet;
    }

    /**
     * Returns true if the changelog is already computed.
     */
    public boolean hasChangeSetComputed() {
        File changelogFile = new File(getRootDir(), "changelog.xml");
        return changelogFile.exists();
    }

    private ChangeLogSet<? extends Entry> calcChangeSet() {
        File changelogFile = new File(getRootDir(), "changelog.xml");
        if(!changelogFile.exists())
281
            return ChangeLogSet.createEmpty(this);
282 283 284 285 286 287 288 289

        try {
            return scm.parse(this,changelogFile);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
290
        return ChangeLogSet.createEmpty(this);
291 292 293 294 295
    }

    @Override
    public Map<String,String> getEnvVars() {
        Map<String,String> env = super.getEnvVars();
K
kohsuke 已提交
296
        env.put("WORKSPACE", getProject().getWorkspace().getRemote());
K
kohsuke 已提交
297 298 299 300
        // 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","");
301 302 303 304

        JDK jdk = project.getJDK();
        if(jdk !=null)
            jdk.buildEnvVars(env);
305
        project.getScm().buildEnvVars(this,env);
306 307 308

        return env;
    }
K
kohsuke 已提交
309

310 311 312 313
    public Calendar due() {
        return timestamp;
    }

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    /**
     * Provides additional variables and their values to {@link Builder}s.
     *
     * <p>
     * This mechanism is used by {@link MatrixConfiguration} to pass
     * the configuration values to the current build. It is up to
     * {@link Builder}s to decide whether it wants to recognize the values
     * or how to use them.
     *
     * ugly ugly hack.
     */
    public Map<String,String> getBuildVariables() {
        return Collections.emptyMap();
    }
    
329 330 331
    /**
     * Gets {@link AbstractTestResultAction} associated with this build if any.
     */
332 333 334
    public AbstractTestResultAction getTestResultAction() {
        return getAction(AbstractTestResultAction.class);
    }
335

K
kohsuke 已提交
336 337 338 339 340
    /**
     * Invoked by {@link Executor} to performs a build.
     */
    public abstract void run();

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
//
//
// fingerprint related stuff
//
//

    @Override
    public String getWhyKeepLog() {
        // if any of the downstream project is configured with 'keep dependency component',
        // we need to keep this log
        for (Map.Entry<AbstractProject, RangeSet> e : getDownstreamBuilds().entrySet()) {
            AbstractProject<?,?> p = e.getKey();
            if(!p.isKeepDependencies())     continue;

            // is there any active build that depends on us?
            for (AbstractBuild build : p.getBuilds()) {
                if(e.getValue().includes(build.getNumber()))
                    return "kept because of "+build;
            }
        }

        return super.getWhyKeepLog();
    }

    /**
     * Gets the dependency relationship from this build (as the source)
     * and that project (as the sink.)
     *
     * @return
     *      range of build numbers that represent which downstream builds are using this build.
     *      The range will be empty if no build of that project matches this.
     */
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    public RangeSet getDownstreamRelationship(AbstractProject that) {
        RangeSet rs = new RangeSet();

        FingerprintAction f = getAction(FingerprintAction.class);
        if(f==null)     return rs;

        // look for fingerprints that point to this build as the source, and merge them all
        for (Fingerprint e : f.getFingerprints().values()) {
            BuildPtr o = e.getOriginal();
            if(o!=null && o.is(this))
                rs.add(e.getRangeSet(that));
        }

        return rs;
    }
388

389 390 391 392 393 394 395 396
    /**
     * Gets the dependency relationship from this build (as the sink)
     * and that project (as the source.)
     *
     * @return
     *      Build number of the upstream build that feed into this build,
     *      or -1 if no record is available.
     */
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    public int getUpstreamRelationship(AbstractProject that) {
        FingerprintAction f = getAction(FingerprintAction.class);
        if(f==null)     return -1;

        int n = -1;

        // look for fingerprints that point to the given project as the source, and merge them all
        for (Fingerprint e : f.getFingerprints().values()) {
            BuildPtr o = e.getOriginal();
            if(o!=null && o.is(that))
                n = Math.max(n,o.getNumber());
        }

        return n;
    }
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

    /**
     * Gets the downstream builds of this build, which are the builds of the
     * downstream projects that use artifacts of this build.
     *
     * @return
     *      For each project with fingerprinting enabled, returns the range
     *      of builds (which can be empty if no build uses the artifact from this build.)
     */
    public Map<AbstractProject,RangeSet> getDownstreamBuilds() {
        Map<AbstractProject,RangeSet> r = new HashMap<AbstractProject,RangeSet>();
        for (AbstractProject p : getParent().getDownstreamProjects()) {
            if(p.isFingerprintConfigured())
                r.put(p,getDownstreamRelationship(p));
        }
        return r;
    }
    
    /**
     * Gets the upstream builds of this build, which are the builds of the
     * upstream projects whose artifacts feed into this build.
K
kohsuke 已提交
433 434
     *
     * @see #getTransitiveUpstreamBuilds()
435 436
     */
    public Map<AbstractProject,Integer> getUpstreamBuilds() {
K
kohsuke 已提交
437 438 439 440 441 442 443 444 445 446 447 448
        return _getUpstreamBuilds(getParent().getUpstreamProjects());
    }

    /**
     * Works like {@link #getUpstreamBuilds()}  but also includes all the transitive
     * dependencies as well.
     */
    public Map<AbstractProject,Integer> getTransitiveUpstreamBuilds() {
        return _getUpstreamBuilds(getParent().getTransitiveUpstreamProjects());
    }

    private Map<AbstractProject, Integer> _getUpstreamBuilds(Collection<AbstractProject> projects) {
449
        Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>();
K
kohsuke 已提交
450
        for (AbstractProject p : projects) {
451 452 453 454 455 456 457
            int n = getUpstreamRelationship(p);
            if(n>=0)
                r.put(p,n);
        }
        return r;
    }

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
    /**
     * Gets the changes in the dependency between the given build and this build.
     */
    public Map<AbstractProject,DependencyChange> getDependencyChanges(AbstractBuild from) {
        if(from==null)             return Collections.emptyMap(); // make it easy to call this from views
        FingerprintAction n = this.getAction(FingerprintAction.class);
        FingerprintAction o = from.getAction(FingerprintAction.class);
        if(n==null || o==null)     return Collections.emptyMap();

        Map<AbstractProject,Integer> ndep = n.getDependencies();
        Map<AbstractProject,Integer> odep = o.getDependencies();

        Map<AbstractProject,DependencyChange> r = new HashMap<AbstractProject,DependencyChange>();

        for (Map.Entry<AbstractProject,Integer> entry : odep.entrySet()) {
            AbstractProject p = entry.getKey();
            Integer oldNumber = entry.getValue();
            Integer newNumber = ndep.get(p);
            if(newNumber!=null && oldNumber.compareTo(newNumber)<0) {
                r.put(p,new DependencyChange(p,oldNumber,newNumber));
            }
        }

        return r;
    }

    /**
     * Represents a change in the dependency.
     */
    public static final class DependencyChange {
        /**
         * The dependency project.
         */
        public final AbstractProject project;
        /**
         * Version of the dependency project used in the previous build.
         */
        public final int fromId;
        /**
         * {@link Build} object for {@link #fromId}. Can be null if the log is gone.
         */
        public final AbstractBuild from;
        /**
         * Version of the dependency project used in this build.
         */
        public final int toId;

        public final AbstractBuild to;

        public DependencyChange(AbstractProject<?,?> project, int fromId, int toId) {
            this.project = project;
            this.fromId = fromId;
            this.toId = toId;
            this.from = project.getBuildByNumber(fromId);
            this.to = project.getBuildByNumber(toId);
        }
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534

        /**
         * Gets the {@link AbstractBuild} objects (fromId,toId].
         * <p>
         * This method returns all such available builds in the ascending order
         * of IDs, but due to log rotations, some builds may be already unavailable. 
         */
        public List<AbstractBuild> getBuilds() {
            List<AbstractBuild> r = new ArrayList<AbstractBuild>();

            AbstractBuild<?,?> b = (AbstractBuild)project.getNearestBuild(fromId);
            if(b!=null && b.getNumber()==fromId)
                b = b.getNextBuild(); // fromId exclusive

            while(b!=null && b.getNumber()<=toId) {
                r.add(b);
                b = b.getNextBuild();
            }

            return r;
        }
535 536 537
    }
    

538 539 540 541 542
//
//
// web methods
//
//
K
kohsuke 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556
    /**
     * Stops this build if it's still going.
     *
     * If we use this/executor/stop URL, it causes 404 if the build is already killed,
     * as {@link #getExecutor()} returns null.
     */
    public synchronized void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        Executor e = getExecutor();
        if(e!=null)
            e.doStop(req,rsp);
        else
            // nothing is building
            rsp.forwardToPreviousPage(req);
    }
557
}