/
ConnectionManagerWorkflowImpl.java
736 lines (634 loc) · 33.7 KB
/
ConnectionManagerWorkflowImpl.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
/*
* Copyright (c) 2022 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.workers.temporal.scheduling;
import com.fasterxml.jackson.databind.JsonNode;
import io.airbyte.config.FailureReason;
import io.airbyte.config.FailureReason.FailureType;
import io.airbyte.config.StandardCheckConnectionInput;
import io.airbyte.config.StandardCheckConnectionOutput;
import io.airbyte.config.StandardCheckConnectionOutput.Status;
import io.airbyte.config.StandardSyncInput;
import io.airbyte.config.StandardSyncOutput;
import io.airbyte.config.StandardSyncSummary;
import io.airbyte.config.StandardSyncSummary.ReplicationStatus;
import io.airbyte.scheduler.models.IntegrationLauncherConfig;
import io.airbyte.scheduler.models.JobRunConfig;
import io.airbyte.workers.helper.FailureHelper;
import io.airbyte.workers.temporal.TemporalJobType;
import io.airbyte.workers.temporal.check.connection.CheckConnectionActivity;
import io.airbyte.workers.temporal.check.connection.CheckConnectionActivity.CheckConnectionInput;
import io.airbyte.workers.temporal.exception.RetryableException;
import io.airbyte.workers.temporal.scheduling.activities.AutoDisableConnectionActivity;
import io.airbyte.workers.temporal.scheduling.activities.AutoDisableConnectionActivity.AutoDisableConnectionActivityInput;
import io.airbyte.workers.temporal.scheduling.activities.AutoDisableConnectionActivity.AutoDisableConnectionOutput;
import io.airbyte.workers.temporal.scheduling.activities.ConfigFetchActivity;
import io.airbyte.workers.temporal.scheduling.activities.ConfigFetchActivity.ScheduleRetrieverInput;
import io.airbyte.workers.temporal.scheduling.activities.ConfigFetchActivity.ScheduleRetrieverOutput;
import io.airbyte.workers.temporal.scheduling.activities.ConnectionDeletionActivity;
import io.airbyte.workers.temporal.scheduling.activities.ConnectionDeletionActivity.ConnectionDeletionInput;
import io.airbyte.workers.temporal.scheduling.activities.GenerateInputActivity;
import io.airbyte.workers.temporal.scheduling.activities.GenerateInputActivity.GeneratedJobInput;
import io.airbyte.workers.temporal.scheduling.activities.GenerateInputActivity.SyncInput;
import io.airbyte.workers.temporal.scheduling.activities.GenerateInputActivity.SyncInputWithAttemptNumber;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.AttemptCreationInput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.AttemptCreationOutput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.AttemptFailureInput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.AttemptNumberCreationOutput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.AttemptNumberFailureInput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.EnsureCleanJobStateInput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.JobCancelledInput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.JobCancelledInputWithAttemptNumber;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.JobCreationInput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.JobCreationOutput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.JobFailureInput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.JobSuccessInput;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.JobSuccessInputWithAttemptNumber;
import io.airbyte.workers.temporal.scheduling.activities.JobCreationAndStatusUpdateActivity.ReportJobStartInput;
import io.airbyte.workers.temporal.scheduling.shared.ActivityConfiguration;
import io.airbyte.workers.temporal.scheduling.state.WorkflowInternalState;
import io.airbyte.workers.temporal.scheduling.state.WorkflowState;
import io.airbyte.workers.temporal.scheduling.state.listener.NoopStateListener;
import io.airbyte.workers.temporal.sync.SyncWorkflow;
import io.temporal.api.enums.v1.ParentClosePolicy;
import io.temporal.failure.ActivityFailure;
import io.temporal.failure.CanceledFailure;
import io.temporal.failure.ChildWorkflowFailure;
import io.temporal.workflow.CancellationScope;
import io.temporal.workflow.ChildWorkflowOptions;
import io.temporal.workflow.Workflow;
import java.time.Duration;
import java.time.Instant;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ConnectionManagerWorkflowImpl implements ConnectionManagerWorkflow {
public static final long NON_RUNNING_JOB_ID = -1;
public static final int NON_RUNNING_ATTEMPT_ID = -1;
private static final int TASK_QUEUE_CHANGE_CURRENT_VERSION = 1;
private static final int AUTO_DISABLE_FAILING_CONNECTION_CHANGE_CURRENT_VERSION = 1;
private static final String RENAME_ATTEMPT_ID_TO_NUMBER_TAG = "rename_attempt_id_to_number";
private static final int RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION = 1;
private static final String ENSURE_CLEAN_JOB_STATE = "ensure_clean_job_state";
private static final int ENSURE_CLEAN_JOB_STATE_CURRENT_VERSION = 1;
private static final String CHECK_BEFORE_SYNC_TAG = "check_before_sync";
private static final int CHECK_BEFORE_SYNC_CURRENT_VERSION = 1;
private WorkflowState workflowState = new WorkflowState(UUID.randomUUID(), new NoopStateListener());
private final WorkflowInternalState workflowInternalState = new WorkflowInternalState();
private final GenerateInputActivity getSyncInputActivity =
Workflow.newActivityStub(GenerateInputActivity.class, ActivityConfiguration.SHORT_ACTIVITY_OPTIONS);
private final JobCreationAndStatusUpdateActivity jobCreationAndStatusUpdateActivity =
Workflow.newActivityStub(JobCreationAndStatusUpdateActivity.class, ActivityConfiguration.SHORT_ACTIVITY_OPTIONS);
private final ConfigFetchActivity configFetchActivity =
Workflow.newActivityStub(ConfigFetchActivity.class, ActivityConfiguration.SHORT_ACTIVITY_OPTIONS);
private final ConnectionDeletionActivity connectionDeletionActivity =
Workflow.newActivityStub(ConnectionDeletionActivity.class, ActivityConfiguration.SHORT_ACTIVITY_OPTIONS);
private final AutoDisableConnectionActivity autoDisableConnectionActivity =
Workflow.newActivityStub(AutoDisableConnectionActivity.class, ActivityConfiguration.SHORT_ACTIVITY_OPTIONS);
private final CheckConnectionActivity checkActivity =
Workflow.newActivityStub(CheckConnectionActivity.class, ActivityConfiguration.CHECK_ACTIVITY_OPTIONS);
private CancellationScope cancellableSyncWorkflow;
private UUID connectionId;
public ConnectionManagerWorkflowImpl() {}
@Override
public void run(final ConnectionUpdaterInput connectionUpdaterInput) throws RetryableException {
try {
try {
cancellableSyncWorkflow = generateSyncWorkflowRunnable(connectionUpdaterInput);
cancellableSyncWorkflow.run();
} catch (final CanceledFailure cf) {
// When a scope is cancelled temporal will throw a CanceledFailure as you can see here:
// https://github.com/temporalio/sdk-java/blob/master/temporal-sdk/src/main/java/io/temporal/workflow/CancellationScope.java#L72
// The naming is very misleading, it is not a failure but the expected behavior...
}
if (workflowState.isDeleted()) {
if (workflowState.isRunning()) {
log.info("Cancelling the current running job because a connection deletion was requested");
reportCancelled(false);
}
log.info("Workflow deletion was requested. Calling deleteConnection activity before terminating the workflow.");
deleteConnectionBeforeTerminatingTheWorkflow();
return;
}
// this means that the current workflow is being cancelled so that a reset can be run instead.
if (workflowState.isCancelledForReset()) {
reportCancelledAndContinueWith(true, connectionUpdaterInput);
}
if (workflowState.isCancelled()) {
reportCancelledAndContinueWith(false, connectionUpdaterInput);
}
} catch (final Exception e) {
log.error("The connection update workflow has failed, will create a new attempt.", e);
reportFailure(connectionUpdaterInput, null);
prepareForNextRunAndContinueAsNew(connectionUpdaterInput);
}
}
private CancellationScope generateSyncWorkflowRunnable(final ConnectionUpdaterInput connectionUpdaterInput) {
return Workflow.newCancellationScope(() -> {
connectionId = connectionUpdaterInput.getConnectionId();
// Clean the job state by failing any jobs for this connection that are currently non-terminal.
// This catches cases where the temporal workflow was terminated and restarted while a job was
// actively running, leaving that job in an orphaned and non-terminal state.
ensureCleanJobState(connectionUpdaterInput);
// workflow state is only ever set in test cases. for production cases, it will always be null.
if (connectionUpdaterInput.getWorkflowState() != null) {
workflowState = connectionUpdaterInput.getWorkflowState();
}
// when a reset is triggered, the previous attempt, cancels itself (unless it is already a reset, in
// which case it does nothing). the previous run that cancels itself then passes on the
// resetConnection flag to the next run so that that run can execute the actual reset
if (connectionUpdaterInput.isResetConnection()) {
workflowState.setResetConnection(true);
}
if (connectionUpdaterInput.isFromJobResetFailure()) {
workflowState.setResetWithScheduling(true);
}
final Duration timeToWait = getTimeToWait(connectionUpdaterInput.getConnectionId());
Workflow.await(timeToWait,
() -> skipScheduling() || connectionUpdaterInput.isFromFailure());
if (workflowState.isDeleted()) {
log.info("Returning from workflow cancellation scope because workflow deletion was requested.");
return;
}
if (workflowState.isUpdated()) {
// Act as a return
prepareForNextRunAndContinueAsNew(connectionUpdaterInput);
}
workflowInternalState.setJobId(getOrCreateJobId(connectionUpdaterInput));
workflowInternalState.setAttemptNumber(createAttempt(workflowInternalState.getJobId()));
final GeneratedJobInput jobInputs = getJobInput();
reportJobStarting();
StandardSyncOutput standardSyncOutput = null;
try {
final SyncCheckConnectionFailure syncCheckConnectionFailure = checkConnections(jobInputs);
if (syncCheckConnectionFailure.isFailed()) {
final StandardSyncOutput checkFailureOutput = syncCheckConnectionFailure.buildFailureOutput();
workflowState.setFailed(getFailStatus(checkFailureOutput));
reportFailure(connectionUpdaterInput, checkFailureOutput);
} else {
standardSyncOutput = runChildWorkflow(jobInputs);
workflowState.setFailed(getFailStatus(standardSyncOutput));
if (workflowState.isFailed()) {
reportFailure(connectionUpdaterInput, standardSyncOutput);
} else {
reportSuccess(connectionUpdaterInput, standardSyncOutput);
}
}
prepareForNextRunAndContinueAsNew(connectionUpdaterInput);
} catch (final ChildWorkflowFailure childWorkflowFailure) {
// when we cancel a method, we call the cancel method of the cancellation scope. This will throw an
// exception since we expect it, we just
// silently ignore it.
if (childWorkflowFailure.getCause() instanceof CanceledFailure) {
// do nothing, cancellation handled by cancellationScope
} else if (childWorkflowFailure.getCause()instanceof final ActivityFailure af) {
// Allows us to classify unhandled failures from the sync workflow. e.g. If the normalization
// activity throws an exception, for
// example, this lets us set the failureOrigin to normalization.
workflowInternalState.getFailures().add(FailureHelper.failureReasonFromWorkflowAndActivity(
childWorkflowFailure.getWorkflowType(),
af.getActivityType(),
af.getCause(),
workflowInternalState.getJobId(),
workflowInternalState.getAttemptNumber()));
reportFailure(connectionUpdaterInput, standardSyncOutput);
prepareForNextRunAndContinueAsNew(connectionUpdaterInput);
} else {
workflowInternalState.getFailures().add(
FailureHelper.unknownOriginFailure(childWorkflowFailure.getCause(), workflowInternalState.getJobId(),
workflowInternalState.getAttemptNumber()));
reportFailure(connectionUpdaterInput, standardSyncOutput);
prepareForNextRunAndContinueAsNew(connectionUpdaterInput);
}
}
});
}
private void reportSuccess(final ConnectionUpdaterInput connectionUpdaterInput, final StandardSyncOutput standardSyncOutput) {
workflowState.setSuccess(true);
final int attemptCreationVersion =
Workflow.getVersion(RENAME_ATTEMPT_ID_TO_NUMBER_TAG, Workflow.DEFAULT_VERSION, RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION);
if (attemptCreationVersion < RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION) {
runMandatoryActivity(jobCreationAndStatusUpdateActivity::jobSuccess, new JobSuccessInput(
workflowInternalState.getJobId(),
workflowInternalState.getAttemptNumber(),
standardSyncOutput));
} else {
runMandatoryActivity(jobCreationAndStatusUpdateActivity::jobSuccessWithAttemptNumber, new JobSuccessInputWithAttemptNumber(
workflowInternalState.getJobId(),
workflowInternalState.getAttemptNumber(),
standardSyncOutput));
}
resetNewConnectionInput(connectionUpdaterInput);
}
private void reportFailure(final ConnectionUpdaterInput connectionUpdaterInput,
final StandardSyncOutput standardSyncOutput) {
final int attemptCreationVersion =
Workflow.getVersion(RENAME_ATTEMPT_ID_TO_NUMBER_TAG, Workflow.DEFAULT_VERSION, RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION);
if (attemptCreationVersion < RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION) {
runMandatoryActivity(jobCreationAndStatusUpdateActivity::attemptFailure, new AttemptFailureInput(
workflowInternalState.getJobId(),
workflowInternalState.getAttemptNumber(),
standardSyncOutput,
FailureHelper.failureSummary(workflowInternalState.getFailures(), workflowInternalState.getPartialSuccess())));
} else {
runMandatoryActivity(jobCreationAndStatusUpdateActivity::attemptFailureWithAttemptNumber, new AttemptNumberFailureInput(
workflowInternalState.getJobId(),
workflowInternalState.getAttemptNumber(),
standardSyncOutput,
FailureHelper.failureSummary(workflowInternalState.getFailures(), workflowInternalState.getPartialSuccess())));
}
final int maxAttempt = configFetchActivity.getMaxAttempt().getMaxAttempt();
final int attemptNumber = connectionUpdaterInput.getAttemptNumber();
if (workflowState.isResetConnection()) {
workflowState.setContinueAsReset(true);
}
final FailureType failureType =
standardSyncOutput != null ? standardSyncOutput.getFailures().isEmpty() ? null : standardSyncOutput.getFailures().get(0).getFailureType()
: null;
if (maxAttempt > attemptNumber && failureType != FailureType.CONFIG_ERROR) {
// restart from failure
connectionUpdaterInput.setAttemptNumber(attemptNumber + 1);
connectionUpdaterInput.setFromFailure(true);
} else {
final String failureReason = failureType == FailureType.CONFIG_ERROR ? "Connection Check Failed " + connectionId
: "Job failed after too many retries for connection " + connectionId;
runMandatoryActivity(jobCreationAndStatusUpdateActivity::jobFailure, new JobFailureInput(connectionUpdaterInput.getJobId(), failureReason));
final int autoDisableConnectionVersion =
Workflow.getVersion("auto_disable_failing_connection", Workflow.DEFAULT_VERSION, AUTO_DISABLE_FAILING_CONNECTION_CHANGE_CURRENT_VERSION);
if (autoDisableConnectionVersion != Workflow.DEFAULT_VERSION) {
final AutoDisableConnectionActivityInput autoDisableConnectionActivityInput =
new AutoDisableConnectionActivityInput(connectionId, Instant.ofEpochMilli(Workflow.currentTimeMillis()));
final AutoDisableConnectionOutput output = runMandatoryActivityWithOutput(
autoDisableConnectionActivity::autoDisableFailingConnection, autoDisableConnectionActivityInput);
if (output.isDisabled()) {
log.info("Auto-disabled for constantly failing for Connection {}", connectionId);
}
}
resetNewConnectionInput(connectionUpdaterInput);
if (workflowState.isResetConnection()) {
connectionUpdaterInput.setFromJobResetFailure(true);
}
}
}
private SyncCheckConnectionFailure checkConnections(final GenerateInputActivity.GeneratedJobInput jobInputs) {
final JobRunConfig jobRunConfig = jobInputs.getJobRunConfig();
final StandardSyncInput syncInput = jobInputs.getSyncInput();
final JsonNode sourceConfig = syncInput.getSourceConfiguration();
final JsonNode destinationConfig = syncInput.getDestinationConfiguration();
final IntegrationLauncherConfig sourceLauncherConfig = jobInputs.getSourceLauncherConfig();
final IntegrationLauncherConfig destinationLauncherConfig = jobInputs.getDestinationLauncherConfig();
final SyncCheckConnectionFailure checkFailure = new SyncCheckConnectionFailure(jobRunConfig);
final int attemptCreationVersion =
Workflow.getVersion(CHECK_BEFORE_SYNC_TAG, Workflow.DEFAULT_VERSION, CHECK_BEFORE_SYNC_CURRENT_VERSION);
if (attemptCreationVersion < CHECK_BEFORE_SYNC_CURRENT_VERSION) {
// return early if this instance of the workflow was created beforehand
return checkFailure;
}
final StandardCheckConnectionInput sourceConfiguration = new StandardCheckConnectionInput().withConnectionConfiguration(sourceConfig);
final CheckConnectionInput checkSourceInput = new CheckConnectionInput(jobRunConfig, sourceLauncherConfig, sourceConfiguration);
if (workflowState.isResetConnection() || checkFailure.isFailed()) {
log.info("SOURCE CHECK: Skipped");
} else {
log.info("SOURCE CHECK: Starting");
final StandardCheckConnectionOutput sourceCheckResponse = runMandatoryActivityWithOutput(checkActivity::run, checkSourceInput);
if (sourceCheckResponse.getStatus() == Status.FAILED) {
checkFailure.setFailureOrigin(FailureReason.FailureOrigin.SOURCE);
checkFailure.setFailureOutput(sourceCheckResponse);
log.info("SOURCE CHECK: Failed");
} else {
log.info("SOURCE CHECK: Successful");
}
}
final StandardCheckConnectionInput destinationConfiguration = new StandardCheckConnectionInput().withConnectionConfiguration(destinationConfig);
final CheckConnectionInput checkDestinationInput = new CheckConnectionInput(jobRunConfig, destinationLauncherConfig, destinationConfiguration);
if (checkFailure.isFailed()) {
log.info("DESTINATION CHECK: Skipped");
} else {
log.info("DESTINATION CHECK: Starting");
final StandardCheckConnectionOutput destinationCheckResponse = runMandatoryActivityWithOutput(checkActivity::run, checkDestinationInput);
if (destinationCheckResponse.getStatus() == Status.FAILED) {
checkFailure.setFailureOrigin(FailureReason.FailureOrigin.DESTINATION);
checkFailure.setFailureOutput(destinationCheckResponse);
log.info("DESTINATION CHECK: Failed");
} else {
log.info("DESTINATION CHECK: Successful");
}
}
return checkFailure;
}
private void resetNewConnectionInput(final ConnectionUpdaterInput connectionUpdaterInput) {
connectionUpdaterInput.setJobId(null);
connectionUpdaterInput.setAttemptNumber(1);
connectionUpdaterInput.setFromFailure(false);
}
@Override
public void submitManualSync() {
if (workflowState.isRunning()) {
log.info("Can't schedule a manual workflow if a sync is running for connection {}", connectionId);
return;
}
workflowState.setSkipScheduling(true);
}
@Override
public void cancelJob() {
if (!workflowState.isRunning()) {
log.info("Can't cancel a non-running sync for connection {}", connectionId);
return;
}
workflowState.setCancelled(true);
cancellableSyncWorkflow.cancel();
}
@Override
public void deleteConnection() {
workflowState.setDeleted(true);
cancelJob();
}
@Override
public void connectionUpdated() {
workflowState.setUpdated(true);
}
@Override
public void resetConnection() {
workflowState.setResetConnection(true);
workflowState.setResetWithScheduling(false);
if (workflowState.isRunning()) {
workflowState.setCancelledForReset(true);
cancellableSyncWorkflow.cancel();
}
}
@Override
public void retryFailedActivity() {
workflowState.setRetryFailedActivity(true);
}
@Override
public WorkflowState getState() {
return workflowState;
}
@Override
public JobInformation getJobInformation() {
final Long jobId = workflowInternalState.getJobId();
final Integer attemptNumber = workflowInternalState.getAttemptNumber();
return new JobInformation(
jobId == null ? NON_RUNNING_JOB_ID : jobId,
attemptNumber == null ? NON_RUNNING_ATTEMPT_ID : attemptNumber);
}
@Override
public QuarantinedInformation getQuarantinedInformation() {
final Long jobId = workflowInternalState.getJobId();
final Integer attemptNumber = workflowInternalState.getAttemptNumber();
return new QuarantinedInformation(
connectionId,
jobId == null ? NON_RUNNING_JOB_ID : jobId,
attemptNumber == null ? NON_RUNNING_ATTEMPT_ID : attemptNumber,
workflowState.isQuarantined());
}
/**
* return true if the workflow is in a state that require it to continue. If the state is to process
* an update or delete the workflow, it won't continue with a run of the {@link SyncWorkflow} but it
* will: - restart for an update - Update the connection status and terminate the workflow for a
* delete
*/
private Boolean skipScheduling() {
return workflowState.isSkipScheduling() || workflowState.isDeleted() || workflowState.isUpdated() ||
(!workflowState.isResetWithScheduling() && workflowState.isResetConnection());
}
private void prepareForNextRunAndContinueAsNew(final ConnectionUpdaterInput connectionUpdaterInput) {
// Continue the workflow as new
connectionUpdaterInput.setResetConnection(workflowState.isContinueAsReset());
workflowInternalState.getFailures().clear();
workflowInternalState.setPartialSuccess(null);
final boolean isDeleted = workflowState.isDeleted();
workflowState.reset();
if (!isDeleted) {
Workflow.continueAsNew(connectionUpdaterInput);
}
}
/**
* This is running a lambda function that takes {@param input} as an input. If the run of the lambda
* is thowing an exception, the workflow will be in a quarantined state and can then be manual
* un-quarantined or a retry of the failed lambda can be trigger through a signal method.
*
* We aimed to use this method for call of the temporal activity.
*/
private <INPUT, OUTPUT> OUTPUT runMandatoryActivityWithOutput(final Function<INPUT, OUTPUT> mapper, final INPUT input) {
try {
return mapper.apply(input);
} catch (final Exception e) {
log.error("Failed to run an activity for the connection " + connectionId, e);
workflowState.setQuarantined(true);
workflowState.setRetryFailedActivity(false);
Workflow.await(() -> workflowState.isRetryFailedActivity());
log.error("Retrying an activity for the connection " + connectionId, e);
workflowState.setQuarantined(false);
workflowState.setRetryFailedActivity(false);
return runMandatoryActivityWithOutput(mapper, input);
}
}
/**
* Similar to runMandatoryActivityWithOutput but for methods that don't return
*/
private <INPUT> void runMandatoryActivity(final Consumer<INPUT> consumer, final INPUT input) {
runMandatoryActivityWithOutput((inputInternal) -> {
consumer.accept(inputInternal);
return null;
}, input);
}
/**
* Calculate the duration to wait so the workflow adheres to its schedule. This lets us 'schedule'
* the next run.
*
* This is calculated by {@link ConfigFetchActivity#getTimeToWait(ScheduleRetrieverInput)} and
* depends on the last successful run and the schedule.
*
* Wait time is infinite If the workflow is manual or disabled since we never want to schedule this.
*/
private Duration getTimeToWait(final UUID connectionId) {
// Scheduling
final ScheduleRetrieverInput scheduleRetrieverInput = new ScheduleRetrieverInput(connectionId);
final ScheduleRetrieverOutput scheduleRetrieverOutput = runMandatoryActivityWithOutput(configFetchActivity::getTimeToWait,
scheduleRetrieverInput);
return scheduleRetrieverOutput.getTimeToWait();
}
private void ensureCleanJobState(final ConnectionUpdaterInput connectionUpdaterInput) {
final int ensureCleanJobStateVersion =
Workflow.getVersion(ENSURE_CLEAN_JOB_STATE, Workflow.DEFAULT_VERSION, ENSURE_CLEAN_JOB_STATE_CURRENT_VERSION);
// For backwards compatibility and determinism, skip if workflow existed before this change
if (ensureCleanJobStateVersion < ENSURE_CLEAN_JOB_STATE_CURRENT_VERSION) {
return;
}
if (connectionUpdaterInput.getJobId() != null) {
log.info("This workflow is already attached to a job, so no need to clean job state.");
return;
}
runMandatoryActivity(jobCreationAndStatusUpdateActivity::ensureCleanJobState, new EnsureCleanJobStateInput(connectionId));
}
/**
* Creates a new job if it is not present in the input. If the jobId is specified in the input of
* the connectionManagerWorkflow, we will return it. Otherwise we will create a job and return its
* id.
*/
private Long getOrCreateJobId(final ConnectionUpdaterInput connectionUpdaterInput) {
if (connectionUpdaterInput.getJobId() != null) {
return connectionUpdaterInput.getJobId();
}
final JobCreationOutput jobCreationOutput =
runMandatoryActivityWithOutput(
jobCreationAndStatusUpdateActivity::createNewJob,
new JobCreationInput(
connectionUpdaterInput.getConnectionId(), workflowState.isResetConnection()));
connectionUpdaterInput.setJobId(jobCreationOutput.getJobId());
return jobCreationOutput.getJobId();
}
/**
* Create a new attempt for a given jobId
*
* @param jobId - the jobId associated with the new attempt
*
* @return The attempt number
*/
private Integer createAttempt(final long jobId) {
final int attemptCreationVersion =
Workflow.getVersion(RENAME_ATTEMPT_ID_TO_NUMBER_TAG, Workflow.DEFAULT_VERSION, RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION);
// Retrieve the attempt number but name it attempt id
if (attemptCreationVersion < RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION) {
final AttemptCreationOutput attemptCreationOutput =
runMandatoryActivityWithOutput(
jobCreationAndStatusUpdateActivity::createNewAttempt,
new AttemptCreationInput(
jobId));
return attemptCreationOutput.getAttemptId();
}
final AttemptNumberCreationOutput attemptNumberCreationOutput =
runMandatoryActivityWithOutput(
jobCreationAndStatusUpdateActivity::createNewAttemptNumber,
new AttemptCreationInput(
jobId));
return attemptNumberCreationOutput.getAttemptNumber();
}
/**
* Generate the input that is needed by the job. It will generate the configuration needed by the
* job and will generate a different output if the job is a sync or a reset.
*/
private GeneratedJobInput getJobInput() {
final Long jobId = workflowInternalState.getJobId();
final Integer attemptNumber = workflowInternalState.getAttemptNumber();
final int attemptCreationVersion =
Workflow.getVersion(RENAME_ATTEMPT_ID_TO_NUMBER_TAG, Workflow.DEFAULT_VERSION, RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION);
if (attemptCreationVersion < RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION) {
final SyncInput getSyncInputActivitySyncInput = new SyncInput(
attemptNumber,
jobId,
workflowState.isResetConnection());
final GeneratedJobInput syncWorkflowInputs = runMandatoryActivityWithOutput(
getSyncInputActivity::getSyncWorkflowInput,
getSyncInputActivitySyncInput);
return syncWorkflowInputs;
}
final SyncInputWithAttemptNumber getSyncInputActivitySyncInput = new SyncInputWithAttemptNumber(
attemptNumber,
jobId,
workflowState.isResetConnection());
final GeneratedJobInput syncWorkflowInputs = runMandatoryActivityWithOutput(
getSyncInputActivity::getSyncWorkflowInputWithAttemptNumber,
getSyncInputActivitySyncInput);
return syncWorkflowInputs;
}
/**
* Report the job as started in the job tracker and set it as running in the workflow internal
* state.
*/
private void reportJobStarting() {
runMandatoryActivity(
jobCreationAndStatusUpdateActivity::reportJobStart,
new ReportJobStartInput(
workflowInternalState.getJobId()));
workflowState.setRunning(true);
}
/**
* Start the child {@link SyncWorkflow}. We are using a child workflow here for two main reason:
* <p>
* - Originally the Sync workflow was living by himself and was launch by the scheduler. In order to
* limit the potential migration issues, we kept the {@link SyncWorkflow} as is and launch it as a
* child workflow.
* <p>
* - The {@link SyncWorkflow} has different requirements than the {@link ConnectionManagerWorkflow}
* since the latter is a long running workflow, in the future, using a different Node pool would
* make sense.
*/
private StandardSyncOutput runChildWorkflow(final GeneratedJobInput jobInputs) {
final int taskQueueChangeVersion =
Workflow.getVersion("task_queue_change_from_connection_updater_to_sync", Workflow.DEFAULT_VERSION, TASK_QUEUE_CHANGE_CURRENT_VERSION);
String taskQueue = TemporalJobType.SYNC.name();
if (taskQueueChangeVersion < TASK_QUEUE_CHANGE_CURRENT_VERSION) {
taskQueue = TemporalJobType.CONNECTION_UPDATER.name();
}
final SyncWorkflow childSync = Workflow.newChildWorkflowStub(SyncWorkflow.class,
ChildWorkflowOptions.newBuilder()
.setWorkflowId("sync_" + workflowInternalState.getJobId())
.setTaskQueue(taskQueue)
// This will cancel the child workflow when the parent is terminated
.setParentClosePolicy(ParentClosePolicy.PARENT_CLOSE_POLICY_REQUEST_CANCEL)
.build());
return childSync.run(
jobInputs.getJobRunConfig(),
jobInputs.getSourceLauncherConfig(),
jobInputs.getDestinationLauncherConfig(),
jobInputs.getSyncInput(),
connectionId);
}
/**
* Set the internal status as failed and save the failures reasons
*
* @return True if the job failed, false otherwise
*/
private boolean getFailStatus(final StandardSyncOutput standardSyncOutput) {
final StandardSyncSummary standardSyncSummary = standardSyncOutput.getStandardSyncSummary();
if (standardSyncSummary != null && standardSyncSummary.getStatus() == ReplicationStatus.FAILED) {
workflowInternalState.getFailures().addAll(standardSyncOutput.getFailures());
workflowInternalState.setPartialSuccess(standardSyncSummary.getTotalStats().getRecordsCommitted() > 0);
return true;
}
return false;
}
/**
* Delete a connection
*/
private void deleteConnectionBeforeTerminatingTheWorkflow() {
final ConnectionDeletionInput connectionDeletionInput = new ConnectionDeletionInput(connectionId);
runMandatoryActivity(connectionDeletionActivity::deleteConnection, connectionDeletionInput);
}
/**
* Set a job as cancel and continue to the next job if and continue as a reset if needed
*/
private void reportCancelledAndContinueWith(final boolean isReset, final ConnectionUpdaterInput connectionUpdaterInput) {
reportCancelled(isReset);
resetNewConnectionInput(connectionUpdaterInput);
prepareForNextRunAndContinueAsNew(connectionUpdaterInput);
}
private void reportCancelled(final boolean isReset) {
workflowState.setContinueAsReset(isReset);
final Long jobId = workflowInternalState.getJobId();
final Integer attemptNumber = workflowInternalState.getAttemptNumber();
final Set<FailureReason> failures = workflowInternalState.getFailures();
final Boolean partialSuccess = workflowInternalState.getPartialSuccess();
final int attemptCreationVersion =
Workflow.getVersion(RENAME_ATTEMPT_ID_TO_NUMBER_TAG, Workflow.DEFAULT_VERSION, RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION);
if (attemptCreationVersion < RENAME_ATTEMPT_ID_TO_NUMBER_CURRENT_VERSION) {
runMandatoryActivity(jobCreationAndStatusUpdateActivity::jobCancelled,
new JobCancelledInput(
jobId,
attemptNumber,
FailureHelper.failureSummaryForCancellation(jobId, attemptNumber, failures, partialSuccess)));
} else {
runMandatoryActivity(jobCreationAndStatusUpdateActivity::jobCancelledWithAttemptNumber,
new JobCancelledInputWithAttemptNumber(
jobId,
attemptNumber,
FailureHelper.failureSummaryForCancellation(jobId, attemptNumber, failures, partialSuccess)));
}
}
}