Queue.java 17.3 KB
Newer Older
K
kohsuke 已提交
1 2
package hudson.model;

3
import hudson.Util;
K
kohsuke 已提交
4 5 6
import hudson.model.Node.Mode;
import hudson.util.OneShotEvent;

K
kohsuke 已提交
7 8 9 10 11 12 13
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
K
kohsuke 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
import java.util.Calendar;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Build queue.
 *
 * <p>
 * This class implements the core scheduling logic.
 *
 * @author Kohsuke Kawaguchi
 */
public class Queue {

    private static final Comparator<Item> itemComparator = new Comparator<Item>() {
        public int compare(Item lhs, Item rhs) {
            int r = lhs.timestamp.getTime().compareTo(rhs.timestamp.getTime());
            if(r!=0)    return r;

            return lhs.id-rhs.id;
        }
    };

    /**
     * Items in the queue ordered by {@link Item#timestamp}.
     *
     * <p>
     * This consists of {@link Item}s that cannot be run yet
     * because its time has not yet come.
     */
    private final Set<Item> queue = new TreeSet<Item>(itemComparator);

    /**
     * {@link Project}s that can be built immediately
     * but blocked because another build is in progress.
     */
61
    private final Set<AbstractProject> blockedProjects = new HashSet<AbstractProject>();
K
kohsuke 已提交
62 63 64 65 66

    /**
     * {@link Project}s that can be built immediately
     * that are waiting for available {@link Executor}.
     */
67
    private final List<AbstractProject> buildables = new LinkedList<AbstractProject>();
K
kohsuke 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

    /**
     * Data structure created for each idle {@link Executor}.
     * This is an offer from the queue to an executor.
     *
     * <p>
     * It eventually receives a {@link #project} to build.
     */
    private static class JobOffer {
        final Executor executor;

        /**
         * Used to wake up an executor, when it has an offered
         * {@link Project} to build.
         */
        final OneShotEvent event = new OneShotEvent();
        /**
         * The project that this {@link Executor} is going to build.
         * (Or null, in which case event is used to trigger a queue maintenance.)
         */
88
        AbstractProject project;
K
kohsuke 已提交
89 90 91 92 93

        public JobOffer(Executor executor) {
            this.executor = executor;
        }

94
        public void set(AbstractProject p) {
K
kohsuke 已提交
95 96 97 98 99
            this.project = p;
            event.signal();
        }

        public boolean isAvailable() {
K
kohsuke 已提交
100
            return project==null && !executor.getOwner().isOffline();
K
kohsuke 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        }

        public Node getNode() {
            return executor.getOwner().getNode();
        }

        public boolean isNotExclusive() {
            return getNode().getMode()== Mode.NORMAL;
        }
    }

    private final Map<Executor,JobOffer> parked = new HashMap<Executor,JobOffer>();

    /**
     * Loads the queue contents that was {@link #save() saved}.
     */
    public synchronized void load() {
        // write out the contents of the queue
        try {
            File queueFile = getQueueFile();
            if(!queueFile.exists())
                return;

            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(queueFile)));
            String line;
            while((line=in.readLine())!=null) {
127 128 129
                AbstractProject j = Hudson.getInstance().getItemByFullName(line,AbstractProject.class);
                if(j!=null)
                    j.scheduleBuild();
K
kohsuke 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
            }
            in.close();
            // discard the queue file now that we are done
            queueFile.delete();
        } catch(IOException e) {
            LOGGER.log(Level.WARNING, "Failed to load the queue file "+getQueueFile(),e);
        }
    }

    /**
     * Persists the queue contents to the disk.
     */
    public synchronized void save() {
        // write out the contents of the queue
        try {
            PrintWriter w = new PrintWriter(new FileOutputStream(
                getQueueFile()));
            for (Item i : getItems())
148
                w.println(i.project.getName());
K
kohsuke 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161
            w.close();
        } catch(IOException e) {
            LOGGER.log(Level.WARNING, "Failed to write out the queue file "+getQueueFile(),e);
        }
    }

    private File getQueueFile() {
        return new File(Hudson.getInstance().getRootDir(),"queue.txt");
    }

    /**
     * Schedule a new build for this project.
     */
