-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathQueue.java
3140 lines (2807 loc) · 115 KB
/
Queue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
320
321
322
323
324
325
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
356
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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Stephen Connolly, Tom Huybrechts, InfraDNA, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.BulkChange;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.XmlFile;
import hudson.init.Initializer;
import static hudson.init.InitMilestone.JOB_CONFIG_ADAPTED;
import static hudson.util.Iterators.reverse;
import hudson.cli.declarative.CLIResolver;
import hudson.model.labels.LabelAssignmentAction;
import hudson.model.queue.AbstractQueueTask;
import hudson.model.queue.Executables;
import hudson.model.queue.QueueListener;
import hudson.model.queue.QueueTaskFuture;
import hudson.model.queue.ScheduleResult;
import hudson.model.queue.ScheduleResult.Created;
import hudson.model.queue.SubTask;
import hudson.model.queue.FutureImpl;
import hudson.model.queue.MappingWorksheet;
import hudson.model.queue.MappingWorksheet.Mapping;
import hudson.model.queue.QueueSorter;
import hudson.model.queue.QueueTaskDispatcher;
import hudson.model.queue.Tasks;
import hudson.model.queue.WorkUnit;
import hudson.model.Node.Mode;
import hudson.model.listeners.SaveableListener;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.FoldableAction;
import hudson.model.queue.CauseOfBlockage.BecauseLabelIsBusy;
import hudson.model.queue.CauseOfBlockage.BecauseNodeIsOffline;
import hudson.model.queue.CauseOfBlockage.BecauseLabelIsOffline;
import hudson.model.queue.CauseOfBlockage.BecauseNodeIsBusy;
import hudson.model.queue.WorkUnitContext;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import java.nio.file.Files;
import hudson.util.Futures;
import jenkins.security.QueueItemAuthenticatorProvider;
import jenkins.security.stapler.StaplerAccessibleType;
import jenkins.util.SystemProperties;
import jenkins.util.Timer;
import hudson.triggers.SafeTimerTask;
import java.util.concurrent.TimeUnit;
import hudson.util.XStream2;
import hudson.util.ConsistentHash;
import hudson.util.ConsistentHash.Hash;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import jenkins.security.QueueItemAuthenticator;
import jenkins.util.AtmostOneTaskExecutor;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
import org.jenkinsci.bytecode.AdaptField;
import org.jenkinsci.remoting.RoleChecker;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnegative;
import javax.servlet.http.HttpServletResponse;
import jenkins.model.queue.AsynchronousExecution;
import jenkins.model.queue.CompositeCauseOfBlockage;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Build queue.
*
* <p>
* 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 execute when.
*
* <p>
* Items in queue goes through several stages, as depicted below:
* <pre>{@code
* (enter) --> waitingList --+--> blockedProjects
* | ^
* | |
* | v
* +--> buildables ---> pending ---> left
* ^ |
* | |
* +---(rarely)---+
* }</pre>
*
* <p>
* Note: In the normal case of events pending items only move to left. However they can move back
* if the node they are assigned to execute on disappears before their {@link Executor} thread
* starts, where the node is removed before the {@link Executable} has been instantiated it
* is safe to move the pending item back to buildable. Once the {@link Executable} has been
* instantiated the only option is to let the {@link Executable} bomb out as soon as it starts
* to try an execute on the node that no longer exists.
*
* <p>
* 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.
*
* @author Kohsuke Kawaguchi
* @see QueueListener
* @see QueueTaskDispatcher
*/
@ExportedBean
public class Queue extends ResourceController implements Saveable {
/**
* Items that are waiting for its quiet period to pass.
*
* <p>
* This consists of {@link Item}s that cannot be run yet
* because its time has not yet come.
*/
private final Set<WaitingItem> waitingList = new TreeSet<>();
/**
* {@link Task}s that can be built immediately
* but blocked because another build is in progress,
* required {@link Resource}s are not available,
* blocked via {@link QueueTaskDispatcher#canRun(Item)},
* or otherwise blocked by {@link Task#isBuildBlocked()}.
*/
private final ItemList<BlockedItem> blockedProjects = new ItemList<>();
/**
* {@link Task}s that can be built immediately
* that are waiting for available {@link Executor}.
* This list is sorted in such a way that earlier items are built earlier.
*/
private final ItemList<BuildableItem> buildables = new ItemList<>();
/**
* {@link Task}s that are being handed over to the executor, but execution
* has not started yet.
*/
private final ItemList<BuildableItem> pendings = new ItemList<>();
private transient volatile Snapshot snapshot = new Snapshot(waitingList, blockedProjects, buildables, pendings);
/**
* Items that left queue would stay here for a while to enable tracking via {@link Item#getId()}.
*
* This map is forgetful, since we can't remember everything that executed in the past.
*/
private final Cache<Long,LeftItem> leftItems = CacheBuilder.newBuilder().expireAfterWrite(5*60, TimeUnit.SECONDS).build();
/**
* Data structure created for each idle {@link Executor}.
* This is a job offer from the queue to an executor.
*
* <p>
* For each idle executor, this gets created to allow the scheduling logic
* to assign a work. Once a work is assigned, the executor actually gets
* started to carry out the task in question.
*/
public static class JobOffer extends MappingWorksheet.ExecutorSlot {
public final Executor executor;
/**
* The work unit that this {@link Executor} is going to handle.
*/
private WorkUnit workUnit;
private JobOffer(Executor executor) {
this.executor = executor;
}
@Override
protected void set(WorkUnit p) {
assert this.workUnit == null;
this.workUnit = p;
assert executor.isParking();
executor.start(workUnit);
// LOGGER.info("Starting "+executor.getName());
}
@Override
public Executor getExecutor() {
return executor;
}
/**
* @deprecated discards information; prefer {@link #getCauseOfBlockage}
*/
@Deprecated
public boolean canTake(BuildableItem item) {
return getCauseOfBlockage(item) == null;
}
/**
* Checks whether the {@link Executor} represented by this object is capable of executing the given task.
* @return a reason why it cannot, or null if it could
* @since 2.37
*/
public @CheckForNull CauseOfBlockage getCauseOfBlockage(BuildableItem item) {
Node node = getNode();
if (node == null) {
return CauseOfBlockage.fromMessage(Messages._Queue_node_has_been_removed_from_configuration(executor.getOwner().getDisplayName()));
}
CauseOfBlockage reason = node.canTake(item);
if (reason != null) {
return reason;
}
for (QueueTaskDispatcher d : QueueTaskDispatcher.all()) {
try {
reason = d.canTake(node, item);
} catch (Throwable t) {
// We cannot guarantee the task can be taken by the node because something wrong happened
LOGGER.log(Level.WARNING, t, () -> String.format("Exception evaluating if the node '%s' can take the task '%s'", node.getNodeName(), item.task.getName()));
reason = CauseOfBlockage.fromMessage(Messages._Queue_ExceptionCanTake());
}
if (reason != null) {
return reason;
}
}
// inlining isAvailable:
if (workUnit != null) { // unlikely in practice (should not have even found this executor if so)
return CauseOfBlockage.fromMessage(Messages._Queue_executor_slot_already_in_use());
}
if (executor.getOwner().isOffline()) {
return new CauseOfBlockage.BecauseNodeIsOffline(node);
}
if (!executor.getOwner().isAcceptingTasks()) { // Node.canTake (above) does not consider RetentionStrategy.isAcceptingTasks
return new CauseOfBlockage.BecauseNodeIsNotAcceptingTasks(node);
}
return null;
}
/**
* Is this executor ready to accept some tasks?
*/
public boolean isAvailable() {
return workUnit == null && !executor.getOwner().isOffline() && executor.getOwner().isAcceptingTasks();
}
@CheckForNull
public Node getNode() {
return executor.getOwner().getNode();
}
public boolean isNotExclusive() {
return getNode().getMode() == Mode.NORMAL;
}
@Override
public String toString() {
return String.format("JobOffer[%s #%d]",executor.getOwner().getName(), executor.getNumber());
}
}
private volatile transient LoadBalancer loadBalancer;
private volatile transient QueueSorter sorter;
private transient final AtmostOneTaskExecutor<Void> maintainerThread = new AtmostOneTaskExecutor<>(new Callable<Void>() {
@Override
public Void call() throws Exception {
maintain();
return null;
}
@Override
public String toString() {
return "Periodic Jenkins queue maintenance";
}
});
private transient final ReentrantLock lock = new ReentrantLock();
private transient final Condition condition = lock.newCondition();
public Queue(@Nonnull LoadBalancer loadBalancer) {
this.loadBalancer = loadBalancer.sanitize();
// 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).periodic();
}
public LoadBalancer getLoadBalancer() {
return loadBalancer;
}
public void setLoadBalancer(@Nonnull LoadBalancer loadBalancer) {
if(loadBalancer==null) throw new IllegalArgumentException();
this.loadBalancer = loadBalancer.sanitize();
}
public QueueSorter getSorter() {
return sorter;
}
public void setSorter(QueueSorter sorter) {
this.sorter = sorter;
}
/**
* Simple queue state persistence object.
*/
static class State {
public long counter;
public List<Item> items = new ArrayList<>();
}
/**
* Loads the queue contents that was {@link #save() saved}.
*/
public void load() {
lock.lock();
try { try {
// Clear items, for the benefit of reloading.
waitingList.clear();
blockedProjects.clear();
buildables.clear();
pendings.clear();
// first try the old format
File queueFile = getQueueFile();
if (queueFile.exists()) {
try (BufferedReader in = Files.newBufferedReader(Util.fileToPath(queueFile), Charset.defaultCharset())) {
String line;
while ((line = in.readLine()) != null) {
AbstractProject j = Jenkins.get().getItemByFullName(line, AbstractProject.class);
if (j != null)
j.scheduleBuild();
}
}
// discard the queue file now that we are done
queueFile.delete();
} else {
queueFile = getXMLQueueFile();
if (queueFile.exists()) {
Object unmarshaledObj = new XmlFile(XSTREAM, queueFile).read();
List items;
if (unmarshaledObj instanceof State) {
State state = (State) unmarshaledObj;
items = state.items;
WaitingItem.COUNTER.set(state.counter);
} else {
// backward compatibility - it's an old List queue.xml
items = (List) unmarshaledObj;
long maxId = 0;
for (Object o : items) {
if (o instanceof Item) {
maxId = Math.max(maxId, ((Item)o).id);
}
}
WaitingItem.COUNTER.set(maxId);
}
for (Object o : items) {
if (o instanceof Task) {
// backward compatibility
schedule((Task)o, 0);
} else if (o instanceof Item) {
Item item = (Item)o;
if (item.task == null) {
continue; // botched persistence. throw this one away
}
if (item instanceof WaitingItem) {
item.enter(this);
} else if (item instanceof BlockedItem) {
item.enter(this);
} else if (item instanceof BuildableItem) {
item.enter(this);
} else {
throw new IllegalStateException("Unknown item type! " + item);
}
}
}
// I just had an incident where all the executors are dead at AbstractProject._getRuns()
// because runs is null. Debugger revealed that this is caused by a MatrixConfiguration
// object that doesn't appear to be de-serialized properly.
// I don't know how this problem happened, but to diagnose this problem better
// when it happens again, save the old queue file for introspection.
File bk = new File(queueFile.getPath() + ".bak");
bk.delete();
queueFile.renameTo(bk);
queueFile.delete();
}
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load the queue file " + getXMLQueueFile(), e);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Persists the queue contents to the disk.
*/
public void save() {
if(BulkChange.contains(this)) return;
if (Jenkins.getInstanceOrNull() == null) {
return;
}
XmlFile queueFile = new XmlFile(XSTREAM, getXMLQueueFile());
lock.lock();
try {
// write out the queue state we want to save
State state = new State();
state.counter = WaitingItem.COUNTER.longValue();
// write out the tasks on the queue
for (Item item: getItems()) {
if(item.task instanceof TransientTask) continue;
state.items.add(item);
}
try {
queueFile.write(state);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to write out the queue file " + getXMLQueueFile(), e);
}
} finally {
lock.unlock();
}
SaveableListener.fireOnChange(this, queueFile);
}
/**
* Wipes out all the items currently in the queue, as if all of them are cancelled at once.
*/
public void clear() {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
lock.lock();
try { try {
for (WaitingItem i : new ArrayList<>(
waitingList)) // copy the list as we'll modify it in the loop
i.cancel(this);
blockedProjects.cancelAll();
pendings.cancelAll();
buildables.cancelAll();
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
scheduleMaintenance();
}
private File getQueueFile() {
return new File(Jenkins.get().getRootDir(), "queue.txt");
}
/*package*/ File getXMLQueueFile() {
return new File(Jenkins.get().getRootDir(), "queue.xml");
}
/**
* @deprecated as of 1.311
* Use {@link #schedule(AbstractProject)}
*/
@Deprecated
public boolean add(AbstractProject p) {
return schedule(p)!=null;
}
/**
* Schedule a new build for this project.
* @see #schedule(Task, int)
*/
public @CheckForNull WaitingItem schedule(AbstractProject p) {
return schedule(p, p.getQuietPeriod());
}
/**
* Schedules a new build with a custom quiet period.
*
* <p>
* Left for backward compatibility with <1.114.
*
* @since 1.105
* @deprecated as of 1.311
* Use {@link #schedule(Task, int)}
*/
@Deprecated
public boolean add(AbstractProject p, int quietPeriod) {
return schedule(p, quietPeriod)!=null;
}
/**
* @deprecated as of 1.521
* Use {@link #schedule2(Task, int, List)}
*/
@Deprecated
public WaitingItem schedule(Task p, int quietPeriod, List<Action> actions) {
return schedule2(p, quietPeriod, actions).getCreateItem();
}
/**
* Schedules an execution of a task.
*
* @param actions
* These actions can be used for associating information scoped to a particular build, to
* the task being queued. Upon the start of the build, these {@link Action}s will be automatically
* added to the {@link Run} object, and hence available to everyone.
* For the convenience of the caller, this list can contain null, and those will be silently ignored.
* @since 1.311
* @return
* {@link hudson.model.queue.ScheduleResult.Refused} if Jenkins refused to add this task into the queue (for example because the system
* is about to shutdown.) Otherwise the task is either merged into existing items in the queue
* (in which case you get {@link hudson.model.queue.ScheduleResult.Existing} instance back), or a new item
* gets created in the queue (in which case you get {@link Created}.
*
* Note the nature of the queue
* is that such {@link Item} only captures the state of the item at a particular moment,
* and by the time you inspect the object, some of its information can be already stale.
*
* That said, one can still look at {@link Queue.Item#future}, {@link Queue.Item#getId()}, etc.
*/
public @Nonnull ScheduleResult schedule2(Task p, int quietPeriod, List<Action> actions) {
// remove nulls
actions = new ArrayList<>(actions);
actions.removeIf(Objects::isNull);
lock.lock();
try { try {
for (QueueDecisionHandler h : QueueDecisionHandler.all())
if (!h.shouldSchedule(p, actions))
return ScheduleResult.refused(); // veto
return scheduleInternal(p, quietPeriod, actions);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Schedules an execution of a task.
*
* @since 1.311
* @return
* {@link hudson.model.queue.ScheduleResult.Existing} if this task is already in the queue and
* therefore the add operation was no-op. Otherwise {@link hudson.model.queue.ScheduleResult.Created}
* indicates the {@link WaitingItem} object added, although the nature of the queue
* is that such {@link Item} only captures the state of the item at a particular moment,
* and by the time you inspect the object, some of its information can be already stale.
*
* That said, one can still look at {@link WaitingItem#future}, {@link WaitingItem#getId()}, etc.
*/
private @Nonnull ScheduleResult scheduleInternal(Task p, int quietPeriod, List<Action> actions) {
lock.lock();
try { try {
Calendar due = new GregorianCalendar();
due.add(Calendar.SECOND, quietPeriod);
// Do we already have this task in the queue? Because if so, we won't schedule a new one.
List<Item> duplicatesInQueue = new ArrayList<>();
for (Item item : liveGetItems(p)) {
boolean shouldScheduleItem = false;
for (QueueAction action : item.getActions(QueueAction.class)) {
shouldScheduleItem |= action.shouldSchedule(actions);
}
for (QueueAction action : Util.filter(actions, QueueAction.class)) {
shouldScheduleItem |= action.shouldSchedule((new ArrayList<>(item.getAllActions())));
}
if (!shouldScheduleItem) {
duplicatesInQueue.add(item);
}
}
if (duplicatesInQueue.isEmpty()) {
LOGGER.log(Level.FINE, "{0} added to queue", p);
// put the item in the queue
WaitingItem added = new WaitingItem(due, p, actions);
added.enter(this);
scheduleMaintenance(); // let an executor know that a new item is in the queue.
return ScheduleResult.created(added);
}
LOGGER.log(Level.FINE, "{0} is already in the queue", p);
// but let the actions affect the existing stuff.
for (Item item : duplicatesInQueue) {
for (FoldableAction a : Util.filter(actions, FoldableAction.class)) {
a.foldIntoExisting(item, p, actions);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "after folding {0}, {1} includes {2}", new Object[] {a, item, item.getAllActions()});
}
}
}
boolean queueUpdated = false;
for (WaitingItem wi : Util.filter(duplicatesInQueue, WaitingItem.class)) {
// make sure to always use the shorter of the available due times
if (wi.timestamp.before(due))
continue;
// waitingList is sorted, so when we change a timestamp we need to maintain order
wi.leave(this);
wi.timestamp = due;
wi.enter(this);
queueUpdated = true;
}
if (queueUpdated) scheduleMaintenance();
// REVISIT: when there are multiple existing items in the queue that matches the incoming one,
// whether the new one should affect all existing ones or not is debatable. I for myself
// thought this would only affect one, so the code was bit of surprise, but I'm keeping the current
// behaviour.
return ScheduleResult.existing(duplicatesInQueue.get(0));
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* @deprecated as of 1.311
* Use {@link #schedule(Task, int)}
*/
@Deprecated
public boolean add(Task p, int quietPeriod) {
return schedule(p, quietPeriod)!=null;
}
public @CheckForNull WaitingItem schedule(Task p, int quietPeriod) {
return schedule(p, quietPeriod, new Action[0]);
}
/**
* @deprecated as of 1.311
* Use {@link #schedule(Task, int, Action...)}
*/
@Deprecated
public boolean add(Task p, int quietPeriod, Action... actions) {
return schedule(p, quietPeriod, actions)!=null;
}
/**
* Convenience wrapper method around {@link #schedule(Task, int, List)}
*/
public @CheckForNull WaitingItem schedule(Task p, int quietPeriod, Action... actions) {
return schedule2(p, quietPeriod, actions).getCreateItem();
}
/**
* Convenience wrapper method around {@link #schedule2(Task, int, List)}
*/
public @Nonnull ScheduleResult schedule2(Task p, int quietPeriod, Action... actions) {
return schedule2(p, quietPeriod, Arrays.asList(actions));
}
/**
* Cancels the item in the queue. If the item is scheduled more than once, cancels the first occurrence.
*
* @return true if the project was indeed in the queue and was removed.
* false if this was no-op.
*/
public boolean cancel(Task p) {
lock.lock();
try { try {
LOGGER.log(Level.FINE, "Cancelling {0}", p);
for (WaitingItem item : waitingList) {
if (item.task.equals(p)) {
return item.cancel(this);
}
}
// use bitwise-OR to make sure that both branches get evaluated all the time
return blockedProjects.cancel(p) != null | buildables.cancel(p) != null;
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
private void updateSnapshot() {
Snapshot revised = new Snapshot(waitingList, blockedProjects, buildables, pendings);
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "{0} → {1}; leftItems={2}", new Object[] {snapshot, revised, leftItems.asMap()});
}
snapshot = revised;
}
public boolean cancel(Item item) {
LOGGER.log(Level.FINE, "Cancelling {0} item#{1}", new Object[] {item.task, item.id});
lock.lock();
try { try {
return item.cancel(this);
} finally { updateSnapshot(); } } finally {
lock.unlock();
}
}
/**
* Called from {@code queue.jelly} and {@code queue-items.jelly}.
*/
@RequirePOST
public HttpResponse doCancelItem(@QueryParameter long id) throws IOException, ServletException {
Item item = getItem(id);
if (item != null) {
if(item.hasCancelPermission()){
if(cancel(item)) {
return HttpResponses.status(HttpServletResponse.SC_NO_CONTENT);
}
return HttpResponses.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not cancel run for id " + id);
}
return HttpResponses.error(422, "Item for id (" + id + ") is not cancellable");
} // else too late, ignore (JENKINS-14813)
return HttpResponses.error(HttpServletResponse.SC_NOT_FOUND, "Provided id (" + id + ") not found");
}
public boolean isEmpty() {
Snapshot snapshot = this.snapshot;
return snapshot.waitingList.isEmpty() && snapshot.blockedProjects.isEmpty() && snapshot.buildables.isEmpty()
&& snapshot.pendings.isEmpty();
}
private WaitingItem peek() {
return waitingList.iterator().next();
}
/**
* Gets a snapshot of items in the queue.
*
* Generally speaking the array is sorted such that the items that are most likely built sooner are
* at the end.
*/
@Exported(inline=true)
public Item[] getItems() {
Snapshot s = this.snapshot;
List<Item> r = new ArrayList<>();
for(WaitingItem p : s.waitingList) {
r = checkPermissionsAndAddToList(r, p);
}
for (BlockedItem p : s.blockedProjects){
r = checkPermissionsAndAddToList(r, p);
}
for (BuildableItem p : reverse(s.buildables)) {
r = checkPermissionsAndAddToList(r, p);
}
for (BuildableItem p : reverse(s.pendings)) {
r= checkPermissionsAndAddToList(r, p);
}
Item[] items = new Item[r.size()];
r.toArray(items);
return items;
}
private List<Item> checkPermissionsAndAddToList(List<Item> r, Item t) {
if (t.task instanceof hudson.security.AccessControlled) {
if (((hudson.security.AccessControlled)t.task).hasPermission(hudson.model.Item.READ)
|| ((hudson.security.AccessControlled) t.task).hasPermission(hudson.security.Permission.READ)) {
r.add(t);
}
}
return r;
}
/**
* Returns an array of Item for which it is only visible the name of the task.
*
* Generally speaking the array is sorted such that the items that are most likely built sooner are
* at the end.
*/
@Restricted(NoExternalUse.class)
@Exported(inline=true)
public StubItem[] getDiscoverableItems() {
Snapshot s = this.snapshot;
List<StubItem> r = new ArrayList<>();
for(WaitingItem p : s.waitingList) {
r = filterDiscoverableItemListBasedOnPermissions(r, p);
}
for (BlockedItem p : s.blockedProjects){
r = filterDiscoverableItemListBasedOnPermissions(r, p);
}
for (BuildableItem p : reverse(s.buildables)) {
r = filterDiscoverableItemListBasedOnPermissions(r, p);
}
for (BuildableItem p : reverse(s.pendings)) {
r= filterDiscoverableItemListBasedOnPermissions(r, p);
}
StubItem[] items = new StubItem[r.size()];
r.toArray(items);
return items;
}
private List<StubItem> filterDiscoverableItemListBasedOnPermissions(List<StubItem> r, Item t) {
if (t.task instanceof hudson.model.Item) {
if (!((hudson.model.Item)t.task).hasPermission(hudson.model.Item.READ) && ((hudson.model.Item)t.task).hasPermission(hudson.model.Item.DISCOVER)) {
r.add(new StubItem(new StubTask(t.task)));
}
}
return r;
}
/**
* Like {@link #getItems()}, but returns an approximation that might not be completely up-to-date.
*
* <p>
* At the expense of accuracy, this method does not usually lock {@link Queue} and therefore is faster
* in a highly concurrent situation.
*
* <p>
* The list obtained is an accurate snapshot of the queue at some point in the past. The snapshot
* is updated and normally no more than one second old, but this is a soft commitment that might
* get violated when the lock on {@link Queue} is highly contended.
*
* <p>
* This method is primarily added to make UI threads run faster.
*
* @since 1.483
* @deprecated Use {@link #getItems()} directly. As of 1.607 the approximation is no longer needed.
*/
@Deprecated
public List<Item> getApproximateItemsQuickly() {
return Arrays.asList(getItems());
}
public Item getItem(long id) {
Snapshot snapshot = this.snapshot;
for (Item item : snapshot.blockedProjects) {
if (item.id == id)
return item;
}
for (Item item : snapshot.buildables) {
if (item.id == id)
return item;
}
for (Item item : snapshot.pendings) {
if (item.id == id)
return item;
}
for (Item item : snapshot.waitingList) {
if (item.id == id) {
return item;
}
}
return leftItems.getIfPresent(id);
}
/**
* Gets all the {@link BuildableItem}s that are waiting for an executor in the given {@link Computer}.
*/
public List<BuildableItem> getBuildableItems(Computer c) {
Snapshot snapshot = this.snapshot;
List<BuildableItem> result = new ArrayList<>();
_getBuildableItems(c, snapshot.buildables, result);
_getBuildableItems(c, snapshot.pendings, result);
return result;
}
private void _getBuildableItems(Computer c, List<BuildableItem> col, List<BuildableItem> result) {
Node node = c.getNode();
if (node == null) // Deleted computers cannot take build items...
return;
for (BuildableItem p : col) {
if (node.canTake(p) == null)
result.add(p);
}
}
/**
* Gets the snapshot of all {@link BuildableItem}s.
*/
public List<BuildableItem> getBuildableItems() {
Snapshot snapshot = this.snapshot;
ArrayList<BuildableItem> r = new ArrayList<>(snapshot.buildables);
r.addAll(snapshot.pendings);
return r;
}
/**
* Gets the snapshot of all {@link BuildableItem}s.
*/
public List<BuildableItem> getPendingItems() {
return new ArrayList<>(snapshot.pendings);
}
/**
* Gets the snapshot of all {@link BlockedItem}s.
*/
protected List<BlockedItem> getBlockedItems() {
return new ArrayList<>(snapshot.blockedProjects);
}
/**
* Returns the snapshot of all {@link LeftItem}s.
*
* @since 1.519
*/
public Collection<LeftItem> getLeftItems() {
return Collections.unmodifiableCollection(leftItems.asMap().values());
}
/**
* Immediately clear the {@link #getLeftItems} cache.
* Useful for tests which need to verify that no links to a build remain.
* @since 1.519
*/
public void clearLeftItems() {
leftItems.invalidateAll();
}
/**
* Gets all items that are in the queue but not blocked
*
* @since 1.402
*/
public List<Item> getUnblockedItems() {
Snapshot snapshot = this.snapshot;
List<Item> queuedNotBlocked = new ArrayList<>();
queuedNotBlocked.addAll(snapshot.waitingList);
queuedNotBlocked.addAll(snapshot.buildables);
queuedNotBlocked.addAll(snapshot.pendings);
// but not 'blockedProjects'
return queuedNotBlocked;
}
/**
* Works just like {@link #getUnblockedItems()} but return tasks.
*
* @since 1.402
*/
public Set<Task> getUnblockedTasks() {
List<Item> items = getUnblockedItems();
Set<Task> unblockedTasks = new HashSet<>(items.size());
for (Queue.Item t : items)