/
WorkflowRun.java
1092 lines (1003 loc) · 44.5 KB
/
WorkflowRun.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) 2013-2014, CloudBees, 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 org.jenkinsci.plugins.workflow.job;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.AbortException;
import hudson.BulkChange;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Functions;
import hudson.XmlFile;
import hudson.console.AnnotatedLargeText;
import hudson.console.LineTransformationOutputStream;
import hudson.console.ModelHyperlinkNote;
import hudson.model.Executor;
import hudson.model.Item;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.Queue;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.StreamBuildListener;
import hudson.model.TaskListener;
import hudson.model.User;
import hudson.model.listeners.RunListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.scm.ChangeLogSet;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import hudson.security.ACL;
import hudson.slaves.NodeProperty;
import hudson.util.DaemonThreadFactory;
import hudson.util.Iterators;
import hudson.util.NamingThreadFactory;
import hudson.util.NullStream;
import hudson.util.PersistedList;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.GuardedBy;
import jenkins.model.CauseOfInterruption;
import jenkins.model.Jenkins;
import jenkins.model.lazy.BuildReference;
import jenkins.model.lazy.LazyBuildMixIn;
import jenkins.model.queue.AsynchronousExecution;
import jenkins.scm.RunWithSCM;
import jenkins.security.NotReallyRoleSensitiveCallable;
import jenkins.util.Timer;
import org.acegisecurity.Authentication;
import org.jenkinsci.plugins.workflow.FilePathUtils;
import org.jenkinsci.plugins.workflow.actions.LogAction;
import org.jenkinsci.plugins.workflow.actions.ThreadNameAction;
import org.jenkinsci.plugins.workflow.actions.TimingAction;
import org.jenkinsci.plugins.workflow.flow.BlockableResume;
import org.jenkinsci.plugins.workflow.flow.DurabilityHintProvider;
import org.jenkinsci.plugins.workflow.flow.FlowCopier;
import org.jenkinsci.plugins.workflow.flow.FlowDefinition;
import org.jenkinsci.plugins.workflow.flow.FlowDurabilityHint;
import org.jenkinsci.plugins.workflow.flow.FlowExecution;
import org.jenkinsci.plugins.workflow.flow.FlowExecutionList;
import org.jenkinsci.plugins.workflow.flow.FlowExecutionListener;
import org.jenkinsci.plugins.workflow.flow.FlowExecutionOwner;
import org.jenkinsci.plugins.workflow.flow.GraphListener;
import org.jenkinsci.plugins.workflow.flow.StashManager;
import org.jenkinsci.plugins.workflow.graph.BlockEndNode;
import org.jenkinsci.plugins.workflow.graph.FlowEndNode;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
import org.jenkinsci.plugins.workflow.job.console.WorkflowConsoleLogger;
import org.jenkinsci.plugins.workflow.job.properties.DurabilityHintJobProperty;
import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.StepExecution;
import org.jenkinsci.plugins.workflow.support.PipelineIOUtils;
import org.jenkinsci.plugins.workflow.support.concurrent.Futures;
import org.jenkinsci.plugins.workflow.support.concurrent.WithThreadName;
import org.jenkinsci.plugins.workflow.support.steps.input.POSTHyperlinkNote;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.interceptor.RequirePOST;
@SuppressWarnings("SynchronizeOnNonFinalField")
@SuppressFBWarnings(value="JLM_JSR166_UTILCONCURRENT_MONITORENTER", justification="completed is an unusual usage")
public final class WorkflowRun extends Run<WorkflowJob,WorkflowRun> implements FlowExecutionOwner.Executable, LazyBuildMixIn.LazyLoadingRun<WorkflowJob,WorkflowRun>, RunWithSCM<WorkflowJob,WorkflowRun> {
private static final Logger LOGGER = Logger.getLogger(WorkflowRun.class.getName());
private enum StopState {
TERM, KILL;
public String url() {
return this.name().toLowerCase(Locale.ENGLISH);
}
}
/** null until started, or after serious failures or hard kill */
private @CheckForNull FlowExecution execution;
/**
* {@link Future} that yields {@link #execution}, when it is fully configured and ready to be exposed.
*/
private transient SettableFuture<FlowExecution> executionPromise = SettableFuture.create();
private transient final LazyBuildMixIn.RunMixIn<WorkflowJob,WorkflowRun> runMixIn = new LazyBuildMixIn.RunMixIn<WorkflowJob,WorkflowRun>() {
@Override protected WorkflowRun asRun() {
return WorkflowRun.this;
}
};
private transient StreamBuildListener listener;
private transient boolean allowTerm;
private transient boolean allowKill;
/**
* Cumulative list of people who contributed to the build problem.
*
* <p>
* This is a list of {@link User#getId() user ids} who made a change
* since the last non-broken build. Can be null (which should be
* treated like empty set), because of the compatibility.
*
* <p>
* This field is semi-final --- once set the value will never be modified.
*/
private volatile Set<String> culprits;
/**
* Flag for whether or not the build has completed somehow.
* Non-null soon after the build starts or is reloaded from disk.
* Recomputed in {@link #onLoad} based on {@link FlowExecution#isComplete}.
* TODO may be better to make this a persistent field.
* That would allow the execution of a completed build to be loaded on demand (JENKINS-45585), reducing overhead for some operations.
* It would also remove the need to null out {@link #execution} merely to force {@link #isInProgress} to be false
* in the case of broken or hard-killed builds which lack a single head node.
*/
private AtomicBoolean completed;
private transient Object logCopyGuard = new Object();
/** map from node IDs to log positions from which we should copy text */
private Map<String,Long> logsToCopy;
/** JENKINS-26761: supposed to always be set but sometimes is not. Access only through {@link #checkouts(TaskListener)}. */
private @CheckForNull List<SCMCheckout> checkouts;
// TODO could use a WeakReference to reduce memory, but that complicates how we add to it incrementally; perhaps keep a List<WeakReference<ChangeLogSet<?>>>
private transient List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets;
/** True when first started, false when running after a restart. */
private transient boolean firstTime;
private synchronized Object getLogCopyGuard() {
if (logCopyGuard == null) {
logCopyGuard = new Object();
}
return logCopyGuard;
}
public WorkflowRun(WorkflowJob job) throws IOException {
super(job);
firstTime = true;
checkouts = new PersistedList<>(this);
//System.err.printf("created %s @%h%n", this, this);
}
public WorkflowRun(WorkflowJob job, File dir) throws IOException {
super(job, dir);
//System.err.printf("loaded %s @%h%n", this, this);
}
@Override public LazyBuildMixIn.RunMixIn<WorkflowJob,WorkflowRun> getRunMixIn() {
return runMixIn;
}
@Override protected BuildReference<WorkflowRun> createReference() {
return getRunMixIn().createReference();
}
@Override protected void dropLinks() {
getRunMixIn().dropLinks();
}
@Exported
@Override public WorkflowRun getPreviousBuild() {
return getRunMixIn().getPreviousBuild();
}
@Exported
@Override public WorkflowRun getNextBuild() {
return getRunMixIn().getNextBuild();
}
/**
* Actually executes the workflow.
*/
@Override public void run() {
if (!firstTime) {
throw sleep();
}
try {
onStartBuilding();
OutputStream logger = new FileOutputStream(getLogFile());
listener = new StreamBuildListener(logger, Charset.defaultCharset());
listener.started(getCauses());
Authentication auth = Jenkins.getAuthentication();
if (!auth.equals(ACL.SYSTEM)) {
String name = auth.getName();
if (!auth.equals(Jenkins.ANONYMOUS)) {
name = ModelHyperlinkNote.encodeTo(User.get(name));
}
listener.getLogger().println(hudson.model.Messages.Run_running_as_(name));
}
RunListener.fireStarted(this, listener);
updateSymlinks(listener);
FlowDefinition definition = getParent().getDefinition();
if (definition == null) {
throw new AbortException("No flow definition, cannot run");
}
Owner owner = new Owner(this);
FlowExecution newExecution = definition.create(owner, listener, getAllActions());
boolean loggedHintOverride = false;
if (getParent().isResumeBlocked()) {
if (newExecution instanceof BlockableResume) {
((BlockableResume) newExecution).setResumeBlocked(true);
listener.getLogger().println("Resume disabled by user, switching to high-performance, low-durability mode.");
loggedHintOverride = true;
}
}
if (!loggedHintOverride) { // Avoid double-logging
listener.getLogger().println("Running in Durability level: "+DurabilityHintProvider.suggestedFor(this.project));
}
FlowExecutionList.get().register(owner);
newExecution.addListener(new GraphL());
completed = new AtomicBoolean();
logsToCopy = new ConcurrentSkipListMap<>();
execution = newExecution;
newExecution.start();
executionPromise.set(newExecution);
FlowExecutionListener.fireRunning(execution);
} catch (Throwable x) {
execution = null; // ensures isInProgress returns false
finish(Result.FAILURE, x);
try {
executionPromise.setException(x);
} catch (Error e) {
if (e != x) { // cf. CpsThread.runNextChunk
throw e;
}
}
return;
}
throw sleep();
}
private static ScheduledExecutorService copyLogsExecutorService;
private static synchronized ScheduledExecutorService copyLogsExecutorService() {
if (copyLogsExecutorService == null) {
copyLogsExecutorService = new /*ErrorLogging*/ScheduledThreadPoolExecutor(5, new NamingThreadFactory(new DaemonThreadFactory(), "WorkflowRun.copyLogs"));
}
return copyLogsExecutorService;
}
private AsynchronousExecution sleep() {
final AsynchronousExecution asynchronousExecution = new AsynchronousExecution() {
@Override public void interrupt(boolean forShutdown) {
if (forShutdown) {
return;
}
Timer.get().submit(new Runnable() {
@Override public void run() {
if (execution == null) {
return;
}
Executor executor = getExecutor();
if (executor == null) {
LOGGER.log(Level.WARNING, "Lost executor for {0}", WorkflowRun.this);
return;
}
try {
Collection<CauseOfInterruption> causes = executor.getCausesOfInterruption();
execution.interrupt(executor.abortResult(), causes.toArray(new CauseOfInterruption[causes.size()]));
} catch (Exception x) {
LOGGER.log(Level.WARNING, null, x);
}
executor.recordCauseOfInterruption(WorkflowRun.this, listener);
printLater(StopState.TERM, "Click here to forcibly terminate running steps");
}
});
}
@Override public boolean blocksRestart() {
return execution != null && execution.blocksRestart();
}
@Override public boolean displayCell() {
return blocksRestart();
}
};
final AtomicReference<ScheduledFuture<?>> copyLogsTask = new AtomicReference<>();
copyLogsTask.set(copyLogsExecutorService().scheduleAtFixedRate(new Runnable() {
@Override public void run() {
synchronized (getLogCopyGuard()) {
if (completed == null) {
// Loading run, give it a moment.
return;
}
if (completed.get()) {
asynchronousExecution.completed(null);
copyLogsTask.get().cancel(false);
return;
}
Jenkins jenkins = Jenkins.getInstance();
if (jenkins == null || jenkins.isTerminating()) {
LOGGER.log(Level.FINE, "shutting down, breaking waitForCompletion on {0}", this);
// Stop writing content, in case a new set of objects gets loaded after in-VM restart and starts writing to the same file:
listener.closeQuietly();
listener = new StreamBuildListener(new NullStream());
return;
}
try (WithThreadName naming = new WithThreadName(" (" + WorkflowRun.this + ")")) {
copyLogs();
}
}
}
}, 1, 1, TimeUnit.SECONDS));
return asynchronousExecution;
}
private void printLater(final StopState state, final String message) {
Timer.get().schedule(new Runnable() {
@Override public void run() {
if (!isInProgress()) {
return;
}
switch (state) {
case TERM:
allowTerm = true;
break;
case KILL:
allowKill = true;
break;
}
listener.getLogger().println(POSTHyperlinkNote.encodeTo("/" + getUrl() + state.url(), message));
}
}, 15, TimeUnit.SECONDS);
}
/** Sends {@link StepContext#onFailure} to all running (leaf) steps. */
@RequirePOST
public void doTerm() {
checkPermission(Item.CANCEL);
if (!isInProgress() || /* redundant, but make FindBugs happy */ execution == null) {
return;
}
final Throwable x = new FlowInterruptedException(Result.ABORTED);
Futures.addCallback(execution.getCurrentExecutions(/* cf. JENKINS-26148 */true), new FutureCallback<List<StepExecution>>() {
@Override public void onSuccess(List<StepExecution> l) {
for (StepExecution e : Iterators.reverse(l)) {
StepContext context = e.getContext();
context.onFailure(x);
try {
FlowNode n = context.get(FlowNode.class);
if (n != null) {
listener.getLogger().println("Terminating " + n.getDisplayFunctionName());
}
} catch (Exception x) {
LOGGER.log(Level.FINE, null, x);
}
}
}
@Override public void onFailure(Throwable t) {}
});
printLater(StopState.KILL, "Click here to forcibly kill entire build");
}
/** Immediately kills the build. */
@RequirePOST
public void doKill() {
checkPermission(Item.CANCEL);
if (!isBuilding() || /* probably redundant, but just to be sure */ execution == null) {
return;
}
if (listener != null) {
listener.getLogger().println("Hard kill!");
}
execution = null; // ensures isInProgress returns false
FlowInterruptedException suddenDeath = new FlowInterruptedException(Result.ABORTED);
finish(Result.ABORTED, suddenDeath);
executionPromise.setException(suddenDeath);
// TODO CpsFlowExecution.onProgramEnd does some cleanup which we cannot access here; perhaps need a FlowExecution.halt(Throwable) API?
}
@Override public EnvVars getEnvironment(TaskListener listener) throws IOException, InterruptedException {
EnvVars env = super.getEnvironment(listener);
Jenkins instance = Jenkins.getInstance();
if (instance != null) {
for (NodeProperty nodeProperty : instance.getGlobalNodeProperties()) {
nodeProperty.buildEnvVars(env, listener);
}
}
// TODO EnvironmentContributingAction does not support Job yet:
ParametersAction a = getAction(ParametersAction.class);
if (a != null) {
for (ParameterValue v : a) {
v.buildEnvironment(this, env);
}
}
EnvVars.resolve(env);
return env;
}
@Restricted(DoNotUse.class) // Jelly
public boolean hasAllowTerm() {
return isBuilding() && allowTerm;
}
@Restricted(DoNotUse.class) // Jelly
public boolean hasAllowKill() {
return isBuilding() && allowKill;
}
@GuardedBy("logCopyGuard")
private void copyLogs() {
if (logsToCopy == null) { // finished
return;
}
if (logsToCopy instanceof LinkedHashMap) { // upgrade while build is running
logsToCopy = new ConcurrentSkipListMap<>(logsToCopy);
}
boolean modified = false;
for (Map.Entry<String,Long> entry : logsToCopy.entrySet()) {
String id = entry.getKey();
FlowNode node;
try {
if (execution == null) {
return; // broken somehow
}
node = execution.getNode(id);
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
logsToCopy.remove(id);
modified = true;
continue;
}
if (node == null) {
LOGGER.log(Level.WARNING, "no such node {0}", id);
logsToCopy.remove(id);
modified = true;
continue;
}
LogAction la = node.getAction(LogAction.class);
if (la != null) {
AnnotatedLargeText<? extends FlowNode> logText = la.getLogText();
try {
long old = entry.getValue();
OutputStream logger;
String prefix = getLogPrefix(node);
if (prefix != null) {
logger = new LogLinePrefixOutputFilter(listener.getLogger(), "[" + prefix + "] ");
} else {
logger = listener.getLogger();
}
try {
long revised = writeRawLogTo(logText, old, logger);
if (revised != old) {
logsToCopy.put(id, revised);
modified = true;
}
if (logText.isComplete()) {
writeRawLogTo(logText, revised, logger); // defend against race condition?
assert !node.isRunning() : "LargeText.complete yet " + node + " claims to still be running";
logsToCopy.remove(id);
modified = true;
}
} finally {
if (prefix != null) {
((LogLinePrefixOutputFilter)logger).forceEol();
}
}
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
logsToCopy.remove(id);
modified = true;
}
} else if (!node.isRunning()) {
logsToCopy.remove(id);
modified = true;
}
}
if (modified) {
try {
if (this.execution != null && this.execution.getDurabilityHint().isPersistWithEveryStep()) {
save();
}
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
}
}
}
private long writeRawLogTo(AnnotatedLargeText<?> text, long start, OutputStream out) throws IOException {
long len = text.length();
if (start > len) {
LOGGER.log(Level.WARNING, "JENKINS-37664: attempt to copy logs in {0} @{1} past end @{2}", new Object[] {this, start, len});
return len;
} else {
return text.writeRawLogTo(start, out);
}
}
@GuardedBy("logCopyGuard")
private transient LoadingCache<FlowNode,Optional<String>> logPrefixCache;
private @CheckForNull String getLogPrefix(FlowNode node) {
// TODO could also use FlowScanningUtils.fetchEnclosingBlocks(node).filter(FlowScanningUtils.hasActionPredicate(ThreadNameAction.class)),
// but this would not let us cache intermediate results
synchronized (getLogCopyGuard()) {
if (logPrefixCache == null) {
logPrefixCache = CacheBuilder.newBuilder().weakKeys().build(new CacheLoader<FlowNode,Optional<String>>() {
@Override public @Nonnull Optional<String> load(FlowNode node) {
if (node instanceof BlockEndNode) {
return Optional.fromNullable(getLogPrefix(((BlockEndNode) node).getStartNode()));
}
ThreadNameAction threadNameAction = node.getAction(ThreadNameAction.class);
if (threadNameAction != null) {
return Optional.of(threadNameAction.getThreadName());
}
for (FlowNode parent : node.getParents()) {
String prefix = getLogPrefix(parent);
if (prefix != null) {
return Optional.of(prefix);
}
}
return Optional.absent();
}
});
}
return logPrefixCache.getUnchecked(node).orNull();
}
}
private static final class LogLinePrefixOutputFilter extends LineTransformationOutputStream {
private final PrintStream logger;
private final String prefix;
protected LogLinePrefixOutputFilter(PrintStream logger, String prefix) {
this.logger = logger;
this.prefix = prefix;
}
@Override
protected void eol(byte[] b, int len) throws IOException {
logger.append(prefix);
logger.write(b, 0, len);
}
}
private static final Map<String,WorkflowRun> LOADING_RUNS = new HashMap<>();
private String key() {
return getParent().getFullName() + '/' + getId();
}
/** Hack to allow {@link #execution} to use an {@link Owner} referring to this run, even when it has not yet been loaded. */
@Override public void reload() throws IOException {
synchronized (LOADING_RUNS) {
LOADING_RUNS.put(key(), this);
}
// super.reload() forces result to be FAILURE, so working around that
new XmlFile(XSTREAM,new File(getRootDir(),"build.xml")).unmarshal(this);
}
@Override protected void onLoad() {
synchronized (getLogCopyGuard()) {
super.onLoad();
// TODO might need to check for completed
FlowExecution fetchedExecution = execution;
if (fetchedExecution != null) {
try {
if (getParent().isResumeBlocked() && execution instanceof BlockableResume) {
((BlockableResume) execution).setResumeBlocked(true);
}
fetchedExecution.onLoad(new Owner(this));
} catch (Exception x) {
LOGGER.log(Level.WARNING, null, x);
execution = null; // probably too broken to use
}
}
fetchedExecution = execution;
if (fetchedExecution != null) {
fetchedExecution.addListener(new GraphL());
executionPromise.set(fetchedExecution);
completed = new AtomicBoolean(fetchedExecution.isComplete());
if (!fetchedExecution.isComplete()) {
// we've been restarted while we were running. let's get the execution going again.
FlowExecutionListener.fireResumed(fetchedExecution);
try {
OutputStream logger = new FileOutputStream(getLogFile(), true);
listener = new StreamBuildListener(logger, Charset.defaultCharset());
listener.getLogger().println("Resuming build at " + new Date() + " after Jenkins restart");
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
listener = new StreamBuildListener(new NullStream());
}
Timer.get().submit(new Runnable() { // JENKINS-31614
@Override public void run() {
Queue.getInstance().schedule(new AfterRestartTask(WorkflowRun.this), 0);
}
});
}
}
checkouts(null); // only for diagnostics
synchronized (LOADING_RUNS) {
LOADING_RUNS.remove(key()); // or could just make the value type be WeakReference<WorkflowRun>
LOADING_RUNS.notifyAll();
}
}
}
// Overridden since super version has an unwanted assertion about this.state, which we do not use.
@Override public void setResult(Result r) {
if (result == null || r.isWorseThan(result)) {
result = r;
LOGGER.log(Level.FINE, this + " in " + getRootDir() + ": result is set to " + r, LOGGER.isLoggable(Level.FINER) ? new Exception() : null);
}
}
/** Handles normal build completion (including errors) but also handles the case that the flow did not even start correctly, for example due to an error in {@link FlowExecution#start}. */
private void finish(@Nonnull Result r, @CheckForNull Throwable t) {
synchronized (getLogCopyGuard()) {
setResult(r);
duration = Math.max(0, System.currentTimeMillis() - getStartTimeInMillis());
LOGGER.log(Level.INFO, "{0} completed: {1}", new Object[]{toString(), getResult()});
if (listener == null) {
LOGGER.log(Level.WARNING, this + " failed to start", t);
} else {
RunListener.fireCompleted(WorkflowRun.this, listener);
if (t instanceof AbortException) {
listener.error(t.getMessage());
} else if (t instanceof FlowInterruptedException) {
((FlowInterruptedException) t).handle(this, listener);
} else if (t != null) {
listener.getLogger().println(Functions.printThrowable(t).trim()); // TODO 2.43+ use Functions.printStackTrace
}
listener.finished(getResult());
listener.closeQuietly();
}
logsToCopy = null;
try {
save();
} catch (Exception x) {
LOGGER.log(Level.WARNING, "failed to save " + this, x);
}
Timer.get().submit(() -> {
try {
getParent().logRotate();
} catch (Exception x) {
LOGGER.log(Level.WARNING, "failed to perform log rotation after " + this, x);
}
});
onEndBuilding();
if (completed != null) {
completed.set(true);
} else {
completed = new AtomicBoolean(true);
}
FlowExecutionList.get().unregister(new Owner(this));
try {
StashManager.maybeClearAll(this);
} catch (IOException x) {
LOGGER.log(Level.WARNING, "failed to clean up stashes from " + this, x);
}
FlowExecution exec = getExecution();
if (exec != null) {
FlowExecutionListener.fireCompleted(exec);
}
}
}
@Override public void deleteArtifacts() throws IOException {
super.deleteArtifacts();
StashManager.clearAll(this);
}
/**
* Gets the associated execution state.
* @return non-null after the flow has started, even after finished (but may be null temporarily when about to start, or if starting failed)
*/
public @CheckForNull FlowExecution getExecution() {
return execution;
}
/**
* Allows the caller to block on {@link FlowExecution}, which gets created relatively quickly
* after the build gets going.
*/
public ListenableFuture<FlowExecution> getExecutionPromise() {
return executionPromise;
}
@Override public FlowExecutionOwner asFlowExecutionOwner() {
return new Owner(this);
}
@Override
public boolean hasntStartedYet() {
return result == null && execution==null;
}
@Override public boolean isBuilding() {
return result == null || isInProgress();
}
@Exported
@Override protected boolean isInProgress() {
return execution != null && !execution.isComplete() && (completed == null || !completed.get());
}
@Override public boolean isLogUpdated() {
return isBuilding(); // there is no equivalent to a post-production state for flows
}
synchronized @Nonnull List<SCMCheckout> checkouts(@CheckForNull TaskListener listener) {
if (checkouts == null) {
LOGGER.log(Level.WARNING, "JENKINS-26761: no checkouts in {0}", this);
if (listener != null) {
listener.error("JENKINS-26761: list of SCM checkouts in " + this + " was lost; polling will be broken");
}
checkouts = new PersistedList<>(this);
// Could this.save(), but might pollute diagnosis, and (worse) might clobber real data if there is >1 WorkflowRun with the same ID.
}
return checkouts;
}
@Override
@Exported
public synchronized List<ChangeLogSet<? extends ChangeLogSet.Entry>> getChangeSets() {
if (changeSets == null) {
changeSets = new ArrayList<>();
for (SCMCheckout co : checkouts(null)) {
if (co.changelogFile != null && co.changelogFile.isFile()) {
try {
ChangeLogSet<? extends ChangeLogSet.Entry> changeLogSet =
co.scm.createChangeLogParser().parse(this, co.scm.getEffectiveBrowser(), co.changelogFile);
if (!changeLogSet.isEmptySet()) {
changeSets.add(changeLogSet);
}
} catch (Exception x) {
LOGGER.log(Level.WARNING, "could not parse " + co.changelogFile, x);
}
}
}
}
return changeSets;
}
@Override
@CheckForNull public Set<String> getCulpritIds() {
if (shouldCalculateCulprits()) {
HashSet<String> tempCulpritIds = new HashSet<>();
for (User u : getCulprits()) {
tempCulpritIds.add(u.getId());
}
if (isBuilding()) {
return ImmutableSortedSet.copyOf(tempCulpritIds);
} else {
culprits = ImmutableSortedSet.copyOf(tempCulpritIds);
}
}
return culprits;
}
@Override
@Exported
@Nonnull public Set<User> getCulprits() {
return RunWithSCM.super.getCulprits();
}
@Override
public boolean shouldCalculateCulprits() {
return isBuilding() || culprits == null;
}
@RequirePOST
public synchronized HttpResponse doStop() {
Executor e = getOneOffExecutor();
if (e != null) {
return e.doStop();
} else {
doKill();
return HttpResponses.forwardToPreviousPage();
}
}
private void onCheckout(SCM scm, FilePath workspace, TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState pollingBaseline) throws Exception {
if (changelogFile != null && changelogFile.isFile()) {
ChangeLogSet<?> cls = scm.createChangeLogParser().parse(this, scm.getEffectiveBrowser(), changelogFile);
if (!cls.isEmptySet()) {
getChangeSets().add(cls);
}
for (SCMListener l : SCMListener.all()) {
l.onChangeLogParsed(this, scm, listener, cls);
}
}
checkouts(listener).add(new SCMCheckout(scm, FilePathUtils.getNodeName(workspace), workspace.getRemote(), changelogFile, pollingBaseline));
}
static final class SCMCheckout {
final SCM scm;
final String node;
final String workspace;
// TODO JENKINS-27704 make this a String and relativize to Run.rootDir if possible
final @CheckForNull File changelogFile;
final @CheckForNull SCMRevisionState pollingBaseline;
SCMCheckout(SCM scm, String node, String workspace, File changelogFile, SCMRevisionState pollingBaseline) {
this.scm = scm;
this.node = node;
this.workspace = workspace;
this.changelogFile = changelogFile;
this.pollingBaseline = pollingBaseline;
}
// TODO replace with Run.XSTREAM2.addCriticalField(SCMCheckout.class, "scm") when not @Restricted(NoExternalUse.class)
private Object readResolve() {
if (scm == null) {
throw new IllegalStateException("Unloadable scm field");
}
return this;
}
}
private static final class Owner extends FlowExecutionOwner {
private final String job;
private final String id;
private transient @CheckForNull WorkflowRun run;
Owner(WorkflowRun run) {
job = run.getParent().getFullName();
id = run.getId();
this.run = run;
}
private String key() {
return job + '/' + id;
}
private @Nonnull WorkflowRun run() throws IOException {
if (run==null) {
WorkflowRun candidate;
synchronized (LOADING_RUNS) {
candidate = LOADING_RUNS.get(key());
}
if (candidate != null && candidate.getParent().getFullName().equals(job) && candidate.getId().equals(id)) {
run = candidate;
} else {
final Jenkins jenkins = Jenkins.getInstance();
if (jenkins == null) {
throw new IOException("Jenkins is not running"); // do not use Jenkins.getActiveInstance() as that is an ISE
}
WorkflowJob j = ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<WorkflowJob,IOException>() {
@Override public WorkflowJob call() throws IOException {
return jenkins.getItemByFullName(job, WorkflowJob.class);
}
});
if (j == null) {
throw new IOException("no such WorkflowJob " + job);
}
run = j._getRuns().getById(id);
if (run == null) {
throw new IOException("no such build " + id + " in " + job);
}
//System.err.printf("getById found %s @%h%n", run, run);
}
}
return run;
}
@Override public FlowExecution get() throws IOException {
WorkflowRun r = run();
synchronized (LOADING_RUNS) {
int count = 5;
while (r.execution == null && LOADING_RUNS.containsKey(key()) && count-- > 0) {
try (WithThreadName naming = new WithThreadName(": waiting for " + key())) {
LOADING_RUNS.wait(/* 1m */60_000);
} catch (InterruptedException x) {
LOGGER.log(Level.WARNING, "failed to wait for " + r + " to be loaded", x);
break;
}
}
}
FlowExecution exec = r.execution;
if (exec != null) {
return exec;
} else {
throw new IOException(r + " did not yet start");
}
}
@Override public FlowExecution getOrNull() {
try {
ListenableFuture<FlowExecution> promise = run().getExecutionPromise();
if (promise.isDone()) {
return promise.get();
}
} catch (Exception x) {
LOGGER.log(/* not important */Level.FINE, null, x);
}
return null;
}
@Override public File getRootDir() throws IOException {
return run().getRootDir();
}
@Override public Queue.Executable getExecutable() throws IOException {
return run();
}
@Override public String getUrl() throws IOException {
return run().getUrl();
}
@Override public TaskListener getListener() throws IOException {
StreamBuildListener l = run().listener;
if (l != null) {
return l;
} else {
// Seems to happen at least once during resume, but anyway TryRepeatedly will call this method again, rather than caching the result.
LOGGER.log(Level.FINE, "No listener yet for {0}", this);
return TaskListener.NULL;
}
}
@Override public String toString() {
return "Owner[" + key() + ":" + run + "]";
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Owner)) {
return false;
}
Owner that = (Owner) o;
return job.equals(that.job) && id.equals(that.id);