forked from jenkinsci/workflow-cps-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CpsBodyExecution.java
425 lines (375 loc) · 16.4 KB
/
CpsBodyExecution.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
package org.jenkinsci.plugins.workflow.cps;
import com.cloudbees.groovy.cps.Continuable;
import com.cloudbees.groovy.cps.Continuation;
import com.cloudbees.groovy.cps.Next;
import com.cloudbees.groovy.cps.Outcome;
import com.cloudbees.groovy.cps.impl.CpsCallableInvocation;
import com.cloudbees.groovy.cps.impl.FunctionCallEnv;
import com.cloudbees.groovy.cps.impl.TryBlockEnv;
import com.cloudbees.groovy.cps.sandbox.SandboxInvoker;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.SettableFuture;
import hudson.model.Action;
import hudson.model.Result;
import hudson.util.Iterators;
import jenkins.model.CauseOfInterruption;
import org.jenkinsci.plugins.workflow.actions.BodyInvocationAction;
import org.jenkinsci.plugins.workflow.actions.ErrorAction;
import org.jenkinsci.plugins.workflow.cps.nodes.StepEndNode;
import org.jenkinsci.plugins.workflow.cps.nodes.StepStartNode;
import org.jenkinsci.plugins.workflow.cps.persistence.PersistIn;
import org.jenkinsci.plugins.workflow.steps.BodyExecution;
import org.jenkinsci.plugins.workflow.steps.BodyExecutionCallback;
import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.StepExecution;
import javax.annotation.concurrent.GuardedBy;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.logging.Level.*;
import javax.annotation.Nonnull;
import static org.jenkinsci.plugins.workflow.cps.persistence.PersistenceContext.*;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
import org.jenkinsci.plugins.workflow.graphanalysis.LinearBlockHoppingScanner;
/**
* {@link BodyExecution} impl for CPS.
*
* Instantiated when {@linkplain CpsBodyInvoker#start() the execution is scheduled},
* and {@link CpsThreadGroup} gets updated with the new thread in the {@link #launch(CpsBodyInvoker, CpsThread, FlowHead)}
* method, and this is the point in which the actual execution gest under way.
*
* <p>
* This object is serializable while {@link CpsBodyInvoker} isn't.
*
* @author Kohsuke Kawaguchi
* @see CpsBodyInvoker#start()
*/
@PersistIn(PROGRAM)
class CpsBodyExecution extends BodyExecution {
/**
* Thread that's executing the body.
*/
@GuardedBy("this") // 'thread' and 'stopped' needs to be compared & set atomically
private CpsThread thread;
/**
* Set to non-null if the body execution is stopped.
*/
@GuardedBy("this")
private FlowInterruptedException stopped;
private final List<BodyExecutionCallback> callbacks;
/**
* Context for the step who invoked its body.
*/
private final CpsStepContext context;
private String startNodeId;
private final Continuation onSuccess = new SuccessAdapter();
/**
* Unlike {@link #onSuccess} that can only happen after {@link #launch(CpsBodyInvoker, CpsThread, FlowHead)},
* a failure can happen right after {@link CpsBodyInvoker#start()} before we get a chance to be launched.
*/
/*package*/ final Continuation onFailure = new FailureAdapter();
@GuardedBy("this")
private Outcome outcome;
CpsBodyExecution(CpsStepContext context, List<BodyExecutionCallback> callbacks) {
this.context = context;
this.callbacks = callbacks;
}
/**
* Starts evaluating the body.
*
* If the body is a synchronous closure, this method evaluates the closure synchronously.
* Otherwise, the body is asynchronous and the method schedules another thread to evaluate the body.
*
* @param currentThread
* The thread whose context the new thread will inherit.
*/
@CpsVmThreadOnly
/*package*/ void launch(CpsBodyInvoker params, CpsThread currentThread, FlowHead head) {
if (isLaunched())
throw new IllegalStateException("Already launched");
StepStartNode sn = addBodyStartFlowNode(head);
for (Action a : params.startNodeActions) {
if (a!=null)
sn.addAction(a);
}
head.setNewHead(sn);
StepContext sc = new CpsBodySubContext(context, sn);
for (BodyExecutionCallback c : callbacks) {
c.onStart(sc);
}
try {
// TODO: handle arguments to closure
Object x = params.body.getBody(currentThread).call();
// body has completed synchronously. mark this done after the fact
// pointless synchronization to make findbugs happy. This is already done, so there's no cancelling this anyway.
synchronized (this) {
this.thread = currentThread;
}
onSuccess.receive(x);
} catch (CpsCallableInvocation e) {
// execute this closure asynchronously
// TODO: does it make sense that the new thread shares the same head?
CpsThread t = currentThread.group.addThread(createContinuable(currentThread, e), head,
ContextVariableSet.from(currentThread.getContextVariables(), params.contextOverrides));
// let the new CpsThread run. Either get the new thread going normally with (null,null), or abort from the beginning
// due to earlier cancellation
synchronized (this) {
t.resume(new Outcome(null, stopped));
assert this.thread==null;
this.thread = t;
}
} catch (Throwable t) {
// body has completed synchronously and abnormally
synchronized (this) {
this.thread = currentThread;
}
onFailure.receive(t);
}
}
/**
* Creates {@link Continuable} that executes the given invocation and pass its result to {@link FutureCallback}.
*
* The {@link Continuable} itself will just yield null. {@link CpsThreadGroup} considers the whole
* execution a failure if any of the threads fail, so this behaviour ensures that a problem in the closure
* body won't terminate the workflow.
*/
private Continuable createContinuable(CpsThread currentThread, CpsCallableInvocation inv) {
// we need FunctionCallEnv that acts as the back drop of try/catch block.
// TODO: we need to capture the surrounding calling context to capture variables, and switch to ClosureCallEnv
FunctionCallEnv caller = new FunctionCallEnv(null, onSuccess, null, null);
if (currentThread.getExecution().isSandbox())
caller.setInvoker(new SandboxInvoker());
// catch an exception thrown from body and treat that as a failure
TryBlockEnv env = new TryBlockEnv(caller, null);
env.addHandler(Throwable.class, onFailure);
return new Continuable(
// this source location is a place holder for the step implementation.
// perhaps at some point in the future we'll let the Step implementation control this.
inv.invoke(env, null, onSuccess));
}
@Override
public Collection<StepExecution> getCurrentExecutions() {
CpsThread t;
synchronized (this) {
t = thread;
if (t == null) {
return Collections.emptySet();
}
}
final SettableFuture<Collection<StepExecution>> result = SettableFuture.create();
t.getExecution().runInCpsVmThread(new FutureCallback<CpsThreadGroup>() {
@Override public void onSuccess(CpsThreadGroup g) {
try {
List<StepExecution> executions = new ArrayList<>();
// cf. trick in CpsFlowExecution.getCurrentExecutions(true)
Map<FlowHead, CpsThread> m = new LinkedHashMap<>();
for (CpsThread t : g.threads.values()) {
m.put(t.head, t);
}
for (CpsThread t : m.values()) {
// TODO seems cumbersome to have to go through the flow graph to find out whether a head is a descendant of ours, yet FlowHead does not seem to retain a parent field
LinearBlockHoppingScanner scanner = new LinearBlockHoppingScanner();
scanner.setup(t.head.get());
for (FlowNode node : scanner) {
if (node.getId().equals(startNodeId)) {
// this head is inside this body execution
StepExecution execution = t.getStep();
if (execution != null) {
executions.add(execution);
}
break;
}
}
}
result.set(executions);
} catch (Exception x) {
result.setException(x);
}
}
@Override public void onFailure(Throwable t) {
result.setException(t);
}
});
try {
return result.get(1, TimeUnit.MINUTES);
} catch (ExecutionException | InterruptedException | TimeoutException x) {
// TODO access to CpsThreadGroup.threads must be restricted to the CPS VM thread, but the API signature does not allow us to return a ListenableFuture or throw checked exceptions
throw new RuntimeException(x);
}
}
@Override
public boolean cancel(final CauseOfInterruption... causes) {
// 'stopped' and 'thread' are updated atomically
CpsThread t;
synchronized (this) {
if (isDone()) return false; // already complete
// TODO should perhaps rather override cancel(Throwable) and make this overload just delegate to that one
stopped = new FlowInterruptedException(Result.ABORTED, causes);
t = this.thread;
}
if (t!=null) {
t.getExecution().runInCpsVmThread(new FutureCallback<CpsThreadGroup>() {
@Override
public void onSuccess(CpsThreadGroup g) {
// Similar to getCurrentExecutions but we want the raw CpsThread, not a StepExecution; cf. CpsFlowExecution.interrupt
Map<FlowHead, CpsThread> m = new LinkedHashMap<>();
for (CpsThread t : thread.group.threads.values()) {
m.put(t.head, t);
}
for (CpsThread t : Iterators.reverse(ImmutableList.copyOf(m.values()))) {
LinearBlockHoppingScanner scanner = new LinearBlockHoppingScanner();
scanner.setup(t.head.get());
for (FlowNode node : scanner) {
if (node.getId().equals(startNodeId)) {
t.stop(stopped);
break;
}
}
}
}
@Override
public void onFailure(Throwable t) {
LOGGER.log(Level.WARNING, "could not cancel " + context + " with " + Arrays.toString(causes), t);
}
});
} else {
// if it hasn't begun executing, we'll stop it when
// it begins.
}
return true;
}
@Override
public synchronized boolean isCancelled() {
return stopped!=null && isDone();
}
/**
* Is the execution under way? True after {@link #launch(CpsBodyInvoker, CpsThread, FlowHead)}
*/
public synchronized boolean isLaunched() {
return thread!=null;
}
@Override
public synchronized Object get() throws InterruptedException, ExecutionException {
while (outcome==null) {
wait();
}
if (outcome.isSuccess()) return outcome.getNormal();
else throw new ExecutionException(outcome.getAbnormal());
}
@Override
public synchronized Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
long endTime = System.currentTimeMillis() + unit.toMillis(timeout);
long remaining;
while (outcome==null && (remaining=endTime-System.currentTimeMillis()) > 0) {
wait(remaining);
}
if (outcome==null)
throw new TimeoutException();
if (outcome.isSuccess()) return outcome.getNormal();
else throw new ExecutionException(outcome.getAbnormal());
}
private void setOutcome(Outcome o) {
synchronized (this) {
if (outcome!=null)
throw new IllegalStateException("Outcome is already set");
this.outcome = o;
notifyAll(); // wake up everyone waiting for the outcome.
}
context.saveState();
}
public synchronized boolean isDone() {
return outcome!=null;
}
private class FailureAdapter implements Continuation {
@Override
public Next receive(Object o) {
if (!isLaunched()) {
// failed before we even started. fake the start node that start() would have created.
FlowHead h = CpsThread.current().head;
StepStartNode ssn = addBodyStartFlowNode(h);
h.setNewHead(ssn);
}
StepEndNode en = addBodyEndFlowNode();
Throwable t = (Throwable)o;
en.addAction(new ErrorAction(t));
CpsFlowExecution.maybeAutoPersistNode(en);
setOutcome(new Outcome(null,t));
StepContext sc = new CpsBodySubContext(context, en);
for (BodyExecutionCallback c : callbacks) {
c.onFailure(sc, t);
}
return Next.terminate(null);
}
private static final long serialVersionUID = 1L;
}
private class SuccessAdapter implements Continuation {
@Override
public Next receive(Object o) {
StepEndNode en = addBodyEndFlowNode();
CpsFlowExecution.maybeAutoPersistNode(en);
setOutcome(new Outcome(o,null));
StepContext sc = new CpsBodySubContext(context, en);
for (BodyExecutionCallback c : callbacks) {
c.onSuccess(sc, o);
}
return Next.terminate(null);
}
private static final long serialVersionUID = 1L;
}
/**
* Inserts the flow node that indicates the beginning of the body invocation.
*
* @see #addBodyEndFlowNode()
*/
private @Nonnull StepStartNode addBodyStartFlowNode(FlowHead head) {
CpsFlowExecution.maybeAutoPersistNode(head.get());
StepStartNode start = new StepStartNode(head.getExecution(),
context.getStepDescriptor(), head.get());
head.getExecution().cacheNode(start);
this.startNodeId = start.getId();
start.addAction(new BodyInvocationAction());
return start;
}
/**
* Inserts the flow node that indicates the beginning of the body invocation.
*
* @see #addBodyStartFlowNode(FlowHead)
*/
private @Nonnull StepEndNode addBodyEndFlowNode() {
try {
FlowHead head = CpsThread.current().head;
StepEndNode end = new StepEndNode(head.getExecution(),
getBodyStartNode(), head.get());
head.getExecution().cacheNode(end);
end.addAction(new BodyInvocationAction());
head.setNewHead(end);
return end;
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to grow the flow graph", e);
throw new Error(e);
}
}
public StepStartNode getBodyStartNode() throws IOException {
if (startNodeId==null)
throw new IllegalStateException("StepStartNode is not yet created");
CpsThread t;
synchronized (this) {// to make findbugs happy
t = thread;
}
return (StepStartNode) t.getExecution().getNode(startNodeId);
}
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(CpsBodyExecution.class.getName());
}