Queue.java 25.0 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;
K
kohsuke 已提交
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;
K
kohsuke 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
import java.util.Calendar;
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>
39 40 41
 * 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}
 * so that we can keep track of additional data used for deciding what to exeucte when. 
K
kohsuke 已提交
42 43 44
 *
 * @author Kohsuke Kawaguchi
 */
45
public class Queue extends ResourceController {
K
kohsuke 已提交
46 47 48 49 50 51 52
    /**
     * 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.
     */
53
    private final Set<Item> queue = new TreeSet<Item>();
K
kohsuke 已提交
54 55 56

    /**
     * {@link Project}s that can be built immediately
57 58 59
     * but blocked because another build is in progress,
     * required {@link Resource}s are not available, or otherwise blocked
     * by {@link Task#isBuildBlocked()}.
K
kohsuke 已提交
60
     */
61
    private final Set<Task> blockedProjects = new HashSet<Task>();
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<Task> buildables = new LinkedList<Task>();
K
kohsuke 已提交
68 69 70 71 72 73

    /**
     * Data structure created for each idle {@link Executor}.
     * This is an offer from the queue to an executor.
     *
     * <p>
74
     * It eventually receives a {@link #task} to build.
K
kohsuke 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87
     */
    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
        Task task;
K
kohsuke 已提交
89 90 91 92 93

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

94 95 96
        public void set(Task p) {
            assert this.task ==null;
            this.task = p;
K
kohsuke 已提交
97 98 99 100
            event.signal();
        }

        public boolean isAvailable() {
101
            return task ==null && !executor.getOwner().isOffline();
K
kohsuke 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114
        }

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

115 116 117 118 119 120
    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 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133
    /**
     * 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) {
134 135 136
                AbstractProject j = Hudson.getInstance().getItemByFullName(line,AbstractProject.class);
                if(j!=null)
                    j.scheduleBuild();
K
kohsuke 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
            }
            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())
155
                w.println(i.task.getName());
K
kohsuke 已提交
156 157 158 159 160 161 162 163 164 165 166 167
            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.
168 169 170 171 172
     *
     * @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 已提交
173
     */
174 175 176 177 178 179 180
    public boolean add( AbstractProject p ) {
        return add(p,p.getQuietPeriod());
    }

    /**
     * Schedules a new build with a custom quiet period.
     *
K
kohsuke 已提交
181 182 183
     * <p>
     * Left for backward compatibility with &lt;1.114.
     *
184 185 186
     * @since 1.105
     */
    public synchronized boolean add( AbstractProject p, int quietPeriod ) {
K
kohsuke 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199
        return add((Task)p,quietPeriod);
    }

    /**
     * Schedules an execution of a task.
     *
     * @param quietPeriod
     *      Number of seconds that the task will be placed in queue.
     *      Useful when the same task is likely scheduled for multiple
     *      times.
     * @since 1.114
     */
    public synchronized boolean add( Task p, int quietPeriod ) {
200 201 202 203 204 205
    	Item item = getItem(p);
    	Calendar due = new GregorianCalendar();
    	due.add(Calendar.SECOND, quietPeriod);
        if (item != null) {
            if (item.timestamp.before(due))
                return false; // no double queueing
K
kohsuke 已提交
206

207 208 209 210
            // allow the due date to be pulled in
            item.timestamp = due;
        } else {
            LOGGER.fine(p.getName() + " added to queue");
211

212 213
            // put the item in the queue
            queue.add(new Item(due, p));
K
kohsuke 已提交
214

215
        }
K
kohsuke 已提交
216
        scheduleMaintenance();   // let an executor know that a new item is in the queue.
217
        return true;
K
kohsuke 已提交
218 219
    }

K
kohsuke 已提交
220 221 222 223 224 225 226 227
    /**
     * Cancels the item in the queue.
     *
     * @return
     *      true if the project was indeed in the queue and was removed.
     *      false if this was no-op.
     */
    public synchronized boolean cancel( AbstractProject<?,?> p ) {
228
        LOGGER.fine("Cancelling "+p.getName());
K
kohsuke 已提交
229 230
        for (Iterator itr = queue.iterator(); itr.hasNext();) {
            Item item = (Item) itr.next();
231
            if(item.task ==p) {
K
kohsuke 已提交
232
                itr.remove();
K
kohsuke 已提交
233
                return true;
K
kohsuke 已提交
234 235
            }
        }
K
kohsuke 已提交
236 237
        // use bitwise-OR to make sure that both branches get evaluated all the time
        return blockedProjects.remove(p)|buildables.remove(p);
K
kohsuke 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    }

    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();
256
        for (Task p : blockedProjects) {
257
            r[idx++] = new Item(now, p, true, false);
K
kohsuke 已提交
258
        }
259
        for (Task p : buildables) {
260
            r[idx++] = new Item(now, p, false, true);
K
kohsuke 已提交
261 262 263 264
        }
        return r;
    }

