-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
operator_test.go
6951 lines (6401 loc) · 199 KB
/
operator_test.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"
"errors"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"testing"
"time"
"github.com/argoproj/pkg/strftime"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
apiv1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/fake"
batchfake "k8s.io/client-go/kubernetes/typed/batch/v1/fake"
k8stesting "k8s.io/client-go/testing"
"k8s.io/utils/pointer"
"sigs.k8s.io/yaml"
"github.com/argoproj/argo-workflows/v3/config"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
intstrutil "github.com/argoproj/argo-workflows/v3/util/intstr"
"github.com/argoproj/argo-workflows/v3/util/template"
"github.com/argoproj/argo-workflows/v3/workflow/common"
"github.com/argoproj/argo-workflows/v3/workflow/controller/cache"
hydratorfake "github.com/argoproj/argo-workflows/v3/workflow/hydrator/fake"
"github.com/argoproj/argo-workflows/v3/workflow/sync"
"github.com/argoproj/argo-workflows/v3/workflow/util"
)
// TestOperateWorkflowPanicRecover ensures we can recover from unexpected panics
func TestOperateWorkflowPanicRecover(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Fail()
}
}()
cancel, controller := newController()
defer cancel()
// intentionally set clientset to nil to induce panic
controller.kubeclientset = nil
wf := wfv1.MustUnmarshalWorkflow(helloWorldWf)
ctx := context.Background()
_, err := controller.wfclientset.ArgoprojV1alpha1().Workflows("").Create(ctx, wf, metav1.CreateOptions{})
assert.NoError(t, err)
woc := newWorkflowOperationCtx(wf, controller)
woc.operate(ctx)
}
func Test_wfOperationCtx_reapplyUpdate(t *testing.T) {
ctx := context.Background()
t.Run("Success", func(t *testing.T) {
wf := &wfv1.Workflow{
ObjectMeta: metav1.ObjectMeta{Name: "my-wf"},
Status: wfv1.WorkflowStatus{Nodes: wfv1.Nodes{"foo": wfv1.NodeStatus{Name: "my-foo"}}},
}
cancel, controller := newController(wf)
defer cancel()
controller.hydrator = hydratorfake.Always
woc := newWorkflowOperationCtx(wf, controller)
// fake the behaviour woc.operate()
assert.NoError(t, controller.hydrator.Hydrate(wf))
nodes := wfv1.Nodes{"foo": wfv1.NodeStatus{Name: "my-foo", Phase: wfv1.NodeSucceeded}}
// now force a re-apply update
updatedWf, err := woc.reapplyUpdate(ctx, controller.wfclientset.ArgoprojV1alpha1().Workflows(""), nodes)
if assert.NoError(t, err) && assert.NotNil(t, updatedWf) {
assert.True(t, woc.controller.hydrator.IsHydrated(updatedWf))
if assert.Contains(t, updatedWf.Status.Nodes, "foo") {
assert.Equal(t, "my-foo", updatedWf.Status.Nodes["foo"].Name)
assert.Equal(t, wfv1.NodeSucceeded, updatedWf.Status.Nodes["foo"].Phase, "phase is merged")
}
}
})
t.Run("ErrUpdatingCompletedWorkflow", func(t *testing.T) {
wf := &wfv1.Workflow{
ObjectMeta: metav1.ObjectMeta{Name: "my-wf"},
Status: wfv1.WorkflowStatus{Phase: wfv1.WorkflowError},
}
currWf := wf.DeepCopy()
currWf.Status.Phase = wfv1.WorkflowSucceeded
cancel, controller := newController(currWf)
defer cancel()
woc := newWorkflowOperationCtx(wf, controller)
_, err := woc.reapplyUpdate(ctx, controller.wfclientset.ArgoprojV1alpha1().Workflows(""), wfv1.Nodes{})
assert.EqualError(t, err, "must never update completed workflows")
})
t.Run("ErrUpdatingCompletedNode", func(t *testing.T) {
wf := &wfv1.Workflow{
ObjectMeta: metav1.ObjectMeta{Name: "my-wf"},
Status: wfv1.WorkflowStatus{Nodes: wfv1.Nodes{"my-node": wfv1.NodeStatus{Phase: wfv1.NodeError}}},
}
currWf := wf.DeepCopy()
currWf.Status.Nodes = wfv1.Nodes{"my-node": wfv1.NodeStatus{Phase: wfv1.NodeSucceeded}}
cancel, controller := newController(currWf)
defer cancel()
woc := newWorkflowOperationCtx(wf, controller)
_, err := woc.reapplyUpdate(ctx, controller.wfclientset.ArgoprojV1alpha1().Workflows(""), wf.Status.Nodes)
assert.EqualError(t, err, "must never update completed node my-node")
})
}
func TestResourcesDuration(t *testing.T) {
wf := wfv1.MustUnmarshalWorkflow(`
metadata:
name: my-wf
namespace: my-ns
spec:
entrypoint: main
templates:
- name: main
dag:
tasks:
- name: pod
template: pod
- name: pod
container:
image: my-image
`)
cancel, controller := newController(wf)
defer cancel()
ctx := context.Background()
woc := newWorkflowOperationCtx(wf, controller)
woc.operate(ctx)
makePodsPhase(ctx, woc, apiv1.PodSucceeded)
woc = newWorkflowOperationCtx(woc.wf, controller)
woc.operate(ctx)
assert.NotEmpty(t, woc.wf.Status.ResourcesDuration, "workflow duration not empty")
assert.False(t, woc.wf.Status.Nodes.Any(func(node wfv1.NodeStatus) bool {
return node.ResourcesDuration.IsZero()
}), "zero node durations empty")
}
func TestEstimatedDuration(t *testing.T) {
wf := wfv1.MustUnmarshalWorkflow(`
metadata:
name: my-wf
namespace: my-ns
labels:
workflows.argoproj.io/workflow-template: my-wftmpl
spec:
entrypoint: main
templates:
- name: main
dag:
tasks:
- name: pod
template: pod
- name: pod
container:
image: my-image
`)
cancel, controller := newController(wfv1.MustUnmarshalWorkflow(`
metadata:
name: my-baseline-wf
namespace: my-ns
status:
startedAt: "1970-01-01T00:00:00Z"
finishedAt: "1970-01-01T00:01:00Z"
nodes:
my-baseline-wf:
startedAt: "1970-01-01T00:00:00Z"
finishedAt: "1970-01-01T00:01:00Z"
`), wf)
defer cancel()
ctx := context.Background()
woc := newWorkflowOperationCtx(wf, controller)
woc.operate(ctx)
makePodsPhase(ctx, woc, apiv1.PodSucceeded)
woc = newWorkflowOperationCtx(woc.wf, controller)
woc.operate(ctx)
assert.Equal(t, wfv1.WorkflowSucceeded, woc.wf.Status.Phase)
assert.Equal(t, wfv1.EstimatedDuration(1), woc.wf.Status.EstimatedDuration)
assert.Equal(t, wfv1.EstimatedDuration(1), woc.wf.Status.Nodes[woc.wf.Name].EstimatedDuration)
assert.Equal(t, wfv1.EstimatedDuration(1), woc.wf.Status.Nodes.FindByDisplayName("pod").EstimatedDuration)
}
func TestDefaultProgress(t *testing.T) {
wf := wfv1.MustUnmarshalWorkflow(`
metadata:
name: my-wf
namespace: my-ns
spec:
entrypoint: main
templates:
- name: main
dag:
tasks:
- name: pod
template: pod
- name: pod
container:
image: my-image
`)
cancel, controller := newController(wf)
defer cancel()
ctx := context.Background()
woc := newWorkflowOperationCtx(wf, controller)
woc.operate(ctx)
makePodsPhase(ctx, woc, apiv1.PodSucceeded)
woc = newWorkflowOperationCtx(woc.wf, controller)
woc.operate(ctx)
assert.Equal(t, wfv1.WorkflowSucceeded, woc.wf.Status.Phase)
assert.Equal(t, wfv1.Progress("1/1"), woc.wf.Status.Progress)
assert.Equal(t, wfv1.Progress("1/1"), woc.wf.Status.Nodes[woc.wf.Name].Progress)
assert.Equal(t, wfv1.Progress("1/1"), woc.wf.Status.Nodes.FindByDisplayName("pod").Progress)
}
var sidecarWithVol = `
# Verifies sidecars can reference volumeClaimTemplates
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
name: sidecar-with-volumes
spec:
entrypoint: sidecar-with-volumes
volumeClaimTemplates:
- metadata:
name: claim-vol
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
volumes:
- name: existing-vol
persistentVolumeClaim:
claimName: my-existing-volume
templates:
- name: sidecar-with-volumes
script:
image: python:alpine3.6
command: [python]
source: |
print("hello world")
sidecars:
- name: sidevol
image: docker/whalesay:latest
command: [sh, -c]
args: ["echo generating message in volume; cowsay hello world | tee /mnt/vol/hello_world.txt; sleep 9999"]
volumeMounts:
- name: claim-vol
mountPath: /mnt/vol
- name: existing-vol
mountPath: /mnt/existing-vol
`
func TestGlobalParams(t *testing.T) {
wf := wfv1.MustUnmarshalWorkflow(helloWorldWf)
cancel, controller := newController(wf)
defer cancel()
ctx := context.Background()
woc := newWorkflowOperationCtx(wf, controller)
woc.operate(ctx)
if assert.Contains(t, woc.globalParams, "workflow.creationTimestamp") {
assert.NotContains(t, woc.globalParams["workflow.creationTimestamp"], "UTC")
}
for char := range strftime.FormatChars {
assert.Contains(t, woc.globalParams, fmt.Sprintf("%s.%s", "workflow.creationTimestamp", string(char)))
}
assert.Contains(t, woc.globalParams, "workflow.creationTimestamp.s")
assert.Contains(t, woc.globalParams, "workflow.duration")
assert.Contains(t, woc.globalParams, "workflow.name")
assert.Contains(t, woc.globalParams, "workflow.namespace")
assert.Contains(t, woc.globalParams, "workflow.parameters")
assert.Contains(t, woc.globalParams, "workflow.serviceAccountName")
assert.Contains(t, woc.globalParams, "workflow.uid")
// Ensure that the phase label is included after the first operation
woc.operate(ctx)
assert.Contains(t, woc.globalParams, "workflow.labels.workflows.argoproj.io/phase")
}
// TestSidecarWithVolume verifies ia sidecar can have a volumeMount reference to both existing or volumeClaimTemplate volumes
func TestSidecarWithVolume(t *testing.T) {
wf := wfv1.MustUnmarshalWorkflow(sidecarWithVol)
cancel, controller := newController(wf)
defer cancel()
ctx := context.Background()
woc := newWorkflowOperationCtx(wf, controller)
woc.operate(ctx)
assert.Equal(t, wfv1.WorkflowRunning, woc.wf.Status.Phase)
pods, err := listPods(woc)
assert.NoError(t, err)
assert.True(t, len(pods.Items) > 0, "pod was not created successfully")
pod := pods.Items[0]
claimVolFound := false
existingVolFound := false
for _, ctr := range pod.Spec.Containers {
if ctr.Name == "sidevol" {
for _, vol := range ctr.VolumeMounts {
if vol.Name == "claim-vol" {
claimVolFound = true
}
if vol.Name == "existing-vol" {
existingVolFound = true
}
}
}
}
assert.True(t, claimVolFound, "claim vol was not referenced by sidecar")
assert.True(t, existingVolFound, "existing vol was not referenced by sidecar")
}
func makeVolumeGcStrategyTemplate(strategy wfv1.VolumeClaimGCStrategy, phase wfv1.NodePhase) string {
return fmt.Sprintf(`
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
name: workflow-with-volumes
spec:
entrypoint: workflow-with-volumes
volumeClaimGC:
strategy: %s
volumeClaimTemplates:
- metadata:
name: claim-vol
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
volumes:
- name: existing-vol
persistentVolumeClaim:
claimName: my-existing-volume
templates:
- name: workflow-with-volumes
script:
image: python:alpine3.6
command: [python]
volumeMounts:
- name: claim-vol
mountPath: /mnt/vol
- name: existing-vol
mountPath: /mnt/existing-vol
source: |
print("hello world")
status:
phase: %s
startedAt: 2020-08-01T15:32:09Z
nodes:
workflow-with-volumes:
id: workflow-with-volumes
name: workflow-with-volumes
displayName: workflow-with-volumes
type: Pod
templateName: workflow-with-volumes
templateScope: local/workflow-with-volumes
startedAt: 2020-08-01T15:32:09Z
phase: %s
persistentVolumeClaims:
- name: claim-vol
persistentVolumeClaim:
claimName: workflow-with-volumes-claim-vol
`, strategy, phase, phase)
}
func TestVolumeGCStrategy(t *testing.T) {
tests := []struct {
name string
strategy wfv1.VolumeClaimGCStrategy
phase wfv1.NodePhase
expectedVolumesRemaining int
}{{
name: "failed/OnWorkflowCompletion",
strategy: wfv1.VolumeClaimGCOnCompletion,
phase: wfv1.NodeFailed,
expectedVolumesRemaining: 0,
}, {
name: "failed/OnWorkflowSuccess",
strategy: wfv1.VolumeClaimGCOnSuccess,
phase: wfv1.NodeFailed,
expectedVolumesRemaining: 1,
}, {
name: "succeeded/OnWorkflowSuccess",
strategy: wfv1.VolumeClaimGCOnSuccess,
phase: wfv1.NodeSucceeded,
expectedVolumesRemaining: 0,
}, {
name: "succeeded/OnWorkflowCompletion",
strategy: wfv1.VolumeClaimGCOnCompletion,
phase: wfv1.NodeSucceeded,
expectedVolumesRemaining: 0,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
wf := wfv1.MustUnmarshalWorkflow(makeVolumeGcStrategyTemplate(tt.strategy, tt.phase))
cancel, controller := newController(wf)
defer cancel()
ctx := context.Background()
wfcset := controller.wfclientset.ArgoprojV1alpha1().Workflows("")
woc := newWorkflowOperationCtx(wf, controller)
woc.operate(ctx)
wf, err := wfcset.Get(ctx, wf.ObjectMeta.Name, metav1.GetOptions{})
if assert.NoError(t, err) {
assert.Len(t, wf.Status.PersistentVolumeClaims, tt.expectedVolumesRemaining)
}
})
}
}
// TestProcessNodesWithRetries tests the processNodesWithRetries() method.
func TestProcessNodesWithRetries(t *testing.T) {
cancel, controller := newController()
defer cancel()
assert.NotNil(t, controller)
wf := wfv1.MustUnmarshalWorkflow(helloWorldWf)
assert.NotNil(t, wf)
woc := newWorkflowOperationCtx(wf, controller)
assert.NotNil(t, woc)
// Verify that there are no nodes in the wf status.
assert.Zero(t, len(woc.wf.Status.Nodes))
// Add the parent node for retries.
nodeName := "test-node"
nodeID := woc.wf.NodeID(nodeName)
node := woc.initializeNode(nodeName, wfv1.NodeTypeRetry, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
retries := wfv1.RetryStrategy{}
retries.Limit = intstrutil.ParsePtr("2")
woc.wf.Status.Nodes[nodeID] = *node
assert.Equal(t, node.Phase, wfv1.NodeRunning)
// Ensure there are no child nodes yet.
lastChild := getChildNodeIndex(node, woc.wf.Status.Nodes, -1)
assert.Nil(t, lastChild)
// Add child nodes.
for i := 0; i < 2; i++ {
childNode := fmt.Sprintf("child-node-%d", i)
woc.initializeNode(childNode, wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
woc.addChildNode(nodeName, childNode)
}
n := woc.wf.GetNodeByName(nodeName)
lastChild = getChildNodeIndex(n, woc.wf.Status.Nodes, -1)
assert.NotNil(t, lastChild)
// Last child is still running. processNodesWithRetries() should return false since
// there should be no retries at this point.
n, _, err := woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.NoError(t, err)
assert.Equal(t, n.Phase, wfv1.NodeRunning)
// Mark lastChild as successful.
woc.markNodePhase(lastChild.Name, wfv1.NodeSucceeded)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.NoError(t, err)
// The parent node also gets marked as Succeeded.
assert.Equal(t, n.Phase, wfv1.NodeSucceeded)
// Mark the parent node as running again and the lastChild as failed.
woc.markNodePhase(n.Name, wfv1.NodeRunning)
woc.markNodePhase(lastChild.Name, wfv1.NodeFailed)
_, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.NoError(t, err)
n = woc.wf.GetNodeByName(nodeName)
assert.Equal(t, n.Phase, wfv1.NodeRunning)
// Add a third node that has failed.
childNode := "child-node-3"
woc.initializeNode(childNode, wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeFailed)
woc.addChildNode(nodeName, childNode)
n = woc.wf.GetNodeByName(nodeName)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.NoError(t, err)
assert.Equal(t, n.Phase, wfv1.NodeFailed)
}
// TestProcessNodesWithRetries tests retrying when RetryOn.Error is enabled
func TestProcessNodesWithRetriesOnErrors(t *testing.T) {
cancel, controller := newController()
defer cancel()
assert.NotNil(t, controller)
wf := wfv1.MustUnmarshalWorkflow(helloWorldWf)
assert.NotNil(t, wf)
woc := newWorkflowOperationCtx(wf, controller)
assert.NotNil(t, woc)
// Verify that there are no nodes in the wf status.
assert.Zero(t, len(woc.wf.Status.Nodes))
// Add the parent node for retries.
nodeName := "test-node"
nodeID := woc.wf.NodeID(nodeName)
node := woc.initializeNode(nodeName, wfv1.NodeTypeRetry, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
retries := wfv1.RetryStrategy{}
retries.Limit = intstrutil.ParsePtr("2")
retries.RetryPolicy = wfv1.RetryPolicyAlways
woc.wf.Status.Nodes[nodeID] = *node
assert.Equal(t, node.Phase, wfv1.NodeRunning)
// Ensure there are no child nodes yet.
lastChild := getChildNodeIndex(node, woc.wf.Status.Nodes, -1)
assert.Nil(t, lastChild)
// Add child nodes.
for i := 0; i < 2; i++ {
childNode := fmt.Sprintf("child-node-%d", i)
woc.initializeNode(childNode, wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
woc.addChildNode(nodeName, childNode)
}
n := woc.wf.GetNodeByName(nodeName)
lastChild = getChildNodeIndex(n, woc.wf.Status.Nodes, -1)
assert.NotNil(t, lastChild)
// Last child is still running. processNodesWithRetries() should return false since
// there should be no retries at this point.
n, _, err := woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
assert.Equal(t, n.Phase, wfv1.NodeRunning)
// Mark lastChild as successful.
woc.markNodePhase(lastChild.Name, wfv1.NodeSucceeded)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
// The parent node also gets marked as Succeeded.
assert.Equal(t, n.Phase, wfv1.NodeSucceeded)
// Mark the parent node as running again and the lastChild as errored.
n = woc.markNodePhase(n.Name, wfv1.NodeRunning)
woc.markNodePhase(lastChild.Name, wfv1.NodeError)
_, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.NoError(t, err)
n = woc.wf.GetNodeByName(nodeName)
assert.Equal(t, n.Phase, wfv1.NodeRunning)
// Add a third node that has errored.
childNode := "child-node-3"
woc.initializeNode(childNode, wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeError)
woc.addChildNode(nodeName, childNode)
n = woc.wf.GetNodeByName(nodeName)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
assert.Equal(t, n.Phase, wfv1.NodeError)
}
// TestProcessNodesWithRetries tests retrying when RetryOnTransientError is enabled
func TestProcessNodesWithRetriesOnTransientErrors(t *testing.T) {
cancel, controller := newController()
defer cancel()
assert.NotNil(t, controller)
wf := wfv1.MustUnmarshalWorkflow(helloWorldWf)
assert.NotNil(t, wf)
woc := newWorkflowOperationCtx(wf, controller)
assert.NotNil(t, woc)
// Verify that there are no nodes in the wf status.
assert.Zero(t, len(woc.wf.Status.Nodes))
// Add the parent node for retries.
nodeName := "test-node"
nodeID := woc.wf.NodeID(nodeName)
node := woc.initializeNode(nodeName, wfv1.NodeTypeRetry, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
retries := wfv1.RetryStrategy{}
retries.Limit = intstrutil.ParsePtr("2")
retries.RetryPolicy = wfv1.RetryPolicyOnTransientError
woc.wf.Status.Nodes[nodeID] = *node
assert.Equal(t, node.Phase, wfv1.NodeRunning)
// Ensure there are no child nodes yet.
lastChild := getChildNodeIndex(node, woc.wf.Status.Nodes, -1)
assert.Nil(t, lastChild)
// Add child nodes.
for i := 0; i < 2; i++ {
childNode := fmt.Sprintf("child-node-%d", i)
woc.initializeNode(childNode, wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
woc.addChildNode(nodeName, childNode)
}
n := woc.wf.GetNodeByName(nodeName)
lastChild = getChildNodeIndex(n, woc.wf.Status.Nodes, -1)
assert.NotNil(t, lastChild)
// Last child is still running. processNodesWithRetries() should return false since
// there should be no retries at this point.
n, _, err := woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
assert.Equal(t, n.Phase, wfv1.NodeRunning)
// Mark lastChild as successful.
woc.markNodePhase(lastChild.Name, wfv1.NodeSucceeded)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
// The parent node also gets marked as Succeeded.
assert.Equal(t, n.Phase, wfv1.NodeSucceeded)
// Mark the parent node as running again and the lastChild as errored with a message that indicates the error
// is transient.
n = woc.markNodePhase(n.Name, wfv1.NodeRunning)
transientEnvVarKey := "TRANSIENT_ERROR_PATTERN"
transientErrMsg := "This error is transient"
woc.markNodePhase(lastChild.Name, wfv1.NodeError, transientErrMsg)
_ = os.Setenv(transientEnvVarKey, transientErrMsg)
_, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.NoError(t, err)
n = woc.wf.GetNodeByName(nodeName)
assert.Equal(t, n.Phase, wfv1.NodeRunning)
_ = os.Unsetenv(transientEnvVarKey)
// Add a third node that has errored.
childNode := "child-node-3"
woc.initializeNode(childNode, wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeError)
woc.addChildNode(nodeName, childNode)
n = woc.wf.GetNodeByName(nodeName)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
assert.Equal(t, n.Phase, wfv1.NodeError)
}
func TestProcessNodesWithRetriesWithBackoff(t *testing.T) {
cancel, controller := newController()
defer cancel()
assert.NotNil(t, controller)
wf := wfv1.MustUnmarshalWorkflow(helloWorldWf)
assert.NotNil(t, wf)
woc := newWorkflowOperationCtx(wf, controller)
assert.NotNil(t, woc)
// Verify that there are no nodes in the wf status.
assert.Zero(t, len(woc.wf.Status.Nodes))
// Add the parent node for retries.
nodeName := "test-node"
nodeID := woc.wf.NodeID(nodeName)
node := woc.initializeNode(nodeName, wfv1.NodeTypeRetry, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
retries := wfv1.RetryStrategy{}
retries.Limit = intstrutil.ParsePtr("2")
retries.Backoff = &wfv1.Backoff{
Duration: "10s",
Factor: intstrutil.ParsePtr("2"),
MaxDuration: "10m",
}
retries.RetryPolicy = wfv1.RetryPolicyAlways
woc.wf.Status.Nodes[nodeID] = *node
assert.Equal(t, node.Phase, wfv1.NodeRunning)
// Ensure there are no child nodes yet.
lastChild := getChildNodeIndex(node, woc.wf.Status.Nodes, -1)
assert.Nil(t, lastChild)
woc.initializeNode("child-node-1", wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
woc.addChildNode(nodeName, "child-node-1")
n := woc.wf.GetNodeByName(nodeName)
lastChild = getChildNodeIndex(n, woc.wf.Status.Nodes, -1)
assert.NotNil(t, lastChild)
// Last child is still running. processNodesWithRetries() should return false since
// there should be no retries at this point.
n, _, err := woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
assert.Equal(t, n.Phase, wfv1.NodeRunning)
// Mark lastChild as successful.
woc.markNodePhase(lastChild.Name, wfv1.NodeSucceeded)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
// The parent node also gets marked as Succeeded.
assert.Equal(t, n.Phase, wfv1.NodeSucceeded)
}
func TestProcessNodesWithRetriesWithExponentialBackoff(t *testing.T) {
require := require.New(t)
cancel, controller := newController()
defer cancel()
require.NotNil(controller)
wf := wfv1.MustUnmarshalWorkflow(helloWorldWf)
require.NotNil(wf)
woc := newWorkflowOperationCtx(wf, controller)
require.NotNil(woc)
// Verify that there are no nodes in the wf status.
require.Zero(len(woc.wf.Status.Nodes))
// Add the parent node for retries.
nodeName := "test-node"
nodeID := woc.wf.NodeID(nodeName)
node := woc.initializeNode(nodeName, wfv1.NodeTypeRetry, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
retries := wfv1.RetryStrategy{}
retries.Limit = intstrutil.ParsePtr("2")
retries.RetryPolicy = wfv1.RetryPolicyAlways
retries.Backoff = &wfv1.Backoff{
Duration: "5m",
Factor: intstrutil.ParsePtr("2"),
}
woc.wf.Status.Nodes[nodeID] = *node
require.Equal(wfv1.NodeRunning, node.Phase)
// Ensure there are no child nodes yet.
lastChild := getChildNodeIndex(node, woc.wf.Status.Nodes, -1)
require.Nil(lastChild)
woc.initializeNode("child-node-1", wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeFailed)
woc.addChildNode(nodeName, "child-node-1")
n := woc.wf.GetNodeByName(nodeName)
// Last child has failed. processNodesWithRetries() should return false due to the default backoff.
var err error
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
require.NoError(err)
require.Equal(wfv1.NodeRunning, n.Phase)
// First backoff should be between 295 and 300 seconds.
backoff, err := parseRetryMessage(n.Message)
require.NoError(err)
require.LessOrEqual(backoff, 300)
require.Less(295, backoff)
woc.initializeNode("child-node-2", wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeError)
woc.addChildNode(nodeName, "child-node-2")
n = woc.wf.GetNodeByName(nodeName)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
require.NoError(err)
require.Equal(wfv1.NodeRunning, n.Phase)
// Second backoff should be between 595 and 600 seconds.
backoff, err = parseRetryMessage(n.Message)
require.NoError(err)
require.LessOrEqual(backoff, 600)
require.Less(595, backoff)
// Mark lastChild as successful.
lastChild = getChildNodeIndex(n, woc.wf.Status.Nodes, -1)
require.NotNil(lastChild)
woc.markNodePhase(lastChild.Name, wfv1.NodeSucceeded)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
require.NoError(err)
// The parent node also gets marked as Succeeded.
require.Equal(wfv1.NodeSucceeded, n.Phase)
}
func parseRetryMessage(message string) (int, error) {
pattern := regexp.MustCompile(`Backoff for (\d+) minutes (\d+) seconds`)
matches := pattern.FindStringSubmatch(message)
if len(matches) != 3 {
return 0, fmt.Errorf("unexpected message: %v", message)
}
minutes, err := strconv.Atoi(matches[1])
if err != nil {
return 0, err
}
seconds, err := strconv.Atoi(matches[2])
if err != nil {
return 0, err
}
totalSeconds := minutes*60 + seconds
return totalSeconds, nil
}
// TestProcessNodesWithRetries tests retrying when RetryOn.Error is disabled
func TestProcessNodesNoRetryWithError(t *testing.T) {
cancel, controller := newController()
defer cancel()
assert.NotNil(t, controller)
wf := wfv1.MustUnmarshalWorkflow(helloWorldWf)
assert.NotNil(t, wf)
woc := newWorkflowOperationCtx(wf, controller)
assert.NotNil(t, woc)
// Verify that there are no nodes in the wf status.
assert.Zero(t, len(woc.wf.Status.Nodes))
// Add the parent node for retries.
nodeName := "test-node"
nodeID := woc.wf.NodeID(nodeName)
node := woc.initializeNode(nodeName, wfv1.NodeTypeRetry, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
retries := wfv1.RetryStrategy{}
retries.Limit = intstrutil.ParsePtr("2")
retries.RetryPolicy = wfv1.RetryPolicyOnFailure
woc.wf.Status.Nodes[nodeID] = *node
assert.Equal(t, node.Phase, wfv1.NodeRunning)
// Ensure there are no child nodes yet.
lastChild := getChildNodeIndex(node, woc.wf.Status.Nodes, -1)
assert.Nil(t, lastChild)
// Add child nodes.
for i := 0; i < 2; i++ {
childNode := fmt.Sprintf("child-node-%d", i)
woc.initializeNode(childNode, wfv1.NodeTypePod, "", &wfv1.WorkflowStep{}, "", wfv1.NodeRunning)
woc.addChildNode(nodeName, childNode)
}
n := woc.wf.GetNodeByName(nodeName)
lastChild = getChildNodeIndex(n, woc.wf.Status.Nodes, -1)
assert.NotNil(t, lastChild)
// Last child is still running. processNodesWithRetries() should return false since
// there should be no retries at this point.
n, _, err := woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
assert.Equal(t, n.Phase, wfv1.NodeRunning)
// Mark lastChild as successful.
woc.markNodePhase(lastChild.Name, wfv1.NodeSucceeded)
n, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.Nil(t, err)
// The parent node also gets marked as Succeeded.
assert.Equal(t, n.Phase, wfv1.NodeSucceeded)
// Mark the parent node as running again and the lastChild as errored.
// Parent node should also be errored because retry on error is disabled
n = woc.markNodePhase(n.Name, wfv1.NodeRunning)
woc.markNodePhase(lastChild.Name, wfv1.NodeError)
_, _, err = woc.processNodeRetries(n, retries, &executeTemplateOpts{})
assert.NoError(t, err)
n = woc.wf.GetNodeByName(nodeName)
assert.Equal(t, wfv1.NodeError, n.Phase)
}
var backoffMessage = `
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
creationTimestamp: "2020-05-05T15:18:40Z"
generateName: retry-backoff-
generation: 21
labels:
workflows.argoproj.io/completed: "true"
workflows.argoproj.io/phase: Failed
name: retry-backoff-s69z6
namespace: argo
resourceVersion: "348670"
selfLink: /apis/argoproj.io/v1alpha1/namespaces/argo/workflows/retry-backoff-s69z6
uid: 110dbef4-c54b-4963-9739-03e9878810d9
spec:
entrypoint: retry-backoff
templates:
-
container:
args:
- import random; import sys; exit_code = random.choice([1, 1]); sys.exit(exit_code)
command:
- python
- -c
image: python:alpine3.6
name: ""
resources: {}
inputs: {}
metadata: {}
name: retry-backoff
outputs: {}
retryStrategy:
backoff:
duration: "2"
factor: 2
maxDuration: 1m
limit: 10
status:
nodes:
retry-backoff-s69z6:
children:
- retry-backoff-s69z6-1807967148
- retry-backoff-s69z6-130058153
displayName: retry-backoff-s69z6
id: retry-backoff-s69z6
name: retry-backoff-s69z6
phase: Running
startedAt: "2020-05-05T15:18:40Z"
templateName: retry-backoff
templateScope: local/retry-backoff-s69z6
type: Retry
retry-backoff-s69z6-130058153:
displayName: retry-backoff-s69z6(1)
finishedAt: "2020-05-05T15:18:43Z"
hostNodeName: minikube
id: retry-backoff-s69z6-130058153
message: failed with exit code 1
name: retry-backoff-s69z6(1)
outputs:
artifacts:
- archiveLogs: true
name: main-logs
s3:
accessKeySecret:
key: accesskey
name: my-minio-cred
bucket: my-bucket
endpoint: minio:9000
insecure: true
key: retry-backoff-s69z6/retry-backoff-s69z6-130058153/main.log
secretKeySecret:
key: secretkey
name: my-minio-cred
exitCode: "1"
phase: Failed
resourcesDuration:
cpu: 1
memory: 0
startedAt: "2020-05-05T15:18:45Z"
templateName: retry-backoff
templateScope: local/retry-backoff-s69z6
type: Pod
retry-backoff-s69z6-1807967148:
displayName: retry-backoff-s69z6(0)
finishedAt: "2020-05-05T15:18:43Z"
hostNodeName: minikube
id: retry-backoff-s69z6-1807967148
message: failed with exit code 1
name: retry-backoff-s69z6(0)
outputs:
artifacts:
- archiveLogs: true
name: main-logs
s3:
accessKeySecret:
key: accesskey
name: my-minio-cred
bucket: my-bucket
endpoint: minio:9000
insecure: true
key: retry-backoff-s69z6/retry-backoff-s69z6-1807967148/main.log
secretKeySecret:
key: secretkey
name: my-minio-cred
exitCode: "1"
phase: Failed
resourcesDuration:
cpu: 2
memory: 0
startedAt: "2020-05-05T15:18:40Z"
templateName: retry-backoff
templateScope: local/retry-backoff-s69z6
type: Pod
phase: Running
resourcesDuration:
cpu: 5
memory: 0
startedAt: "2020-05-05T15:18:40Z"
`
func TestBackoffMessage(t *testing.T) {
cancel, controller := newController()
defer cancel()
assert.NotNil(t, controller)
wf := wfv1.MustUnmarshalWorkflow(backoffMessage)
assert.NotNil(t, wf)
woc := newWorkflowOperationCtx(wf, controller)
assert.NotNil(t, woc)
retryNode := woc.wf.GetNodeByName("retry-backoff-s69z6")
// Simulate backoff of 4 secods
firstNode := getChildNodeIndex(retryNode, woc.wf.Status.Nodes, 0)
firstNode.StartedAt = metav1.Time{Time: time.Now().Add(-8 * time.Second)}
firstNode.FinishedAt = metav1.Time{Time: time.Now().Add(-6 * time.Second)}
woc.wf.Status.Nodes[firstNode.ID] = *firstNode
lastNode := getChildNodeIndex(retryNode, woc.wf.Status.Nodes, -1)
lastNode.StartedAt = metav1.Time{Time: time.Now().Add(-3 * time.Second)}
lastNode.FinishedAt = metav1.Time{Time: time.Now().Add(-1 * time.Second)}
woc.wf.Status.Nodes[lastNode.ID] = *lastNode
newRetryNode, proceed, err := woc.processNodeRetries(retryNode, *woc.wf.Spec.Templates[0].RetryStrategy, &executeTemplateOpts{})
assert.NoError(t, err)
assert.False(t, proceed)
assert.Equal(t, "Backoff for 4 seconds", newRetryNode.Message)
// Advance time one second