-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
util.go
1054 lines (964 loc) · 34.8 KB
/
util.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 util
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
apiv1 "k8s.io/api/core/v1"
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/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers/internalinterfaces"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/pointer"
"sigs.k8s.io/yaml"
"github.com/argoproj/argo-workflows/v3/errors"
"github.com/argoproj/argo-workflows/v3/pkg/apis/workflow"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
wfclientset "github.com/argoproj/argo-workflows/v3/pkg/client/clientset/versioned"
"github.com/argoproj/argo-workflows/v3/pkg/client/clientset/versioned/typed/workflow/v1alpha1"
cmdutil "github.com/argoproj/argo-workflows/v3/util/cmd"
errorsutil "github.com/argoproj/argo-workflows/v3/util/errors"
"github.com/argoproj/argo-workflows/v3/util/retry"
unstructutil "github.com/argoproj/argo-workflows/v3/util/unstructured"
waitutil "github.com/argoproj/argo-workflows/v3/util/wait"
"github.com/argoproj/argo-workflows/v3/workflow/common"
"github.com/argoproj/argo-workflows/v3/workflow/hydrator"
"github.com/argoproj/argo-workflows/v3/workflow/packer"
"github.com/argoproj/argo-workflows/v3/workflow/templateresolution"
"github.com/argoproj/argo-workflows/v3/workflow/validate"
)
// NewWorkflowInformer returns the workflow informer used by the controller. This is actually
// a custom built UnstructuredInformer which is in actuality returning unstructured.Unstructured
// objects. We no longer return WorkflowInformer due to:
// https://github.com/kubernetes/kubernetes/issues/57705
// https://github.com/argoproj/argo-workflows/issues/632
func NewWorkflowInformer(dclient dynamic.Interface, ns string, resyncPeriod time.Duration, tweakListOptions internalinterfaces.TweakListOptionsFunc, indexers cache.Indexers) cache.SharedIndexInformer {
resource := schema.GroupVersionResource{
Group: workflow.Group,
Version: "v1alpha1",
Resource: workflow.WorkflowPlural,
}
informer := unstructutil.NewFilteredUnstructuredInformer(
resource,
dclient,
ns,
resyncPeriod,
indexers,
tweakListOptions,
)
return informer
}
// InstanceIDRequirement returns the label requirement to filter against a controller instance (or not)
func InstanceIDRequirement(instanceID string) labels.Requirement {
var instanceIDReq *labels.Requirement
var err error
if instanceID != "" {
instanceIDReq, err = labels.NewRequirement(common.LabelKeyControllerInstanceID, selection.Equals, []string{instanceID})
} else {
instanceIDReq, err = labels.NewRequirement(common.LabelKeyControllerInstanceID, selection.DoesNotExist, nil)
}
if err != nil {
panic(err)
}
return *instanceIDReq
}
// WorkflowLister implements the List() method of v1alpha.WorkflowLister interface but does so using
// an Unstructured informer and converting objects to workflows. Ignores objects that failed to convert.
type WorkflowLister interface {
List() ([]*wfv1.Workflow, error)
}
type workflowLister struct {
informer cache.SharedIndexInformer
}
func (l *workflowLister) List() ([]*wfv1.Workflow, error) {
workflows := make([]*wfv1.Workflow, 0)
for _, m := range l.informer.GetStore().List() {
wf, err := FromUnstructured(m.(*unstructured.Unstructured))
if err != nil {
log.Warnf("Failed to unmarshal workflow %v object: %v", m, err)
continue
}
workflows = append(workflows, wf)
}
return workflows, nil
}
// NewWorkflowLister returns a new workflow lister
func NewWorkflowLister(informer cache.SharedIndexInformer) WorkflowLister {
return &workflowLister{
informer: informer,
}
}
// FromUnstructured converts an unstructured object to a workflow.
// This function performs a lot of allocations and con resulting in a lot of memory
// being used. Users should avoid invoking this function if the data they need is
// available from `unstructured.Unstructured`. especially if they're looping.
// Available values include: `GetLabels()`, `GetName()`, `GetNamespace()` etc.
// Single values can be accessed using `unstructured.Nested*`, e.g.
// `unstructured.NestedString(un.Object, "spec", "phase")`.
func FromUnstructured(un *unstructured.Unstructured) (*wfv1.Workflow, error) {
var wf wfv1.Workflow
err := FromUnstructuredObj(un, &wf)
return &wf, err
}
func FromUnstructuredObj(un *unstructured.Unstructured, v interface{}) error {
err := runtime.DefaultUnstructuredConverter.FromUnstructured(un.Object, v)
if err != nil {
if err.Error() == "cannot convert int64 to v1alpha1.AnyString" {
data, err := json.Marshal(un)
if err != nil {
return err
}
return json.Unmarshal(data, v)
}
return err
}
return nil
}
// ToUnstructured converts an workflow to an Unstructured object
func ToUnstructured(wf *wfv1.Workflow) (*unstructured.Unstructured, error) {
obj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(wf)
if err != nil {
return nil, err
}
un := &unstructured.Unstructured{Object: obj}
// we need to add these values so that the `EventRecorder` does not error
un.SetKind(workflow.WorkflowKind)
un.SetAPIVersion(workflow.APIVersion)
return un, nil
}
// IsWorkflowCompleted returns whether or not a workflow is considered completed
func IsWorkflowCompleted(wf *wfv1.Workflow) bool {
if wf.ObjectMeta.Labels != nil {
return wf.ObjectMeta.Labels[common.LabelKeyCompleted] == "true"
}
return false
}
// SubmitWorkflow validates and submit a single workflow and override some of the fields of the workflow
func SubmitWorkflow(ctx context.Context, wfIf v1alpha1.WorkflowInterface, wfClientset wfclientset.Interface, namespace string, wf *wfv1.Workflow, opts *wfv1.SubmitOpts) (*wfv1.Workflow, error) {
err := ApplySubmitOpts(wf, opts)
if err != nil {
return nil, err
}
wftmplGetter := templateresolution.WrapWorkflowTemplateInterface(wfClientset.ArgoprojV1alpha1().WorkflowTemplates(namespace))
cwftmplGetter := templateresolution.WrapClusterWorkflowTemplateInterface(wfClientset.ArgoprojV1alpha1().ClusterWorkflowTemplates())
_, err = validate.ValidateWorkflow(wftmplGetter, cwftmplGetter, wf, validate.ValidateOpts{})
if err != nil {
return nil, err
}
if opts.DryRun {
return wf, nil
} else if opts.ServerDryRun {
wf, err := CreateServerDryRun(ctx, wf, wfClientset)
if err != nil {
return nil, err
}
return wf, err
} else {
return wfIf.Create(ctx, wf, metav1.CreateOptions{})
}
}
// CreateServerDryRun fills the workflow struct with the server's representation without creating it and returns an error, if there is any
func CreateServerDryRun(ctx context.Context, wf *wfv1.Workflow, wfClientset wfclientset.Interface) (*wfv1.Workflow, error) {
// Keep the workflow metadata because it will be overwritten by the Post request
workflowTypeMeta := wf.TypeMeta
err := wfClientset.ArgoprojV1alpha1().RESTClient().Post().
Namespace(wf.Namespace).
Resource("workflows").
Body(wf).
Param("dryRun", "All").
Do(ctx).
Into(wf)
wf.TypeMeta = workflowTypeMeta
return wf, err
}
func PopulateSubmitOpts(command *cobra.Command, submitOpts *wfv1.SubmitOpts, includeDryRun bool) {
command.Flags().StringVar(&submitOpts.Name, "name", "", "override metadata.name")
command.Flags().StringVar(&submitOpts.GenerateName, "generate-name", "", "override metadata.generateName")
command.Flags().StringVar(&submitOpts.Entrypoint, "entrypoint", "", "override entrypoint")
command.Flags().StringArrayVarP(&submitOpts.Parameters, "parameter", "p", []string{}, "pass an input parameter")
command.Flags().StringVar(&submitOpts.ServiceAccount, "serviceaccount", "", "run all pods in the workflow using specified serviceaccount")
command.Flags().StringVarP(&submitOpts.ParameterFile, "parameter-file", "f", "", "pass a file containing all input parameters")
command.Flags().StringVarP(&submitOpts.Labels, "labels", "l", "", "Comma separated labels to apply to the workflow. Will override previous values.")
if includeDryRun {
command.Flags().BoolVar(&submitOpts.DryRun, "dry-run", false, "modify the workflow on the client-side without creating it")
command.Flags().BoolVar(&submitOpts.ServerDryRun, "server-dry-run", false, "send request to server with dry-run flag which will modify the workflow without creating it")
}
}
// Apply the Submit options into workflow object
func ApplySubmitOpts(wf *wfv1.Workflow, opts *wfv1.SubmitOpts) error {
if opts == nil {
opts = &wfv1.SubmitOpts{}
}
if opts.Entrypoint != "" {
wf.Spec.Entrypoint = opts.Entrypoint
}
if opts.ServiceAccount != "" {
wf.Spec.ServiceAccountName = opts.ServiceAccount
}
wfLabels := wf.GetLabels()
if wfLabels == nil {
wfLabels = make(map[string]string)
}
if opts.Labels != "" {
passedLabels, err := cmdutil.ParseLabels(opts.Labels)
if err != nil {
return fmt.Errorf("expected labels of the form: NAME1=VALUE2,NAME2=VALUE2. Received: %s: %w", opts.Labels, err)
}
for k, v := range passedLabels {
wfLabels[k] = v
}
}
wf.SetLabels(wfLabels)
wfAnnotations := wf.GetAnnotations()
if wfAnnotations == nil {
wfAnnotations = make(map[string]string)
}
if opts.Annotations != "" {
fmt.Println(opts.Annotations)
passedAnnotations, err := cmdutil.ParseLabels(opts.Annotations)
if err != nil {
return fmt.Errorf("expected Annotations of the form: NAME1=VALUE2,NAME2=VALUE2. Received: %s: %w", opts.Labels, err)
}
for k, v := range passedAnnotations {
wfAnnotations[k] = v
}
}
wf.SetAnnotations(wfAnnotations)
if len(opts.Parameters) > 0 || opts.ParameterFile != "" {
newParams := make([]wfv1.Parameter, 0)
passedParams := make(map[string]bool)
for _, paramStr := range opts.Parameters {
parts := strings.SplitN(paramStr, "=", 2)
if len(parts) != 2 {
return fmt.Errorf("expected parameter of the form: NAME=VALUE. Received: %s", paramStr)
}
param := wfv1.Parameter{Name: parts[0], Value: wfv1.AnyStringPtr(parts[1])}
newParams = append(newParams, param)
passedParams[param.Name] = true
}
// Add parameters from a parameter-file, if one was provided
if opts.ParameterFile != "" {
var body []byte
var err error
if cmdutil.IsURL(opts.ParameterFile) {
body, err = ReadFromUrl(opts.ParameterFile)
if err != nil {
return errors.InternalWrapError(err)
}
} else {
body, err = ioutil.ReadFile(opts.ParameterFile)
if err != nil {
return errors.InternalWrapError(err)
}
}
yamlParams := map[string]json.RawMessage{}
err = yaml.Unmarshal(body, &yamlParams)
if err != nil {
return errors.InternalWrapError(err)
}
for k, v := range yamlParams {
// We get quoted strings from the yaml file.
value, err := strconv.Unquote(string(v))
if err != nil {
// the string is already clean.
value = string(v)
}
param := wfv1.Parameter{Name: k, Value: wfv1.AnyStringPtr(value)}
if _, ok := passedParams[param.Name]; ok {
// this parameter was overridden via command line
continue
}
newParams = append(newParams, param)
passedParams[param.Name] = true
}
}
for _, param := range wf.Spec.Arguments.Parameters {
if _, ok := passedParams[param.Name]; ok {
// this parameter was overridden via command line
continue
}
newParams = append(newParams, param)
}
wf.Spec.Arguments.Parameters = newParams
}
if opts.GenerateName != "" {
wf.ObjectMeta.GenerateName = opts.GenerateName
}
if opts.Name != "" {
wf.ObjectMeta.Name = opts.Name
}
if opts.OwnerReference != nil {
wf.SetOwnerReferences(append(wf.GetOwnerReferences(), *opts.OwnerReference))
}
return nil
}
// SuspendWorkflow suspends a workflow by setting spec.suspend to true. Retries conflict errors
func SuspendWorkflow(ctx context.Context, wfIf v1alpha1.WorkflowInterface, workflowName string) error {
err := waitutil.Backoff(retry.DefaultRetry, func() (bool, error) {
wf, err := wfIf.Get(ctx, workflowName, metav1.GetOptions{})
if err != nil {
return !errorsutil.IsTransientErr(err), err
}
if IsWorkflowCompleted(wf) {
return false, errSuspendedCompletedWorkflow
}
if wf.Spec.Suspend == nil || !*wf.Spec.Suspend {
wf.Spec.Suspend = pointer.BoolPtr(true)
_, err := wfIf.Update(ctx, wf, metav1.UpdateOptions{})
if apierr.IsConflict(err) {
return false, nil
}
return !errorsutil.IsTransientErr(err), err
}
return true, nil
})
return err
}
// ResumeWorkflow resumes a workflow by setting spec.suspend to nil and any suspended nodes to Successful.
// Retries conflict errors
func ResumeWorkflow(ctx context.Context, wfIf v1alpha1.WorkflowInterface, hydrator hydrator.Interface, workflowName string, nodeFieldSelector string) error {
if len(nodeFieldSelector) > 0 {
return updateSuspendedNode(ctx, wfIf, hydrator, workflowName, nodeFieldSelector, SetOperationValues{Phase: wfv1.NodeSucceeded})
} else {
err := waitutil.Backoff(retry.DefaultRetry, func() (bool, error) {
wf, err := wfIf.Get(ctx, workflowName, metav1.GetOptions{})
if err != nil {
return !errorsutil.IsTransientErr(err), err
}
err = hydrator.Hydrate(wf)
if err != nil {
return true, err
}
workflowUpdated := false
if wf.Spec.Suspend != nil && *wf.Spec.Suspend {
wf.Spec.Suspend = nil
workflowUpdated = true
}
// To resume a workflow with a suspended node we simply mark the node as Successful
for nodeID, node := range wf.Status.Nodes {
if node.IsActiveSuspendNode() {
if node.Outputs != nil {
for i, param := range node.Outputs.Parameters {
if param.ValueFrom != nil && param.ValueFrom.Supplied != nil {
if param.ValueFrom.Default != nil {
node.Outputs.Parameters[i].Value = param.ValueFrom.Default
node.Outputs.Parameters[i].ValueFrom = nil
} else {
return false, fmt.Errorf("raw output parameter '%s' has not been set and does not have a default value", param.Name)
}
}
}
}
node.Phase = wfv1.NodeSucceeded
node.FinishedAt = metav1.Time{Time: time.Now().UTC()}
wf.Status.Nodes[nodeID] = node
workflowUpdated = true
}
}
if workflowUpdated {
err := hydrator.Dehydrate(wf)
if err != nil {
return false, fmt.Errorf("unable to compress or offload workflow nodes: %s", err)
}
_, err = wfIf.Update(ctx, wf, metav1.UpdateOptions{})
if err != nil {
if apierr.IsConflict(err) {
return false, nil
}
return false, err
}
}
return true, nil
})
return err
}
}
func SelectorMatchesNode(selector fields.Selector, node wfv1.NodeStatus) bool {
nodeFields := fields.Set{
"displayName": node.DisplayName,
"templateName": node.TemplateName,
"phase": string(node.Phase),
"name": node.Name,
}
if node.TemplateRef != nil {
nodeFields["templateRef.name"] = node.TemplateRef.Name
nodeFields["templateRef.template"] = node.TemplateRef.Template
}
if node.Inputs != nil {
for _, inParam := range node.Inputs.Parameters {
nodeFields[fmt.Sprintf("inputs.parameters.%s.value", inParam.Name)] = inParam.Value.String()
}
}
return selector.Matches(nodeFields)
}
type SetOperationValues struct {
Phase wfv1.NodePhase
Message string
OutputParameters map[string]string
}
func AddParamToGlobalScope(wf *wfv1.Workflow, log *log.Entry, param wfv1.Parameter) bool {
wfUpdated := false
if param.GlobalName == "" {
return wfUpdated
}
index := -1
if wf.Status.Outputs != nil {
for i, gParam := range wf.Status.Outputs.Parameters {
if gParam.Name == param.GlobalName {
index = i
break
}
}
} else {
wf.Status.Outputs = &wfv1.Outputs{}
}
paramName := fmt.Sprintf("workflow.outputs.parameters.%s", param.GlobalName)
if index == -1 {
log.Infof("setting %s: '%s'", paramName, param.Value)
gParam := wfv1.Parameter{Name: param.GlobalName, Value: param.Value}
wf.Status.Outputs.Parameters = append(wf.Status.Outputs.Parameters, gParam)
wfUpdated = true
} else {
prevVal := *wf.Status.Outputs.Parameters[index].Value
if prevVal != *param.Value {
log.Infof("overwriting %s: '%s' -> '%s'", paramName, wf.Status.Outputs.Parameters[index].Value, param.Value)
wf.Status.Outputs.Parameters[index].Value = param.Value
wfUpdated = true
}
}
return wfUpdated
}
func updateSuspendedNode(ctx context.Context, wfIf v1alpha1.WorkflowInterface, hydrator hydrator.Interface, workflowName string, nodeFieldSelector string, values SetOperationValues) error {
selector, err := fields.ParseSelector(nodeFieldSelector)
if err != nil {
return err
}
err = waitutil.Backoff(retry.DefaultRetry, func() (bool, error) {
wf, err := wfIf.Get(ctx, workflowName, metav1.GetOptions{})
if err != nil {
return !errorsutil.IsTransientErr(err), err
}
err = hydrator.Hydrate(wf)
if err != nil {
return false, err
}
nodeUpdated := false
for nodeID, node := range wf.Status.Nodes {
if node.IsActiveSuspendNode() {
if SelectorMatchesNode(selector, node) {
// Update phase
if values.Phase != "" {
node.Phase = values.Phase
if values.Phase.Fulfilled() {
node.FinishedAt = metav1.Time{Time: time.Now().UTC()}
}
nodeUpdated = true
}
// Update message
if values.Message != "" {
node.Message = values.Message
nodeUpdated = true
}
// Update output parameters
if len(values.OutputParameters) > 0 {
if node.Outputs == nil {
return true, fmt.Errorf("cannot set output parameters because node is not expecting any raw parameters")
}
for name, val := range values.OutputParameters {
hit := false
for i, param := range node.Outputs.Parameters {
if param.Name == name {
if param.ValueFrom == nil || param.ValueFrom.Supplied == nil {
return true, fmt.Errorf("cannot set output parameter '%s' because it does not use valueFrom.raw or it was already set", param.Name)
}
node.Outputs.Parameters[i].Value = wfv1.AnyStringPtr(val)
node.Outputs.Parameters[i].ValueFrom = nil
nodeUpdated = true
hit = true
AddParamToGlobalScope(wf, log.NewEntry(log.StandardLogger()), node.Outputs.Parameters[i])
break
}
}
if !hit {
return true, fmt.Errorf("node is not expecting output parameter '%s'", name)
}
}
}
wf.Status.Nodes[nodeID] = node
}
}
}
if !nodeUpdated {
return true, fmt.Errorf("currently, set only targets suspend nodes: no suspend nodes matching nodeFieldSelector: %s", nodeFieldSelector)
}
err = hydrator.Dehydrate(wf)
if err != nil {
return true, fmt.Errorf("unable to compress or offload workflow nodes: %s", err)
}
_, err = wfIf.Update(ctx, wf, metav1.UpdateOptions{})
if err != nil {
if apierr.IsConflict(err) {
// Try again if we have a conflict
return false, nil
}
return true, err
}
return true, nil
})
return err
}
const letters = "abcdefghijklmnopqrstuvwxyz0123456789"
func init() {
rand.Seed(time.Now().UnixNano())
}
func randString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
// FormulateResubmitWorkflow formulate a new workflow from a previous workflow, optionally re-using successful nodes
func FormulateResubmitWorkflow(wf *wfv1.Workflow, memoized bool) (*wfv1.Workflow, error) {
newWF := wfv1.Workflow{}
newWF.TypeMeta = wf.TypeMeta
// Resubmitted workflow will use generated names
if wf.ObjectMeta.GenerateName != "" {
newWF.ObjectMeta.GenerateName = wf.ObjectMeta.GenerateName
} else {
newWF.ObjectMeta.GenerateName = wf.ObjectMeta.Name + "-"
}
// When resubmitting workflow with memoized nodes, we need to use a predetermined workflow name
// in order to formulate the node statuses. Which means we cannot reuse metadata.generateName
// The following simulates the behavior of generateName
if memoized {
switch wf.Status.Phase {
case wfv1.WorkflowFailed, wfv1.WorkflowError:
default:
return nil, errors.Errorf(errors.CodeBadRequest, "workflow must be Failed/Error to resubmit in memoized mode")
}
newWF.ObjectMeta.Name = newWF.ObjectMeta.GenerateName + randString(5)
}
// carry over the unmodified spec
newWF.Spec = wf.Spec
if newWF.Spec.ActiveDeadlineSeconds != nil && *newWF.Spec.ActiveDeadlineSeconds == 0 {
// if it was terminated, unset the deadline
newWF.Spec.ActiveDeadlineSeconds = nil
}
newWF.Spec.Shutdown = ""
// carry over user labels and annotations from previous workflow.
if newWF.ObjectMeta.Labels == nil {
newWF.ObjectMeta.Labels = make(map[string]string)
}
for key, val := range wf.ObjectMeta.Labels {
switch key {
case common.LabelKeyCreator, common.LabelKeyPhase, common.LabelKeyCompleted, common.LabelKeyWorkflowArchivingStatus:
// ignore
default:
newWF.ObjectMeta.Labels[key] = val
}
}
// Append an additional label so it's easy for user to see the
// name of the original workflow that has been resubmitted.
newWF.ObjectMeta.Labels[common.LabelKeyPreviousWorkflowName] = wf.ObjectMeta.Name
if newWF.ObjectMeta.Annotations == nil {
newWF.ObjectMeta.Annotations = make(map[string]string)
}
for key, val := range wf.ObjectMeta.Annotations {
newWF.ObjectMeta.Annotations[key] = val
}
// Setting OwnerReference from original Workflow
newWF.OwnerReferences = append(newWF.OwnerReferences, wf.OwnerReferences...)
if !memoized {
return &newWF, nil
}
// Iterate the previous nodes.
replaceRegexp := regexp.MustCompile("^" + wf.ObjectMeta.Name)
newWF.Status.Nodes = make(map[string]wfv1.NodeStatus)
onExitNodeName := wf.ObjectMeta.Name + ".onExit"
err := packer.DecompressWorkflow(wf)
if err != nil {
log.Fatal(err)
}
for _, node := range wf.Status.Nodes {
newNode := node.DeepCopy()
if strings.HasPrefix(node.Name, onExitNodeName) {
continue
}
originalID := node.ID
newNode.Name = replaceRegexp.ReplaceAllString(node.Name, newWF.ObjectMeta.Name)
newNode.ID = newWF.NodeID(newNode.Name)
if node.BoundaryID != "" {
newNode.BoundaryID = convertNodeID(&newWF, replaceRegexp, node.BoundaryID, wf.Status.Nodes)
}
if newNode.FailedOrError() && newNode.Type == wfv1.NodeTypePod {
newNode.StartedAt = metav1.Time{}
newNode.FinishedAt = metav1.Time{}
} else {
newNode.StartedAt = metav1.Time{Time: time.Now().UTC()}
newNode.FinishedAt = newNode.StartedAt
}
newChildren := make([]string, len(node.Children))
for i, childID := range node.Children {
newChildren[i] = convertNodeID(&newWF, replaceRegexp, childID, wf.Status.Nodes)
}
newNode.Children = newChildren
newOutboundNodes := make([]string, len(node.OutboundNodes))
for i, outboundID := range node.OutboundNodes {
newOutboundNodes[i] = convertNodeID(&newWF, replaceRegexp, outboundID, wf.Status.Nodes)
}
newNode.OutboundNodes = newOutboundNodes
if !newNode.FailedOrError() && newNode.Type == wfv1.NodeTypePod {
newNode.Phase = wfv1.NodeSkipped
newNode.Type = wfv1.NodeTypeSkipped
newNode.Message = fmt.Sprintf("original pod: %s", originalID)
} else {
newNode.Phase = wfv1.NodePending
newNode.Message = ""
}
newWF.Status.Nodes[newNode.ID] = *newNode
}
newWF.Status.StoredTemplates = make(map[string]wfv1.Template)
for id, tmpl := range wf.Status.StoredTemplates {
newWF.Status.StoredTemplates[id] = tmpl
}
newWF.Status.Conditions = wfv1.Conditions{{Status: metav1.ConditionFalse, Type: wfv1.ConditionTypeCompleted}}
newWF.Status.Phase = wfv1.WorkflowUnknown
return &newWF, nil
}
// convertNodeID converts an old nodeID to a new nodeID
func convertNodeID(newWf *wfv1.Workflow, regex *regexp.Regexp, oldNodeID string, oldNodes map[string]wfv1.NodeStatus) string {
node := oldNodes[oldNodeID]
newNodeName := regex.ReplaceAllString(node.Name, newWf.ObjectMeta.Name)
return newWf.NodeID(newNodeName)
}
// RetryWorkflow updates a workflow, deleting all failed steps as well as the onExit node (and children)
func RetryWorkflow(ctx context.Context, kubeClient kubernetes.Interface, hydrator hydrator.Interface, wfClient v1alpha1.WorkflowInterface, name string, restartSuccessful bool, nodeFieldSelector string) (*wfv1.Workflow, error) {
var updated *wfv1.Workflow
err := waitutil.Backoff(retry.DefaultRetry, func() (bool, error) {
var err error
updated, err = retryWorkflow(ctx, kubeClient, hydrator, wfClient, name, restartSuccessful, nodeFieldSelector)
return !errorsutil.IsTransientErr(err), err
})
if err != nil {
return nil, err
}
return updated, err
}
func retryWorkflow(ctx context.Context, kubeClient kubernetes.Interface, hydrator hydrator.Interface, wfClient v1alpha1.WorkflowInterface, name string, restartSuccessful bool, nodeFieldSelector string) (*wfv1.Workflow, error) {
wf, err := wfClient.Get(ctx, name, metav1.GetOptions{})
if err != nil {
return nil, err
}
switch wf.Status.Phase {
case wfv1.WorkflowFailed, wfv1.WorkflowError:
default:
return nil, errors.Errorf(errors.CodeBadRequest, "workflow must be Failed/Error to retry")
}
err = hydrator.Hydrate(wf)
if err != nil {
return nil, err
}
newWF := wf.DeepCopy()
podIf := kubeClient.CoreV1().Pods(wf.ObjectMeta.Namespace)
// Delete/reset fields which indicate workflow completed
delete(newWF.Labels, common.LabelKeyCompleted)
delete(newWF.Labels, common.LabelKeyWorkflowArchivingStatus)
newWF.Status.Conditions.UpsertCondition(wfv1.Condition{Status: metav1.ConditionFalse, Type: wfv1.ConditionTypeCompleted})
newWF.ObjectMeta.Labels[common.LabelKeyPhase] = string(wfv1.NodeRunning)
newWF.Status.Phase = wfv1.WorkflowRunning
newWF.Status.Nodes = make(wfv1.Nodes)
newWF.Status.Message = ""
newWF.Status.StartedAt = metav1.Time{Time: time.Now().UTC()}
newWF.Status.FinishedAt = metav1.Time{}
newWF.Spec.Shutdown = ""
if newWF.Spec.ActiveDeadlineSeconds != nil && *newWF.Spec.ActiveDeadlineSeconds == 0 {
// if it was terminated, unset the deadline
newWF.Spec.ActiveDeadlineSeconds = nil
}
onExitNodeName := wf.ObjectMeta.Name + ".onExit"
// Get all children of nodes that match filter
nodeIDsToReset, err := getNodeIDsToReset(restartSuccessful, nodeFieldSelector, wf.Status.Nodes)
if err != nil {
return nil, err
}
// Iterate the previous nodes. If it was successful Pod carry it forward
deletedNodes := make(map[string]bool)
for _, node := range wf.Status.Nodes {
doForceResetNode := false
if _, present := nodeIDsToReset[node.ID]; present {
// if we are resetting this node then don't carry it across regardless of its phase
doForceResetNode = true
}
switch node.Phase {
case wfv1.NodeSucceeded, wfv1.NodeSkipped:
if !strings.HasPrefix(node.Name, onExitNodeName) && !doForceResetNode {
newWF.Status.Nodes[node.ID] = node
continue
}
case wfv1.NodeError, wfv1.NodeFailed, wfv1.NodeOmitted:
if !strings.HasPrefix(node.Name, onExitNodeName) && (node.Type == wfv1.NodeTypeDAG || node.Type == wfv1.NodeTypeStepGroup) {
newNode := node.DeepCopy()
newNode.Phase = wfv1.NodeRunning
newNode.Message = ""
newNode.StartedAt = metav1.Time{Time: time.Now().UTC()}
newNode.FinishedAt = metav1.Time{}
newWF.Status.Nodes[newNode.ID] = *newNode
continue
} else {
deletedNodes[node.ID] = true
}
// do not add this status to the node. pretend as if this node never existed.
default:
// Do not allow retry of workflows with pods in Running/Pending phase
return nil, errors.InternalErrorf("Workflow cannot be retried with node %s in %s phase", node.Name, node.Phase)
}
if node.Type == wfv1.NodeTypePod {
log.Infof("Deleting pod: %s", node.ID)
err := podIf.Delete(ctx, node.ID, metav1.DeleteOptions{})
if err != nil && !apierr.IsNotFound(err) {
return nil, errors.InternalWrapError(err)
}
} else if node.Name == wf.ObjectMeta.Name {
newNode := node.DeepCopy()
newNode.Phase = wfv1.NodeRunning
newNode.Message = ""
newNode.StartedAt = metav1.Time{Time: time.Now().UTC()}
newNode.FinishedAt = metav1.Time{}
newWF.Status.Nodes[newNode.ID] = *newNode
continue
}
}
if len(deletedNodes) > 0 {
for _, node := range newWF.Status.Nodes {
var newChildren []string
for _, child := range node.Children {
if !deletedNodes[child] {
newChildren = append(newChildren, child)
}
}
node.Children = newChildren
var outboundNodes []string
for _, outboundNode := range node.OutboundNodes {
if !deletedNodes[outboundNode] {
outboundNodes = append(outboundNodes, outboundNode)
}
}
node.OutboundNodes = outboundNodes
newWF.Status.Nodes[node.ID] = node
}
}
err = hydrator.Dehydrate(newWF)
if err != nil {
return nil, fmt.Errorf("unable to compress or offload workflow nodes: %s", err)
}
newWF.Status.StoredTemplates = make(map[string]wfv1.Template)
for id, tmpl := range wf.Status.StoredTemplates {
newWF.Status.StoredTemplates[id] = tmpl
}
return wfClient.Update(ctx, newWF, metav1.UpdateOptions{})
}
func getNodeIDsToReset(restartSuccessful bool, nodeFieldSelector string, nodes wfv1.Nodes) (map[string]bool, error) {
nodeIDsToReset := make(map[string]bool)
if !restartSuccessful || len(nodeFieldSelector) == 0 {
return nodeIDsToReset, nil
}
selector, err := fields.ParseSelector(nodeFieldSelector)
if err != nil {
return nil, err
} else {
for _, node := range nodes {
if SelectorMatchesNode(selector, node) {
// traverse all children of the node
var queue []string
queue = append(queue, node.ID)
for len(queue) > 0 {
childNode := queue[0]
// if the child isn't already in nodeIDsToReset then we add it and traverse its children
if _, present := nodeIDsToReset[childNode]; !present {
nodeIDsToReset[childNode] = true
queue = append(queue, nodes[childNode].Children...)
}
queue = queue[1:]
}
}
}
}
return nodeIDsToReset, nil
}
var errSuspendedCompletedWorkflow = errors.Errorf(errors.CodeBadRequest, "cannot suspend completed workflows")
// IsWorkflowSuspended returns whether or not a workflow is considered suspended
func IsWorkflowSuspended(wf *wfv1.Workflow) bool {
if wf.Spec.Suspend != nil && *wf.Spec.Suspend {
return true
}
for _, node := range wf.Status.Nodes {
if node.IsActiveSuspendNode() {
return true
}
}
return false
}
// TerminateWorkflow terminates a workflow by setting its spec.shutdown to ShutdownStrategyTerminate
func TerminateWorkflow(ctx context.Context, wfClient v1alpha1.WorkflowInterface, name string) error {
return patchShutdownStrategy(ctx, wfClient, name, wfv1.ShutdownStrategyTerminate)
}
// StopWorkflow terminates a workflow by setting its spec.shutdown to ShutdownStrategyStop
// Or terminates a single resume step referenced by nodeFieldSelector
func StopWorkflow(ctx context.Context, wfClient v1alpha1.WorkflowInterface, hydrator hydrator.Interface, name string, nodeFieldSelector string, message string) error {
if len(nodeFieldSelector) > 0 {
return updateSuspendedNode(ctx, wfClient, hydrator, name, nodeFieldSelector, SetOperationValues{Phase: wfv1.NodeFailed, Message: message})
}
return patchShutdownStrategy(ctx, wfClient, name, wfv1.ShutdownStrategyStop)
}
// patchShutdownStrategy patches the shutdown strategy to a workflow.
func patchShutdownStrategy(ctx context.Context, wfClient v1alpha1.WorkflowInterface, name string, strategy wfv1.ShutdownStrategy) error {
patchObj := map[string]interface{}{
"spec": map[string]interface{}{
"shutdown": strategy,
},
}
var err error
patch, err := json.Marshal(patchObj)
if err != nil {
return errors.InternalWrapError(err)
}
err = waitutil.Backoff(retry.DefaultRetry, func() (bool, error) {
_, err := wfClient.Patch(ctx, name, types.MergePatchType, patch, metav1.PatchOptions{})
if apierr.IsConflict(err) {
return false, nil
}
return !errorsutil.IsTransientErr(err), err
})
return err
}
func SetWorkflow(ctx context.Context, wfClient v1alpha1.WorkflowInterface, hydrator hydrator.Interface, name string, nodeFieldSelector string, values SetOperationValues) error {
if nodeFieldSelector != "" {
return updateSuspendedNode(ctx, wfClient, hydrator, name, nodeFieldSelector, values)
}
return fmt.Errorf("'set' currently only targets suspend nodes, use a node field selector to target them")
}
// Reads from stdin
func ReadFromStdin() ([]byte, error) {
reader := bufio.NewReader(os.Stdin)
body, err := ioutil.ReadAll(reader)
if err != nil {
return []byte{}, err
}
return body, err
}
// Reads the content of a url
func ReadFromUrl(url string) ([]byte, error) {
response, err := http.Get(url)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(response.Body)
_ = response.Body.Close()
if err != nil {
return nil, err
}
return body, err
}
// ReadFromFilePathsOrUrls reads the content of a single or a list of file paths and/or urls
func ReadFromFilePathsOrUrls(filePathsOrUrls ...string) ([][]byte, error) {
var fileContents [][]byte
var body []byte
var err error
for _, filePathOrUrl := range filePathsOrUrls {
if cmdutil.IsURL(filePathOrUrl) {
body, err = ReadFromUrl(filePathOrUrl)
if err != nil {
return [][]byte{}, err
}
} else {
body, err = ioutil.ReadFile(filePathOrUrl)
if err != nil {
return [][]byte{}, err
}
}
fileContents = append(fileContents, body)
}
return fileContents, err
}
// ReadManifest reads from stdin, a single file/url, or a list of files and/or urls
func ReadManifest(manifestPaths ...string) ([][]byte, error) {
var manifestContents [][]byte
var err error
if len(manifestPaths) == 1 && manifestPaths[0] == "-" {
body, err := ReadFromStdin()
if err != nil {
return [][]byte{}, err
}
manifestContents = append(manifestContents, body)
} else {