K
kohsuke 已提交
265 266 267 268 269
    /**
     * Gets the information about the queue item for the given project.
     *
     * @return null if the project is not in the queue.
     */
270
    public synchronized Item getItem(Task p) {
K
kohsuke 已提交
271 272 273 274 275
        if(blockedProjects.contains(p))
            return new Item(new GregorianCalendar(),p,true,false);
        if(buildables.contains(p))
            return new Item(new GregorianCalendar(),p,false,true); 
        for (Item item : queue) {
276
            if (item.task == p)
K
kohsuke 已提交
277 278 279 280 281
                return item;
        }
        return null;
    }

282 283 284 285 286 287 288 289 290
    /**
     * Left for backward compatibility.
     * 
     * @see #getItem(Task)
     */
    public synchronized Item getItem(AbstractProject p) {
        return getItem((Task)p);
    }

K
kohsuke 已提交
291
    /**
K
kohsuke 已提交
292
     * Returns true if this queue contains the said project.
K
kohsuke 已提交
293
     */
294
    public synchronized boolean contains(Task p) {
K
kohsuke 已提交
295 296 297
        if(blockedProjects.contains(p) || buildables.contains(p))
            return true;
        for (Item item : queue) {
298
            if (item.task == p)
K
kohsuke 已提交
299 300 301 302 303 304 305 306 307 308
                return true;
        }
        return false;
    }

    /**
     * Called by the executor to fetch something to build next.
     *
     * This method blocks until a next project becomes buildable.
     */
309
    public Task pop() throws InterruptedException {
K
kohsuke 已提交
310
        final Executor exec = Executor.currentExecutor();
311

K
kohsuke 已提交
312 313 314 315 316 317 318 319 320 321
        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 已提交
322
                    // reuse executor thread to do a queue maintenance.
K
kohsuke 已提交
323 324 325 326 327
                    // at the end of this we get all the buildable jobs
                    // in the buildables field.
                    maintain();

                    // allocate buildable jobs to executors
328
                    Iterator<Task> itr = buildables.iterator();
K
kohsuke 已提交
329
                    while(itr.hasNext()) {
330
                        Task p = itr.next();
331 332

                        // one last check to make sure this build is not blocked.
333
                        if(isBuildBlocked(p)) {
334 335 336 337 338
                            itr.remove();
                            blockedProjects.add(p);
                            continue;
                        }
                        
K
kohsuke 已提交
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 370
                        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) {
371 372 373 374
                    // retract the offer object
                    assert parked.get(exec)==offer;
                    parked.remove(exec);

K
kohsuke 已提交
375
                    // am I woken up because I have a project to build?
376 377
                    if(offer.task !=null) {
                        LOGGER.fine("Pop returning "+offer.task +" for "+exec.getName());
K
kohsuke 已提交
378
                        // if so, just build it
379
                        return offer.task;
K
kohsuke 已提交
380 381 382 383 384 385 386
                    }
                    // otherwise run a queue maintenance
                }
            }
        } finally {
            synchronized(this) {
                // remove myself from the parked list
387
                JobOffer offer = parked.remove(exec);
388
                if(offer!=null && offer.task !=null) {
389 390 391 392 393
                    // 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.
394 395
                    if(!contains(offer.task))
                        buildables.add(offer.task);
K
kohsuke 已提交
396
                }
397 398 399 400 401 402

                // 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 已提交
403 404 405 406 407
            }
        }
    }

    /**
K
kohsuke 已提交
408
     * Chooses the executor to carry out the build for the given project.
K
kohsuke 已提交
409 410 411 412
     *
     * @return
     *      null if no {@link Executor} can run it.
     */
