-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
controller.go
1261 lines (1139 loc) · 44.6 KB
/
controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package controller
import (
"context"
"encoding/json"
"fmt"
"strconv"
"syscall"
"time"
"github.com/argoproj/pkg/errors"
syncpkg "github.com/argoproj/pkg/sync"
log "github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
"golang.org/x/time/rate"
apiv1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
runtimeutil "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
v1 "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
apiwatch "k8s.io/client-go/tools/watch"
"k8s.io/client-go/util/workqueue"
"upper.io/db.v3/lib/sqlbuilder"
"github.com/argoproj/argo-workflows/v3"
"github.com/argoproj/argo-workflows/v3/config"
argoErr "github.com/argoproj/argo-workflows/v3/errors"
"github.com/argoproj/argo-workflows/v3/persist/sqldb"
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/informers/externalversions"
wfextvv1alpha1 "github.com/argoproj/argo-workflows/v3/pkg/client/informers/externalversions/workflow/v1alpha1"
"github.com/argoproj/argo-workflows/v3/pkg/plugins/spec"
authutil "github.com/argoproj/argo-workflows/v3/util/auth"
"github.com/argoproj/argo-workflows/v3/util/diff"
"github.com/argoproj/argo-workflows/v3/util/env"
errorsutil "github.com/argoproj/argo-workflows/v3/util/errors"
"github.com/argoproj/argo-workflows/v3/workflow/artifactrepositories"
"github.com/argoproj/argo-workflows/v3/workflow/common"
controllercache "github.com/argoproj/argo-workflows/v3/workflow/controller/cache"
"github.com/argoproj/argo-workflows/v3/workflow/controller/entrypoint"
"github.com/argoproj/argo-workflows/v3/workflow/controller/estimation"
"github.com/argoproj/argo-workflows/v3/workflow/controller/indexes"
"github.com/argoproj/argo-workflows/v3/workflow/controller/informer"
"github.com/argoproj/argo-workflows/v3/workflow/controller/pod"
"github.com/argoproj/argo-workflows/v3/workflow/cron"
"github.com/argoproj/argo-workflows/v3/workflow/events"
"github.com/argoproj/argo-workflows/v3/workflow/gccontroller"
"github.com/argoproj/argo-workflows/v3/workflow/hydrator"
"github.com/argoproj/argo-workflows/v3/workflow/metrics"
"github.com/argoproj/argo-workflows/v3/workflow/signal"
"github.com/argoproj/argo-workflows/v3/workflow/sync"
"github.com/argoproj/argo-workflows/v3/workflow/util"
plugin "github.com/argoproj/argo-workflows/v3/workflow/util/plugins"
)
// WorkflowController is the controller for workflow resources
type WorkflowController struct {
// namespace of the workflow controller
namespace string
managedNamespace string
configController config.Controller
// Config is the workflow controller's configuration
Config config.Config
// get the artifact repository
artifactRepositories artifactrepositories.Interface
// get images
entrypoint entrypoint.Interface
// cliExecutorImage is the executor image as specified from the command line
cliExecutorImage string
// cliExecutorImagePullPolicy is the executor imagePullPolicy as specified from the command line
cliExecutorImagePullPolicy string
// cliExecutorLogFormat is the format in which argoexec will log
// possible options are json/text
cliExecutorLogFormat string
// restConfig is used by controller to send a SIGUSR1 to the wait sidecar using remotecommand.NewSPDYExecutor().
restConfig *rest.Config
kubeclientset kubernetes.Interface
rateLimiter *rate.Limiter
dynamicInterface dynamic.Interface
wfclientset wfclientset.Interface
// datastructures to support the processing of workflows and workflow pods
wfInformer cache.SharedIndexInformer
wftmplInformer wfextvv1alpha1.WorkflowTemplateInformer
cwftmplInformer wfextvv1alpha1.ClusterWorkflowTemplateInformer
podInformer cache.SharedIndexInformer
configMapInformer cache.SharedIndexInformer
wfQueue workqueue.RateLimitingInterface
podCleanupQueue workqueue.RateLimitingInterface // pods to be deleted or labelled depend on GC strategy
throttler sync.Throttler
workflowKeyLock syncpkg.KeyLock // used to lock workflows for exclusive modification or access
session sqlbuilder.Database
offloadNodeStatusRepo sqldb.OffloadNodeStatusRepo
hydrator hydrator.Interface
wfArchive sqldb.WorkflowArchive
estimatorFactory estimation.EstimatorFactory
syncManager *sync.Manager
metrics *metrics.Metrics
eventRecorderManager events.EventRecorderManager
archiveLabelSelector labels.Selector
cacheFactory controllercache.Factory
wfTaskSetInformer wfextvv1alpha1.WorkflowTaskSetInformer
artGCTaskInformer wfextvv1alpha1.WorkflowArtifactGCTaskInformer
taskResultInformer cache.SharedIndexInformer
// progressPatchTickDuration defines how often the executor will patch pod annotations if an updated progress is found.
// Default is 1m and can be configured using the env var ARGO_PROGRESS_PATCH_TICK_DURATION.
progressPatchTickDuration time.Duration
// progressFileTickDuration defines how often the progress file is read.
// Default is 3s and can be configured using the env var ARGO_PROGRESS_FILE_TICK_DURATION
progressFileTickDuration time.Duration
executorPlugins map[string]map[string]*spec.Plugin // namespace -> name -> plugin
}
const (
workflowResyncPeriod = 20 * time.Minute
workflowTemplateResyncPeriod = 20 * time.Minute
podResyncPeriod = 30 * time.Minute
clusterWorkflowTemplateResyncPeriod = 20 * time.Minute
workflowExistenceCheckPeriod = 1 * time.Minute
workflowTaskSetResyncPeriod = 20 * time.Minute
)
var (
cacheGCPeriod = env.LookupEnvDurationOr("CACHE_GC_PERIOD", 0)
// semaphoreNotifyDelay is a slight delay when notifying/enqueueing workflows to the workqueue
// that are waiting on a semaphore. This value is passed to AddAfter(). We delay adding the next
// workflow because if we add immediately with AddRateLimited(), the next workflow will likely
// be reconciled at a point in time before we have finished the current workflow reconciliation
// as well as incrementing the semaphore counter availability, and so the next workflow will
// believe it cannot run. By delaying for 1s, we would have finished the semaphore counter
// updates, and the next workflow will see the updated availability.
semaphoreNotifyDelay = env.LookupEnvDurationOr("SEMAPHORE_NOTIFY_DELAY", time.Second)
)
func init() {
if cacheGCPeriod != 0 {
log.WithField("cacheGCPeriod", cacheGCPeriod).Info("GC for memoization caches will be performed every")
}
}
// NewWorkflowController instantiates a new WorkflowController
func NewWorkflowController(ctx context.Context, restConfig *rest.Config, kubeclientset kubernetes.Interface, wfclientset wfclientset.Interface, namespace, managedNamespace, executorImage, executorImagePullPolicy, executorLogFormat, configMap string, executorPlugins bool) (*WorkflowController, error) {
dynamicInterface, err := dynamic.NewForConfig(restConfig)
if err != nil {
return nil, err
}
wfc := WorkflowController{
restConfig: restConfig,
kubeclientset: kubeclientset,
dynamicInterface: dynamicInterface,
wfclientset: wfclientset,
namespace: namespace,
managedNamespace: managedNamespace,
cliExecutorImage: executorImage,
cliExecutorImagePullPolicy: executorImagePullPolicy,
cliExecutorLogFormat: executorLogFormat,
configController: config.NewController(namespace, configMap, kubeclientset),
workflowKeyLock: syncpkg.NewKeyLock(),
cacheFactory: controllercache.NewCacheFactory(kubeclientset, namespace),
eventRecorderManager: events.NewEventRecorderManager(kubeclientset),
progressPatchTickDuration: env.LookupEnvDurationOr(common.EnvVarProgressPatchTickDuration, 1*time.Minute),
progressFileTickDuration: env.LookupEnvDurationOr(common.EnvVarProgressFileTickDuration, 3*time.Second),
}
if executorPlugins {
wfc.executorPlugins = map[string]map[string]*spec.Plugin{}
}
wfc.UpdateConfig(ctx)
wfc.metrics = metrics.New(wfc.getMetricsServerConfig())
wfc.entrypoint = entrypoint.New(kubeclientset, wfc.Config.Images)
workqueue.SetProvider(wfc.metrics) // must execute SetProvider before we created the queues
wfc.wfQueue = wfc.metrics.RateLimiterWithBusyWorkers(&fixedItemIntervalRateLimiter{}, "workflow_queue")
wfc.throttler = wfc.newThrottler()
wfc.podCleanupQueue = wfc.metrics.RateLimiterWithBusyWorkers(workqueue.DefaultControllerRateLimiter(), "pod_cleanup_queue")
return &wfc, nil
}
func (wfc *WorkflowController) newThrottler() sync.Throttler {
f := func(key string) { wfc.wfQueue.AddRateLimited(key) }
return sync.ChainThrottler{
sync.NewThrottler(wfc.Config.Parallelism, sync.SingleBucket, f),
sync.NewThrottler(wfc.Config.NamespaceParallelism, sync.NamespaceBucket, f),
}
}
// runGCcontroller runs the workflow garbage collector controller
func (wfc *WorkflowController) runGCcontroller(ctx context.Context, workflowTTLWorkers int) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
gcCtrl := gccontroller.NewController(wfc.wfclientset, wfc.wfInformer, wfc.metrics, wfc.Config.RetentionPolicy)
err := gcCtrl.Run(ctx.Done(), workflowTTLWorkers)
if err != nil {
panic(err)
}
}
func (wfc *WorkflowController) runCronController(ctx context.Context) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
cronController := cron.NewCronController(wfc.wfclientset, wfc.dynamicInterface, wfc.namespace, wfc.GetManagedNamespace(), wfc.Config.InstanceID, wfc.metrics, wfc.eventRecorderManager)
cronController.Run(ctx)
}
var indexers = cache.Indexers{
indexes.ClusterWorkflowTemplateIndex: indexes.MetaNamespaceLabelIndexFunc(common.LabelKeyClusterWorkflowTemplate),
indexes.CronWorkflowIndex: indexes.MetaNamespaceLabelIndexFunc(common.LabelKeyCronWorkflow),
indexes.WorkflowTemplateIndex: indexes.MetaNamespaceLabelIndexFunc(common.LabelKeyWorkflowTemplate),
indexes.SemaphoreConfigIndexName: indexes.WorkflowSemaphoreKeysIndexFunc(),
indexes.WorkflowPhaseIndex: indexes.MetaWorkflowPhaseIndexFunc(),
indexes.ConditionsIndex: indexes.ConditionsIndexFunc,
indexes.UIDIndex: indexes.MetaUIDFunc,
}
// Run starts an Workflow resource controller
func (wfc *WorkflowController) Run(ctx context.Context, wfWorkers, workflowTTLWorkers, podCleanupWorkers int) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
defer wfc.wfQueue.ShutDown()
defer wfc.podCleanupQueue.ShutDown()
log.WithField("version", argo.GetVersion().Version).
WithField("defaultRequeueTime", GetRequeueTime()).
Info("Starting Workflow Controller")
log.WithField("workflow", wfWorkers).
WithField("workflowTtl", workflowTTLWorkers).
WithField("podCleanup", podCleanupWorkers).
Info("Current Worker Numbers")
wfc.wfInformer = util.NewWorkflowInformer(wfc.dynamicInterface, wfc.GetManagedNamespace(), workflowResyncPeriod, wfc.tweakListOptions, indexers)
wfc.wftmplInformer = informer.NewTolerantWorkflowTemplateInformer(wfc.dynamicInterface, workflowTemplateResyncPeriod, wfc.managedNamespace)
wfc.wfTaskSetInformer = wfc.newWorkflowTaskSetInformer()
wfc.artGCTaskInformer = wfc.newArtGCTaskInformer()
wfc.taskResultInformer = wfc.newWorkflowTaskResultInformer()
wfc.addWorkflowInformerHandlers(ctx)
wfc.podInformer = wfc.newPodInformer(ctx)
wfc.updateEstimatorFactory()
wfc.configMapInformer = wfc.newConfigMapInformer()
// Create Synchronization Manager
wfc.createSynchronizationManager(ctx)
// init managers: throttler and SynchronizationManager
if err := wfc.initManagers(ctx); err != nil {
log.Fatal(err)
}
go wfc.runConfigMapWatcher(ctx.Done())
go wfc.wfInformer.Run(ctx.Done())
go wfc.wftmplInformer.Informer().Run(ctx.Done())
go wfc.podInformer.Run(ctx.Done())
go wfc.configMapInformer.Run(ctx.Done())
go wfc.wfTaskSetInformer.Informer().Run(ctx.Done())
go wfc.artGCTaskInformer.Informer().Run(ctx.Done())
go wfc.taskResultInformer.Run(ctx.Done())
wfc.createClusterWorkflowTemplateInformer(ctx)
// Wait for all involved caches to be synced, before processing items from the queue is started
if !cache.WaitForCacheSync(
ctx.Done(),
wfc.wfInformer.HasSynced,
wfc.wftmplInformer.Informer().HasSynced,
wfc.podInformer.HasSynced,
wfc.configMapInformer.HasSynced,
wfc.wfTaskSetInformer.Informer().HasSynced,
wfc.artGCTaskInformer.Informer().HasSynced,
wfc.taskResultInformer.HasSynced,
) {
log.Fatal("Timed out waiting for caches to sync")
}
// Start the metrics server
go wfc.metrics.RunServer(ctx)
for i := 0; i < podCleanupWorkers; i++ {
go wait.UntilWithContext(ctx, wfc.runPodCleanup, time.Second)
}
go wfc.workflowGarbageCollector(ctx.Done())
go wfc.archivedWorkflowGarbageCollector(ctx.Done())
go wfc.runGCcontroller(ctx, workflowTTLWorkers)
go wfc.runCronController(ctx)
go wait.Until(wfc.syncWorkflowPhaseMetrics, 15*time.Second, ctx.Done())
go wait.Until(wfc.syncPodPhaseMetrics, 15*time.Second, ctx.Done())
go wait.Until(wfc.syncManager.CheckWorkflowExistence, workflowExistenceCheckPeriod, ctx.Done())
for i := 0; i < wfWorkers; i++ {
go wait.Until(wfc.runWorker, time.Second, ctx.Done())
}
if cacheGCPeriod != 0 {
go wait.JitterUntilWithContext(ctx, wfc.syncAllCacheForGC, cacheGCPeriod, 0.0, true)
}
<-ctx.Done()
}
// Create and the Synchronization Manager
func (wfc *WorkflowController) createSynchronizationManager(ctx context.Context) {
getSyncLimit := func(lockKey string) (int, error) {
lockName, err := sync.DecodeLockName(lockKey)
if err != nil {
return 0, err
}
configMap, err := wfc.kubeclientset.CoreV1().ConfigMaps(lockName.Namespace).Get(ctx, lockName.ResourceName, metav1.GetOptions{})
if err != nil {
return 0, err
}
value, found := configMap.Data[lockName.Key]
if !found {
return 0, argoErr.New(argoErr.CodeBadRequest, fmt.Sprintf("Sync configuration key '%s' not found in ConfigMap", lockName.Key))
}
return strconv.Atoi(value)
}
nextWorkflow := func(key string) {
wfc.wfQueue.AddAfter(key, semaphoreNotifyDelay)
}
isWFDeleted := func(key string) bool {
_, exists, err := wfc.wfInformer.GetIndexer().GetByKey(key)
if err != nil {
log.WithFields(log.Fields{"key": key, "error": err}).Error("Failed to get workflow from informer")
return false
}
return exists
}
wfc.syncManager = sync.NewLockManager(getSyncLimit, nextWorkflow, isWFDeleted)
}
// list all running workflows to initialize throttler and syncManager
func (wfc *WorkflowController) initManagers(ctx context.Context) error {
labelSelector := labels.NewSelector().Add(util.InstanceIDRequirement(wfc.Config.InstanceID))
req, _ := labels.NewRequirement(common.LabelKeyPhase, selection.Equals, []string{string(wfv1.WorkflowRunning)})
if req != nil {
labelSelector = labelSelector.Add(*req)
}
listOpts := metav1.ListOptions{LabelSelector: labelSelector.String()}
wfList, err := wfc.wfclientset.ArgoprojV1alpha1().Workflows(wfc.namespace).List(ctx, listOpts)
if err != nil {
return err
}
wfc.syncManager.Initialize(wfList.Items)
if err := wfc.throttler.Init(wfList.Items); err != nil {
return err
}
return nil
}
func (wfc *WorkflowController) runConfigMapWatcher(stopCh <-chan struct{}) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
ctx := context.Background()
retryWatcher, err := apiwatch.NewRetryWatcher("1", &cache.ListWatch{
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return wfc.kubeclientset.CoreV1().ConfigMaps(wfc.managedNamespace).Watch(ctx, metav1.ListOptions{})
},
})
if err != nil {
panic(err)
}
defer retryWatcher.Stop()
for {
select {
case event := <-retryWatcher.ResultChan():
cm, ok := event.Object.(*apiv1.ConfigMap)
if !ok {
log.Errorf("invalid config map object received in config watcher. Ignored processing")
continue
}
log.Debugf("received config map %s/%s update", cm.Namespace, cm.Name)
if cm.GetName() == wfc.configController.GetName() && wfc.namespace == cm.GetNamespace() {
log.Infof("Received Workflow Controller config map %s/%s update", cm.Namespace, cm.Name)
wfc.UpdateConfig(ctx)
}
wfc.notifySemaphoreConfigUpdate(cm)
case <-stopCh:
return
}
}
}
// notifySemaphoreConfigUpdate will notify semaphore config update to pending workflows
func (wfc *WorkflowController) notifySemaphoreConfigUpdate(cm *apiv1.ConfigMap) {
wfs, err := wfc.wfInformer.GetIndexer().ByIndex(indexes.SemaphoreConfigIndexName, fmt.Sprintf("%s/%s", cm.Namespace, cm.Name))
if err != nil {
log.Errorf("failed get the workflow from informer. %v", err)
}
for _, obj := range wfs {
un, ok := obj.(*unstructured.Unstructured)
if !ok {
log.Warnf("received object from indexer %s is not an unstructured", indexes.SemaphoreConfigIndexName)
continue
}
wfc.wfQueue.AddRateLimited(fmt.Sprintf("%s/%s", un.GetNamespace(), un.GetName()))
}
}
// Check if the controller has RBAC access to ClusterWorkflowTemplates
func (wfc *WorkflowController) createClusterWorkflowTemplateInformer(ctx context.Context) {
cwftGetAllowed, err := authutil.CanI(ctx, wfc.kubeclientset, "get", "clusterworkflowtemplates", wfc.namespace, "")
errors.CheckError(err)
cwftListAllowed, err := authutil.CanI(ctx, wfc.kubeclientset, "list", "clusterworkflowtemplates", wfc.namespace, "")
errors.CheckError(err)
cwftWatchAllowed, err := authutil.CanI(ctx, wfc.kubeclientset, "watch", "clusterworkflowtemplates", wfc.namespace, "")
errors.CheckError(err)
if cwftGetAllowed && cwftListAllowed && cwftWatchAllowed {
wfc.cwftmplInformer = informer.NewTolerantClusterWorkflowTemplateInformer(wfc.dynamicInterface, clusterWorkflowTemplateResyncPeriod)
go wfc.cwftmplInformer.Informer().Run(ctx.Done())
// since the above call is asynchronous, make sure we populate our cache before we try to use it later
if !cache.WaitForCacheSync(
ctx.Done(),
wfc.cwftmplInformer.Informer().HasSynced,
) {
log.Fatal("Timed out waiting for ClusterWorkflowTemplate cache to sync")
}
} else {
log.Warnf("Controller doesn't have RBAC access for ClusterWorkflowTemplates")
}
}
func (wfc *WorkflowController) UpdateConfig(ctx context.Context) {
c, err := wfc.configController.Get(ctx)
if err != nil {
log.Fatalf("Failed to register watch for controller config map: %v", err)
}
wfc.Config = *c
err = wfc.updateConfig()
if err != nil {
log.Fatalf("Failed to update config: %v", err)
}
}
func (wfc *WorkflowController) queuePodForCleanup(namespace string, podName string, action podCleanupAction) {
wfc.podCleanupQueue.AddRateLimited(newPodCleanupKey(namespace, podName, action))
}
func (wfc *WorkflowController) queuePodForCleanupAfter(namespace string, podName string, action podCleanupAction, duration time.Duration) {
wfc.podCleanupQueue.AddAfter(newPodCleanupKey(namespace, podName, action), duration)
}
func (wfc *WorkflowController) runPodCleanup(ctx context.Context) {
for wfc.processNextPodCleanupItem(ctx) {
}
}
// all pods will ultimately be cleaned up by either deleting them, or labelling them
func (wfc *WorkflowController) processNextPodCleanupItem(ctx context.Context) bool {
key, quit := wfc.podCleanupQueue.Get()
if quit {
return false
}
defer func() {
wfc.podCleanupQueue.Forget(key)
wfc.podCleanupQueue.Done(key)
}()
namespace, podName, action := parsePodCleanupKey(key.(podCleanupKey))
logCtx := log.WithFields(log.Fields{"key": key, "action": action})
logCtx.Info("cleaning up pod")
err := func() error {
pods := wfc.kubeclientset.CoreV1().Pods(namespace)
switch action {
case terminateContainers:
if terminationGracePeriod, err := wfc.signalContainers(namespace, podName, syscall.SIGTERM); err != nil {
return err
} else if terminationGracePeriod > 0 {
wfc.queuePodForCleanupAfter(namespace, podName, killContainers, terminationGracePeriod)
}
case killContainers:
if _, err := wfc.signalContainers(namespace, podName, syscall.SIGKILL); err != nil {
return err
}
case labelPodCompleted:
_, err := pods.Patch(
ctx,
podName,
types.MergePatchType,
[]byte(`{"metadata": {"labels": {"workflows.argoproj.io/completed": "true"}}}`),
metav1.PatchOptions{},
)
if err != nil {
return err
}
case deletePod:
propagation := metav1.DeletePropagationBackground
err := pods.Delete(ctx, podName, metav1.DeleteOptions{
PropagationPolicy: &propagation,
GracePeriodSeconds: wfc.Config.PodGCGracePeriodSeconds,
})
if err != nil && !apierr.IsNotFound(err) {
return err
}
}
return nil
}()
if err != nil {
logCtx.WithError(err).Warn("failed to clean-up pod")
if errorsutil.IsTransientErr(err) {
wfc.podCleanupQueue.AddRateLimited(key)
}
}
return true
}
func (wfc *WorkflowController) getPod(namespace string, podName string) (*apiv1.Pod, error) {
obj, exists, err := wfc.podInformer.GetStore().GetByKey(namespace + "/" + podName)
if err != nil {
return nil, err
}
if !exists {
return nil, nil
}
pod, ok := obj.(*apiv1.Pod)
if !ok {
return nil, fmt.Errorf("object is not a pod")
}
return pod, nil
}
func (wfc *WorkflowController) signalContainers(namespace string, podName string, sig syscall.Signal) (time.Duration, error) {
pod, err := wfc.getPod(namespace, podName)
if pod == nil || err != nil {
return 0, err
}
for _, c := range pod.Status.ContainerStatuses {
if c.State.Running == nil {
continue
}
// problems are already logged at info level, so we just ignore errors here
_ = signal.SignalContainer(wfc.restConfig, pod, c.Name, sig)
}
if pod.Spec.TerminationGracePeriodSeconds == nil {
return 30 * time.Second, nil
}
return time.Duration(*pod.Spec.TerminationGracePeriodSeconds) * time.Second, nil
}
func (wfc *WorkflowController) workflowGarbageCollector(stopCh <-chan struct{}) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
periodicity := env.LookupEnvDurationOr("WORKFLOW_GC_PERIOD", 5*time.Minute)
log.WithField("periodicity", periodicity).Info("Performing periodic GC")
ticker := time.NewTicker(periodicity)
for {
select {
case <-stopCh:
ticker.Stop()
return
case <-ticker.C:
if wfc.offloadNodeStatusRepo.IsEnabled() {
log.Info("Performing periodic workflow GC")
oldRecords, err := wfc.offloadNodeStatusRepo.ListOldOffloads(wfc.GetManagedNamespace())
if err != nil {
log.WithField("err", err).Error("Failed to list old offloaded nodes")
continue
}
log.WithField("len_wfs", len(oldRecords)).Info("Deleting old offloads that are not live")
for uid, versions := range oldRecords {
if err := wfc.deleteOffloadedNodesForWorkflow(uid, versions); err != nil {
log.WithError(err).WithField("uid", uid).Error("Failed to delete old offloaded nodes")
}
}
log.Info("Workflow GC finished")
}
}
}
}
func (wfc *WorkflowController) deleteOffloadedNodesForWorkflow(uid string, versions []string) error {
workflows, err := wfc.wfInformer.GetIndexer().ByIndex(indexes.UIDIndex, uid)
if err != nil {
return err
}
var wf *wfv1.Workflow
switch l := len(workflows); l {
case 0:
log.WithField("uid", uid).Info("Workflow missing, probably deleted")
case 1:
un, ok := workflows[0].(*unstructured.Unstructured)
if !ok {
return fmt.Errorf("object %+v is not an unstructured", workflows[0])
}
wf, err = util.FromUnstructured(un)
if err != nil {
return err
}
key := wf.ObjectMeta.Namespace + "/" + wf.ObjectMeta.Name
wfc.workflowKeyLock.Lock(key)
defer wfc.workflowKeyLock.Unlock(key)
// workflow might still be hydrated
if wfc.hydrator.IsHydrated(wf) {
log.WithField("uid", wf.UID).Info("Hydrated workflow encountered")
err = wfc.hydrator.Dehydrate(wf)
if err != nil {
return err
}
}
default:
return fmt.Errorf("expected no more than 1 workflow, got %d", l)
}
for _, version := range versions {
// skip delete if offload is live
if wf != nil && wf.Status.OffloadNodeStatusVersion == version {
continue
}
if err := wfc.offloadNodeStatusRepo.Delete(uid, version); err != nil {
return err
}
}
return nil
}
func (wfc *WorkflowController) archivedWorkflowGarbageCollector(stopCh <-chan struct{}) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
periodicity := env.LookupEnvDurationOr("ARCHIVED_WORKFLOW_GC_PERIOD", 24*time.Hour)
if wfc.Config.Persistence == nil {
log.Info("Persistence disabled - so archived workflow GC disabled - you must restart the controller if you enable this")
return
}
if !wfc.Config.Persistence.Archive {
log.Info("Archive disabled - so archived workflow GC disabled - you must restart the controller if you enable this")
return
}
ttl := wfc.Config.Persistence.ArchiveTTL
if ttl == config.TTL(0) {
log.Info("Archived workflows TTL zero - so archived workflow GC disabled - you must restart the controller if you enable this")
return
}
log.WithFields(log.Fields{"ttl": ttl, "periodicity": periodicity}).Info("Performing archived workflow GC")
ticker := time.NewTicker(periodicity)
defer ticker.Stop()
for {
select {
case <-stopCh:
return
case <-ticker.C:
log.Info("Performing archived workflow GC")
err := wfc.wfArchive.DeleteExpiredWorkflows(time.Duration(ttl))
if err != nil {
log.WithField("err", err).Error("Failed to delete archived workflows")
}
}
}
}
func (wfc *WorkflowController) runWorker() {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
ctx := context.Background()
for wfc.processNextItem(ctx) {
}
}
// processNextItem is the worker logic for handling workflow updates
func (wfc *WorkflowController) processNextItem(ctx context.Context) bool {
key, quit := wfc.wfQueue.Get()
if quit {
return false
}
defer wfc.wfQueue.Done(key)
obj, exists, err := wfc.wfInformer.GetIndexer().GetByKey(key.(string))
if err != nil {
log.WithFields(log.Fields{"key": key, "error": err}).Error("Failed to get workflow from informer")
return true
}
if !exists {
// This happens after a workflow was labeled with completed=true
// or was deleted, but the work queue still had an entry for it.
return true
}
wfc.workflowKeyLock.Lock(key.(string))
defer wfc.workflowKeyLock.Unlock(key.(string))
// The workflow informer receives unstructured objects to deal with the possibility of invalid
// workflow manifests that are unable to unmarshal to workflow objects
un, ok := obj.(*unstructured.Unstructured)
if !ok {
log.WithFields(log.Fields{"key": key}).Warn("Index is not an unstructured")
return true
}
if !reconciliationNeeded(un) {
log.WithFields(log.Fields{"key": key}).Debug("Won't process Workflow since it's completed")
return true
}
wf, err := util.FromUnstructured(un)
if err != nil {
log.WithFields(log.Fields{"key": key, "error": err}).Warn("Failed to unmarshal key to workflow object")
woc := newWorkflowOperationCtx(wf, wfc)
woc.markWorkflowFailed(ctx, fmt.Sprintf("cannot unmarshall spec: %s", err.Error()))
woc.persistUpdates(ctx)
return true
}
// this will ensure we process every incomplete workflow once every 20m
wfc.wfQueue.AddAfter(key, workflowResyncPeriod)
woc := newWorkflowOperationCtx(wf, wfc)
if !wfc.throttler.Admit(key.(string)) {
log.WithField("key", key).Info("Workflow processing has been postponed due to max parallelism limit")
if woc.wf.Status.Phase == wfv1.WorkflowUnknown {
woc.markWorkflowPhase(ctx, wfv1.WorkflowPending, "Workflow processing has been postponed because too many workflows are already running")
woc.persistUpdates(ctx)
}
return true
}
// make sure this is removed from the throttler is complete
defer func() {
// must be done with woc
if !reconciliationNeeded(woc.wf) {
wfc.throttler.Remove(key.(string))
}
}()
err = wfc.hydrator.Hydrate(woc.wf)
if err != nil {
woc.log.Errorf("hydration failed: %v", err)
woc.markWorkflowError(ctx, err)
woc.persistUpdates(ctx)
return true
}
startTime := time.Now()
woc.operate(ctx)
wfc.metrics.OperationCompleted(time.Since(startTime).Seconds())
if woc.wf.Status.Fulfilled() {
err := woc.completeTaskSet(ctx)
if err != nil {
log.WithError(err).Warn("error to complete the taskset")
}
}
// TODO: operate should return error if it was unable to operate properly
// so we can requeue the work for a later time
// See: https://github.com/kubernetes/client-go/blob/master/examples/workqueue/main.go
// c.handleErr(err, key)
return true
}
func reconciliationNeeded(wf metav1.Object) bool {
return wf.GetLabels()[common.LabelKeyCompleted] != "true" || slices.Contains(wf.GetFinalizers(), common.FinalizerArtifactGC)
}
// enqueueWfFromPodLabel will extract the workflow name from pod label and
// enqueue workflow for processing
func (wfc *WorkflowController) enqueueWfFromPodLabel(obj interface{}) error {
pod, ok := obj.(*apiv1.Pod)
if !ok {
return fmt.Errorf("Key in index is not a pod")
}
if pod.Labels == nil {
return fmt.Errorf("Pod did not have labels")
}
workflowName, ok := pod.Labels[common.LabelKeyWorkflow]
if !ok {
// Ignore pods unrelated to workflow (this shouldn't happen unless the watch is setup incorrectly)
return fmt.Errorf("Watch returned pod unrelated to any workflow")
}
wfc.wfQueue.AddRateLimited(pod.ObjectMeta.Namespace + "/" + workflowName)
return nil
}
func (wfc *WorkflowController) tweakListOptions(options *metav1.ListOptions) {
labelSelector := labels.NewSelector().
Add(util.InstanceIDRequirement(wfc.Config.InstanceID))
options.LabelSelector = labelSelector.String()
}
func getWfPriority(obj interface{}) (int32, time.Time) {
un, ok := obj.(*unstructured.Unstructured)
if !ok {
return 0, time.Now()
}
priority, hasPriority, err := unstructured.NestedInt64(un.Object, "spec", "priority")
if err != nil {
return 0, un.GetCreationTimestamp().Time
}
if !hasPriority {
priority = 0
}
return int32(priority), un.GetCreationTimestamp().Time
}
func (wfc *WorkflowController) addWorkflowInformerHandlers(ctx context.Context) {
wfc.wfInformer.AddEventHandler(
cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
un, ok := obj.(*unstructured.Unstructured)
if !ok {
log.Warnf("Workflow FilterFunc: '%v' is not an unstructured", obj)
return false
}
return reconciliationNeeded(un)
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
// for a new workflow, we do not want to rate limit its execution using AddRateLimited
wfc.wfQueue.AddAfter(key, wfc.Config.InitialDelay.Duration)
priority, creation := getWfPriority(obj)
wfc.throttler.Add(key, priority, creation)
}
},
UpdateFunc: func(old, new interface{}) {
oldWf, newWf := old.(*unstructured.Unstructured), new.(*unstructured.Unstructured)
// this check is very important to prevent doing many reconciliations we do not need to do
if oldWf.GetResourceVersion() == newWf.GetResourceVersion() {
return
}
key, err := cache.MetaNamespaceKeyFunc(new)
if err == nil {
wfc.wfQueue.AddRateLimited(key)
priority, creation := getWfPriority(new)
wfc.throttler.Add(key, priority, creation)
}
},
DeleteFunc: func(obj interface{}) {
// IndexerInformer uses a delta queue, therefore for deletes we have to use this
// key function.
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err == nil {
wfc.releaseAllWorkflowLocks(obj)
// no need to add to the queue - this workflow is done
wfc.throttler.Remove(key)
}
},
},
},
)
wfc.wfInformer.AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
un, ok := obj.(*unstructured.Unstructured)
// no need to check the `common.LabelKeyCompleted` as we already know it must be complete
return ok && un.GetLabels()[common.LabelKeyWorkflowArchivingStatus] == "Pending"
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
wfc.archiveWorkflow(ctx, obj)
},
UpdateFunc: func(_, obj interface{}) {
wfc.archiveWorkflow(ctx, obj)
},
},
},
)
wfc.wfInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
DeleteFunc: func(obj interface{}) {
wf, ok := obj.(*unstructured.Unstructured)
if ok { // maybe cache.DeletedFinalStateUnknown
wfc.metrics.StopRealtimeMetricsForKey(string(wf.GetUID()))
}
},
})
}
func (wfc *WorkflowController) archiveWorkflow(ctx context.Context, obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
log.Error("failed to get key for object")
return
}
wfc.workflowKeyLock.Lock(key)
defer wfc.workflowKeyLock.Unlock(key)
err = wfc.archiveWorkflowAux(ctx, obj)
if err != nil {
log.WithField("key", key).WithError(err).Error("failed to archive workflow")
}
}
func (wfc *WorkflowController) archiveWorkflowAux(ctx context.Context, obj interface{}) error {
un, ok := obj.(*unstructured.Unstructured)
if !ok {
return nil
}
wf, err := util.FromUnstructured(un)
if err != nil {
return fmt.Errorf("failed to convert to workflow from unstructured: %w", err)
}
err = wfc.hydrator.Hydrate(wf)
if err != nil {
return fmt.Errorf("failed to hydrate workflow: %w", err)
}
log.WithFields(log.Fields{"namespace": wf.Namespace, "workflow": wf.Name, "uid": wf.UID}).Info("archiving workflow")
err = wfc.wfArchive.ArchiveWorkflow(wf)
if err != nil {
return fmt.Errorf("failed to archive workflow: %w", err)
}
data, err := json.Marshal(map[string]interface{}{
"metadata": metav1.ObjectMeta{
Labels: map[string]string{
common.LabelKeyWorkflowArchivingStatus: "Archived",
},
},
})
if err != nil {
return fmt.Errorf("failed to marshal patch: %w", err)
}
_, err = wfc.wfclientset.ArgoprojV1alpha1().Workflows(un.GetNamespace()).Patch(
ctx,
un.GetName(),
types.MergePatchType,
data,
metav1.PatchOptions{},
)
if err != nil {
// from this point on we have successfully archived the workflow, and it is possible for the workflow to have actually
// been deleted, so it's not a problem to get a `IsNotFound` error
if apierr.IsNotFound(err) {
return nil
}
return fmt.Errorf("failed to archive workflow: %w", err)
}
return nil
}
var (
incompleteReq, _ = labels.NewRequirement(common.LabelKeyCompleted, selection.Equals, []string{"false"})
workflowReq, _ = labels.NewRequirement(common.LabelKeyWorkflow, selection.Exists, nil)
)
func (wfc *WorkflowController) instanceIDReq() labels.Requirement {
return util.InstanceIDRequirement(wfc.Config.InstanceID)
}
func (wfc *WorkflowController) newWorkflowPodWatch(ctx context.Context) *cache.ListWatch {
c := wfc.kubeclientset.CoreV1().Pods(wfc.GetManagedNamespace())
// completed=false
labelSelector := labels.NewSelector().
Add(*workflowReq).
Add(*incompleteReq).
Add(wfc.instanceIDReq())
listFunc := func(options metav1.ListOptions) (runtime.Object, error) {
options.LabelSelector = labelSelector.String()
return c.List(ctx, options)
}
watchFunc := func(options metav1.ListOptions) (watch.Interface, error) {
options.Watch = true
options.LabelSelector = labelSelector.String()
return c.Watch(ctx, options)
}
return &cache.ListWatch{ListFunc: listFunc, WatchFunc: watchFunc}
}
func (wfc *WorkflowController) newPodInformer(ctx context.Context) cache.SharedIndexInformer {
source := wfc.newWorkflowPodWatch(ctx)
informer := cache.NewSharedIndexInformer(source, &apiv1.Pod{}, podResyncPeriod, cache.Indexers{
indexes.WorkflowIndex: indexes.MetaWorkflowIndexFunc,
indexes.NodeIDIndex: indexes.MetaNodeIDIndexFunc,
indexes.PodPhaseIndex: indexes.PodPhaseIndexFunc,
})
informer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {