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

3
import hudson.Util;
K
kohsuke 已提交
4
import hudson.model.Node.Mode;
5 6
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
K
kohsuke 已提交
7
import hudson.util.OneShotEvent;
8 9 10
import org.acegisecurity.AccessDeniedException;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
K
kohsuke 已提交
11

12
import javax.management.timer.Timer;
13 14 15 16 17 18 19
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;
20
import java.lang.ref.WeakReference;
S
stephenconnolly 已提交
21
import java.util.Map.Entry;
22
import java.util.*;
K
kohsuke 已提交
23 24 25 26 27
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Build queue.
28 29
 *
 * <p>
30 31
 * This class implements the core scheduling logic. {@link Task} represents the executable
 * task that are placed in the queue. While in the queue, it's wrapped into {@link Item}
32
 * so that we can keep track of additional data used for deciding what to exeucte when.
33 34
 *
 * <p>
35 36 37 38 39 40 41 42
 * Items in queue goes through several stages, as depicted below:
 * <pre>
 * (enter) --> waitingList --+--> blockedProjects
 *                           |        ^
 *                           |        |
 *                           |        v
 *                           +--> buildables ---> (executed)
 * </pre>
43 44
 *
 * <p>
45 46 47
 * In addition, at any stage, an item can be removed from the queue (for example, when the user
 * cancels a job in the queue.) See the corresponding field for their exact meanings.
 *
K
kohsuke 已提交
48 49
 * @author Kohsuke Kawaguchi
 */
50
public class Queue extends ResourceController {
K
kohsuke 已提交
51
    /**
52
     * Items that are waiting for its quiet period to pass.
53 54
     *
     * <p>
K
kohsuke 已提交
55 56 57
     * This consists of {@link Item}s that cannot be run yet
     * because its time has not yet come.
     */
58
    private final Set<WaitingItem> waitingList = new TreeSet<WaitingItem>();
K
kohsuke 已提交
59 60 61

    /**
     * {@link Project}s that can be built immediately
62 63 64
     * but blocked because another build is in progress,
     * required {@link Resource}s are not available, or otherwise blocked
     * by {@link Task#isBuildBlocked()}.
65 66
     *
     * <p>
67 68
     * Conceptually a set of {@link BlockedItem}, but we often need to look up
     * {@link BlockedItem} from {@link Task}, so organized as a map.
K
kohsuke 已提交
69
     */
70
    private final Map<Task,BlockedItem> blockedProjects = new HashMap<Task,BlockedItem>();
K
kohsuke 已提交
71 72 73 74

    /**
     * {@link Project}s that can be built immediately
     * that are waiting for available {@link Executor}.
75 76
     *
     * <p>
77 78 79
     * Conceptually, this is a list of {@link BuildableItem} (FIFO list, not a set, so that
     * the item doesn't starve in the queue), but we often need to look up
     * {@link BuildableItem} from {@link Task}, so organized as a {@link LinkedHashMap}.
K
kohsuke 已提交
80
     */
81
    private final LinkedHashMap<Task,BuildableItem> buildables = new LinkedHashMap<Task,BuildableItem>();
82

K
kohsuke 已提交
83 84 85
    /**
     * Data structure created for each idle {@link Executor}.
     * This is an offer from the queue to an executor.
86 87
     *
     * <p>
88
     * It eventually receives a {@link #item} to build.
K
kohsuke 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101
     */
    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.)
         */
102
        BuildableItem item;
K
kohsuke 已提交
103 104 105 106 107

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

108 109 110
        public void set(BuildableItem p) {
            assert this.item == null;
            this.item = p;
K
kohsuke 已提交
111 112 113 114
            event.signal();
        }

        public boolean isAvailable() {
115
            return item == null && !executor.getOwner().isOffline() && executor.getOwner().isAcceptingTasks();
K
kohsuke 已提交
116 117 118 119 120 121 122
        }

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

        public boolean isNotExclusive() {
123
            return getNode().getMode() == Mode.NORMAL;
K
kohsuke 已提交
124 125 126
        }
    }

S
stephenconnolly 已提交
127 128 129
    /**
     * The executors that are currently parked while waiting for a job to run.
     */