162
    public synchronized void add( AbstractProject p ) {
K
kohsuke 已提交
163 164 165 166 167 168 169 170 171 172 173
        if(contains(p))
            return; // no double queueing

        // put the item in the queue
        Calendar due = new GregorianCalendar();
        due.add(Calendar.SECOND, p.getQuietPeriod());
        queue.add(new Item(due,p));

        scheduleMaintenance();   // let an executor know that a new item is in the queue.
    }

174
    public synchronized void cancel( AbstractProject<?,?> p ) {
K
kohsuke 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        for (Iterator itr = queue.iterator(); itr.hasNext();) {
            Item item = (Item) itr.next();
            if(item.project==p) {
                itr.remove();
                return;
            }
        }
        blockedProjects.remove(p);
        buildables.remove(p);
    }

    public synchronized boolean isEmpty() {
        return queue.isEmpty() && blockedProjects.isEmpty() && buildables.isEmpty();
    }

    private synchronized Item peek() {
        return queue.iterator().next();
    }

    /**
     * Gets a snapshot of items in the queue.
     */
    public synchronized Item[] getItems() {
        Item[] r = new Item[queue.size()+blockedProjects.size()+buildables.size()];
        queue.toArray(r);
        int idx=queue.size();
        Calendar now = new GregorianCalendar();
202
        for (AbstractProject p : blockedProjects) {
203
            r[idx++] = new Item(now, p, true, false);
K
kohsuke 已提交
204
        }
205
        for (AbstractProject p : buildables) {
206
            r[idx++] = new Item(now, p, false, true);
K
kohsuke 已提交
207 208 209 210 211
        }
        return r;
    }

    /**
K
kohsuke 已提交
212
     * Returns true if this queue contains the said project.
K
kohsuke 已提交
213
     */
214
    public synchronized boolean contains(AbstractProject p) {
K
kohsuke 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        // if this project is already scheduled,
        // don't do anything
        if(blockedProjects.contains(p) || buildables.contains(p))
            return true;
        for (Item item : queue) {
            if (item.project == p)
                return true;
        }
        return false;
    }

    /**
     * Called by the executor to fetch something to build next.
     *
     * This method blocks until a next project becomes buildable.
     */
231
    public AbstractProject pop() throws InterruptedException {
K
kohsuke 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244
        final Executor exec = Executor.currentExecutor();
        boolean successfulReturn = false;

        try {
            while(true) {
                final JobOffer offer = new JobOffer(exec);
                long sleep = -1;

                synchronized(this) {
                    // consider myself parked
                    assert !parked.containsKey(exec);
                    parked.put(exec,offer);

K
kohsuke 已提交
245
                    // reuse executor thread to do a queue maintenance.
K
kohsuke 已提交
246 247 248 249 250
                    // at the end of this we get all the buildable jobs
                    // in the buildables field.
                    maintain();

                    // allocate buildable jobs to executors
251
                    Iterator<AbstractProject> itr = buildables.iterator();
K
kohsuke 已提交
252
                    while(itr.hasNext()) {
253
                        AbstractProject p = itr.next();
K
kohsuke 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
                        JobOffer runner = choose(p);
                        if(runner==null)
                            // if we couldn't find the executor that fits,
                            // just leave it in the buildables list and
                            // check if we can execute other projects
                            continue;

                        // found a matching executor. use it.
                        runner.set(p);
                        itr.remove();
                    }

                    // we went over all the buildable projects and awaken
                    // all the executors that got work to do. now, go to sleep
                    // until this thread is awakened. If this executor assigned a job to
                    // itself above, the block method will return immediately.

                    if(!queue.isEmpty()) {
                        // wait until the first item in the queue is due
                        sleep = peek().timestamp.getTimeInMillis()-new GregorianCalendar().getTimeInMillis();
                        if(sleep <100)    sleep =100;    // avoid wait(0)
                    }
                }

                // this needs to be done outside synchronized block,
                // so that executors can maintain a queue while others are sleeping
                if(sleep ==-1)
                    offer.event.block();
                else
                    offer.event.block(sleep);

                synchronized(this) {
                    // am I woken up because I have a project to build?
                    if(offer.project!=null) {
                        // if so, just build it
                        successfulReturn = true;
                        return offer.project;
                    }
                    // otherwise run a queue maintenance
                }
            }
        } finally {
            synchronized(this) {
                // remove myself from the parked list
                JobOffer offer = parked.get(exec);
                if(offer!=null) {
                    if(!successfulReturn && offer.project!=null) {
                        // we are already assigned a project,
                        // ask for someone else to build it.
                        // note that while this thread is waiting for CPU
                        // someone else can schedule this build again.
                        if(!contains(offer.project))
                            buildables.add(offer.project);
                    }

                    // since this executor might have been chosen for
                    // maintenance, schedule another one. Worst case
                    // we'll just run a pointless maintenance, and that's
                    // fine.
                    scheduleMaintenance();
                }
            }
        }
    }

    /**
K
kohsuke 已提交
320
     * Chooses the executor to carry out the build for the given project.
K
kohsuke 已提交
321 322 323 324
     *
     * @return
     *      null if no {@link Executor} can run it.
     */
