/
Executor.java
951 lines (867 loc) · 30.5 KB
/
Executor.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
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Red Hat, Inc., Stephen Connolly, Tom Huybrechts
*
* 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 hudson.FilePath;
import hudson.Util;
import hudson.model.Queue.Executable;
import hudson.model.queue.Executables;
import hudson.model.queue.SubTask;
import hudson.model.queue.Tasks;
import hudson.model.queue.WorkUnit;
import hudson.security.ACL;
import hudson.util.InterceptingProxy;
import hudson.util.TimeUnit2;
import jenkins.model.CauseOfInterruption;
import jenkins.model.CauseOfInterruption.UserInterruption;
import jenkins.model.InterruptedBuildAction;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.model.queue.Executables.*;
import static java.util.logging.Level.*;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jenkins.model.queue.AsynchronousExecution;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* Thread that executes builds.
* Since 1.536, {@link Executor}s start threads on-demand.
* <p>Callers should use {@link #isActive()} instead of {@link #isAlive()}.
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Executor extends Thread implements ModelObject {
protected final @Nonnull Computer owner;
private final Queue queue;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
@GuardedBy("lock")
private long startTime;
/**
* Used to track when a job was last executed.
*/
private final long creationTime = System.currentTimeMillis();
/**
* Executor number that identifies it among other executors for the same {@link Computer}.
*/
private int number;
/**
* {@link hudson.model.Queue.Executable} being executed right now, or null if the executor is idle.
*/
@GuardedBy("lock")
private Queue.Executable executable;
/**
* Used to mark that the execution is continuing asynchronously even though {@link Executor} as {@link Thread}
* has finished.
*/
@GuardedBy("lock")
private AsynchronousExecution asynchronousExecution;
/**
* When {@link Queue} allocates a work for this executor, this field is set
* and the executor is {@linkplain Thread#start() started}.
*/
@GuardedBy("lock")
private WorkUnit workUnit;
private Throwable causeOfDeath;
private boolean induceDeath;
@GuardedBy("lock")
private boolean started;
/**
* When the executor is interrupted, we allow the code that interrupted the thread to override the
* result code it prefers.
*/
@GuardedBy("lock")
private Result interruptStatus;
/**
* Cause of interruption. Access needs to be synchronized.
*/
@GuardedBy("lock")
private final List<CauseOfInterruption> causes = new Vector<CauseOfInterruption>();
public Executor(@Nonnull Computer owner, int n) {
super("Executor #"+n+" for "+owner.getDisplayName());
this.owner = owner;
this.queue = Jenkins.getInstance().getQueue();
this.number = n;
}
@Override
public void interrupt() {
interrupt(Result.ABORTED);
}
void interruptForShutdown() {
interrupt(Result.ABORTED, true);
}
/**
* Interrupt the execution,
* but instead of marking the build as aborted, mark it as specified result.
*
* @since 1.417
*/
public void interrupt(Result result) {
interrupt(result, false);
}
private void interrupt(Result result, boolean forShutdown) {
Authentication a = Jenkins.getAuthentication();
if (a == ACL.SYSTEM)
interrupt(result, forShutdown, new CauseOfInterruption[0]);
else {
// worth recording who did it
// avoid using User.get() to avoid deadlock.
interrupt(result, forShutdown, new UserInterruption(a.getName()));
}
}
/**
* Interrupt the execution. Mark the cause and the status accordingly.
*/
public void interrupt(Result result, CauseOfInterruption... causes) {
interrupt(result, false, causes);
}
private void interrupt(Result result, boolean forShutdown, CauseOfInterruption... causes) {
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, String.format("%s is interrupted(%s): %s", getDisplayName(), result, Util.join(Arrays.asList(causes),",")), new InterruptedException());
lock.writeLock().lock();
try {
if (!started) {
// not yet started, so simply dispose this
owner.removeExecutor(this);
return;
}
interruptStatus = result;
for (CauseOfInterruption c : causes) {
if (!this.causes.contains(c))
this.causes.add(c);
}
if (asynchronousExecution != null) {
asynchronousExecution.interrupt(forShutdown);
} else {
super.interrupt();
}
} finally {
lock.writeLock().unlock();
}
}
public Result abortResult() {
lock.readLock().lock();
try {
Result r = interruptStatus;
if (r == null) r =
Result.ABORTED; // this is when we programmatically throw InterruptedException instead of calling the interrupt method.
return r;
} finally {
lock.readLock().unlock();
}
}
/**
* report cause of interruption and record it to the build, if available.
*
* @since 1.425
*/
public void recordCauseOfInterruption(Run<?,?> build, TaskListener listener) {
List<CauseOfInterruption> r;
// atomically get&clear causes.
lock.writeLock().lock();
try {
if (causes.isEmpty()) return;
r = new ArrayList<CauseOfInterruption>(causes);
causes.clear();
} finally {
lock.writeLock().unlock();
}
build.addAction(new InterruptedBuildAction(r));
for (CauseOfInterruption c : r)
c.print(listener);
}
/**
* There are some cases where an executor is started but the node is removed or goes off-line before we are ready
* to start executing the assigned work unit. This method is called to clear the assigned work unit so that
* the {@link Queue#maintain()} method can return the item to the buildable state.
*
* Note: once we create the {@link Executable} we cannot unwind the state and the build will have to end up being
* marked as a failure.
*/
private void resetWorkUnit(String reason) {
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
try {
pw.printf("%s grabbed %s from queue but %s %s. ", getName(), workUnit, owner.getDisplayName(), reason);
if (owner.getTerminatedBy().isEmpty()) {
pw.print("No termination trace available.");
} else {
pw.println("Termination trace follows:");
for (Computer.TerminationRequest request: owner.getTerminatedBy()) {
request.printStackTrace(pw);
}
}
} finally {
pw.close();
}
LOGGER.log(WARNING, writer.toString());
lock.writeLock().lock();
try {
if (executable != null) {
throw new IllegalStateException("Cannot reset the work unit after the executable has been created");
}
workUnit = null;
} finally {
lock.writeLock().unlock();
}
}
@Override
public void run() {
if (!owner.isOnline()) {
resetWorkUnit("went off-line before the task's worker thread started");
owner.removeExecutor(this);
queue.scheduleMaintenance();
return;
}
if (owner.getNode() == null) {
resetWorkUnit("was removed before the task's worker thread started");
owner.removeExecutor(this);
queue.scheduleMaintenance();
return;
}
final WorkUnit workUnit;
lock.writeLock().lock();
try {
startTime = System.currentTimeMillis();
workUnit = this.workUnit;
} finally {
lock.writeLock().unlock();
}
ACL.impersonate(ACL.SYSTEM);
try {
if (induceDeath) throw new ThreadDeath();
SubTask task;
// transition from idle to building.
// perform this state change as an atomic operation wrt other queue operations
task = Queue.withLock(new java.util.concurrent.Callable<SubTask>() {
@Override
public SubTask call() throws Exception {
if (!owner.isOnline()) {
resetWorkUnit("went off-line before the task's worker thread was ready to execute");
return null;
}
if (owner.getNode() == null) {
resetWorkUnit("was removed before the task's worker thread was ready to execute");
return null;
}
// after this point we cannot unwind the assignment of the work unit, if the owner
// is removed or goes off-line then the build will just have to fail.
workUnit.setExecutor(Executor.this);
queue.onStartExecuting(Executor.this);
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" grabbed "+workUnit+" from queue");
SubTask task = workUnit.work;
Executable executable = task.createExecutable();
lock.writeLock().lock();
try {
Executor.this.executable = executable;
} finally {
lock.writeLock().unlock();
}
workUnit.setExecutable(executable);
return task;
}
});
Executable executable;
lock.readLock().lock();
try {
if (this.workUnit == null) {
// we called resetWorkUnit, so bail. Outer finally will remove this and schedule queue maintenance
return;
}
executable = this.executable;
} finally {
lock.readLock().unlock();
}
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" is going to execute "+executable);
Throwable problems = null;
try {
workUnit.context.synchronizeStart();
// this code handles the behavior of null Executables returned
// by tasks. In such case Jenkins starts the workUnit in order
// to report results to console outputs.
if (executable == null) {
throw new Error("The null Executable has been created for "+workUnit+". The task cannot be executed");
}
if (executable instanceof Actionable) {
for (Action action: workUnit.context.actions) {
((Actionable) executable).addAction(action);
}
}
ACL.impersonate(workUnit.context.item.authenticate());
setName(getName() + " : executing " + executable.toString());
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" is now executing "+executable);
queue.execute(executable, task);
} catch (AsynchronousExecution x) {
lock.writeLock().lock();
try {
x.setExecutor(this);
this.asynchronousExecution = x;
} finally {
lock.writeLock().unlock();
}
} catch (Throwable e) {
problems = e;
} finally {
boolean needFinish1;
lock.readLock().lock();
try {
needFinish1 = asynchronousExecution == null;
} finally {
lock.readLock().unlock();
}
if (needFinish1) {
finish1(problems);
}
}
} catch (InterruptedException e) {
LOGGER.log(FINE, getName()+" interrupted",e);
// die peacefully
} catch(Exception e) {
causeOfDeath = e;
LOGGER.log(SEVERE, "Unexpected executor death", e);
} catch (Error e) {
causeOfDeath = e;
LOGGER.log(SEVERE, "Unexpected executor death", e);
} finally {
if (asynchronousExecution == null) {
finish2();
}
}
}
private void finish1(@CheckForNull Throwable problems) {
if (problems != null) {
// for some reason the executor died. this is really
// a bug in the code, but we don't want the executor to die,
// so just leave some info and go on to build other things
LOGGER.log(Level.SEVERE, "Executor threw an exception", problems);
workUnit.context.abort(problems);
}
long time = System.currentTimeMillis() - startTime;
LOGGER.log(FINE, "{0} completed {1} in {2}ms", new Object[]{getName(), executable, time});
try {
workUnit.context.synchronizeEnd(this, executable, problems, time);
} catch (InterruptedException e) {
workUnit.context.abort(e);
} finally {
workUnit.setExecutor(null);
}
}
private void finish2() {
for (RuntimeException e1: owner.getTerminatedBy()) LOGGER.log(Level.WARNING, String.format("%s termination trace", getName()), e1);
if (causeOfDeath == null) {// let this thread die and be replaced by a fresh unstarted instance
owner.removeExecutor(this);
}
if (this instanceof OneOffExecutor) {
owner.remove((OneOffExecutor) this);
}
queue.scheduleMaintenance();
}
@Restricted(NoExternalUse.class)
public void completedAsynchronous(@CheckForNull Throwable error) {
try {
finish1(error);
} finally {
finish2();
}
asynchronousExecution = null;
}
/**
* For testing only. Simulate a fatal unexpected failure.
*/
public void killHard() {
induceDeath = true;
}
/**
* Returns the current build this executor is running.
*
* @return
* null if the executor is idle.
*/
@Exported
public @CheckForNull Queue.Executable getCurrentExecutable() {
lock.readLock().lock();
try {
return executable;
} finally {
lock.readLock().unlock();
}
}
/**
* Returns the current {@link WorkUnit} (of {@link #getCurrentExecutable() the current executable})
* that this executor is running.
*
* @return
* null if the executor is idle.
*/
@Exported
public WorkUnit getCurrentWorkUnit() {
lock.readLock().lock();
try {
return workUnit;
} finally {
lock.readLock().unlock();
}
}
/**
* If {@linkplain #getCurrentExecutable() current executable} is {@link AbstractBuild},
* return the workspace that this executor is using, or null if the build hasn't gotten
* to that point yet.
*/
public FilePath getCurrentWorkspace() {
lock.readLock().lock();
try {
if (executable == null) {
return null;
}
if (executable instanceof AbstractBuild) {
AbstractBuild ab = (AbstractBuild) executable;
return ab.getWorkspace();
}
return null;
} finally {
lock.readLock().unlock();
}
}
/**
* Same as {@link #getName()}.
*/
public String getDisplayName() {
return "Executor #"+getNumber();
}
/**
* Gets the executor number that uniquely identifies it among
* other {@link Executor}s for the same computer.
*
* @return
* a sequential number starting from 0.
*/
@Exported
public int getNumber() {
return number;
}
/**
* Returns true if this {@link Executor} is ready for action.
*/
@Exported
public boolean isIdle() {
lock.readLock().lock();
try {
return workUnit == null && executable == null;
} finally {
lock.readLock().unlock();
}
}
/**
* The opposite of {@link #isIdle()} — the executor is doing some work.
*/
public boolean isBusy() {
lock.readLock().lock();
try {
return workUnit != null || executable != null;
} finally {
lock.readLock().unlock();
}
}
/**
* Check if executor is ready to accept tasks.
* This method becomes the critical one since 1.536, which introduces the
* on-demand creation of executor threads. Callers should use
* this method instead of {@link #isAlive()}, which would be incorrect for
* non-started threads or running {@link AsynchronousExecution}.
* @return True if the executor is available for tasks
* @since 1.536
*/
public boolean isActive() {
lock.readLock().lock();
try {
return !started || asynchronousExecution != null || isAlive();
} finally {
lock.readLock().unlock();
}
}
/**
* If currently running in asynchronous mode, returns that handle.
* @since 1.607
*/
public @CheckForNull AsynchronousExecution getAsynchronousExecution() {
lock.readLock().lock();
try {
return asynchronousExecution;
} finally {
lock.readLock().unlock();
}
}
/**
* If this executor is running an {@link AsynchronousExecution} and that execution wants to hide the display
* cell for the executor (because there is another executor displaying the job progress and we don't want to
* confuse the user) then this method will return {@code false} to indicate to {@code executors.jelly} that
* the executor cell should be hidden.
*
* @return {@code true} iff the {@code executorCell.jelly} for this {@link Executor} should be displayed in
* {@code executors.jelly}.
* @since 1.607
* @see AsynchronousExecution#displayCell()
*/
public boolean isDisplayCell() {
AsynchronousExecution asynchronousExecution = getAsynchronousExecution();
return asynchronousExecution == null || asynchronousExecution.displayCell();
}
/**
* Returns true if this executor is waiting for a task to execute.
*/
public boolean isParking() {
lock.readLock().lock();
try {
return !started;
} finally {
lock.readLock().unlock();
}
}
/**
* If this thread dies unexpectedly, obtain the cause of the failure.
*
* @return null if the death is expected death or the thread {@link #isActive}.
* @since 1.142
*/
public Throwable getCauseOfDeath() {
return causeOfDeath;
}
/**
* Returns the progress of the current build in the number between 0-100.
*
* @return -1
* if it's impossible to estimate the progress.
*/
@Exported
public int getProgress() {
long d;
lock.readLock().lock();
try {
if (executable == null) {
return -1;
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d <= 0) {
return -1;
}
int num = (int) (getElapsedTime() * 100 / d);
if (num >= 100) {
num = 99;
}
return num;
}
/**
* Returns true if the current build is likely stuck.
*
* <p>
* This is a heuristics based approach, but if the build is suspiciously taking for a long time,
* this method returns true.
*/
@Exported
public boolean isLikelyStuck() {
long d;
long elapsed;
lock.readLock().lock();
try {
if (executable == null) {
return false;
}
elapsed = getElapsedTime();
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d >= 0) {
// if it's taking 10 times longer than ETA, consider it stuck
return d * 10 < elapsed;
} else {
// if no ETA is available, a build taking longer than a day is considered stuck
return TimeUnit2.MILLISECONDS.toHours(elapsed) > 24;
}
}
public long getElapsedTime() {
lock.readLock().lock();
try {
return System.currentTimeMillis() - startTime;
} finally {
lock.readLock().unlock();
}
}
/**
* Returns the number of milli-seconds the currently executing job spent in the queue
* waiting for an available executor. This excludes the quiet period time of the job.
* @since 1.440
*/
public long getTimeSpentInQueue() {
lock.readLock().lock();
try {
return startTime - workUnit.context.item.buildableStartMilliseconds;
} finally {
lock.readLock().unlock();
}
}
/**
* Gets the string that says how long since this build has started.
*
* @return
* string like "3 minutes" "1 day" etc.
*/
public String getTimestampString() {
return Util.getPastTimeString(getElapsedTime());
}
/**
* Computes a human-readable text that shows the expected remaining time
* until the build completes.
*/
public String getEstimatedRemainingTime() {
long d;
lock.readLock().lock();
try {
if (executable == null) {
return Messages.Executor_NotAvailable();
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return Messages.Executor_NotAvailable();
}
long eta = d - getElapsedTime();
if (eta <= 0) {
return Messages.Executor_NotAvailable();
}
return Util.getTimeSpanString(eta);
}
/**
* The same as {@link #getEstimatedRemainingTime()} but return
* it as a number of milli-seconds.
*/
public long getEstimatedRemainingTimeMillis() {
long d;
lock.readLock().lock();
try {
if (executable == null) {
return -1;
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return -1;
}
long eta = d - getElapsedTime();
if (eta <= 0) {
return -1;
}
return eta;
}
/**
* Can't start executor like you normally start a thread.
*
* @see #start(WorkUnit)
*/
@Override
public void start() {
throw new UnsupportedOperationException();
}
/*protected*/ void start(WorkUnit task) {
lock.writeLock().lock();
try {
this.workUnit = task;
super.start();
started = true;
} finally {
lock.writeLock().unlock();
}
}
/**
* @deprecated as of 1.489
* Use {@link #doStop()}.
*/
@RequirePOST
public void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
doStop().generateResponse(req,rsp,this);
}
/**
* Stops the current build.
*
* @since 1.489
*/
@RequirePOST
public HttpResponse doStop() {
lock.writeLock().lock(); // need write lock as interrupt will change the field
try {
if (executable != null) {
Tasks.getOwnerTaskOf(getParentOf(executable)).checkAbortPermission();
interrupt();
}
} finally {
lock.writeLock().unlock();
}
return HttpResponses.forwardToPreviousPage();
}
/**
* Throws away this executor and get a new one.
*/
@RequirePOST
public HttpResponse doYank() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
if (isActive())
throw new Failure("Can't yank a live executor");
owner.removeExecutor(this);
return HttpResponses.redirectViaContextPath("/");
}
/**
* Checks if the current user has a permission to stop this build.
*/
public boolean hasStopPermission() {
lock.readLock().lock();
try {
return executable != null && Tasks.getOwnerTaskOf(getParentOf(executable)).hasAbortPermission();
} finally {
lock.readLock().unlock();
}
}
public @Nonnull Computer getOwner() {
return owner;
}
/**
* Returns when this executor started or should start being idle.
*/
public long getIdleStartMilliseconds() {
lock.readLock().lock();
try {
if (isIdle())
return Math.max(creationTime, owner.getConnectTime());
else {
return Math.max(startTime + Math.max(0, Executables.getEstimatedDurationFor(executable)),
System.currentTimeMillis() + 15000);
}
} finally {
lock.readLock().unlock();
}
}
/**
* Exposes the executor to the remote API.
*/
public Api getApi() {
return new Api(this);
}
/**
* Creates a proxy object that executes the callee in the context that impersonates
* this executor. Useful to export an object to a remote channel.
*/
public <T> T newImpersonatingProxy(Class<T> type, T core) {
return new InterceptingProxy() {
protected Object call(Object o, Method m, Object[] args) throws Throwable {
final Executor old = IMPERSONATION.get();
IMPERSONATION.set(Executor.this);
try {
return m.invoke(o,args);
} finally {
IMPERSONATION.set(old);
}
}
}.wrap(type,core);
}
/**
* Returns the executor of the current thread or null if current thread is not an executor.
*/
public static @CheckForNull Executor currentExecutor() {
Thread t = Thread.currentThread();
if (t instanceof Executor) return (Executor) t;
return IMPERSONATION.get();
}
/**
* Finds the executor currently running a given process.
* @param executable a possibly running executable
* @return the executor (possibly a {@link OneOffExecutor}) whose {@link Executor#getCurrentExecutable} matches that,
* or null if it could not be found (for example because the execution has already completed)
* @since 1.607
*/
public static @CheckForNull Executor of(Executable executable) {
Jenkins jenkins = Jenkins.getInstance();
if (jenkins == null) {
return null;
}
for (Computer computer : jenkins.getComputers()) {
for (Executor executor : computer.getExecutors()) {
if (executor.getCurrentExecutable() == executable) {
return executor;
}
}
for (Executor executor : computer.getOneOffExecutors()) {
if (executor.getCurrentExecutable() == executable) {
return executor;
}
}
}
return null;
}
/**
* Returns the estimated duration for the executable.
* Protects against {@link AbstractMethodError}s if the {@link Executable} implementation
* was compiled against Hudson < 1.383
*
* @deprecated as of 1.388
* Use {@link Executables#getEstimatedDurationFor(Queue.Executable)}
*/
public static long getEstimatedDurationFor(Executable e) {
return Executables.getEstimatedDurationFor(e);
}
/**
* Mechanism to allow threads (in particular the channel request handling threads) to
* run on behalf of {@link Executor}.
*/
private static final ThreadLocal<Executor> IMPERSONATION = new ThreadLocal<Executor>();
private static final Logger LOGGER = Logger.getLogger(Executor.class.getName());
}