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

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

25
import javax.servlet.ServletException;
26 27 28 29
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Calendar;
30
import java.util.Map;
31
import java.util.HashMap;
32
import java.util.Collections;
33 34
import java.util.List;
import java.util.ArrayList;
K
kohsuke 已提交
35

36 37 38 39 40 41 42 43
/**
 * 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
 */
44
public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Run<P,R> implements Queue.Executable {
45 46

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

52 53 54 55 56
    /**
     * Version of Hudson that built this.
     */
    private String hudsonVersion;

57 58 59 60 61 62 63 64 65 66 67
    /**
     * 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;

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    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 已提交
88
        if(builtOn==null || builtOn.equals(""))
89 90 91 92 93 94 95 96
            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 已提交
97
    @Exported(name="builtOn")
98 99 100 101 102 103 104 105 106 107 108
    public String getBuiltOnStr() {
        return builtOn;
    }

    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 已提交
109 110 111 112 113 114 115
        /**
         * Returns the current {@link Node} on which we are buildling.
         */
        protected final Node getCurrentNode() {
            return Executor.currentExecutor().getOwner().getNode();
        }

116
        public Result run(BuildListener listener) throws Exception {
117
            Node node = getCurrentNode();
118 119
            assert builtOn==null;
            builtOn = node.getNodeName();
120
            hudsonVersion = Hudson.VERSION;
121 122 123 124 125

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

126
            if(checkout(listener))
127 128
                return Result.FAILURE;

129 130 131 132
            Result result = doRun(listener);
            if(result!=null)
                return result;  // abort here

K
kohsuke 已提交
133 134
            if(getResult()==null || getResult()==Result.SUCCESS)
                createLastSuccessfulLink(listener);
135 136 137 138

            return Result.SUCCESS;
        }

139
        private void createLastSuccessfulLink(BuildListener listener) throws InterruptedException {
140 141 142
            if(!isWindows()) {
                try {
                    // ignore a failure.
143
                    new LocalProc(new String[]{"rm","-f","../lastSuccessful"},new String[0],listener.getLogger(),getProject().getBuildDir()).join();
144 145 146 147 148 149 150 151 152 153 154 155 156

                    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 );
                }
            }
157
        }
158

159 160 161 162 163 164 165 166 167 168 169 170
        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;
171 172
        }

K
kohsuke 已提交
173 174 175 176 177 178 179 180 181
        /**
         * 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.
         */
182 183
        protected abstract Result doRun(BuildListener listener) throws Exception;
    }
K
kohsuke 已提交
184

185 186 187 188 189
    /**
     * Gets the changes incorporated into this build.
     *
     * @return never null.
     */
K
kohsuke 已提交
190
    @Exported
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    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())
211
            return ChangeLogSet.createEmpty(this);
212 213 214 215 216 217 218 219

        try {
            return scm.parse(this,changelogFile);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
220
        return ChangeLogSet.createEmpty(this);
221 222 223 224 225
    }

    @Override
    public Map<String,String> getEnvVars() {
        Map<String,String> env = super.getEnvVars();
K
kohsuke 已提交
226
        env.put("WORKSPACE", getProject().getWorkspace().getRemote());
227 228 229 230

        JDK jdk = project.getJDK();
        if(jdk !=null)
            jdk.buildEnvVars(env);
231
        project.getScm().buildEnvVars(this,env);
232 233 234

        return env;
    }
K
kohsuke 已提交
235

236 237 238 239
    public Calendar due() {
        return timestamp;
    }

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    /**
     * 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();
    }
    
255 256 257
    /**
     * Gets {@link AbstractTestResultAction} associated with this build if any.
     */
258 259 260
    public AbstractTestResultAction getTestResultAction() {
        return getAction(AbstractTestResultAction.class);
    }
261

K
kohsuke 已提交
262 263 264 265 266
    /**
     * Invoked by {@link Executor} to performs a build.
     */
    public abstract void run();

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
//
//
// 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.
     */
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    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;
    }
314

315 316 317 318 319 320 321 322
    /**
     * 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.
     */
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    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;
    }
338 339 340 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

    /**
     * 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.
     */
    public Map<AbstractProject,Integer> getUpstreamBuilds() {
        Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>();
        for (AbstractProject p : getParent().getUpstreamProjects()) {
            int n = getUpstreamRelationship(p);
            if(n>=0)
                r.put(p,n);
        }
        return r;
    }

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    /**
     * 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);
        }
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

        /**
         * 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;
        }
447 448 449
    }
    

450 451 452 453 454
//
//
// web methods
//
//
K
kohsuke 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468
    /**
     * 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);
    }
469
}