325
    private JobOffer choose(AbstractProject<?,?> p) {
K
kohsuke 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        if(Hudson.getInstance().isQuietingDown()) {
            // if we are quieting down, don't run anything so that
            // all executors will be free.
            return null;
        }

        Node n = p.getAssignedNode();
        if(n!=null) {
            // if a project has assigned node, it can be only built on it
            for (JobOffer offer : parked.values()) {
                if(offer.isAvailable() && offer.getNode()==n)
                    return offer;
            }
            return null;
        }

        // otherwise let's see if the last node that this project was built is available
        // it has up-to-date workspace, so that's usually preferable.
        // (but we can't use an exclusive node)
        n = p.getLastBuiltOn();
        if(n!=null && n.getMode()==Mode.NORMAL) {
            for (JobOffer offer : parked.values()) {
                if(offer.isAvailable() && offer.getNode()==n)
                    return offer;
            }
        }

        // duration of a build on a slave tends not to have an impact on
        // the master/slave communication, so that means we should favor
        // running long jobs on slaves.
356
        AbstractBuild succ = p.getLastSuccessfulBuild();
K
kohsuke 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 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
        if(succ!=null && succ.getDuration()>15*60*1000) {
            // consider a long job to be > 15 mins
            for (JobOffer offer : parked.values()) {
                if(offer.isAvailable() && offer.getNode() instanceof Slave && offer.isNotExclusive())
                    return offer;
            }
        }

        // lastly, just look for any idle executor
        for (JobOffer offer : parked.values()) {
            if(offer.isAvailable() && offer.isNotExclusive())
                return offer;
        }

        // nothing available
        return null;
    }

    /**
     * Checks the queue and runs anything that can be run.
     *
     * <p>
     * When conditions are changed, this method should be invoked.
     *
     * This wakes up one {@link Executor} so that it will maintain a queue.
     */
    public synchronized void scheduleMaintenance() {
        // this code assumes that after this method is called
        // no more executors will be offered job except by
        // the pop() code.
        for (Entry<Executor, JobOffer> av : parked.entrySet()) {
            if(av.getValue().project==null) {
                av.getValue().event.signal();
                return;
            }
        }
    }


    /**
K
kohsuke 已提交
397
     * Queue maintenance.
K
kohsuke 已提交
398 399 400 401 402
     *
     * Move projects between {@link #queue}, {@link #blockedProjects}, and {@link #buildables}
     * appropriately.
     */
    private synchronized void maintain() {
403
        Iterator<AbstractProject> itr = blockedProjects.iterator();
K
kohsuke 已提交
404
        while(itr.hasNext()) {
405 406
            AbstractProject<?,?> p = itr.next();
            AbstractBuild lastBuild = p.getLastBuild();
K
kohsuke 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419
            if (lastBuild == null || !lastBuild.isBuilding()) {
                // ready to be executed
                itr.remove();
                buildables.add(p);
            }
        }

        while(!queue.isEmpty()) {
            Item top = peek();

            if(!top.timestamp.before(new GregorianCalendar()))
                return; // finished moving all ready items from queue

420
            AbstractBuild lastBuild = top.project.getLastBuild();
K
kohsuke 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
            if(lastBuild==null || !lastBuild.isBuilding()) {
                // ready to be executed immediately
                queue.remove(top);
                buildables.add(top.project);
            } else {
                // this can't be built know because another build is in progress
                // set this project aside.
                queue.remove(top);
                blockedProjects.add(top.project);
            }
        }
    }

    /**
     * Item in a queue.
     */
    public class Item {
        /**
         * This item can be run after this time.
         */
441
        public final Calendar timestamp;
K
kohsuke 已提交
442 443 444 445

        /**
         * Project to be built.
         */
446
        public final AbstractProject<?,?> project;
K
kohsuke 已提交
447 448 449

        /**
         * Unique number of this {@link Item}.
K
kohsuke 已提交
450
         * Used to differentiate {@link Item}s with the same due date.
K
kohsuke 已提交
451
         */
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
        public final int id;

        /**
         * Build is blocked because another build is in progress.
         * This flag is only used in {@link Queue#getItems()} for
         * 'pseudo' items that are actually not really in the queue.
         */
        public final boolean isBlocked;

        /**
         * Build is waiting the executor to become available.
         * This flag is only used in {@link Queue#getItems()} for
         * 'pseudo' items that are actually not really in the queue.
         */
        public final boolean isBuildable;
K
kohsuke 已提交
467

468
        public Item(Calendar timestamp, AbstractProject project) {
469 470 471 472
            this(timestamp,project,false,false);
        }

        public Item(Calendar timestamp, AbstractProject project, boolean isBlocked, boolean isBuildable) {
K
kohsuke 已提交
473 474
            this.timestamp = timestamp;
            this.project = project;
475 476
            this.isBlocked = isBlocked;
            this.isBuildable = isBuildable;
K
kohsuke 已提交
477 478 479 480 481
            synchronized(Queue.this) {
                this.id = iota++;
            }
        }

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
        /**
         * Gets a human-readable status message describing why it's in the queu.
         */
        public String getWhy() {
            if(isBuildable) {
                Node node = project.getAssignedNode();
                Hudson hudson = Hudson.getInstance();
                if(node==hudson && hudson.getSlaves().isEmpty())
                    node = null;    // no master/slave. pointless to talk about nodes

                String name = null;
                if(node!=null) {
                    if(node==hudson)
                        name = "master";
                    else
                        name = node.getNodeName();
                }
K
kohsuke 已提交
499

500 501 502 503
                return "Waiting for next available executor"+(name==null?"":" on "+name);
            }

            if(isBlocked) {
K
kohsuke 已提交
504 505 506 507 508 509 510
                AbstractBuild<?, ?> build = project.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;
511 512 513 514 515 516
            }

            long diff = timestamp.getTimeInMillis() - System.currentTimeMillis();
            if(diff>0) {
                return "In the quiet period. Expires in "+ Util.getTimeSpanString(diff);
            }
K
kohsuke 已提交
517

518
            return "???";
K
kohsuke 已提交
519 520 521 522 523 524 525 526 527 528
        }
    }

    /**
     * Unique number generator
     */
    private int iota=0;

    private static final Logger LOGGER = Logger.getLogger(Queue.class.getName());
}