130
    private final Map<Executor, JobOffer> parked = new HashMap<Executor, JobOffer>();
K
kohsuke 已提交
131

132 133 134 135 136 137
    public Queue() {
        // if all the executors are busy doing something, then the queue won't be maintained in
        // timely fashion, so use another thread to make sure it happens.
        new MaintainTask(this);
    }

K
kohsuke 已提交
138 139 140 141 142 143 144
    /**
     * Loads the queue contents that was {@link #save() saved}.
     */
    public synchronized void load() {
        // write out the contents of the queue
        try {
            File queueFile = getQueueFile();
145
            if (!queueFile.exists())
K
kohsuke 已提交
146 147 148 149
                return;

            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(queueFile)));
            String line;
150 151 152
            while ((line = in.readLine()) != null) {
                AbstractProject j = Hudson.getInstance().getItemByFullName(line, AbstractProject.class);
                if (j != null)
153
                    j.scheduleBuild();
K
kohsuke 已提交
154 155 156 157
            }
            in.close();
            // discard the queue file now that we are done
            queueFile.delete();
158 159
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Failed to load the queue file " + getQueueFile(), e);
K
kohsuke 已提交
160 161 162 163 164 165 166 167 168 169
        }
    }

    /**
     * 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(
170
                    getQueueFile()));
K
kohsuke 已提交
171
            for (Item i : getItems())
172
                w.println(i.task.getName());
K
kohsuke 已提交
173
            w.close();
174 175
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Failed to write out the queue file " + getQueueFile(), e);
K
kohsuke 已提交
176 177 178 179
        }
    }

    private File getQueueFile() {
180
        return new File(Hudson.getInstance().getRootDir(), "queue.txt");
K
kohsuke 已提交
181 182 183 184
    }

    /**
     * Schedule a new build for this project.
185
     *
186 187 188
     * @return true if the project is actually added to the queue.
     *         false if the queue contained it and therefore the add()
     *         was noop
K
kohsuke 已提交
189
     */
190 191
    public boolean add(AbstractProject p) {
        return add(p, p.getQuietPeriod());
192 193 194 195
    }

    /**
     * Schedules a new build with a custom quiet period.
196 197
     *
     * <p>
K
kohsuke 已提交
198 199
     * Left for backward compatibility with &lt;1.114.
     *
200 201
     * @since 1.105
     */
202 203
    public synchronized boolean add(AbstractProject p, int quietPeriod) {
        return add((Task) p, quietPeriod);
K
kohsuke 已提交
204 205 206 207 208
    }

    /**
     * Schedules an execution of a task.
     *
209 210 211
     * @param quietPeriod Number of seconds that the task will be placed in queue.
     *                    Useful when the same task is likely scheduled for multiple
     *                    times.
K
kohsuke 已提交
212 213
     * @since 1.114
     */
214 215 216 217
    public synchronized boolean add(Task p, int quietPeriod) {
        Item item = getItem(p);
        Calendar due = new GregorianCalendar();
        due.add(Calendar.SECOND, quietPeriod);
218
        if (item != null) {
219 220 221 222 223 224 225
            if (!(item instanceof WaitingItem))
                // already in the blocked or buildable stage
                // no need to requeue
                return false;

            WaitingItem wi = (WaitingItem) item;
            if (wi.timestamp.before(due))
226
                return false; // no double queueing
K
kohsuke 已提交
227

228
            // allow the due date to be pulled in
229
            wi.timestamp = due;
230 231
        } else {
            LOGGER.fine(p.getName() + " added to queue");
232

233
            // put the item in the queue
234
            waitingList.add(new WaitingItem(due,p));
K
kohsuke 已提交
235

236
        }
K
kohsuke 已提交
237
        scheduleMaintenance();   // let an executor know that a new item is in the queue.
238
        return true;
K
kohsuke 已提交
239 240
    }

K
kohsuke 已提交
241 242 243
    /**
     * Cancels the item in the queue.
     *
244 245
     * @return true if the project was indeed in the queue and was removed.
     *         false if this was no-op.
K
kohsuke 已提交
246
     */
247 248
    public synchronized boolean cancel(AbstractProject<?, ?> p) {
        LOGGER.fine("Cancelling " + p.getName());
249
        for (Iterator itr = waitingList.iterator(); itr.hasNext();) {
K
kohsuke 已提交
250
            Item item = (Item) itr.next();
251
            if (item.task == p) {
K
kohsuke 已提交
252
                itr.remove();
K
kohsuke 已提交
253
                return true;
K
kohsuke 已提交
254 255
            }
        }
K
kohsuke 已提交
256
        // use bitwise-OR to make sure that both branches get evaluated all the time
257
        return blockedProjects.remove(p)!=null | buildables.remove(p)!=null;
K
kohsuke 已提交
258 259 260
    }

    public synchronized boolean isEmpty() {
261
        return waitingList.isEmpty() && blockedProjects.isEmpty() && buildables.isEmpty();
K
kohsuke 已提交
262 263
    }

264
    private synchronized WaitingItem peek() {
265
        return waitingList.iterator().next();
K
kohsuke 已提交
266 267 268 269 270 271
    }

    /**
     * Gets a snapshot of items in the queue.
     */
    public synchronized Item[] getItems() {
272 273 274
        Item[] r = new Item[waitingList.size() + blockedProjects.size() + buildables.size()];
        waitingList.toArray(r);
        int idx = waitingList.size();
275 276 277 278
        for (BlockedItem p : blockedProjects.values())
            r[idx++] = p;
        for (BuildableItem p : buildables.values())
            r[idx++] = p;
K
kohsuke 已提交
279 280 281
        return r;
    }

282 283 284 285
    public synchronized List<BuildableItem> getBuildableItems(Computer c) {
        List<BuildableItem> result = new ArrayList<BuildableItem>();
        for (BuildableItem p : buildables.values()) {
            Label l = p.task.getAssignedLabel();
286 287 288 289 290
            if (l != null) {
                // if a project has assigned label, it can be only built on it
                if (!l.contains(c.getNode()))
                    continue;
            }
291
            result.add(p);
292
        }
293
        return result;
294 295
    }

K
kohsuke 已提交
296 297 298 299 300
    /**
     * Gets the information about the queue item for the given project.
     *
     * @return null if the project is not in the queue.
     */
301 302
    public synchronized Item getItem(Task t) {
        BlockedItem bp = blockedProjects.get(t);
303
        if (bp!=null)
304 305
            return bp;
        BuildableItem bi = buildables.get(t);
306
        if(bi!=null)
307 308
            return bi;

309
        for (Item item : waitingList) {
310
            if (item.task == t)
K
kohsuke 已提交
311 312 313 314 315
                return item;
        }
        return null;
    }

316 317
    /**
     * Left for backward compatibility.
318
     *
319 320 321
     * @see #getItem(Task)
     */
    public synchronized Item getItem(AbstractProject p) {
322
        return getItem((Task) p);
323 324
    }

K
kohsuke 已提交
325
    /**
K
kohsuke 已提交
326
     * Returns true if this queue contains the said project.
K
kohsuke 已提交
327
     */
328 329
    public synchronized boolean contains(Task t) {
        if (blockedProjects.containsKey(t) || buildables.containsKey(t))
K
kohsuke 已提交
330
            return true;
331
        for (Item item : waitingList) {
332
            if (item.task == t)
K
kohsuke 已提交
333 334 335 336 337 338 339
                return true;
        }
        return false;
    }

    /**
     * Called by the executor to fetch something to build next.
340
     * <p>
K
kohsuke 已提交
341 342
     * This method blocks until a next project becomes buildable.
     */
343
    public Task pop() throws InterruptedException {
K
kohsuke 已提交
344
        final Executor exec = Executor.currentExecutor();
345

K
kohsuke 已提交
346
        try {
347
            while (true) {
K
kohsuke 已提交
348 349 350
                final JobOffer offer = new JobOffer(exec);
                long sleep = -1;

351
                synchronized (this) {
K
kohsuke 已提交
352 353
                    // consider myself parked
                    assert !parked.containsKey(exec);
354
                    parked.put(exec, offer);
K
kohsuke 已提交
355

K
kohsuke 已提交
356
                    // reuse executor thread to do a queue maintenance.
K
kohsuke 已提交
357 358 359 360 361
                    // at the end of this we get all the buildable jobs
                    // in the buildables field.
                    maintain();

                    // allocate buildable jobs to executors
362
                    Iterator<BuildableItem> itr = buildables.values().iterator();
363
                    while (itr.hasNext()) {
364
                        BuildableItem p = itr.next();
365 366

                        // one last check to make sure this build is not blocked.
367
                        if (isBuildBlocked(p.task)) {
368
                            itr.remove();
369
                            blockedProjects.put(p.task,new BlockedItem(p));
370 371
                            continue;
                        }
372

373
                        JobOffer runner = choose(p.task);
374
                        if (runner == null)
K
kohsuke 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
                            // 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.

390
                    if (!waitingList.isEmpty()) {
K
kohsuke 已提交
391
                        // wait until the first item in the queue is due
392 393
                        sleep = peek().timestamp.getTimeInMillis() - new GregorianCalendar().getTimeInMillis();
                        if (sleep < 100) sleep = 100;    // avoid wait(0)
K
kohsuke 已提交
394 395 396 397 398
                    }
                }

                // this needs to be done outside synchronized block,
                // so that executors can maintain a queue while others are sleeping
399
                if (sleep == -1)
K
kohsuke 已提交
400 401 402 403
                    offer.event.block();
                else
                    offer.event.block(sleep);

404
                synchronized (this) {
405
                    // retract the offer object
406
                    assert parked.get(exec) == offer;
407 408
                    parked.remove(exec);

K
kohsuke 已提交
409
                    // am I woken up because I have a project to build?
410 411
                    if (offer.item != null) {
                        LOGGER.fine("Pop returning " + offer.item + " for " + exec.getName());
K
kohsuke 已提交
412
                        // if so, just build it
413
                        return offer.item.task;
K
kohsuke 已提交
414 415 416 417 418
                    }
                    // otherwise run a queue maintenance
                }
            }
        } finally {
419
            synchronized (this) {
K
kohsuke 已提交
420
                // remove myself from the parked list
421
                JobOffer offer = parked.remove(exec);
422
                if (offer != null && offer.item != null) {
423 424 425 426 427
                    // 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,
                    // so check the contains method first.
428
                    if (!contains(offer.item.task))
429
                        buildables.put(offer.item.task,offer.item);
K
kohsuke 已提交
430
                }
431 432 433 434 435 436

                // 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 已提交
437 438 439 440 441
            }
        }
    }

    /**
K
kohsuke 已提交
442
     * Chooses the executor to carry out the build for the given project.
K
kohsuke 已提交
443
     *
444
     * @return null if no {@link Executor} can run it.
K
kohsuke 已提交
445
     */
446
    private JobOffer choose(Task p) {
447
        if (Hudson.getInstance().isQuietingDown()) {
K
kohsuke 已提交
448 449 450 451 452
            // if we are quieting down, don't run anything so that
            // all executors will be free.
            return null;
        }

453
        Label l = p.getAssignedLabel();
454
        if (l != null) {
455
            // if a project has assigned label, it can be only built on it
K
kohsuke 已提交
456
            for (JobOffer offer : parked.values()) {
457
                if (offer.isAvailable() && l.contains(offer.getNode()))
K
kohsuke 已提交
458 459 460 461 462
                    return offer;
            }
            return null;
        }

463
        // if we are a large deployment, then we will favor slaves
464
        boolean isLargeHudson = Hudson.getInstance().getSlaves().size() > 10;
465

466
        // otherwise let's see if the last node where this project was built is available
K
kohsuke 已提交
467 468
        // it has up-to-date workspace, so that's usually preferable.
        // (but we can't use an exclusive node)
469
        Node n = p.getLastBuiltOn();
470
        if (n != null && n.getMode() == Mode.NORMAL) {
K
kohsuke 已提交
471
            for (JobOffer offer : parked.values()) {
472 473
                if (offer.isAvailable() && offer.getNode() == n) {
                    if (isLargeHudson && offer.getNode() instanceof Slave)
S
stephenconnolly 已提交
474
                        // but if we are a large Hudson, then we really do want to keep the master free from builds
475
                        continue;
K
kohsuke 已提交
476
                    return offer;
477
                }
K
kohsuke 已提交
478 479 480 481 482 483
            }
        }

        // 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.
484 485
        // Similarly if we have many slaves, master should be made available
        // for HTTP requests and coordination as much as possible
486
        if (isLargeHudson || p.getEstimatedDuration() > 15 * 60 * 1000) {
K
kohsuke 已提交
487 488
            // consider a long job to be > 15 mins
            for (JobOffer offer : parked.values()) {
489
                if (offer.isAvailable() && offer.getNode() instanceof Slave && offer.isNotExclusive())
K
kohsuke 已提交
490 491 492 493 494 495
                    return offer;
            }
        }

        // lastly, just look for any idle executor
        for (JobOffer offer : parked.values()) {
496
            if (offer.isAvailable() && offer.isNotExclusive())
K
kohsuke 已提交
497 498 499 500 501 502 503 504 505
                return offer;
        }

        // nothing available
        return null;
    }

    /**
     * Checks the queue and runs anything that can be run.
506 507
     *
     * <p>
K
kohsuke 已提交
508
     * When conditions are changed, this method should be invoked.
509
     * <p>
K
kohsuke 已提交
510 511 512 513 514 515 516
     * 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()) {
517
            if (av.getValue().item == null) {
K
kohsuke 已提交
518 519 520 521 522 523
                av.getValue().event.signal();
                return;
            }
        }
    }

524 525 526
    /**
     * Checks if the given task is blocked.
     */
527
    private boolean isBuildBlocked(Task t) {
528 529 530
        return t.isBuildBlocked() || !canRun(t.getResourceList());
    }

K
kohsuke 已提交
531 532

    /**
K
kohsuke 已提交
533
     * Queue maintenance.
534
     * <p>
535
     * Move projects between {@link #waitingList}, {@link #blockedProjects}, and {@link #buildables}
K
kohsuke 已提交
536 537 538
     * appropriately.
     */
    private synchronized void maintain() {
539 540
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine("Queue maintenance started " + this);
541

542
        Iterator<BlockedItem> itr = blockedProjects.values().iterator();
543
        while (itr.hasNext()) {
544 545
            BlockedItem p = itr.next();
            if (!isBuildBlocked(p.task)) {
K
kohsuke 已提交
546
                // ready to be executed
547
                LOGGER.fine(p.task.getName() + " no longer blocked");
K
kohsuke 已提交
548
                itr.remove();
549
                buildables.put(p.task,new BuildableItem(p));
K
kohsuke 已提交
550 551 552
            }
        }

553
        while (!waitingList.isEmpty()) {
554
            WaitingItem top = peek();
K
kohsuke 已提交
555

556
            if (!top.timestamp.before(new GregorianCalendar()))
K
kohsuke 已提交
557 558
                return; // finished moving all ready items from queue

559
            Task p = top.task;
560
            if (!isBuildBlocked(p)) {
K
kohsuke 已提交
561
                // ready to be executed immediately
562
                waitingList.remove(top);
563
                LOGGER.fine(p.getName() + " ready to build");
564
                buildables.put(p,new BuildableItem(top));
K
kohsuke 已提交
565
            } else {
566
                // this can't be built now because another build is in progress
K
kohsuke 已提交
567
                // set this project aside.
568
                waitingList.remove(top);
569
                LOGGER.fine(p.getName() + " is blocked");
570
                blockedProjects.put(p,new BlockedItem(top));
K
kohsuke 已提交
571 572 573 574
            }
        }
    }

K
kohsuke 已提交
575 576
    /**
     * Task whose execution is controlled by the queue.
577
     * <p>
K
kohsuke 已提交
578 579 580 581
     * {@link #equals(Object) Value equality} of {@link Task}s is used
     * to collapse two tasks into one. This is used to avoid infinite
     * queue backlog.
     */
582
    public interface Task extends ModelObject, ResourceActivity {
583
        /**
584 585 586
         * If this task needs to be run on a node with a particular label,
         * return that {@link Label}. Otherwise null, indicating
         * it can run on anywhere.
587
         */
588
        Label getAssignedLabel();
589 590 591 592 593 594 595 596 597 598 599

        /**
         * If the previous execution of this task run on a certain node
         * and this task prefers to run on the same node, return that.
         * Otherwise null.
         */
        Node getLastBuiltOn();

        /**
         * Returns true if the execution should be blocked
         * for temporary reasons.
600 601
         *
         * <p>
K
kohsuke 已提交
602 603
         * This can be used to define mutual exclusion that goes beyond
         * {@link #getResourceList()}.
604 605 606 607 608 609 610 611 612 613 614
         */
        boolean isBuildBlocked();

        /**
         * When {@link #isBuildBlocked()} is true, this method returns
         * human readable description of why the build is blocked.
         * Used for HTML rendering.
         */
        String getWhyBlocked();

        /**
K
kohsuke 已提交
615
         * Unique name of this task.
K
kohsuke 已提交
616
         *
617 618
         * @see hudson.model.Item#getName()
         *      TODO: this doesn't make sense anymore. remove it.
619 620 621
         */
        String getName();

622 623 624 625 626
        /**
         * @see hudson.model.Item#getFullDisplayName()
         */
        String getFullDisplayName();

627 628 629 630
        /**
         * Estimate of how long will it take to execute this task.
         * Measured in milliseconds.
         *
631
         * @return -1 if it's impossible to estimate.
632 633 634
         */
        long getEstimatedDuration();

K
kohsuke 已提交
635
        /**
636
         * Creates {@link Executable}, which performs the actual execution of the task.
K
kohsuke 已提交
637
         */
638
        Executable createExecutable() throws IOException;
639 640 641 642 643 644 645 646

        /**
         * Checks the permission to see if the current user can abort this executable.
         * Returns normally from this method if it's OK.
         *
         * @throws AccessDeniedException if the permission is not granted.
         */
        void checkAbortPermission();
K
kohsuke 已提交
647 648 649 650 651 652

        /**
         * Works just like {@link #checkAbortPermission()} except it indicates the status by a return value,
         * instead of exception.
         */
        boolean hasAbortPermission();
653 654 655 656 657
    }

    public interface Executable extends Runnable {
        /**
         * Task from which this executable was created.
K
kohsuke 已提交
658
         * Never null.
659 660 661 662 663 664 665
         */
        Task getParent();

        /**
         * Called by {@link Executor} to perform the task
         */
        void run();
666 667
    }

K
kohsuke 已提交
668 669 670
    /**
     * Item in a queue.
     */
671
    @ExportedBean(defaultVisibility = 999)
672
    public abstract class Item {
K
kohsuke 已提交
673 674 675
        /**
         * Project to be built.
         */
676
        public final Task task;
K
kohsuke 已提交
677

678
        /**
679 680 681
         * Build is blocked because another build is in progress,
         * required {@link Resource}s are not available, or otherwise blocked
         * by {@link Task#isBuildBlocked()}.
682
         */
K
kohsuke 已提交
683
        @Exported
684
        public boolean isBlocked() { return this instanceof BlockedItem; }
685 686 687 688 689 690

        /**
         * 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.
         */
K
kohsuke 已提交
691
        @Exported
692
        public boolean isBuildable() { return this instanceof BuildableItem; }
693

694
        protected Item(Task project) {
695
            this.task = project;
K
kohsuke 已提交
696 697
        }

698 699 700
        /**
         * Gets a human-readable status message describing why it's in the queu.
         */
K
kohsuke 已提交
701
        @Exported
702
        public abstract String getWhy();
K
kohsuke 已提交
703

704 705 706 707
        public boolean hasCancelPermission() {
            return task.hasAbortPermission();
        }
    }
708

709 710 711 712 713 714 715 716 717
    /**
     * {@link Item} in the {@link Queue#waitingList} stage.
     */
    public final class WaitingItem extends Item implements Comparable<WaitingItem> {
        /**
         * This item can be run after this time.
         */
        @Exported
        public Calendar timestamp;
718

K
kohsuke 已提交
719 720 721 722 723 724
        /**
         * Unique number of this {@link WaitingItem}.
         * Used to differentiate {@link WaitingItem}s with the same due date, to make it sortable.
         */
        public final int id;

725 726 727
        WaitingItem(Calendar timestamp, Task project) {
            super(project);
            this.timestamp = timestamp;
K
kohsuke 已提交
728 729 730
            synchronized (Queue.this) {
                this.id = iota++;
            }
731 732 733 734 735 736 737 738 739 740 741
        }

        public int compareTo(WaitingItem that) {
            int r = this.timestamp.getTime().compareTo(that.timestamp.getTime());
            if (r != 0) return r;

            return this.id - that.id;
        }

        @Override
        public String getWhy() {
742
            long diff = timestamp.getTimeInMillis() - System.currentTimeMillis();
743
            if (diff > 0)
K
i18n  
kohsuke 已提交
744
                return Messages.Queue_InQuietPeriod(Util.getTimeSpanString(diff));
745 746 747 748
            else
                return Messages.Queue_Unknown();
        }
    }
K
kohsuke 已提交
749

750 751 752 753 754 755 756 757 758 759 760 761 762
    /**
     * Common part between {@link BlockedItem} and {@link BuildableItem}.
     */
    public abstract class NotWaitingItem extends Item {
        /**
         * When did this job exit the {@link Queue#waitingList} phase?
         */
        @Exported
        public final long buildableStartMilliseconds;

        protected NotWaitingItem(WaitingItem wi) {
            super(wi.task);
            buildableStartMilliseconds = System.currentTimeMillis();
K
kohsuke 已提交
763
        }
764

765 766 767
        protected NotWaitingItem(NotWaitingItem ni) {
            super(ni.task);
            buildableStartMilliseconds = ni.buildableStartMilliseconds;
768
        }
769
    }
770

771 772 773 774 775 776 777
    /**
     * {@link Item} in the {@link Queue#blockedProjects} stage.
     */
    public final class BlockedItem extends NotWaitingItem {
        public BlockedItem(WaitingItem wi) {
            super(wi);
        }
778

779 780 781 782 783 784 785 786 787 788 789 790 791
        public BlockedItem(NotWaitingItem ni) {
            super(ni);
        }

        @Override
        public String getWhy() {
            ResourceActivity r = getBlockingActivity(task);
            if (r != null) {
                if (r == task) // blocked by itself, meaning another build is in progress
                    return Messages.Queue_InProgress();
                return Messages.Queue_BlockedBy(r.getDisplayName());
            }
            return task.getWhyBlocked();
792
        }
793
    }
794

795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
    /**
     * {@link Item} in the {@link Queue#buildables} stage.
     */
    public final class BuildableItem extends NotWaitingItem {
        public BuildableItem(WaitingItem wi) {
            super(wi);
        }

        public BuildableItem(NotWaitingItem ni) {
            super(ni);
        }

        @Override
        public String getWhy() {
            Label node = task.getAssignedLabel();
            Hudson hudson = Hudson.getInstance();
            if (hudson.getSlaves().isEmpty())
                node = null;    // no master/slave. pointless to talk about nodes

            String name = null;
            if (node != null) {
                name = node.getName();
                if (node.isOffline()) {
                    if (node.getNodes().size() > 1)
                        return "All nodes of label '" + name + "' is offline";
                    else
                        return name + " is offline";
                }
            }

            return "Waiting for next available executor" + (name == null ? "" : " on " + name);
        }
K
kohsuke 已提交
827 828 829 830 831
    }

    /**
     * Unique number generator
     */
832
    private int iota = 0;
K
kohsuke 已提交
833 834

    private static final Logger LOGGER = Logger.getLogger(Queue.class.getName());
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851

    /**
     * Regularly invokes {@link Queue#maintain()} and clean itself up when
     * {@link Queue} gets GC-ed.
     */
    private static class MaintainTask extends SafeTimerTask {
        private final WeakReference<Queue> queue;

        MaintainTask(Queue queue) {
            this.queue = new WeakReference<Queue>(queue);

            long interval = 5 * Timer.ONE_SECOND;
            Trigger.timer.schedule(this, interval, interval);
        }

        protected void doRun() {
            Queue q = queue.get();
852
            if (q != null)
853 854 855 856 857
                q.maintain();
            else
                cancel();
        }
    }
K
kohsuke 已提交
858
}