-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathDeterministicRunnerImpl.java
662 lines (584 loc) · 19.4 KB
/
DeterministicRunnerImpl.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
/*
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Modifications copyright (C) 2017 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.uber.cadence.internal.sync;
import com.uber.cadence.ChildPolicy;
import com.uber.cadence.WorkflowExecution;
import com.uber.cadence.WorkflowType;
import com.uber.cadence.converter.DataConverter;
import com.uber.cadence.converter.JsonDataConverter;
import com.uber.cadence.internal.common.CheckedExceptionWrapper;
import com.uber.cadence.internal.metrics.NoopScope;
import com.uber.cadence.internal.replay.ContinueAsNewWorkflowExecutionParameters;
import com.uber.cadence.internal.replay.DeciderCache;
import com.uber.cadence.internal.replay.DecisionContext;
import com.uber.cadence.internal.replay.ExecuteActivityParameters;
import com.uber.cadence.internal.replay.ExecuteLocalActivityParameters;
import com.uber.cadence.internal.replay.SignalExternalWorkflowParameters;
import com.uber.cadence.internal.replay.StartChildWorkflowExecutionParameters;
import com.uber.cadence.workflow.Functions.Func;
import com.uber.cadence.workflow.Functions.Func1;
import com.uber.cadence.workflow.Promise;
import com.uber.m3.tally.Scope;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Throws Error in case of any unexpected condition. It is to fail a decision, not a workflow. */
class DeterministicRunnerImpl implements DeterministicRunner {
private static class NamedRunnable {
private final String name;
private final Runnable runnable;
private NamedRunnable(String name, Runnable runnable) {
this.name = name;
this.runnable = runnable;
}
}
private static final Logger log = LoggerFactory.getLogger(DeterministicRunnerImpl.class);
static final String WORKFLOW_ROOT_THREAD_NAME = "workflow-root";
private static final ThreadLocal<WorkflowThread> currentThreadThreadLocal = new ThreadLocal<>();
private final Lock lock = new ReentrantLock();
private final ExecutorService threadPool;
private final SyncDecisionContext decisionContext;
private final Deque<WorkflowThread> threads = new ArrayDeque<>(); // protected by lock
// Values from RunnerLocalInternal
private final Map<RunnerLocalInternal<?>, Object> runnerLocalMap = new HashMap<>();
private final List<WorkflowThread> threadsToAdd = Collections.synchronizedList(new ArrayList<>());
private final List<NamedRunnable> toExecuteInWorkflowThread = new ArrayList<>();
private final Supplier<Long> clock;
private DeciderCache cache;
private boolean inRunUntilAllBlocked;
private boolean closeRequested;
private boolean closed;
static WorkflowThread currentThreadInternal() {
WorkflowThread result = currentThreadThreadLocal.get();
if (result == null) {
throw new Error("Called from non workflow or workflow callback thread");
}
return result;
}
static void setCurrentThreadInternal(WorkflowThread coroutine) {
currentThreadThreadLocal.set(coroutine);
}
/**
* Time at which any thread that runs under sync can make progress. For example when {@link
* com.uber.cadence.workflow.Workflow#sleep(long)} expires. 0 means no blocked threads.
*/
private long nextWakeUpTime;
/**
* Used to check for failedPromises that contain an error, but never where accessed. It is to
* avoid failure swallowing by failedPromises which is very hard to troubleshoot.
*/
private Set<Promise> failedPromises = new HashSet<>();
private boolean exitRequested;
private Object exitValue;
private WorkflowThread rootWorkflowThread;
private final CancellationScopeImpl runnerCancellationScope;
DeterministicRunnerImpl(Runnable root) {
this(System::currentTimeMillis, root);
}
DeterministicRunnerImpl(Supplier<Long> clock, Runnable root) {
this(getDefaultThreadPool(), newDummySyncDecisionContext(), clock, root, null);
}
private static ThreadPoolExecutor getDefaultThreadPool() {
ThreadPoolExecutor result =
new ThreadPoolExecutor(0, 1000, 1, TimeUnit.SECONDS, new SynchronousQueue<>());
result.setThreadFactory(
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "deterministic runner thread");
}
});
return result;
}
DeterministicRunnerImpl(
ExecutorService threadPool,
SyncDecisionContext decisionContext,
Supplier<Long> clock,
Runnable root) {
this(threadPool, decisionContext, clock, root, null);
}
DeterministicRunnerImpl(
ExecutorService threadPool,
SyncDecisionContext decisionContext,
Supplier<Long> clock,
Runnable root,
DeciderCache cache) {
this.threadPool = threadPool;
this.decisionContext =
decisionContext != null ? decisionContext : newDummySyncDecisionContext();
this.clock = clock;
this.cache = cache;
runnerCancellationScope = new CancellationScopeImpl(true, null, null);
// TODO: workflow instance specific thread name
rootWorkflowThread =
new WorkflowThreadImpl(
true,
threadPool,
this,
WORKFLOW_ROOT_THREAD_NAME,
false,
runnerCancellationScope,
root,
cache);
threads.addLast(rootWorkflowThread);
rootWorkflowThread.start();
}
private static SyncDecisionContext newDummySyncDecisionContext() {
return new SyncDecisionContext(
new DummyDecisionContext(), JsonDataConverter.getInstance(), (next) -> next, null);
}
SyncDecisionContext getDecisionContext() {
return decisionContext;
}
@Override
public void runUntilAllBlocked() throws Throwable {
lock.lock();
try {
checkClosed();
inRunUntilAllBlocked = true;
Throwable unhandledException = null;
// Keep repeating until at least one of the threads makes progress.
boolean progress;
outerLoop:
do {
threadsToAdd.clear();
if (!toExecuteInWorkflowThread.isEmpty()) {
List<WorkflowThread> callbackThreads = new ArrayList<>(toExecuteInWorkflowThread.size());
for (NamedRunnable nr : toExecuteInWorkflowThread) {
WorkflowThread thread =
new WorkflowThreadImpl(
false,
threadPool,
this,
nr.name,
false,
runnerCancellationScope,
nr.runnable,
cache);
callbackThreads.add(thread);
}
// It is important to prepend threads as there are callbacks
// like signals that have to run before any other threads.
// Otherwise signal might be never processed if it was received
// after workflow decided to close.
// Adding the callbacks in the same order as they appear in history.
for (int i = callbackThreads.size() - 1; i >= 0; i--) {
threads.addFirst(callbackThreads.get(i));
}
}
toExecuteInWorkflowThread.clear();
progress = false;
Iterator<WorkflowThread> ci = threads.iterator();
nextWakeUpTime = 0;
while (ci.hasNext()) {
WorkflowThread c = ci.next();
progress = c.runUntilBlocked() || progress;
if (exitRequested) {
close();
break outerLoop;
}
if (c.isDone()) {
ci.remove();
if (c.getUnhandledException() != null) {
unhandledException = c.getUnhandledException();
break;
}
} else {
long t = c.getBlockedUntil();
if (t > nextWakeUpTime) {
nextWakeUpTime = t;
}
}
}
if (unhandledException != null) {
close();
throw unhandledException;
}
for (WorkflowThread c : threadsToAdd) {
threads.addLast(c);
}
} while (progress && !threads.isEmpty());
if (nextWakeUpTime < currentTimeMillis()) {
nextWakeUpTime = 0;
}
} finally {
inRunUntilAllBlocked = false;
// Close was requested while running
if (closeRequested) {
close();
}
lock.unlock();
}
}
@Override
public boolean isDone() {
lock.lock();
try {
return closed || threads.isEmpty();
} finally {
lock.unlock();
}
}
@Override
@SuppressWarnings("unchecked")
public Object getExitValue() {
lock.lock();
try {
if (!closed) {
throw new Error("not done");
}
} finally {
lock.unlock();
}
return exitValue;
}
@Override
public void cancel(String reason) {
executeInWorkflowThread("cancel workflow callback", () -> rootWorkflowThread.cancel(reason));
}
@Override
public void close() {
List<Future<?>> threadFutures = new ArrayList<>();
lock.lock();
if (closed) {
lock.unlock();
return;
}
// Do not close while runUntilAllBlocked executes.
// closeRequested tells it to call close() at the end.
closeRequested = true;
if (inRunUntilAllBlocked) {
lock.unlock();
return;
}
try {
for (WorkflowThread c : threads) {
threadFutures.add(c.stopNow());
}
threads.clear();
// We cannot use an iterator to unregister failed Promises since f.get()
// will remove the promise directly from failedPromises. This causes an
// ConcurrentModificationException
// For this reason we will loop over a copy of failedPromises.
Set<Promise> failedPromisesLoop = new HashSet<>(failedPromises);
for (Promise f : failedPromisesLoop) {
if (!f.isCompleted()) {
throw new Error("expected failed");
}
try {
f.get();
throw new Error("unreachable");
} catch (RuntimeException e) {
log.warn(
"Promise that was completedExceptionally was never accessed. "
+ "The ignored exception:",
CheckedExceptionWrapper.unwrap(e));
}
}
} finally {
closed = true;
lock.unlock();
}
// Context is destroyed in c.StopNow(). Wait on all tasks outside the lock since
// these tasks use the same lock to execute.
for (Future<?> future : threadFutures) {
try {
future.get();
} catch (InterruptedException e) {
throw new Error("Unexpected interrupt", e);
} catch (ExecutionException e) {
throw new Error("Unexpected failure stopping coroutine", e);
}
}
}
@Override
public String stackTrace() {
StringBuilder result = new StringBuilder();
lock.lock();
try {
checkClosed();
for (WorkflowThread coroutine : threads) {
if (result.length() > 0) {
result.append("\n");
}
coroutine.addStackTrace(result);
}
} finally {
lock.unlock();
}
return result.toString();
}
private void checkClosed() {
if (closed) {
throw new Error("closed");
}
}
@Override
public long currentTimeMillis() {
return clock.get();
}
@Override
public long getNextWakeUpTime() {
lock.lock();
try {
checkClosed();
if (decisionContext != null) {
long nextFireTime = decisionContext.getNextFireTime();
if (nextWakeUpTime == 0) {
return nextFireTime;
}
if (nextFireTime == 0) {
return nextWakeUpTime;
}
return Math.min(nextWakeUpTime, nextFireTime);
}
return nextWakeUpTime;
} finally {
lock.unlock();
}
}
WorkflowThread newThread(Runnable runnable, boolean detached, String name) {
checkWorkflowThreadOnly();
checkClosed();
WorkflowThread result =
new WorkflowThreadImpl(
false,
threadPool,
this,
name,
detached,
CancellationScopeImpl.current(),
runnable,
cache);
threadsToAdd.add(result); // This is synchronized collection.
return result;
}
/**
* Executes before any other threads next time runUntilBlockedCalled. Must never be called from
* any workflow threads.
*/
@Override
public void executeInWorkflowThread(String name, Runnable runnable) {
lock.lock();
try {
checkClosed();
toExecuteInWorkflowThread.add(new NamedRunnable(name, runnable));
} finally {
lock.unlock();
}
}
Lock getLock() {
return lock;
}
/** Register a promise that had failed but wasn't accessed yet. */
void registerFailedPromise(Promise promise) {
failedPromises.add(promise);
}
/** Forget a failed promise as it was accessed. */
void forgetFailedPromise(Promise promise) {
failedPromises.remove(promise);
}
<R> void exit(R value) {
checkClosed();
checkWorkflowThreadOnly();
this.exitValue = value;
this.exitRequested = true;
}
private void checkWorkflowThreadOnly() {
if (!inRunUntilAllBlocked) {
throw new Error("called from non workflow thread");
}
}
@SuppressWarnings("unchecked")
<T> Optional<T> getRunnerLocal(RunnerLocalInternal<T> key) {
if (!runnerLocalMap.containsKey(key)) {
return Optional.empty();
}
return Optional.of((T) runnerLocalMap.get(key));
}
<T> void setRunnerLocal(RunnerLocalInternal<T> key, T value) {
runnerLocalMap.put(key, value);
}
private static final class DummyDecisionContext implements DecisionContext {
@Override
public WorkflowExecution getWorkflowExecution() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public WorkflowType getWorkflowType() {
return new WorkflowType().setName("dummy-workflow");
}
@Override
public boolean isCancelRequested() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public ContinueAsNewWorkflowExecutionParameters getContinueAsNewOnCompletion() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void setContinueAsNewOnCompletion(
ContinueAsNewWorkflowExecutionParameters continueParameters) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public int getExecutionStartToCloseTimeoutSeconds() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public String getTaskList() {
return "dummy-task-list";
}
@Override
public String getDomain() {
return "dummy-domain";
}
@Override
public String getWorkflowId() {
return "dummy-workflow-id";
}
@Override
public String getRunId() {
return "dummy-run-id";
}
@Override
public Duration getExecutionStartToCloseTimeout() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Duration getDecisionTaskTimeout() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public ChildPolicy getChildPolicy() {
return ChildPolicy.TERMINATE;
}
@Override
public Consumer<Exception> scheduleActivityTask(
ExecuteActivityParameters parameters, BiConsumer<byte[], Exception> callback) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Consumer<Exception> scheduleLocalActivityTask(
ExecuteLocalActivityParameters parameters, BiConsumer<byte[], Exception> callback) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Consumer<Exception> startChildWorkflow(
StartChildWorkflowExecutionParameters parameters,
Consumer<WorkflowExecution> executionCallback,
BiConsumer<byte[], Exception> callback) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean isServerSideChildWorkflowRetry() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean isServerSideActivityRetry() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Consumer<Exception> signalWorkflowExecution(
SignalExternalWorkflowParameters signalParameters, BiConsumer<Void, Exception> callback) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Promise<Void> requestCancelWorkflowExecution(WorkflowExecution execution) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void continueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters parameters) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Optional<byte[]> mutableSideEffect(
String id, DataConverter converter, Func1<Optional<byte[]>, Optional<byte[]>> func) {
return func.apply(Optional.empty());
}
@Override
public long currentTimeMillis() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean isReplaying() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Consumer<Exception> createTimer(long delaySeconds, Consumer<Exception> callback) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public byte[] sideEffect(Func<byte[]> func) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public int getVersion(
String changeID, DataConverter converter, int minSupported, int maxSupported) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Random newRandom() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Scope getMetricsScope() {
return NoopScope.getInstance();
}
@Override
public boolean getEnableLoggingInReplay() {
return false;
}
@Override
public UUID randomUUID() {
return UUID.randomUUID();
}
@Override
public long getScheduleTimeMillis() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public long getExecutionTimeMillis() {
throw new UnsupportedOperationException("not implemented");
}
}
}