forked from argoproj/argo-workflows
/
operator.go
3049 lines (2806 loc) · 112 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 (
"encoding/json"
"fmt"
"math"
"reflect"
"regexp"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"time"
"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"
"github.com/valyala/fasttemplate"
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/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/utils/pointer"
"sigs.k8s.io/yaml"
"github.com/argoproj/argo/config"
"github.com/argoproj/argo/errors"
"github.com/argoproj/argo/pkg/apis/workflow"
wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo/pkg/client/clientset/versioned/typed/workflow/v1alpha1"
"github.com/argoproj/argo/util"
errorsutil "github.com/argoproj/argo/util/errors"
"github.com/argoproj/argo/util/intstr"
"github.com/argoproj/argo/util/resource"
"github.com/argoproj/argo/util/retry"
"github.com/argoproj/argo/workflow/common"
controllercache "github.com/argoproj/argo/workflow/controller/cache"
"github.com/argoproj/argo/workflow/metrics"
"github.com/argoproj/argo/workflow/templateresolution"
wfutil "github.com/argoproj/argo/workflow/util"
"github.com/argoproj/argo/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 corralate logs with a workflow
log *log.Entry
// controller reference to workflow controller
controller *WorkflowController
// 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 *config.ArtifactRepository
// map of pods which need to be labeled with completed=true
completedPods map[string]bool
// map of pods which is identified as succeeded=true
succeededPods map[string]bool
// 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`, with two exceptions for user editable fields:
// 1. `wf.Spec.Suspend`
// 2. `wf.Spec.Shutdown`
execWf *wfv1.Workflow
}
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")
)
// maxOperationTime is the maximum time a workflow operation is allowed to run
// for before requeuing the workflow onto the workqueue.
const maxOperationTime = 10 * 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
woc := wfOperationCtx{
wf: wf.DeepCopyObject().(*wfv1.Workflow),
orig: wf,
execWf: wf,
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,
artifactRepository: &wfc.Config.ArtifactRepository,
completedPods: make(map[string]bool),
succeededPods: make(map[string]bool),
deadline: time.Now().UTC().Add(maxOperationTime),
eventRecorder: wfc.eventRecorderManager.Get(wf.Namespace),
preExecutionNodePhases: make(map[string]wfv1.NodePhase),
}
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
func (woc *wfOperationCtx) operate() {
defer func() {
if woc.wf.Status.Fulfilled() {
_ = woc.killDaemonedChildren("")
}
woc.persistUpdates()
}()
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(rerr, true)
} else {
woc.markWorkflowPhase(wfv1.NodeError, true, fmt.Sprintf("%v", r))
}
woc.controller.metrics.OperationPanic()
}
}()
woc.log.Infof("Processing workflow")
// Load the WorkflowSpec for execution
execTmplRef, execArgs, err := woc.loadExecutionSpec()
if err != nil {
woc.log.WithError(err).Errorf("Unable to get Workflow Template Reference for workflow")
woc.markWorkflowError(err, true)
return
}
// Update workflow duration variable
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
}
woc.setGlobalParameters(execArgs)
// Perform one-time workflow validation
if woc.wf.Status.Phase == "" {
woc.markWorkflowRunning()
err := woc.createPDBResource()
if err != nil {
msg := fmt.Sprintf("Unable to create PDB resource for workflow, %s error: %s", woc.wf.Name, err)
woc.markWorkflowFailed(msg)
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowFailed", msg)
return
}
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeNormal, "WorkflowRunning", "Workflow Running")
validateOpts := validate.ValidateOpts{ContainerRuntimeExecutor: woc.controller.GetContainerRuntimeExecutor()}
wftmplGetter := templateresolution.WrapWorkflowTemplateInterface(woc.controller.wfclientset.ArgoprojV1alpha1().WorkflowTemplates(woc.wf.Namespace))
cwftmplGetter := templateresolution.WrapClusterWorkflowTemplateInterface(woc.controller.wfclientset.ArgoprojV1alpha1().ClusterWorkflowTemplates())
// Validate the execution wfSpec
wfConditions, err := validate.ValidateWorkflow(wftmplGetter, cwftmplGetter, woc.wf, validateOpts)
if err != nil {
msg := fmt.Sprintf("invalid spec: %s", err.Error())
woc.markWorkflowFailed(msg)
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowFailed", msg)
return
}
// If we received conditions during validation (such as SpecWarnings), add them to the Workflow object
if len(*wfConditions) > 0 {
woc.wf.Status.Conditions.JoinConditions(wfConditions)
woc.updated = true
}
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.requeue(time.Until(*woc.workflowDeadline))
}
if woc.execWf.Spec.Metrics != nil {
realTimeScope := map[string]func() float64{common.GlobalVarWorkflowDuration: func() float64 {
return time.Since(woc.wf.Status.StartedAt.Time).Seconds()
}}
woc.computeMetrics(woc.execWf.Spec.Metrics.Prometheus, woc.globalParams, realTimeScope, true)
}
} else {
woc.workflowDeadline = woc.getWorkflowDeadline()
err := woc.podReconciliation()
if err == nil {
err = 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.wf.Spec.Suspend != nil && *woc.wf.Spec.Suspend {
woc.log.Infof("workflow suspended")
return
}
if woc.execWf.Spec.Parallelism != nil {
woc.activePods = woc.countActivePods()
}
// 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(err, true)
return
}
if woc.execWf.Spec.ArtifactRepositoryRef != nil {
repo, err := woc.getArtifactRepositoryByRef(woc.execWf.Spec.ArtifactRepositoryRef)
if err == nil {
woc.artifactRepository = repo
} else {
msg := fmt.Sprintf("Failed to load artifact repository configMap: %+v", err)
woc.log.Errorf(msg)
woc.markWorkflowError(err, true)
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowFailed", msg)
return
}
}
err = woc.substituteParamsInVolumes(woc.globalParams)
if err != nil {
woc.log.WithError(err).Error("volumes global param substitution error")
woc.markWorkflowError(err, true)
return
}
err = woc.createPVCs()
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(wfv1.NodePending, false, fmt.Sprintf("Waiting for a PVC to be created. %v", err))
woc.requeue(10 * time.Second)
return
}
msg := "pvc create error"
woc.log.WithError(err).Error(msg)
woc.markWorkflowError(err, true)
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowFailed", fmt.Sprintf("%s %s: %+v", woc.wf.ObjectMeta.Name, msg, err))
return
} else if woc.wf.Status.Phase == wfv1.NodePending {
// Workflow might be in pending state if previous PVC creation is forbidden
woc.markWorkflowRunning()
}
node, err := woc.executeTemplate(woc.wf.ObjectMeta.Name, execTmplRef, tmplCtx, execArgs, &executeTemplateOpts{})
if err != nil {
// the error are handled in the callee so just log it.
msg := "error in entry template execution"
woc.log.WithError(err).Error(msg)
msg = fmt.Sprintf("%s %s: %+v", woc.wf.Name, msg, err)
switch err {
case ErrDeadlineExceeded:
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowTimedOut", msg)
default:
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowFailed", msg)
}
return
}
if node == nil || !node.Fulfilled() {
// node can be nil if a workflow created immediately in a parallelism == 0 state
return
}
workflowStatus := node.Phase
var onExitNode *wfv1.NodeStatus
if woc.execWf.Spec.OnExit != "" && woc.wf.Spec.Shutdown.ShouldExecute(true) {
if workflowStatus == wfv1.NodeSkipped {
// treat skipped the same as Succeeded for workflow.status
woc.globalParams[common.GlobalVarWorkflowStatus] = string(wfv1.NodeSucceeded)
} else {
woc.globalParams[common.GlobalVarWorkflowStatus] = string(workflowStatus)
}
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)
onExitNode, err = woc.executeTemplate(onExitNodeName, &wfv1.WorkflowStep{Template: woc.execWf.Spec.OnExit}, tmplCtx, execArgs, &executeTemplateOpts{onExitTemplate: true})
if err != nil {
// the error are handled in the callee so just log it.
woc.log.WithError(err).Error("error in exit template execution")
return
}
if onExitNode == nil || !onExitNode.Fulfilled() {
return
}
}
err = woc.deletePVCs()
if err != nil {
msg := "failed to delete PVCs"
woc.log.WithError(err).Errorf(msg)
// Mark the workflow with an error message and return, but intentionally do not
// markCompletion so that we can retry PVC deletion (TODO: use workqueue.ReAdd())
// This error phase may be cleared if a subsequent delete attempt is successful.
woc.markWorkflowError(err, false)
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowFailed", fmt.Sprintf("%s %s: %+v", woc.wf.ObjectMeta.Name, msg, err))
return
}
var workflowMessage string
if node.FailedOrError() && woc.execWf.Spec.Shutdown != "" {
workflowMessage = fmt.Sprintf("Stopped with strategy '%s'", woc.execWf.Spec.Shutdown)
} 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.NodeSucceeded, wfv1.NodeSkipped:
if onExitNode != nil && onExitNode.FailedOrError() {
// if main workflow succeeded, but the exit node was unsuccessful
// the workflow is now considered unsuccessful.
woc.markWorkflowPhase(onExitNode.Phase, true, onExitNode.Message)
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowFailed", onExitNode.Message)
} else {
woc.markWorkflowSuccess()
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeNormal, "WorkflowSucceeded", "Workflow completed")
}
case wfv1.NodeFailed:
woc.markWorkflowFailed(workflowMessage)
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowFailed", workflowMessage)
case wfv1.NodeError:
woc.markWorkflowPhase(wfv1.NodeError, true, workflowMessage)
woc.eventRecorder.Event(woc.wf, apiv1.EventTypeWarning, "WorkflowFailed", workflowMessage)
default:
// NOTE: we should never make it here because if the the node was 'Running'
// we should have returned earlier.
err = errors.InternalErrorf("Unexpected node phase %s: %+v", woc.wf.ObjectMeta.Name, err)
woc.markWorkflowError(err, true)
}
if woc.execWf.Spec.Metrics != nil {
realTimeScope := map[string]func() float64{common.GlobalVarWorkflowDuration: func() float64 {
return node.FinishedAt.Sub(node.StartedAt.Time).Seconds()
}}
woc.globalParams[common.GlobalVarWorkflowStatus] = string(workflowStatus)
woc.computeMetrics(woc.execWf.Spec.Metrics.Prometheus, woc.globalParams, realTimeScope, false)
}
}
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) {
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 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)
}
if workflowParameters, err := json.Marshal(woc.execWf.Spec.Arguments.Parameters); err == nil {
woc.globalParams[common.GlobalVarWorkflowParameters] = string(workflowParameters)
}
for _, param := range executionParameters.Parameters {
woc.globalParams["workflow.parameters."+param.Name] = *param.Value
}
for k, v := range woc.wf.ObjectMeta.Annotations {
woc.globalParams["workflow.annotations."+k] = v
}
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 {
woc.globalParams["workflow.outputs.parameters."+param.Name] = *param.Value
}
}
}
// 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() {
if !woc.updated {
return
}
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(err, true)
}
// Release all acquired lock for completed workflow
if woc.wf.Status.Synchronization != nil && woc.wf.Status.Fulfilled() {
if woc.controller.syncManager.ReleaseAll(woc.wf) {
log.WithFields(log.Fields{"key": woc.wf.Name}).Info("Released all acquired locks")
}
}
wf, err := wfClient.Update(woc.wf)
if err != nil {
woc.log.Warnf("Error updating workflow: %v %s", err, apierr.ReasonForError(err))
if argokubeerr.IsRequestEntityTooLargeErr(err) {
woc.persistWorkflowSizeLimitErr(wfClient, err)
return
}
if !apierr.IsConflict(err) {
return
}
woc.log.Info("Re-applying updates on latest version and retrying update")
wf, err := woc.reapplyUpdate(wfClient, nodes)
if err != nil {
woc.log.Infof("Failed to re-apply update: %+v", err)
return
}
woc.wf = wf
} else {
woc.wf = wf
woc.controller.hydrator.HydrateWithNodes(woc.wf, 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")
// HACK(jessesuen) after we successfully persist an update to the workflow, the informer's
// cache is now invalid. It's very common that we will need to immediately re-operate on a
// workflow due to queuing by the pod workers. The following sleep gives a *chance* for the
// informer's cache to catch up to the version of the workflow we just persisted. Without
// this sleep, the next worker to work on this workflow will very likely operate on a stale
// object and redo work.
//
// This line was removed in v2.9.0, but issues arose with the controller picking up outdated versions of workflows,
// operating on them, then attempting to update the resources on the cluster. Since the workflows were outdated,
// conflicts arose when attempting to update, causing our conflict resolution code to be invoked. The conflict
// resolution code was not perfect and workflow information was not correctly persisted, causing undefined behavior.
// This line was reintroduced in v2.9.5, and should remain as long as we use our current informer pattern.
time.Sleep(1 * time.Second)
// 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.
// TODO: The completedPods will be labeled multiple times. I think it would be improved in the future.
// Send succeeded pods or completed pods to gcPods channel to delete it later depend on the PodGCStrategy.
// Notice we do not need to label the pod if we will delete it later for GC. Otherwise, that may even result in
// errors if we label a pod that was deleted already.
if woc.execWf.Spec.PodGC != nil {
switch woc.execWf.Spec.PodGC.Strategy {
case wfv1.PodGCOnPodSuccess:
for podName := range woc.succeededPods {
woc.controller.gcPods <- fmt.Sprintf("%s/%s", woc.wf.ObjectMeta.Namespace, podName)
}
case wfv1.PodGCOnPodCompletion:
for podName := range woc.completedPods {
woc.controller.gcPods <- fmt.Sprintf("%s/%s", woc.wf.ObjectMeta.Namespace, podName)
}
}
} else {
// label pods which will not be deleted
for podName := range woc.completedPods {
woc.controller.completedPods <- fmt.Sprintf("%s/%s", woc.wf.ObjectMeta.Namespace, podName)
}
}
}
// persistWorkflowSizeLimitErr will fail a the workflow with an error when we hit the resource size limit
// See https://github.com/argoproj/argo/issues/913
func (woc *wfOperationCtx) persistWorkflowSizeLimitErr(wfClient v1alpha1.WorkflowInterface, err error) {
woc.wf = woc.orig.DeepCopy()
woc.markWorkflowError(err, true)
_, err = wfClient.Update(woc.wf)
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/api-conventions.md#concurrency-control-and-consistency
func (woc *wfOperationCtx) reapplyUpdate(wfClient v1alpha1.WorkflowInterface, nodes wfv1.Nodes) (*wfv1.Workflow, error) {
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(woc.wf.ObjectMeta.Name, metav1.GetOptions{})
if err != nil {
return nil, err
}
err = woc.controller.hydrator.Hydrate(currWf)
if err != nil {
return nil, err
}
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(&newWf)
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) requeue(afterDuration time.Duration) {
key, err := cache.MetaNamespaceKeyFunc(woc.wf)
if err != nil {
woc.log.Errorf("Failed to requeue workflow %s: %v", woc.wf.ObjectMeta.Name, err)
return
}
woc.controller.wfQueue.AddAfter(key, afterDuration)
}
// 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 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.execWf.Spec.Shutdown != "" || (woc.workflowDeadline != nil && time.Now().UTC().After(*woc.workflowDeadline)) {
var message string
if woc.execWf.Spec.Shutdown != "" {
message = fmt.Sprintf("Stopped with strategy '%s'", woc.execWf.Spec.Shutdown)
} 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 > 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) {
woc.requeue(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.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 && 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() error {
podList, err := woc.getAllWorkflowPods()
if err != nil {
return err
}
seenPods := make(map[string]*apiv1.Pod)
seenPodLock := &sync.Mutex{}
wfNodesLock := &sync.RWMutex{}
performAssessment := func(pod *apiv1.Pod) {
if pod == nil {
return
}
nodeNameForPod := pod.Annotations[common.AnnotationKeyNodeName]
nodeID := woc.wf.NodeID(nodeNameForPod)
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.wf.Status.Nodes[nodeID] = *newState
woc.addOutputsToGlobalScope(node.Outputs)
if node.MemoizationStatus != nil {
c := *woc.controller.cacheFactory.GetCache(controllercache.ConfigMapCache, node.MemoizationStatus.CacheName)
err := c.Save(node.MemoizationStatus.Key, node.ID, node.Outputs)
if err != nil {
woc.log.WithFields(log.Fields{"nodeID": node.ID}).WithError(err).Error("Failed to save node outputs to cache")
node.Phase = wfv1.NodeError
}
}
woc.updated = true
}
node := woc.wf.Status.Nodes[pod.ObjectMeta.Name]
if node.Fulfilled() && !node.IsDaemoned() {
if tmpVal, tmpOk := pod.Labels[common.LabelKeyCompleted]; tmpOk {
if tmpVal == "true" {
return
}
}
woc.completedPods[pod.ObjectMeta.Name] = true
if woc.shouldPrintPodSpec(node) {
printPodSpecLog(pod, woc.wf.Name)
}
if !woc.orig.Status.Nodes[node.ID].Fulfilled() {
woc.onNodeComplete(&node)
}
}
if node.Succeeded() {
woc.succeededPods[pod.ObjectMeta.Name] = true
}
}
}
parallelPodNum := make(chan string, 500)
var wg sync.WaitGroup
for _, pod := range podList.Items {
parallelPodNum <- pod.Name
wg.Add(1)
go func(tmpPod apiv1.Pod) {
defer wg.Done()
performAssessment(&tmpPod)
err = woc.applyExecutionControl(&tmpPod, wfNodesLock)
if err != nil {
woc.log.Warnf("Failed to apply execution control to pod %s", tmpPod.Name)
}
<-parallelPodNum
}(pod)
}
wg.Wait()
// Now check for deleted pods. Iterate our nodes. If any one of our nodes does not show up in
// the seen list it implies that the pod was deleted without the controller seeing the event.
// It is now impossible to infer pod status. The only thing we can do at this point is to mark
// the node with Error.
for nodeID, node := range woc.wf.Status.Nodes {
if node.Type != wfv1.NodeTypePod || node.Fulfilled() || node.StartedAt.IsZero() {
// node is not a pod, it is already complete, or it can be re-run.
continue
}
if _, ok := seenPods[nodeID]; !ok {
// If the node is pending and the pod does not exist, it could be the case that we want to try to submit it
// again instead of marking it as an error. Check if that's the case.
if node.Pending() {
tmplCtx, err := woc.createTemplateContext(node.GetTemplateScope())
if err != nil {
return err
}
_, tmpl, _, err := tmplCtx.ResolveTemplate(&node)
if err != nil {
return err
}
// The pod may have been intentionally deleted (e.g. `kubectl delete pod`).
// If the user has specified re-submit allowed, so we do not mark the node as error (yet).
if tmpl.IsResubmitPendingPods() {
// We want to resubmit. Continue and do not mark as error.
continue
}
if tmpl.Synchronization != nil {
// Wait to acquire the lock
continue
}
}
node.Message = "pod deleted"
node.Phase = wfv1.NodeError
// FinishedAt must be set since retry strategy depends on it to determine the backoff duration.
// See processNodeRetries for more details.
node.FinishedAt = metav1.Time{Time: time.Now().UTC()}
woc.wf.Status.Nodes[nodeID] = node
woc.log.Warnf("pod %s deleted", nodeID)
woc.updated = true
} else {
// At this point we are certain that the pod associated with our node is running or has been run;
// it is safe to extract the k8s-node information given this knowledge.
if node.HostNodeName != seenPods[nodeID].Spec.NodeName {
node.HostNodeName = seenPods[nodeID].Spec.NodeName
woc.wf.Status.Nodes[nodeID] = node
woc.updated = true
}
}
}
return nil
}
// shouldPrintPodSpec return eligible to print to the pod spec
func (woc *wfOperationCtx) shouldPrintPodSpec(node wfv1.NodeStatus) bool {
return woc.controller.Config.PodSpecLogStrategy.AllPods ||
(woc.controller.Config.PodSpecLogStrategy.FailedPod && node.FailedOrError())
}
//fails any suspended and pending nodes if the workflow deadline has passed
func (woc *wfOperationCtx) failSuspendedAndPendingNodesAfterDeadlineOrShutdown() error {
deadlineExceeded := woc.workflowDeadline != nil && time.Now().UTC().After(*woc.workflowDeadline)
if woc.execWf.Spec.Shutdown != "" || deadlineExceeded {
for _, node := range woc.wf.Status.Nodes {
if node.IsActiveSuspendNode() || (node.Phase == wfv1.NodePending && deadlineExceeded) {
var message string
if woc.execWf.Spec.Shutdown != "" {
message = fmt.Sprintf("Stopped with strategy '%s'", woc.execWf.Spec.Shutdown)
} else {
message = "Step exceeded its deadline"
}
woc.markNodePhase(node.Name, wfv1.NodeFailed, message)
}
}
}
return nil
}
// countActivePods counts the number of active (Pending/Running) pods.
// Optionally restricts it to a template invocation (boundaryID)
func (woc *wfOperationCtx) countActivePods(boundaryIDs ...string) int64 {
var boundaryID = ""
if len(boundaryIDs) > 0 {
boundaryID = boundaryIDs[0]
}
var activePods int64
// if we care about parallelism, count the active pods at the template level
for _, node := range woc.wf.Status.Nodes {
if node.Type != wfv1.NodeTypePod {
continue
}
if boundaryID != "" && node.BoundaryID != boundaryID {
continue
}
switch node.Phase {
case wfv1.NodePending, wfv1.NodeRunning:
activePods++
}
}
return activePods
}
// countActiveChildren counts the number of active (Pending/Running) children nodes of parent parentName
func (woc *wfOperationCtx) countActiveChildren(boundaryIDs ...string) int64 {
var boundaryID = ""
if len(boundaryIDs) > 0 {
boundaryID = boundaryIDs[0]
}
var activeChildren int64
// if we care about parallelism, count the active pods at the template level
for _, node := range woc.wf.Status.Nodes {
if boundaryID != "" && node.BoundaryID != boundaryID {
continue
}
switch node.Type {
case wfv1.NodeTypePod, wfv1.NodeTypeSteps, wfv1.NodeTypeDAG:
default:
continue
}
switch node.Phase {
case wfv1.NodePending, wfv1.NodeRunning:
activeChildren++
}
}
return activeChildren
}
// getAllWorkflowPods returns all pods related to the current workflow
func (woc *wfOperationCtx) getAllWorkflowPods() (*apiv1.PodList, error) {
options := metav1.ListOptions{
LabelSelector: fmt.Sprintf("%s=%s",
common.LabelKeyWorkflow,
woc.wf.ObjectMeta.Name),
}
podList, err := woc.controller.kubeclientset.CoreV1().Pods(woc.wf.Namespace).List(options)