413
    private JobOffer choose(Task p) {
K
kohsuke 已提交
414 415 416 417 418 419
        if(Hudson.getInstance().isQuietingDown()) {
            // if we are quieting down, don't run anything so that
            // all executors will be free.
            return null;
        }

420 421 422
        Label l = p.getAssignedLabel();
        if(l!=null) {
            // if a project has assigned label, it can be only built on it
K
kohsuke 已提交
423
            for (JobOffer offer : parked.values()) {
424
                if(offer.isAvailable() && l.contains(offer.getNode()))
K
kohsuke 已提交
425 426 427 428 429
                    return offer;
            }
            return null;
        }

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

433
        // otherwise let's see if the last node where this project was built is available
K
kohsuke 已提交
434 435
        // it has up-to-date workspace, so that's usually preferable.
        // (but we can't use an exclusive node)
436
        Node n = p.getLastBuiltOn();
K
kohsuke 已提交
437 438
        if(n!=null && n.getMode()==Mode.NORMAL) {
            for (JobOffer offer : parked.values()) {
439 440 441 442
                if(offer.isAvailable() && offer.getNode()==n) {
                    if(isLargeHudson && offer.getNode() instanceof Slave)
                        // but if we are a large Hudson, then we really do want to keep the master free from builds 
                        continue;
K
kohsuke 已提交
443
                    return offer;
444
                }
K
kohsuke 已提交
445 446 447 448 449 450
            }
        }

        // 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.
451 452 453
        // Similarly if we have many slaves, master should be made available
        // for HTTP requests and coordination as much as possible
        if(isLargeHudson || p.getEstimatedDuration()>15*60*1000) {
K
kohsuke 已提交
454 455 456 457 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
            // 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()) {
484
            if(av.getValue().task ==null) {
K
kohsuke 已提交
485 486 487 488 489 490
                av.getValue().event.signal();
                return;
            }
        }
    }

491 492 493 494 495 496 497
    /**
     * Checks if the given task is blocked.
     */
    private  boolean isBuildBlocked(Task t) {
        return t.isBuildBlocked() || !canRun(t.getResourceList());
    }

