-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
operator.go
3666 lines (3316 loc) · 134 KB
/
operator.go
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
package controller
import (
"context"
"encoding/json"
"fmt"
"math"
"os"
"reflect"
"regexp"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/antonmedv/expr"
"github.com/argoproj/pkg/humanize"
argokubeerr "github.com/argoproj/pkg/kube/errors"
"github.com/argoproj/pkg/strftime"
jsonpatch "github.com/evanphx/json-patch"
log "github.com/sirupsen/logrus"
apiv1 "k8s.io/api/core/v1"
policyv1beta "k8s.io/api/policy/v1beta1"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/utils/pointer"
"sigs.k8s.io/yaml"
"github.com/argoproj/argo-workflows/v3/errors"
"github.com/argoproj/argo-workflows/v3/pkg/apis/workflow"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo-workflows/v3/pkg/client/clientset/versioned/typed/workflow/v1alpha1"
"github.com/argoproj/argo-workflows/v3/util"
"github.com/argoproj/argo-workflows/v3/util/diff"
envutil "github.com/argoproj/argo-workflows/v3/util/env"
errorsutil "github.com/argoproj/argo-workflows/v3/util/errors"
"github.com/argoproj/argo-workflows/v3/util/expr/argoexpr"
"github.com/argoproj/argo-workflows/v3/util/expr/env"
"github.com/argoproj/argo-workflows/v3/util/intstr"
"github.com/argoproj/argo-workflows/v3/util/resource"
"github.com/argoproj/argo-workflows/v3/util/retry"
argoruntime "github.com/argoproj/argo-workflows/v3/util/runtime"
"github.com/argoproj/argo-workflows/v3/util/slice"
"github.com/argoproj/argo-workflows/v3/util/template"
waitutil "github.com/argoproj/argo-workflows/v3/util/wait"
"github.com/argoproj/argo-workflows/v3/workflow/common"
controllercache "github.com/argoproj/argo-workflows/v3/workflow/controller/cache"
"github.com/argoproj/argo-workflows/v3/workflow/controller/estimation"
"github.com/argoproj/argo-workflows/v3/workflow/controller/indexes"
"github.com/argoproj/argo-workflows/v3/workflow/metrics"
"github.com/argoproj/argo-workflows/v3/workflow/progress"
argosync "github.com/argoproj/argo-workflows/v3/workflow/sync"
"github.com/argoproj/argo-workflows/v3/workflow/templateresolution"
wfutil "github.com/argoproj/argo-workflows/v3/workflow/util"
"github.com/argoproj/argo-workflows/v3/workflow/validate"
)
// wfOperationCtx is the context for evaluation and operation of a single workflow
type wfOperationCtx struct {
// wf is the workflow object. It should not be used in execution logic. woc.wfSpec should be used instead
wf *wfv1.Workflow
// orig is the original workflow object for purposes of creating a patch
orig *wfv1.Workflow
// updated indicates whether or not the workflow object itself was updated
// and needs to be persisted back to kubernetes
updated bool
// log is an logrus logging context to correlate logs with a workflow
log *log.Entry
// controller reference to workflow controller
controller *WorkflowController
// estimate duration
estimator estimation.Estimator
// globalParams holds any parameters that are available to be referenced
// in the global scope (e.g. workflow.parameters.XXX).
globalParams common.Parameters
// volumes holds a DeepCopy of wf.Spec.Volumes to perform substitutions.
// It is then used in addVolumeReferences() when creating a pod.
volumes []apiv1.Volume
// ArtifactRepository contains the default location of an artifact repository for container artifacts
artifactRepository *wfv1.ArtifactRepository
// deadline is the dealine time in which this operation should relinquish
// its hold on the workflow so that an operation does not run for too long
// and starve other workqueue items. It also enables workflow progress to
// be periodically synced to the database.
deadline time.Time
// activePods tracks the number of active (Running/Pending) pods for controlling
// parallelism
activePods int64
// workflowDeadline is the deadline which the workflow is expected to complete before we
// terminate the workflow.
workflowDeadline *time.Time
eventRecorder record.EventRecorder
// preExecutionNodePhases contains the phases of all the nodes before the current operation. Necessary to infer
// changes in phase for metric emission
preExecutionNodePhases map[string]wfv1.NodePhase
// execWf holds the Workflow for use in execution.
// In Normal workflow scenario: It holds copy of workflow object
// In Submit From WorkflowTemplate: It holds merged workflow with WorkflowDefault, Workflow and WorkflowTemplate
// 'execWf.Spec' should usually be used instead `wf.Spec`
execWf *wfv1.Workflow
taskSet map[string]wfv1.Template
}
var (
// ErrDeadlineExceeded indicates the operation exceeded its deadline for execution
ErrDeadlineExceeded = errors.New(errors.CodeTimeout, "Deadline exceeded")
// ErrParallelismReached indicates this workflow reached its parallelism limit
ErrParallelismReached = errors.New(errors.CodeForbidden, "Max parallelism reached")
ErrResourceRateLimitReached = errors.New(errors.CodeForbidden, "resource creation rate-limit reached")
// ErrTimeout indicates a specific template timed out
ErrTimeout = errors.New(errors.CodeTimeout, "timeout")
)
// maxOperationTime is the maximum time a workflow operation is allowed to run
// for before requeuing the workflow onto the workqueue.
var (
maxOperationTime = envutil.LookupEnvDurationOr("MAX_OPERATION_TIME", 30*time.Second)
)
// failedNodeStatus is a subset of NodeStatus that is only used to Marshal certain fields into a JSON of failed nodes
type failedNodeStatus struct {
DisplayName string `json:"displayName"`
Message string `json:"message"`
TemplateName string `json:"templateName"`
Phase string `json:"phase"`
PodName string `json:"podName"`
FinishedAt metav1.Time `json:"finishedAt"`
}
// newWorkflowOperationCtx creates and initializes a new wfOperationCtx object.
func newWorkflowOperationCtx(wf *wfv1.Workflow, wfc *WorkflowController) *wfOperationCtx {
// NEVER modify objects from the store. It's a read-only, local cache.
// You can use DeepCopy() to make a deep copy of original object and modify this copy
// Or create a copy manually for better performance
wfCopy := wf.DeepCopyObject().(*wfv1.Workflow)
woc := wfOperationCtx{
wf: wfCopy,
orig: wf,
execWf: wfCopy,
updated: false,
log: log.WithFields(log.Fields{
"workflow": wf.ObjectMeta.Name,
"namespace": wf.ObjectMeta.Namespace,
}),
controller: wfc,
globalParams: make(map[string]string),
volumes: wf.Spec.DeepCopy().Volumes,
deadline: time.Now().UTC().Add(maxOperationTime),
eventRecorder: wfc.eventRecorderManager.Get(wf.Namespace),
preExecutionNodePhases: make(map[string]wfv1.NodePhase),
taskSet: make(map[string]wfv1.Template),
}
if woc.wf.Status.Nodes == nil {
woc.wf.Status.Nodes = make(map[string]wfv1.NodeStatus)
}
if woc.wf.Status.StoredTemplates == nil {
woc.wf.Status.StoredTemplates = make(map[string]wfv1.Template)
}
return &woc
}
// operate is the main operator logic of a workflow. It evaluates the current state of the workflow,
// and its pods and decides how to proceed down the execution path.
// TODO: an error returned by this method should result in requeuing the workflow to be retried at a
// later time
// As you must not call `persistUpdates` twice, you must not call `operate` twice.
func (woc *wfOperationCtx) operate(ctx context.Context) {
defer argoruntime.RecoverFromPanic(woc.log)
defer func() {
if woc.wf.Status.Fulfilled() {
woc.killDaemonedChildren("")
}
woc.persistUpdates(ctx)
}()
defer func() {
if r := recover(); r != nil {
woc.log.WithFields(log.Fields{"stack": string(debug.Stack()), "r": r}).Errorf("Recovered from panic")
if rerr, ok := r.(error); ok {
woc.markWorkflowError(ctx, rerr)
} else {
woc.markWorkflowError(ctx, fmt.Errorf("%v", r))
}
woc.controller.metrics.OperationPanic()
}
}()
woc.log.Info("Processing workflow")
// Set the Execute workflow spec for execution
// ExecWF is a runtime execution spec which merged from Wf, WFT and Wfdefault
err := woc.setExecWorkflow(ctx)
if err != nil {
woc.log.WithError(err).Errorf("Unable to set ExecWorkflow")
return
}
if woc.wf.Status.ArtifactRepositoryRef == nil {
ref, err := woc.controller.artifactRepositories.Resolve(ctx, woc.execWf.Spec.ArtifactRepositoryRef, woc.wf.Namespace)
if err != nil {
woc.markWorkflowError(ctx, fmt.Errorf("failed to resolve artifact repository: %w", err))
return
}
woc.wf.Status.ArtifactRepositoryRef = ref
woc.updated = true
}
repo, err := woc.controller.artifactRepositories.Get(ctx, woc.wf.Status.ArtifactRepositoryRef)
if err != nil {
woc.markWorkflowError(ctx, fmt.Errorf("failed to get artifact repository: %v", err))
return
}
woc.artifactRepository = repo
// Workflow Level Synchronization lock
if woc.execWf.Spec.Synchronization != nil {
acquired, wfUpdate, msg, err := woc.controller.syncManager.TryAcquire(woc.wf, "", woc.execWf.Spec.Synchronization)
if err != nil {
woc.log.Warn("Failed to acquire the lock")
woc.markWorkflowFailed(ctx, fmt.Sprintf("Failed to acquire the synchronization lock. %s", err.Error()))
return
}
woc.updated = wfUpdate
if !acquired {
woc.log.Warn("Workflow processing has been postponed due to concurrency limit")
phase := woc.wf.Status.Phase
if phase == wfv1.WorkflowUnknown {
phase = wfv1.WorkflowPending
}
woc.markWorkflowPhase(ctx, phase, msg)
return
}
}
// Update workflow duration variable
if woc.wf.Status.StartedAt.IsZero() {
woc.globalParams[common.GlobalVarWorkflowDuration] = fmt.Sprintf("%f", time.Duration(0).Seconds())
} else {
woc.globalParams[common.GlobalVarWorkflowDuration] = fmt.Sprintf("%f", time.Since(woc.wf.Status.StartedAt.Time).Seconds())
}
// Populate the phase of all the nodes prior to execution
for _, node := range woc.wf.Status.Nodes {
woc.preExecutionNodePhases[node.ID] = node.Phase
}
if woc.execWf.Spec.Metrics != nil {
localScope, realTimeScope := woc.prepareDefaultMetricScope()
woc.computeMetrics(woc.execWf.Spec.Metrics.Prometheus, localScope, realTimeScope, true)
}
if woc.wf.Status.Phase == wfv1.WorkflowUnknown {
woc.markWorkflowRunning(ctx)
setWfPodNamesAnnotation(woc.wf)
err := woc.createPDBResource(ctx)
if err != nil {
msg := fmt.Sprintf("Unable to create PDB resource for workflow, %s error: %s", woc.wf.Name, err)
woc.markWorkflowFailed(ctx, msg)
return
}
if err := woc.updateWorkflowMetadata(); err != nil {
woc.markWorkflowError(ctx, err)
return
}
woc.workflowDeadline = woc.getWorkflowDeadline()
// Workflow will not be requeued if workflow steps are in pending state.
// Workflow needs to requeue on its deadline,
if woc.workflowDeadline != nil {
woc.requeueAfter(time.Until(*woc.workflowDeadline))
}
woc.wf.Status.EstimatedDuration = woc.estimateWorkflowDuration()
} else {
woc.workflowDeadline = woc.getWorkflowDeadline()
woc.taskResultReconciliation()
err := woc.podReconciliation(ctx)
if err == nil {
woc.failSuspendedAndPendingNodesAfterDeadlineOrShutdown()
}
if err != nil {
woc.log.WithError(err).WithField("workflow", woc.wf.ObjectMeta.Name).Error("workflow timeout")
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowTimedOut", "Workflow timed out")
// TODO: we need to re-add to the workqueue, but should happen in caller
return
}
}
if woc.ShouldSuspend() {
woc.log.Info("workflow suspended")
return
}
if woc.execWf.Spec.Parallelism != nil {
woc.activePods = woc.getActivePods("")
}
// Create a starting template context.
tmplCtx, err := woc.createTemplateContext(wfv1.ResourceScopeLocal, "")
if err != nil {
woc.log.WithError(err).Error("Failed to create a template context")
woc.markWorkflowError(ctx, err)
return
}
err = woc.substituteParamsInVolumes(woc.globalParams)
if err != nil {
woc.log.WithError(err).Error("volumes global param substitution error")
woc.markWorkflowError(ctx, err)
return
}
err = woc.createPVCs(ctx)
if err != nil {
if errorsutil.IsTransientErr(err) {
// Error was most likely caused by a lack of resources.
// In this case, Workflow will be in pending state and requeue.
woc.markWorkflowPhase(ctx, wfv1.WorkflowPending, fmt.Sprintf("Waiting for a PVC to be created. %v", err))
woc.requeue()
return
}
err = fmt.Errorf("pvc create error: %w", err)
woc.log.WithError(err).Error("pvc create error")
woc.markWorkflowError(ctx, err)
return
} else if woc.wf.Status.Phase == wfv1.WorkflowPending {
// Workflow might be in pending state if previous PVC creation is forbidden
woc.markWorkflowRunning(ctx)
}
node, err := woc.executeTemplate(ctx, woc.wf.ObjectMeta.Name, &wfv1.WorkflowStep{Template: woc.execWf.Spec.Entrypoint}, tmplCtx, woc.execWf.Spec.Arguments, &executeTemplateOpts{})
if err != nil {
woc.log.WithError(err).Error("error in entry template execution")
// we wrap this error up to report a clear message
x := fmt.Errorf("error in entry template execution: %w", err)
switch err {
case ErrDeadlineExceeded:
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowTimedOut", x.Error())
case ErrParallelismReached:
default:
if !errorsutil.IsTransientErr(err) && !woc.wf.Status.Phase.Completed() && os.Getenv("BUBBLE_ENTRY_TEMPLATE_ERR") != "false" {
woc.markWorkflowError(ctx, x)
}
}
return
}
workflowStatus := map[wfv1.NodePhase]wfv1.WorkflowPhase{
wfv1.NodePending: wfv1.WorkflowPending,
wfv1.NodeRunning: wfv1.WorkflowRunning,
wfv1.NodeSucceeded: wfv1.WorkflowSucceeded,
wfv1.NodeSkipped: wfv1.WorkflowSucceeded,
wfv1.NodeFailed: wfv1.WorkflowFailed,
wfv1.NodeError: wfv1.WorkflowError,
wfv1.NodeOmitted: wfv1.WorkflowSucceeded,
}[node.Phase]
woc.globalParams[common.GlobalVarWorkflowStatus] = string(workflowStatus)
err = woc.executeWfLifeCycleHook(ctx, tmplCtx)
if err != nil {
woc.markNodeError(node.Name, err)
}
// Reconcile TaskSet and Agent for HTTP templates
woc.taskSetReconciliation(ctx)
if !node.Fulfilled() {
// node can be nil if a workflow created immediately in a parallelism == 0 state
return
}
var onExitNode *wfv1.NodeStatus
if woc.execWf.Spec.HasExitHook() && woc.GetShutdownStrategy().ShouldExecute(true) {
var failures []failedNodeStatus
for _, node := range woc.wf.Status.Nodes {
if node.Phase == wfv1.NodeFailed || node.Phase == wfv1.NodeError {
failures = append(failures,
failedNodeStatus{
DisplayName: node.DisplayName,
Message: node.Message,
TemplateName: node.TemplateName,
Phase: string(node.Phase),
PodName: node.ID,
FinishedAt: node.FinishedAt,
})
}
}
failedNodeBytes, err := json.Marshal(failures)
if err != nil {
woc.log.Errorf("Error marshalling failed nodes list: %+v", err)
// No need to return here
}
// This strconv.Quote is necessary so that the escaped quotes are not removed during parameter substitution
woc.globalParams[common.GlobalVarWorkflowFailures] = strconv.Quote(string(failedNodeBytes))
woc.log.Infof("Running OnExit handler: %s", woc.execWf.Spec.OnExit)
onExitNodeName := common.GenerateOnExitNodeName(woc.wf.ObjectMeta.Name)
exitHook := woc.execWf.Spec.GetExitHook(woc.execWf.Spec.Arguments)
onExitNode, err = woc.executeTemplate(ctx, onExitNodeName, &wfv1.WorkflowStep{Template: exitHook.Template, TemplateRef: exitHook.TemplateRef}, tmplCtx, exitHook.Arguments, &executeTemplateOpts{onExitTemplate: true})
if err != nil {
x := fmt.Errorf("error in exit template execution : %w", err)
switch err {
case ErrDeadlineExceeded:
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowTimedOut", x.Error())
case ErrParallelismReached:
default:
if !errorsutil.IsTransientErr(err) && !woc.wf.Status.Phase.Completed() && os.Getenv("BUBBLE_ENTRY_TEMPLATE_ERR") != "false" {
woc.markWorkflowError(ctx, x)
return
}
}
return
}
// If the onExit node (or any child of the onExit node) requires HTTP reconciliation, do it here
if onExitNode != nil && woc.nodeRequiresTaskSetReconciliation(onExitNode.Name) {
woc.taskSetReconciliation(ctx)
}
if onExitNode == nil || !onExitNode.Fulfilled() {
return
}
}
var workflowMessage string
if node.FailedOrError() && woc.GetShutdownStrategy().Enabled() {
workflowMessage = fmt.Sprintf("Stopped with strategy '%s'", woc.GetShutdownStrategy())
} else {
workflowMessage = node.Message
}
// If we get here, the workflow completed, all PVCs were deleted successfully, and
// exit handlers were executed. We now need to infer the workflow phase from the
// node phase.
switch workflowStatus {
case wfv1.WorkflowSucceeded:
if onExitNode != nil && onExitNode.FailedOrError() {
// if main workflow succeeded, but the exit node was unsuccessful
// the workflow is now considered unsuccessful.
switch onExitNode.Phase {
case wfv1.NodeFailed:
woc.markWorkflowFailed(ctx, onExitNode.Message)
default:
woc.markWorkflowError(ctx, fmt.Errorf(onExitNode.Message))
}
} else {
woc.markWorkflowSuccess(ctx)
}
case wfv1.WorkflowFailed:
woc.markWorkflowFailed(ctx, workflowMessage)
case wfv1.WorkflowError:
woc.markWorkflowPhase(ctx, wfv1.WorkflowError, workflowMessage)
default:
// NOTE: we should never make it here because if the node was 'Running' we should have
// returned earlier.
err = errors.InternalErrorf("Unexpected node phase %s: %+v", woc.wf.ObjectMeta.Name, err)
woc.markWorkflowError(ctx, err)
}
if woc.execWf.Spec.Metrics != nil {
woc.globalParams[common.GlobalVarWorkflowStatus] = string(workflowStatus)
localScope, realTimeScope := woc.prepareMetricScope(node)
woc.computeMetrics(woc.execWf.Spec.Metrics.Prometheus, localScope, realTimeScope, false)
}
err = woc.deletePVCs(ctx)
if err != nil {
woc.log.WithError(err).Warn("failed to delete PVCs")
}
}
func (woc *wfOperationCtx) updateWorkflowMetadata() error {
if md := woc.execWf.Spec.WorkflowMetadata; md != nil {
for n, v := range md.Labels {
woc.wf.Labels[n] = v
}
for n, v := range md.Annotations {
woc.wf.Annotations[n] = v
}
env := env.GetFuncMap(template.EnvMap(woc.globalParams))
for n, f := range md.LabelsFrom {
r, err := expr.Eval(f.Expression, env)
if err != nil {
return fmt.Errorf("failed to evaluate label %q expression %q: %w", n, f.Expression, err)
}
v, ok := r.(string)
if !ok {
return fmt.Errorf("failed to evaluate label %q expression %q evaluted to %T but must be a string", n, f.Expression, r)
}
woc.wf.Labels[n] = v
}
woc.updated = true
}
return nil
}
func (woc *wfOperationCtx) getWorkflowDeadline() *time.Time {
if woc.execWf.Spec.ActiveDeadlineSeconds == nil {
return nil
}
if woc.wf.Status.StartedAt.IsZero() {
return nil
}
startedAt := woc.wf.Status.StartedAt.Truncate(time.Second)
deadline := startedAt.Add(time.Duration(*woc.execWf.Spec.ActiveDeadlineSeconds) * time.Second).UTC()
return &deadline
}
// setGlobalParameters sets the globalParam map with global parameters
func (woc *wfOperationCtx) setGlobalParameters(executionParameters wfv1.Arguments) error {
woc.globalParams[common.GlobalVarWorkflowName] = woc.wf.ObjectMeta.Name
woc.globalParams[common.GlobalVarWorkflowNamespace] = woc.wf.ObjectMeta.Namespace
woc.globalParams[common.GlobalVarWorkflowServiceAccountName] = woc.execWf.Spec.ServiceAccountName
woc.globalParams[common.GlobalVarWorkflowUID] = string(woc.wf.ObjectMeta.UID)
woc.globalParams[common.GlobalVarWorkflowCreationTimestamp] = woc.wf.ObjectMeta.CreationTimestamp.Format(time.RFC3339)
if annotation := woc.wf.ObjectMeta.GetAnnotations(); annotation != nil {
val, ok := annotation[common.AnnotationKeyCronWfScheduledTime]
if ok {
woc.globalParams[common.GlobalVarWorkflowCronScheduleTime] = val
}
}
woc.globalParams[common.GlobalVarWorkflowStatus] = string(woc.wf.Status.Phase)
if woc.execWf.Spec.Priority != nil {
woc.globalParams[common.GlobalVarWorkflowPriority] = strconv.Itoa(int(*woc.execWf.Spec.Priority))
}
for char := range strftime.FormatChars {
cTimeVar := fmt.Sprintf("%s.%s", common.GlobalVarWorkflowCreationTimestamp, string(char))
woc.globalParams[cTimeVar] = strftime.Format("%"+string(char), woc.wf.ObjectMeta.CreationTimestamp.Time)
}
woc.globalParams[common.GlobalVarWorkflowCreationTimestamp+".s"] = strconv.FormatInt(woc.wf.ObjectMeta.CreationTimestamp.Time.Unix(), 10)
woc.globalParams[common.GlobalVarWorkflowCreationTimestamp+".RFC3339"] = woc.wf.ObjectMeta.CreationTimestamp.Format(time.RFC3339)
if workflowParameters, err := json.Marshal(woc.execWf.Spec.Arguments.Parameters); err == nil {
woc.globalParams[common.GlobalVarWorkflowParameters] = string(workflowParameters)
}
for _, param := range executionParameters.Parameters {
if param.Value == nil && param.ValueFrom == nil {
return fmt.Errorf("either value or valueFrom must be specified in order to set global parameter %s", param.Name)
}
if param.ValueFrom != nil && param.ValueFrom.ConfigMapKeyRef != nil {
cmValue, err := common.GetConfigMapValue(woc.controller.configMapInformer, woc.wf.ObjectMeta.Namespace, param.ValueFrom.ConfigMapKeyRef.Name, param.ValueFrom.ConfigMapKeyRef.Key)
if err != nil {
return fmt.Errorf("failed to set global parameter %s from configmap with name %s and key %s: %w",
param.Name, param.ValueFrom.ConfigMapKeyRef.Name, param.ValueFrom.ConfigMapKeyRef.Key, err)
}
woc.globalParams["workflow.parameters."+param.Name] = cmValue
} else {
woc.globalParams["workflow.parameters."+param.Name] = param.Value.String()
}
}
if workflowAnnotations, err := json.Marshal(woc.wf.ObjectMeta.Annotations); err == nil {
woc.globalParams[common.GlobalVarWorkflowAnnotations] = string(workflowAnnotations)
}
for k, v := range woc.wf.ObjectMeta.Annotations {
woc.globalParams["workflow.annotations."+k] = v
}
if workflowLabels, err := json.Marshal(woc.wf.ObjectMeta.Labels); err == nil {
woc.globalParams[common.GlobalVarWorkflowLabels] = string(workflowLabels)
}
for k, v := range woc.wf.ObjectMeta.Labels {
woc.globalParams["workflow.labels."+k] = v
}
if woc.wf.Status.Outputs != nil {
for _, param := range woc.wf.Status.Outputs.Parameters {
if param.HasValue() {
woc.globalParams["workflow.outputs.parameters."+param.Name] = param.GetValue()
}
}
}
return nil
}
// persistUpdates will update a workflow with any updates made during workflow operation.
// It also labels any pods as completed if we have extracted everything we need from it.
// NOTE: a previous implementation used Patch instead of Update, but Patch does not work with
// the fake CRD clientset which makes unit testing extremely difficult.
func (woc *wfOperationCtx) persistUpdates(ctx context.Context) {
if !woc.updated {
return
}
diff.LogChanges(woc.orig, woc.wf)
resource.UpdateResourceDurations(woc.wf)
progress.UpdateProgress(woc.wf)
// You MUST not call `persistUpdates` twice.
// * Fails the `reapplyUpdate` cannot work unless resource versions are different.
// * It will double the number of Kubernetes API requests.
if woc.orig.ResourceVersion != woc.wf.ResourceVersion {
woc.log.Panic("cannot persist updates with mismatched resource versions")
}
wfClient := woc.controller.wfclientset.ArgoprojV1alpha1().Workflows(woc.wf.ObjectMeta.Namespace)
// try and compress nodes if needed
nodes := woc.wf.Status.Nodes
err := woc.controller.hydrator.Dehydrate(woc.wf)
if err != nil {
woc.log.Warnf("Failed to dehydrate: %v", err)
woc.markWorkflowError(ctx, err)
}
// Release all acquired lock for completed workflow
if woc.wf.Status.Synchronization != nil && woc.wf.Status.Fulfilled() {
if woc.controller.syncManager.ReleaseAll(woc.wf) {
woc.log.WithFields(log.Fields{"key": woc.wf.Name}).Info("Released all acquired locks")
}
}
wf, err := wfClient.Update(ctx, woc.wf, metav1.UpdateOptions{})
if err != nil {
woc.log.Warnf("Error updating workflow: %v %s", err, apierr.ReasonForError(err))
if argokubeerr.IsRequestEntityTooLargeErr(err) {
woc.persistWorkflowSizeLimitErr(ctx, wfClient, err)
return
}
if !apierr.IsConflict(err) {
return
}
woc.log.Info("Re-applying updates on latest version and retrying update")
wf, err := woc.reapplyUpdate(ctx, wfClient, nodes)
if err != nil {
woc.log.WithError(err).Info("Failed to re-apply update")
return
}
woc.wf = wf
} else {
woc.wf = wf
woc.controller.hydrator.HydrateWithNodes(woc.wf, nodes)
}
// The workflow returned from wfClient.Update doesn't have a TypeMeta associated
// with it, so copy from the original workflow.
woc.wf.TypeMeta = woc.orig.TypeMeta
// Create WorkflowNode* events for nodes that have changed phase
woc.recordNodePhaseChangeEvents(woc.orig.Status.Nodes, woc.wf.Status.Nodes)
if !woc.controller.hydrator.IsHydrated(woc.wf) {
panic("workflow should be hydrated")
}
woc.log.WithFields(log.Fields{"resourceVersion": woc.wf.ResourceVersion, "phase": woc.wf.Status.Phase}).Info("Workflow update successful")
switch os.Getenv("INFORMER_WRITE_BACK") {
// By default we write back (as per v2.11), this does not reduce errors, but does reduce
// conflicts and therefore we log fewer warning messages.
case "", "true":
if err := woc.writeBackToInformer(); err != nil {
woc.markWorkflowError(ctx, err)
return
}
case "false":
time.Sleep(1 * time.Second)
}
err = woc.removeCompletedTaskSetStatus(ctx)
if err != nil {
woc.log.WithError(err).Warn("error updating taskset")
}
if woc.wf.Status.Phase.Completed() {
if err := woc.deleteTaskResults(ctx); err != nil {
woc.log.WithError(err).Warn("failed to delete task-results")
}
}
// It is important that we *never* label pods as completed until we successfully updated the workflow
// Failing to do so means we can have inconsistent state.
// Pods may be be labeled multiple times.
woc.queuePodsForCleanup()
}
func (woc *wfOperationCtx) deleteTaskResults(ctx context.Context) error {
deletePropagationBackground := metav1.DeletePropagationBackground
return woc.controller.wfclientset.ArgoprojV1alpha1().WorkflowTaskResults(woc.wf.Namespace).
DeleteCollection(
ctx,
metav1.DeleteOptions{PropagationPolicy: &deletePropagationBackground},
metav1.ListOptions{LabelSelector: common.LabelKeyWorkflow + "=" + woc.wf.Name},
)
}
func (woc *wfOperationCtx) writeBackToInformer() error {
un, err := wfutil.ToUnstructured(woc.wf)
if err != nil {
return fmt.Errorf("failed to convert workflow to unstructured: %w", err)
}
err = woc.controller.wfInformer.GetStore().Update(un)
if err != nil {
return fmt.Errorf("failed to update informer store: %w", err)
}
return nil
}
// persistWorkflowSizeLimitErr will fail a the workflow with an error when we hit the resource size limit
// See https://github.com/argoproj/argo-workflows/issues/913
func (woc *wfOperationCtx) persistWorkflowSizeLimitErr(ctx context.Context, wfClient v1alpha1.WorkflowInterface, err error) {
woc.wf = woc.orig.DeepCopy()
woc.markWorkflowError(ctx, err)
_, err = wfClient.Update(ctx, woc.wf, metav1.UpdateOptions{})
if err != nil {
woc.log.Warnf("Error updating workflow with size error: %v", err)
}
}
// reapplyUpdate GETs the latest version of the workflow, re-applies the updates and
// retries the UPDATE multiple times. For reasoning behind this technique, see:
// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
func (woc *wfOperationCtx) reapplyUpdate(ctx context.Context, wfClient v1alpha1.WorkflowInterface, nodes wfv1.Nodes) (*wfv1.Workflow, error) {
// if this condition is true, then this func will always error
if woc.orig.ResourceVersion != woc.wf.ResourceVersion {
woc.log.Panic("cannot re-apply update with mismatched resource versions")
}
err := woc.controller.hydrator.Hydrate(woc.orig)
if err != nil {
return nil, err
}
// First generate the patch
oldData, err := json.Marshal(woc.orig)
if err != nil {
return nil, err
}
woc.controller.hydrator.HydrateWithNodes(woc.wf, nodes)
newData, err := json.Marshal(woc.wf)
if err != nil {
return nil, err
}
patchBytes, err := jsonpatch.CreateMergePatch(oldData, newData)
if err != nil {
return nil, err
}
// Next get latest version of the workflow, apply the patch and retry the update
attempt := 1
for {
currWf, err := wfClient.Get(ctx, woc.wf.ObjectMeta.Name, metav1.GetOptions{})
if err != nil {
return nil, err
}
// There is something about having informer indexers (introduced in v2.12) that means we are more likely to operate on the
// previous version of the workflow. This means under high load, a previously successful workflow could
// be operated on again. This can error (e.g. if any pod was deleted as part of clean-up). This check prevents that.
// https://github.com/argoproj/argo-workflows/issues/4798
if currWf.Status.Fulfilled() {
return nil, fmt.Errorf("must never update completed workflows")
}
err = woc.controller.hydrator.Hydrate(currWf)
if err != nil {
return nil, err
}
for id, node := range woc.wf.Status.Nodes {
currNode, exists := currWf.Status.Nodes[id]
if exists && currNode.Fulfilled() && node.Phase != currNode.Phase {
return nil, fmt.Errorf("must never update completed node %s", id)
}
}
currWfBytes, err := json.Marshal(currWf)
if err != nil {
return nil, err
}
newWfBytes, err := jsonpatch.MergePatch(currWfBytes, patchBytes)
if err != nil {
return nil, err
}
var newWf wfv1.Workflow
err = json.Unmarshal(newWfBytes, &newWf)
if err != nil {
return nil, err
}
err = woc.controller.hydrator.Dehydrate(&newWf)
if err != nil {
return nil, err
}
wf, err := wfClient.Update(ctx, &newWf, metav1.UpdateOptions{})
if err == nil {
woc.log.Infof("Update retry attempt %d successful", attempt)
woc.controller.hydrator.HydrateWithNodes(wf, nodes)
return wf, nil
}
attempt++
woc.log.Warnf("Update retry attempt %d failed: %v", attempt, err)
if attempt > 5 {
return nil, err
}
}
}
// requeue this workflow onto the workqueue for later processing
func (woc *wfOperationCtx) requeueAfter(afterDuration time.Duration) {
key, _ := cache.MetaNamespaceKeyFunc(woc.wf)
woc.controller.wfQueue.AddAfter(key, afterDuration)
}
func (woc *wfOperationCtx) requeue() {
key, _ := cache.MetaNamespaceKeyFunc(woc.wf)
woc.controller.wfQueue.AddRateLimited(key)
}
// processNodeRetries updates the retry node state based on the child node state and the retry strategy and returns the node.
func (woc *wfOperationCtx) processNodeRetries(node *wfv1.NodeStatus, retryStrategy wfv1.RetryStrategy, opts *executeTemplateOpts) (*wfv1.NodeStatus, bool, error) {
if node.Fulfilled() {
return node, true, nil
}
lastChildNode := getChildNodeIndex(node, woc.wf.Status.Nodes, -1)
if retryStrategy.Expression != "" && len(node.Children) > 0 {
localScope := buildRetryStrategyLocalScope(node, woc.wf.Status.Nodes)
scope := env.GetFuncMap(localScope)
shouldContinue, err := argoexpr.EvalBool(retryStrategy.Expression, scope)
if err != nil {
return nil, false, err
}
if !shouldContinue {
return woc.markNodePhase(node.Name, lastChildNode.Phase, "retryStrategy.expression evaluated to false"), true, nil
}
}
if lastChildNode == nil {
return node, true, nil
}
if !lastChildNode.Fulfilled() {
// last child node is still running.
return node, true, nil
}
if !lastChildNode.FailedOrError() {
node.Outputs = lastChildNode.Outputs.DeepCopy()
woc.wf.Status.Nodes[node.ID] = *node
return woc.markNodePhase(node.Name, wfv1.NodeSucceeded), true, nil
}
if woc.GetShutdownStrategy().Enabled() || (woc.workflowDeadline != nil && time.Now().UTC().After(*woc.workflowDeadline)) {
var message string
if woc.GetShutdownStrategy().Enabled() {
message = fmt.Sprintf("Stopped with strategy '%s'", woc.GetShutdownStrategy())
} else {
message = fmt.Sprintf("retry exceeded workflow deadline %s", *woc.workflowDeadline)
}
woc.log.Infoln(message)
return woc.markNodePhase(node.Name, lastChildNode.Phase, message), true, nil
}
if retryStrategy.Backoff != nil {
maxDurationDeadline := time.Time{}
// Process max duration limit
if retryStrategy.Backoff.MaxDuration != "" && len(node.Children) > 0 {
maxDuration, err := parseStringToDuration(retryStrategy.Backoff.MaxDuration)
if err != nil {
return nil, false, err
}
firstChildNode := getChildNodeIndex(node, woc.wf.Status.Nodes, 0)
maxDurationDeadline = firstChildNode.StartedAt.Add(maxDuration)
if time.Now().After(maxDurationDeadline) {
woc.log.Infoln("Max duration limit exceeded. Failing...")
return woc.markNodePhase(node.Name, lastChildNode.Phase, "Max duration limit exceeded"), true, nil
}
}
// Max duration limit hasn't been exceeded, process back off
if retryStrategy.Backoff.Duration == "" {
return nil, false, fmt.Errorf("no base duration specified for retryStrategy")
}
baseDuration, err := parseStringToDuration(retryStrategy.Backoff.Duration)
if err != nil {
return nil, false, err
}
timeToWait := baseDuration
retryStrategyBackoffFactor, err := intstr.Int32(retryStrategy.Backoff.Factor)
if err != nil {
return nil, false, err
}
if retryStrategyBackoffFactor != nil && *retryStrategyBackoffFactor > 0 {
// Formula: timeToWait = duration * factor^retry_number
// Note that timeToWait should equal to duration for the first retry attempt.
timeToWait = baseDuration * time.Duration(math.Pow(float64(*retryStrategyBackoffFactor), float64(len(node.Children)-1)))
}
waitingDeadline := lastChildNode.FinishedAt.Add(timeToWait)
// If the waiting deadline is after the max duration deadline, then it's futile to wait until then. Stop early
if !maxDurationDeadline.IsZero() && waitingDeadline.After(maxDurationDeadline) {
woc.log.Infoln("Backoff would exceed max duration limit. Failing...")
return woc.markNodePhase(node.Name, lastChildNode.Phase, "Backoff would exceed max duration limit"), true, nil
}
// See if we have waited past the deadline
if time.Now().Before(waitingDeadline) && int32(len(node.Children)) <= retryStrategy.Limit.IntVal {
woc.requeueAfter(timeToWait)
retryMessage := fmt.Sprintf("Backoff for %s", humanize.Duration(timeToWait))
return woc.markNodePhase(node.Name, node.Phase, retryMessage), false, nil
}
woc.log.WithField("node", node.Name).Infof("node has maxDuration set, setting executionDeadline to: %s", humanize.Timestamp(maxDurationDeadline))
opts.executionDeadline = maxDurationDeadline
node = woc.markNodePhase(node.Name, node.Phase, "")
}
var retryOnFailed bool
var retryOnError bool
switch retryStrategy.RetryPolicy {
case wfv1.RetryPolicyAlways:
retryOnFailed = true
retryOnError = true
case wfv1.RetryPolicyOnError:
retryOnFailed = false
retryOnError = true
case wfv1.RetryPolicyOnTransientError:
if (lastChildNode.Phase == wfv1.NodeFailed || lastChildNode.Phase == wfv1.NodeError) && errorsutil.IsTransientErr(errors.InternalError(lastChildNode.Message)) {
retryOnFailed = true
retryOnError = true
}
case wfv1.RetryPolicyOnFailure, "":
retryOnFailed = true
retryOnError = false
default:
return nil, false, fmt.Errorf("%s is not a valid RetryPolicy", retryStrategy.RetryPolicy)
}
if (lastChildNode.Phase == wfv1.NodeFailed && !retryOnFailed) || (lastChildNode.Phase == wfv1.NodeError && !retryOnError) {
woc.log.Infof("Node not set to be retried after status: %s", lastChildNode.Phase)
return woc.markNodePhase(node.Name, lastChildNode.Phase, lastChildNode.Message), true, nil
}
if !lastChildNode.CanRetry() {
woc.log.Infof("Node cannot be retried. Marking it failed")
return woc.markNodePhase(node.Name, lastChildNode.Phase, lastChildNode.Message), true, nil
}
limit, err := intstr.Int32(retryStrategy.Limit)
if err != nil {
return nil, false, err
}
if retryStrategy.Limit != nil && limit != nil && int32(len(node.Children)) > *limit {
woc.log.Infoln("No more retries left. Failing...")
return woc.markNodePhase(node.Name, lastChildNode.Phase, "No more retries left"), true, nil
}
woc.log.Infof("%d child nodes of %s failed. Trying again...", len(node.Children), node.Name)
return node, true, nil
}
// podReconciliation is the process by which a workflow will examine all its related
// pods and update the node state before continuing the evaluation of the workflow.
// Records all pods which were observed completed, which will be labeled completed=true
// after successful persist of the workflow.
func (woc *wfOperationCtx) podReconciliation(ctx context.Context) error {
podList, err := woc.getAllWorkflowPods()
if err != nil {
return err
}
seenPods := make(map[string]*apiv1.Pod)
seenPodLock := &sync.Mutex{}
wfNodesLock := &sync.RWMutex{}
podRunningCondition := wfv1.Condition{Type: wfv1.ConditionTypePodRunning, Status: metav1.ConditionFalse}
performAssessment := func(pod *apiv1.Pod) {
if pod == nil {
return
}
if woc.isAgentPod(pod) {
woc.updateAgentPodStatus(ctx, pod)
return
}
nodeID := woc.nodeID(pod)
seenPodLock.Lock()
seenPods[nodeID] = pod
seenPodLock.Unlock()
wfNodesLock.Lock()
defer wfNodesLock.Unlock()
if node, ok := woc.wf.Status.Nodes[nodeID]; ok {
if newState := woc.assessNodeStatus(pod, &node); newState != nil {
woc.addOutputsToGlobalScope(newState.Outputs)
if newState.MemoizationStatus != nil {
if newState.Succeeded() {
c := woc.controller.cacheFactory.GetCache(controllercache.ConfigMapCache, newState.MemoizationStatus.CacheName)
err := c.Save(ctx, newState.MemoizationStatus.Key, newState.ID, newState.Outputs)
if err != nil {
woc.log.WithFields(log.Fields{"nodeID": newState.ID}).WithError(err).Error("Failed to save node outputs to cache")
newState.Phase = wfv1.NodeError
newState.Message = err.Error()
}
}