forked from argoproj/argo-workflows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperator.go
2306 lines (2133 loc) · 81.7 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"
"os"
"reflect"
"regexp"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"time"
"k8s.io/apimachinery/pkg/util/wait"
"github.com/argoproj/pkg/humanize"
"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/client-go/tools/cache"
"k8s.io/utils/pointer"
"sigs.k8s.io/yaml"
"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/argo"
"github.com/argoproj/argo/util/retry"
"github.com/argoproj/argo/workflow/common"
"github.com/argoproj/argo/workflow/config"
"github.com/argoproj/argo/workflow/packer"
"github.com/argoproj/argo/workflow/templateresolution"
"github.com/argoproj/argo/workflow/util"
"github.com/argoproj/argo/workflow/validate"
argokubeerr "github.com/argoproj/pkg/kube/errors"
)
// wfOperationCtx is the context for evaluation and operation of a single workflow
type wfOperationCtx struct {
// wf is the workflow object
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 map[string]string
// 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
// auditLogger is the argo audit logger
auditLogger *argo.AuditLogger
}
var _ wfv1.TemplateStorage = &wfOperationCtx{}
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,
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),
auditLogger: argo.NewAuditLogger(wf.ObjectMeta.Namespace, wfc.kubeclientset, wf.ObjectMeta.Name),
}
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.Completed() {
_ = woc.killDaemonedChildren("")
}
woc.persistUpdates()
}()
defer func() {
if r := recover(); r != nil {
if rerr, ok := r.(error); ok {
woc.markWorkflowError(rerr, true)
} else {
woc.markWorkflowPhase(wfv1.NodeError, true, fmt.Sprintf("%v", r))
}
woc.log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack())
}
}()
woc.log.Infof("Processing workflow")
// 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.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowFailed}, msg)
return
}
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeNormal, Reason: argo.EventReasonWorkflowRunning}, "Workflow Running")
validateOpts := validate.ValidateOpts{ContainerRuntimeExecutor: woc.controller.GetContainerRuntimeExecutor()}
wftmplGetter := templateresolution.WrapWorkflowTemplateInterface(woc.controller.wfclientset.ArgoprojV1alpha1().WorkflowTemplates(woc.wf.Namespace))
err = validate.ValidateWorkflow(wftmplGetter, woc.wf, validateOpts)
if err != nil {
msg := fmt.Sprintf("invalid spec: %s", err.Error())
woc.markWorkflowFailed(msg)
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowFailed}, msg)
return
}
woc.workflowDeadline = woc.getWorkflowDeadline()
} else {
woc.workflowDeadline = woc.getWorkflowDeadline()
err := woc.podReconciliation()
if err == nil {
err = woc.failSuspendedNodesAfterDeadline()
}
if err != nil {
woc.log.Errorf("%s error: %+v", woc.wf.ObjectMeta.Name, err)
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowTimedOut}, "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.wf.Spec.Parallelism != nil {
woc.activePods = woc.countActivePods()
}
woc.setGlobalParameters()
if woc.wf.Spec.ArtifactRepositoryRef != nil {
repoReference := woc.wf.Spec.ArtifactRepositoryRef
repo, err := getArtifactRepositoryRef(woc.controller, repoReference.ConfigMap, repoReference.Key, woc.wf.ObjectMeta.Namespace)
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.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowFailed}, msg)
return
}
}
err := woc.substituteParamsInVolumes(woc.globalParams)
if err != nil {
msg := fmt.Sprintf("%s volumes global param substitution error: %+v", woc.wf.ObjectMeta.Name, err)
woc.log.Errorf(msg)
woc.markWorkflowError(err, true)
return
}
err = woc.createPVCs()
if err != nil {
msg := fmt.Sprintf("%s pvc create error: %+v", woc.wf.ObjectMeta.Name, err)
woc.log.Errorf(msg)
woc.markWorkflowError(err, true)
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowFailed}, msg)
return
}
// Create a starting template context.
tmplCtx := woc.createTemplateContext("")
var workflowStatus wfv1.NodePhase
var workflowMessage string
node, err := woc.executeTemplate(woc.wf.ObjectMeta.Name, &wfv1.Template{Template: woc.wf.Spec.Entrypoint}, tmplCtx, woc.wf.Spec.Arguments, "")
if err != nil {
msg := fmt.Sprintf("%s error in entry template execution: %+v", woc.wf.Name, err)
// the error are handled in the callee so just log it.
woc.log.Errorf(msg)
switch err {
case ErrDeadlineExceeded:
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowTimedOut}, msg)
default:
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowFailed}, msg)
}
return
}
if node == nil || !node.Completed() {
// node can be nil if a workflow created immediately in a parallelism == 0 state
return
}
workflowStatus = node.Phase
if !node.Successful() && util.IsWorkflowTerminated(woc.wf) {
workflowMessage = "terminated"
} else {
workflowMessage = node.Message
}
var onExitNode *wfv1.NodeStatus
if woc.wf.Spec.OnExit != "" {
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.wf.Spec.OnExit)
onExitNodeName := woc.wf.ObjectMeta.Name + ".onExit"
onExitNode, err = woc.executeTemplate(onExitNodeName, &wfv1.Template{Template: woc.wf.Spec.OnExit}, tmplCtx, woc.wf.Spec.Arguments, "")
if err != nil {
// the error are handled in the callee so just log it.
woc.log.Errorf("%s error in exit template execution: %+v", woc.wf.Name, err)
return
}
if onExitNode == nil || !onExitNode.Completed() {
return
}
}
err = woc.deletePVCs()
if err != nil {
msg := fmt.Sprintf("%s error: %+v", woc.wf.ObjectMeta.Name, err)
woc.log.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.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowFailed}, msg)
return
}
// 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.Successful() {
// if main workflow succeeded, but the exit node was unsuccessful
// the workflow is now considered unsuccessful.
woc.markWorkflowPhase(onExitNode.Phase, true, onExitNode.Message)
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowFailed}, onExitNode.Message)
} else {
woc.markWorkflowSuccess()
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeNormal, Reason: argo.EventReasonWorkflowSucceded}, "Workflow completed")
}
case wfv1.NodeFailed:
woc.markWorkflowFailed(workflowMessage)
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowFailed}, workflowMessage)
case wfv1.NodeError:
woc.markWorkflowPhase(wfv1.NodeError, true, workflowMessage)
woc.auditLogger.LogWorkflowEvent(woc.wf, argo.EventInfo{Type: apiv1.EventTypeWarning, Reason: argo.EventReasonWorkflowFailed}, 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)
}
}
func (woc *wfOperationCtx) getWorkflowDeadline() *time.Time {
if woc.wf.Spec.ActiveDeadlineSeconds == nil {
return nil
}
if woc.wf.Status.StartedAt.IsZero() {
return nil
}
if *woc.wf.Spec.ActiveDeadlineSeconds == 0 {
// A zero value for ActiveDeadlineSeconds has special meaning (killed).
// Return a zero value time object
return &time.Time{}
}
startedAt := woc.wf.Status.StartedAt.Truncate(time.Second)
deadline := startedAt.Add(time.Duration(*woc.wf.Spec.ActiveDeadlineSeconds) * time.Second).UTC()
return &deadline
}
// setGlobalParameters sets the globalParam map with global parameters
func (woc *wfOperationCtx) setGlobalParameters() {
woc.globalParams[common.GlobalVarWorkflowName] = woc.wf.ObjectMeta.Name
woc.globalParams[common.GlobalVarWorkflowNamespace] = woc.wf.ObjectMeta.Namespace
woc.globalParams[common.GlobalVarWorkflowUID] = string(woc.wf.ObjectMeta.UID)
woc.globalParams[common.GlobalVarWorkflowCreationTimestamp] = woc.wf.ObjectMeta.CreationTimestamp.String()
if woc.wf.Spec.Priority != nil {
woc.globalParams[common.GlobalVarWorkflowPriority] = strconv.Itoa(int(*woc.wf.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.wf.Spec.Arguments.Parameters); err == nil {
woc.globalParams[common.GlobalVarWorkflowParameters] = string(workflowParameters)
}
for _, param := range woc.wf.Spec.Arguments.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
}
}
}
func (woc *wfOperationCtx) getNodeByName(nodeName string) *wfv1.NodeStatus {
nodeID := woc.wf.NodeID(nodeName)
node, ok := woc.wf.Status.Nodes[nodeID]
if !ok {
return nil
}
return &node
}
// 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 := packer.CompressWorkflow(woc.wf)
if packer.IsTooLargeError(err) || os.Getenv("ALWAYS_OFFLOAD_NODE_STATUS") == "true" {
if woc.controller.offloadNodeStatusRepo.IsEnabled() {
offloadVersion, err := woc.controller.offloadNodeStatusRepo.Save(string(woc.wf.UID), woc.wf.Namespace, nodes)
if err != nil {
woc.log.Warnf("Failed to offload node status: %v", err)
woc.markWorkflowError(err, true)
} else {
woc.wf.Status.Nodes = nil
woc.wf.Status.CompressedNodes = ""
woc.wf.Status.OffloadNodeStatusVersion = offloadVersion
}
}
} else if err != nil {
woc.log.Warnf("Error compressing workflow: %v", err)
woc.markWorkflowError(err, true)
}
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)
if err != nil {
woc.log.Infof("Failed to re-apply update: %+v", err)
return
}
woc.wf = wf
} else {
woc.wf = wf
}
// restore to pre-compressed state
woc.wf.Status.Nodes = nodes
woc.wf.Status.CompressedNodes = ""
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.
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.wf.Spec.PodGC != nil {
switch woc.wf.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: %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) (*wfv1.Workflow, error) {
// First generate the patch
oldData, err := json.Marshal(woc.orig)
if err != nil {
return nil, errors.InternalWrapError(err)
}
newData, err := json.Marshal(woc.wf)
if err != nil {
return nil, errors.InternalWrapError(err)
}
patchBytes, err := jsonpatch.CreateMergePatch(oldData, newData)
if err != nil {
return nil, errors.InternalWrapError(err)
}
// Next get latest version of the workflow, apply the patch and retyr the Update
attempt := 1
for {
currWf, err := wfClient.Get(woc.wf.ObjectMeta.Name, metav1.GetOptions{})
if !retry.IsRetryableKubeAPIError(err) {
return nil, errors.InternalWrapError(err)
}
currWfBytes, err := json.Marshal(currWf)
if err != nil {
return nil, errors.InternalWrapError(err)
}
newWfBytes, err := jsonpatch.MergePatch(currWfBytes, patchBytes)
if err != nil {
return nil, errors.InternalWrapError(err)
}
var newWf wfv1.Workflow
err = json.Unmarshal(newWfBytes, &newWf)
if err != nil {
return nil, errors.InternalWrapError(err)
}
wf, err := wfClient.Update(&newWf)
if err == nil {
woc.log.Infof("Update retry attempt %d successful", attempt)
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) (*wfv1.NodeStatus, bool, error) {
if node.Completed() {
return node, true, nil
}
lastChildNode, err := woc.getLastChildNode(node)
if err != nil {
return nil, false, fmt.Errorf("Failed to find last child of node " + node.Name)
}
if lastChildNode == nil {
return node, true, nil
}
if retryStrategy.Backoff != nil {
// 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, err := woc.getFirstChildNode(node)
if err != nil {
return nil, false, fmt.Errorf("Failed to find first child of node " + node.Name)
}
if time.Now().After(firstChildNode.FinishedAt.Add(maxDuration)) {
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
if retryStrategy.Backoff.Factor > 0 {
// Formula: timeToWait = duration * factor^retry_number
timeToWait = baseDuration * time.Duration(math.Pow(float64(retryStrategy.Backoff.Factor), float64(len(node.Children))))
}
waitingDeadline := lastChildNode.FinishedAt.Add(timeToWait)
// See if we have waited past the deadline
if time.Now().Before(waitingDeadline) {
retryMessage := fmt.Sprintf("Retrying in %s", humanize.Duration(time.Until(waitingDeadline)))
return woc.markNodePhase(node.Name, node.Phase, retryMessage), false, nil
}
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.Completed() {
// last child node is still running.
return node, true, nil
}
if lastChildNode.Successful() {
node.Outputs = lastChildNode.Outputs.DeepCopy()
woc.wf.Status.Nodes[node.ID] = *node
return woc.markNodePhase(node.Name, wfv1.NodeSucceeded), true, nil
}
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
}
if retryStrategy.Limit != nil && int32(len(node.Children)) > *retryStrategy.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]bool)
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] = true
seenPodLock.Unlock()
wfNodesLock.Lock()
defer wfNodesLock.Unlock()
if node, ok := woc.wf.Status.Nodes[nodeID]; ok {
if newState := assessNodeStatus(pod, &node); newState != nil {
woc.wf.Status.Nodes[nodeID] = *newState
woc.addOutputsToScope("workflow", node.Outputs, nil)
woc.updated = true
}
node := woc.wf.Status.Nodes[pod.ObjectMeta.Name]
if node.Completed() && !node.IsDaemoned() {
if tmpVal, tmpOk := pod.Labels[common.LabelKeyCompleted]; tmpOk {
if tmpVal == "true" {
return
}
}
woc.completedPods[pod.ObjectMeta.Name] = true
}
if node.Successful() {
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.Completed() || node.StartedAt.IsZero() || node.Pending() {
// node is not a pod, it is already complete, or it can be re-run.
continue
}
if _, ok := seenPods[nodeID]; !ok {
node.Message = "pod deleted"
node.Phase = wfv1.NodeError
woc.wf.Status.Nodes[nodeID] = node
woc.log.Warnf("pod %s deleted", nodeID)
woc.updated = true
}
}
return nil
}
//fails any suspended nodes if the workflow deadline has passed
func (woc *wfOperationCtx) failSuspendedNodesAfterDeadline() error {
if woc.workflowDeadline != nil && time.Now().UTC().After(*woc.workflowDeadline) {
for _, node := range woc.wf.Status.Nodes {
if node.IsActiveSuspendNode() {
var message string
if woc.workflowDeadline.IsZero() {
message = "terminated"
} else {
message = fmt.Sprintf("step exceeded workflow deadline %s", *woc.workflowDeadline)
}
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)
if err != nil {
return nil, errors.InternalWrapError(err)
}
return podList, nil
}
// assessNodeStatus compares the current state of a pod with its corresponding node
// and returns the new node status if something changed
func assessNodeStatus(pod *apiv1.Pod, node *wfv1.NodeStatus) *wfv1.NodeStatus {
var newPhase wfv1.NodePhase
var newDaemonStatus *bool
var message string
updated := false
switch pod.Status.Phase {
case apiv1.PodPending:
newPhase = wfv1.NodePending
newDaemonStatus = pointer.BoolPtr(false)
message = getPendingReason(pod)
case apiv1.PodSucceeded:
newPhase = wfv1.NodeSucceeded
newDaemonStatus = pointer.BoolPtr(false)
case apiv1.PodFailed:
// ignore pod failure for daemoned steps
if node.IsDaemoned() {
newPhase = wfv1.NodeSucceeded
} else {
newPhase, message = inferFailedReason(pod)
}
newDaemonStatus = pointer.BoolPtr(false)
case apiv1.PodRunning:
if pod.DeletionTimestamp != nil {
// pod is being terminated
newPhase = wfv1.NodeFailed
message = "pod termination"
} else {
newPhase = wfv1.NodeRunning
tmplStr, ok := pod.Annotations[common.AnnotationKeyTemplate]
if !ok {
log.Warnf("%s missing template annotation", pod.ObjectMeta.Name)
return nil
}
var tmpl wfv1.Template
err := json.Unmarshal([]byte(tmplStr), &tmpl)
if err != nil {
log.Warnf("%s template annotation unreadable: %v", pod.ObjectMeta.Name, err)
return nil
}
if tmpl.Daemon != nil && *tmpl.Daemon {
// pod is running and template is marked daemon. check if everything is ready
for _, ctrStatus := range pod.Status.ContainerStatuses {
if !ctrStatus.Ready {
return nil
}
}
// proceed to mark node status as running (and daemoned)
newPhase = wfv1.NodeRunning
newDaemonStatus = pointer.BoolPtr(true)
log.Infof("Processing ready daemon pod: %v", pod.ObjectMeta.SelfLink)
}
}
default:
newPhase = wfv1.NodeError
message = fmt.Sprintf("Unexpected pod phase for %s: %s", pod.ObjectMeta.Name, pod.Status.Phase)
log.Error(message)
}
if newDaemonStatus != nil {
if !*newDaemonStatus {
// if the daemon status switched to false, we prefer to just unset daemoned status field
// (as opposed to setting it to false)
newDaemonStatus = nil
}
if (newDaemonStatus != nil && node.Daemoned == nil) || (newDaemonStatus == nil && node.Daemoned != nil) {
log.Infof("Setting node %v daemoned: %v -> %v", node, node.Daemoned, newDaemonStatus)
node.Daemoned = newDaemonStatus
updated = true
if pod.Status.PodIP != "" && pod.Status.PodIP != node.PodIP {
// only update Pod IP for daemoned nodes to reduce number of updates
log.Infof("Updating daemon node %s IP %s -> %s", node, node.PodIP, pod.Status.PodIP)
node.PodIP = pod.Status.PodIP
}
}
}
outputStr, ok := pod.Annotations[common.AnnotationKeyOutputs]
if ok && node.Outputs == nil {
updated = true
log.Infof("Setting node %v outputs", node)
var outputs wfv1.Outputs
err := json.Unmarshal([]byte(outputStr), &outputs)
if err != nil {
log.Errorf("Failed to unmarshal %s outputs from pod annotation: %v", pod.Name, err)
node.Phase = wfv1.NodeError
} else {
node.Outputs = &outputs
}
}
if node.Phase != newPhase {
log.Infof("Updating node %s status %s -> %s", node, node.Phase, newPhase)
// if we are transitioning from Pending to a different state, clear out pending message
if node.Phase == wfv1.NodePending {
node.Message = ""
}
updated = true
node.Phase = newPhase
}
if message != "" && node.Message != message {
log.Infof("Updating node %s message: %s", node, message)
updated = true
node.Message = message
}
if node.Completed() && node.FinishedAt.IsZero() {
updated = true
if !node.IsDaemoned() {
node.FinishedAt = getLatestFinishedAt(pod)
}
if node.FinishedAt.IsZero() {
// If we get here, the container is daemoned so the
// finishedAt might not have been set.
node.FinishedAt = metav1.Time{Time: time.Now().UTC()}
}
}
if updated {
return node
}
return nil
}
// getLatestFinishedAt returns the latest finishAt timestamp from all the
// containers of this pod.
func getLatestFinishedAt(pod *apiv1.Pod) metav1.Time {
var latest metav1.Time
for _, ctr := range pod.Status.InitContainerStatuses {
if ctr.State.Terminated != nil && ctr.State.Terminated.FinishedAt.After(latest.Time) {
latest = ctr.State.Terminated.FinishedAt
}
}
for _, ctr := range pod.Status.ContainerStatuses {
if ctr.State.Terminated != nil && ctr.State.Terminated.FinishedAt.After(latest.Time) {
latest = ctr.State.Terminated.FinishedAt
}
}
return latest
}
func getPendingReason(pod *apiv1.Pod) string {
for _, ctrStatus := range pod.Status.ContainerStatuses {
if ctrStatus.State.Waiting != nil {
if ctrStatus.State.Waiting.Message != "" {
return fmt.Sprintf("%s: %s", ctrStatus.State.Waiting.Reason, ctrStatus.State.Waiting.Message)
}
return ctrStatus.State.Waiting.Reason
}
}
// Example:
// - lastProbeTime: null
// lastTransitionTime: 2018-08-29T06:38:36Z
// message: '0/3 nodes are available: 2 Insufficient cpu, 3 MatchNodeSelector.'
// reason: Unschedulable
// status: "False"