K
kohsuke 已提交
498 499

    /**
K
kohsuke 已提交
500
     * Queue maintenance.
K
kohsuke 已提交
501 502 503 504 505
     *
     * Move projects between {@link #queue}, {@link #blockedProjects}, and {@link #buildables}
     * appropriately.
     */
    private synchronized void maintain() {
506 507 508
        if(LOGGER.isLoggable(Level.FINE))
            LOGGER.fine("Queue maintenance started "+this);

509
        Iterator<Task> itr = blockedProjects.iterator();
K
kohsuke 已提交
510
        while(itr.hasNext()) {
511
            Task p = itr.next();
512
            if(!isBuildBlocked(p)) {
K
kohsuke 已提交
513
                // ready to be executed
514
                LOGGER.fine(p.getName()+" no longer blocked");
K
kohsuke 已提交
515 516 517 518 519 520 521 522 523 524 525
                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

526
            Task p = top.task;
527
            if(!isBuildBlocked(p)) {
K
kohsuke 已提交
528 529
                // ready to be executed immediately
                queue.remove(top);
530
                LOGGER.fine(p.getName()+" ready to build");
531
                buildables.add(p);
K
kohsuke 已提交
532
            } else {
533
                // this can't be built now because another build is in progress
K
kohsuke 已提交
534 535
                // set this project aside.
                queue.remove(top);
536
                LOGGER.fine(p.getName()+" is blocked");
537
                blockedProjects.add(p);
K
kohsuke 已提交
538 539 540 541
            }
        }
    }

K
kohsuke 已提交
542 543 544 545 546 547 548
    /**
     * Task whose execution is controlled by the queue.
     * <p>
     * {@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.
     */
549
    public interface Task extends ModelObject, ResourceActivity {
550
        /**
551 552 553
         * 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.
554
         */
555
        Label getAssignedLabel();
556 557 558 559 560 561 562 563 564 565 566

        /**
         * 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.
K
kohsuke 已提交
567 568 569 570
         *
         * <p>
         * This can be used to define mutual exclusion that goes beyond
         * {@link #getResourceList()}.
571 572 573 574 575 576 577 578 579 580 581
         */
        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 已提交
582 583
         * Unique name of this task.
         * @see hudson.model.Item#getName()
K
kohsuke 已提交
584 585
         *
         * TODO: this doesn't make sense anymore. remove it.
586 587 588
         */
        String getName();

589 590 591 592 593
        /**
         * @see hudson.model.Item#getFullDisplayName()
         */
        String getFullDisplayName();

594 595 596 597 598 599 600 601 602
        /**
         * Estimate of how long will it take to execute this task.
         * Measured in milliseconds.
         *
         * @return
         *      -1 if it's impossible to estimate.
         */
        long getEstimatedDuration();

K
kohsuke 已提交
603
        /**
604
         * Creates {@link Executable}, which performs the actual execution of the task.
K
kohsuke 已提交
605
         */
606
        Executable createExecutable() throws IOException;
607 608 609 610 611 612 613 614

        /**
         * 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 已提交
615 616 617 618 619 620

        /**
         * Works just like {@link #checkAbortPermission()} except it indicates the status by a return value,
         * instead of exception.
         */
        boolean hasAbortPermission();
621 622 623 624 625
    }

    public interface Executable extends Runnable {
        /**
         * Task from which this executable was created.
K
kohsuke 已提交
626
         * Never null.
627 628 629 630 631 632 633
         */
        Task getParent();

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

K
kohsuke 已提交
636 637 638
    /**
     * Item in a queue.
     */
K
kohsuke 已提交
639
    @ExportedBean(defaultVisibility=999)
640
    public final class Item implements Comparable<Item> {
K
kohsuke 已提交
641 642 643
        /**
         * This item can be run after this time.
         */
K
kohsuke 已提交
644
        @Exported
645
        public Calendar timestamp;
K
kohsuke 已提交
646 647 648 649

        /**
         * Project to be built.
         */
650
        public final Task task;
K
kohsuke 已提交
651 652 653

        /**
         * Unique number of this {@link Item}.
K
kohsuke 已提交
654
         * Used to differentiate {@link Item}s with the same due date.
K
kohsuke 已提交
655
         */
656 657 658
        public final int id;

        /**
659 660 661 662
         * Build is blocked because another build is in progress,
         * required {@link Resource}s are not available, or otherwise blocked
         * by {@link Task#isBuildBlocked()}.
         * 
663 664 665
         * This flag is only used in {@link Queue#getItems()} for
         * 'pseudo' items that are actually not really in the queue.
         */
K
kohsuke 已提交
666
        @Exported
667 668 669 670 671 672 673
        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.
         */
K
kohsuke 已提交
674
        @Exported
675
        public final boolean isBuildable;
K
kohsuke 已提交
676

677
        public Item(Calendar timestamp, Task project) {
678 679 680
            this(timestamp,project,false,false);
        }

681
        public Item(Calendar timestamp, Task project, boolean isBlocked, boolean isBuildable) {
K
kohsuke 已提交
682
            this.timestamp = timestamp;
683
            this.task = project;
684 685
            this.isBlocked = isBlocked;
            this.isBuildable = isBuildable;
K
kohsuke 已提交
686 687 688 689 690
            synchronized(Queue.this) {
                this.id = iota++;
            }
        }

691 692 693
        /**
         * Gets a human-readable status message describing why it's in the queu.
         */
K
kohsuke 已提交
694
        @Exported
695 696
        public String getWhy() {
            if(isBuildable) {
697
                Label node = task.getAssignedLabel();
698
                Hudson hudson = Hudson.getInstance();
699
                if(hudson.getSlaves().isEmpty())
700 701 702 703
                    node = null;    // no master/slave. pointless to talk about nodes

                String name = null;
                if(node!=null) {
704
                    name = node.getName();
705 706 707 708 709 710
                    if(node.isOffline()) {
                        if(node.getNodes().size()>1)
                            return "All nodes of label '"+name+"' is offline";
                        else
                            return name+" is offline";
                    }
711
                }
K
kohsuke 已提交
712

713 714 715 716
                return "Waiting for next available executor"+(name==null?"":" on "+name);
            }

            if(isBlocked) {
717
                ResourceActivity r = getBlockingActivity(task);
718 719
                if(r!=null) {
                    if(r==task) // blocked by itself, meaning another build is in progress
K
i18n  
kohsuke 已提交
720 721
                        return Messages.Queue_InProgress();
                    return Messages.Queue_BlockedBy(r.getDisplayName());
722
                }
723
                return task.getWhyBlocked();
724 725 726 727
            }

            long diff = timestamp.getTimeInMillis() - System.currentTimeMillis();
            if(diff>0) {
K
i18n  
kohsuke 已提交
728
                return Messages.Queue_InQuietPeriod(Util.getTimeSpanString(diff));
729
            }
K
kohsuke 已提交
730

K
i18n  
kohsuke 已提交
731
            return Messages.Queue_Unknown();
K
kohsuke 已提交
732
        }
733

734
        public boolean hasCancelPermission() {
K
kohsuke 已提交
735
            return task.hasAbortPermission();
736 737
        }

738 739 740 741 742 743 744
        public int compareTo(Item that) {
            int r = this.timestamp.getTime().compareTo(that.timestamp.getTime());
            if(r!=0)    return r;

            return this.id-that.id;
        }

K
kohsuke 已提交
745 746 747 748 749 750 751 752
    }

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

    private static final Logger LOGGER = Logger.getLogger(Queue.class.getName());
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

    /**
     * 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();
            if(q!=null)
                q.maintain();
            else
                cancel();
        }
    }
K
kohsuke 已提交
776
}