Repository navigation
Expand file tree
/
Copy pathcontroller.go
More file actions
1961 lines (1767 loc) · 74.1 KB
/
Copy pathcontroller.go
File metadata and controls
1961 lines (1767 loc) · 74.1 KB
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
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resourceclaim
import (
"context"
"errors"
"fmt"
"maps"
"slices"
"strings"
"sync"
"time"
v1 "k8s.io/api/core/v1"
resourceapi "k8s.io/api/resource/v1"
schedulingapi "k8s.io/api/scheduling/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
utilfeature "k8s.io/apiserver/pkg/util/feature"
corev1apply "k8s.io/client-go/applyconfigurations/core/v1"
schedulingapply "k8s.io/client-go/applyconfigurations/scheduling/v1beta1"
v1informers "k8s.io/client-go/informers/core/v1"
resourceinformers "k8s.io/client-go/informers/resource/v1"
schedulinginformers "k8s.io/client-go/informers/scheduling/v1beta1"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
v1core "k8s.io/client-go/kubernetes/typed/core/v1"
v1listers "k8s.io/client-go/listers/core/v1"
resourcelisters "k8s.io/client-go/listers/resource/v1"
schedulinglisters "k8s.io/client-go/listers/scheduling/v1beta1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
"k8s.io/component-base/metrics"
"k8s.io/dynamic-resource-allocation/resourceclaim"
resourceclaimmetrics "k8s.io/dynamic-resource-allocation/resourceclaim/metrics"
"k8s.io/klog/v2"
podutil "k8s.io/kubernetes/pkg/api/v1/pod"
controllermetrics "k8s.io/kubernetes/pkg/controller/resourceclaim/metrics"
"k8s.io/kubernetes/pkg/features"
"k8s.io/utils/ptr"
)
const (
// podResourceClaimIndex is the lookup name for the index function which indexes by pod ResourceClaim.
podResourceClaimIndex = "podResourceClaim"
// podResourceClaimTemplateIndex is the lookup name for the index function which indexes only by pod ResourceClaim templates.
podResourceClaimTemplateIndex = "podResourceClaimTemplate"
// podGroupResourceClaimIndex is the lookup name for the index function
// which indexes by PodGroup ResourceClaim.
podGroupResourceClaimIndex = "podGroupResourceClaim"
// podGroupResourceClaimTemplateIndex is the lookup name for the index
// function which indexes only by PodGroup ResourceClaim templates.
podGroupResourceClaimTemplateIndex = "podGroupResourceClaimTemplate"
// claimPodOwnerIndex is used to find ResourceClaims which have
// a specific pod as owner. Values for this index are the pod "namespace/UID".
claimPodOwnerIndex = "claimPodOwner"
// claimPodGroupOwnerIndex is used to find ResourceClaims which have a
// specific PodGroup as owner. Values for this index are the PodGroup
// "namespace/UID".
claimPodGroupOwnerIndex = "claimPodGroupOwner"
// podGroupMembersIndex is used to find Pods in a given PodGroup.
podGroupMembersIndex = "podGroupMembers"
// claimMutationCacheSize is the size of the LRU in the claim mutation cache.
claimMutationCacheSize = 1000
// Field manager used to update the pod status.
fieldManager = "ResourceClaimController"
maxUIDCacheEntries = 500
schedulingAPIGroupPrefix = schedulingapi.GroupName + "/"
)
// Controller creates ResourceClaims for ResourceClaimTemplates in a pod spec.
type Controller struct {
// features defines the feature gates that are enabled.
features controllerFeatures
// kubeClient is the kube API client used to communicate with the API
// server.
kubeClient clientset.Interface
// claimLister is the shared ResourceClaim lister used to fetch and store ResourceClaim
// objects from the API server. It is shared with other controllers and
// therefore the ResourceClaim objects in its store should be treated as immutable.
claimLister resourcelisters.ResourceClaimLister
claimsSynced cache.InformerSynced
claimCache cache.MutationCache
// podLister is the shared Pod lister used to fetch Pod
// objects from the API server. It is shared with other controllers and
// therefore the Pod objects in its store should be treated as immutable.
podLister v1listers.PodLister
podSynced cache.InformerSynced
// podGroupLister is the shared PodGroup lister used to fetch PodGroup
// objects from the API server. It is shared with other controllers and
// therefore the PodGroup objects in its store should be treated as immutable.
podGroupLister schedulinglisters.PodGroupLister
podGroupSynced cache.InformerSynced
// templateLister is the shared ResourceClaimTemplate lister used to
// fetch template objects from the API server. It is shared with other
// controllers and therefore the objects in its store should be treated
// as immutable.
templateLister resourcelisters.ResourceClaimTemplateLister
templatesSynced cache.InformerSynced
// podIndexer has the common PodResourceClaim indexer installed To
// limit iteration over pods to those of interest.
podIndexer cache.Indexer
// podGroupIndexer has the common PodGroupResourceClaim indexer installed To
// limit iteration over PodGroups to those of interest.
podGroupIndexer cache.Indexer
// recorder is used to record events in the API server
recorder record.EventRecorder
// syncHandlerFunc runs for each item in the workqueue. It is replaced in
// some tests that exercise the workqueue.
syncHandlerFunc func(context.Context, string) error
queue workqueue.TypedRateLimitingInterface[string]
// The deletedObjects cache keeps track of Pods for which we know that
// they have existed and have been removed. For those we can be sure
// that a ReservedFor entry needs to be removed.
deletedObjects *uidCache
}
const (
claimKeyPrefix = "claim:"
podKeyPrefix = "pod:"
podGroupKeyPrefix = "podgroup:"
)
// controllerFeatures defines which features should be enabled in the controller.
type controllerFeatures struct {
AdminAccess bool
GenericWorkload bool
PrioritizedList bool
WorkloadResourceClaims bool
}
// String describes the features suitably for unit test names.
func (f controllerFeatures) String() string {
enabled := func(b bool) string {
if b {
return "enabled"
}
return "disabled"
}
return fmt.Sprintf(
"adminaccess-%s-genericworkload-%s-prioritizedlist-%s-workloadresourceclaims-%s",
enabled(f.AdminAccess),
enabled(f.GenericWorkload),
enabled(f.PrioritizedList),
enabled(f.WorkloadResourceClaims),
)
}
// nonRetryableError is an error for a key in the workqueue that will not be requeued.
type nonRetryableError struct {
error
}
// NewController creates a ResourceClaim controller.
func NewController(
logger klog.Logger,
kubeClient clientset.Interface,
podInformer v1informers.PodInformer,
podGroupInformer schedulinginformers.PodGroupInformer,
claimInformer resourceinformers.ResourceClaimInformer,
templateInformer resourceinformers.ResourceClaimTemplateInformer) (*Controller, error) {
return newControllerWithFeatures(
logger,
kubeClient,
podInformer,
podGroupInformer,
claimInformer,
templateInformer,
controllerFeatures{
AdminAccess: utilfeature.DefaultFeatureGate.Enabled(features.DRAAdminAccess),
GenericWorkload: utilfeature.DefaultFeatureGate.Enabled(features.GenericWorkload),
PrioritizedList: utilfeature.DefaultFeatureGate.Enabled(features.DRAPrioritizedList),
WorkloadResourceClaims: utilfeature.DefaultFeatureGate.Enabled(features.DRAWorkloadResourceClaims),
},
)
}
func newControllerWithFeatures(
logger klog.Logger,
kubeClient clientset.Interface,
podInformer v1informers.PodInformer,
podGroupInformer schedulinginformers.PodGroupInformer,
claimInformer resourceinformers.ResourceClaimInformer,
templateInformer resourceinformers.ResourceClaimTemplateInformer,
features controllerFeatures) (*Controller, error) {
ec := &Controller{
features: features,
kubeClient: kubeClient,
podLister: podInformer.Lister(),
podIndexer: podInformer.Informer().GetIndexer(),
podSynced: podInformer.Informer().HasSynced,
claimLister: claimInformer.Lister(),
claimsSynced: claimInformer.Informer().HasSynced,
templateLister: templateInformer.Lister(),
templatesSynced: templateInformer.Informer().HasSynced,
queue: workqueue.NewTypedRateLimitingQueueWithConfig(
workqueue.DefaultTypedControllerRateLimiter[string](),
workqueue.TypedRateLimitingQueueConfig[string]{Name: "resource_claim"},
),
deletedObjects: newUIDCache(maxUIDCacheEntries),
}
ec.syncHandlerFunc = ec.syncHandler
resourceclaimmetrics.RegisterMetrics()
controllermetrics.RegisterMetrics(newCustomCollector(ec.claimLister, getAdminAccessMetricLabel, logger))
if _, err := podInformer.Informer().AddEventHandlerWithOptions(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj any) {
ec.enqueuePod(logger, obj, false)
},
UpdateFunc: func(old, updated any) {
ec.enqueuePod(logger, updated, false)
},
DeleteFunc: func(obj any) {
ec.enqueuePod(logger, obj, true)
},
}, cache.HandlerOptions{Logger: &logger}); err != nil {
return nil, err
}
if _, err := claimInformer.Informer().AddEventHandlerWithOptions(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj any) {
logger.V(6).Info("New claim", "claimDump", obj)
ec.enqueueResourceClaim(logger, nil, obj)
},
UpdateFunc: func(old, updated any) {
logger.V(6).Info("Updated claim", "claimDump", updated)
ec.enqueueResourceClaim(logger, old, updated)
},
DeleteFunc: func(obj any) {
logger.V(6).Info("Deleted claim", "claimDump", obj)
ec.enqueueResourceClaim(logger, obj, nil)
},
}, cache.HandlerOptions{Logger: &logger}); err != nil {
return nil, err
}
if _, err := templateInformer.Informer().AddEventHandlerWithOptions(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj any) {
logger.V(6).Info("New claim template", "claimTemplateDump", obj)
ec.enqueueResourceClaimTemplate(logger, obj)
},
UpdateFunc: func(old, updated any) {
logger.V(6).Info("Updated claim template", "claimTemplateDump", updated)
ec.enqueueResourceClaimTemplate(logger, updated)
},
DeleteFunc: func(obj any) {
logger.V(6).Info("Deleted claim template", "claimTemplateDump", obj)
},
}, cache.HandlerOptions{Logger: &logger}); err != nil {
return nil, err
}
if err := ec.podIndexer.AddIndexers(cache.Indexers{podResourceClaimIndex: podResourceClaimIndexFunc}); err != nil {
return nil, fmt.Errorf("could not initialize ResourceClaim controller: %w", err)
}
if err := ec.podIndexer.AddIndexers(cache.Indexers{podResourceClaimTemplateIndex: podResourceClaimTemplateIndexFunc}); err != nil {
return nil, fmt.Errorf("could not initialize ResourceClaim controller: %w", err)
}
if features.GenericWorkload {
ec.podGroupLister = podGroupInformer.Lister()
}
ec.podGroupSynced = func() bool { return true }
if features.WorkloadResourceClaims {
ec.podGroupSynced = podGroupInformer.Informer().HasSynced
ec.podGroupIndexer = podGroupInformer.Informer().GetIndexer()
if _, err := podGroupInformer.Informer().AddEventHandlerWithOptions(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj any) {
logger.V(6).Info("New PodGroup", "podGroupDump", obj)
ec.enqueuePodGroup(logger, obj, false)
},
UpdateFunc: func(old, updated any) {
logger.V(6).Info("Updated PodGroup", "podGroupDump", updated)
ec.enqueuePodGroup(logger, updated, false)
},
DeleteFunc: func(obj any) {
logger.V(6).Info("Deleted PodGroup", "podGroupDump", obj)
ec.enqueuePodGroup(logger, obj, true)
},
}, cache.HandlerOptions{Logger: &logger}); err != nil {
return nil, err
}
if err := ec.podGroupIndexer.AddIndexers(cache.Indexers{podGroupResourceClaimIndex: podGroupResourceClaimIndexFunc}); err != nil {
return nil, fmt.Errorf("could not initialize ResourceClaim controller: %w", err)
}
if err := ec.podGroupIndexer.AddIndexers(cache.Indexers{podGroupResourceClaimTemplateIndex: podGroupResourceClaimTemplateIndexFunc}); err != nil {
return nil, fmt.Errorf("could not initialize ResourceClaim controller: %w", err)
}
if err := ec.podIndexer.AddIndexers(cache.Indexers{podGroupMembersIndex: podGroupMemberIndexFunc}); err != nil {
return nil, fmt.Errorf("could not initialize ResourceClaim controller: %w", err)
}
if err := claimInformer.Informer().GetIndexer().AddIndexers(cache.Indexers{claimPodGroupOwnerIndex: claimPodGroupOwnerIndexFunc}); err != nil {
return nil, fmt.Errorf("could not initialize ResourceClaim controller: %w", err)
}
}
// The mutation cache acts as an additional layer for the informer
// cache and after a create made by the controller returns that
// object until the informer catches up. That is necessary
// when a ResourceClaim got created, updating the pod status fails,
// and then a retry occurs before the informer cache is updated.
// In that scenario, the controller would create another claim
// instead of continuing with the existing one.
claimInformerCache := claimInformer.Informer().GetIndexer()
if err := claimInformerCache.AddIndexers(cache.Indexers{claimPodOwnerIndex: claimPodOwnerIndexFunc}); err != nil {
return nil, fmt.Errorf("could not initialize ResourceClaim controller: %w", err)
}
ec.claimCache = cache.NewIntegerResourceVersionMutationCacheWithOptions(logger, claimInformerCache, cache.MutationCacheOptions{
Indexer: claimInformerCache,
// Very long time to live, unlikely to be needed because
// the informer cache should get updated soon.
TTL: time.Hour,
// Allow storing objects not in the underlying cache - that's the point...
// It's safe because in case of a race (claim is in mutation cache, claim
// gets deleted, controller updates status based on mutation cache) the
// "bad" pod status will get detected and fixed when the informer catches up.
IncludeAdds: true,
// Tracks more recently mutated objects than the default (100)
// so that lookups still succeed locally while the informer cache lags
// behind etcd, avoiding the fallback GET against the apiserver.
MaxCacheSize: claimMutationCacheSize,
},
)
return ec, nil
}
func (ec *Controller) enqueueResourceClaimTemplate(logger klog.Logger, obj any) {
if d, ok := obj.(cache.DeletedFinalStateUnknown); ok {
obj = d.Obj
}
template, ok := obj.(*resourceapi.ResourceClaimTemplate)
if !ok {
// Not a template,return
runtime.HandleErrorWithLogger(logger, nil, "EnqueueResourceClaimTemplate called for unexpected object", "type", fmt.Sprintf("%T", obj))
return
}
logger.V(6).Info("ResourceClaimTemplate added or updated", "resourceClaimTemplate", klog.KObj(template))
// Enqueue all pods with this template name
objects, err := ec.podIndexer.ByIndex(podResourceClaimTemplateIndex, fmt.Sprintf("%s/%s", template.Namespace, template.Name))
if err != nil {
runtime.HandleErrorWithLogger(logger, err, "Unable to list pods for claim template", "resourceClaimTemplate", klog.KObj(template))
return
}
if len(objects) == 0 {
logger.V(6).Info("ResourceClaimTemplate change unrelated to any known pod", "resourceClaimTemplate", klog.KObj(template))
}
for _, object := range objects {
pod, ok1 := object.(*v1.Pod)
if !ok1 {
// Not a pod?!
runtime.HandleErrorWithLogger(logger, nil, "unexpected type in Pod cache", "type", fmt.Sprintf("%T", object))
return
}
logger.V(4).Info(
"Enqueuing pod due to ResourceClaimTemplate change",
"resourceClaimTemplate", klog.KObj(template),
"pod", klog.KObj(pod),
)
ec.enqueuePod(logger, object, false)
}
if ec.features.WorkloadResourceClaims {
// Enqueue all PodGroups with this template name
objects, err := ec.podGroupIndexer.ByIndex(podGroupResourceClaimTemplateIndex, fmt.Sprintf("%s/%s", template.Namespace, template.Name))
if err != nil {
runtime.HandleErrorWithLogger(logger, err, "Unable to list PodGroups for claim template", "resourceClaimTemplate", klog.KObj(template))
return
}
if len(objects) == 0 {
logger.V(6).Info("ResourceClaimTemplate change unrelated to any known PodGroup", "resourceClaimTemplate", klog.KObj(template))
}
for _, object := range objects {
podGroup, ok := object.(*schedulingapi.PodGroup)
if !ok {
// Not a PodGroup?!
runtime.HandleErrorWithLogger(logger, nil, "unexpected type in PodGroup cache", "type", fmt.Sprintf("%T", object))
return
}
logger.V(4).Info(
"Enqueuing PodGroup due to ResourceClaimTemplate change",
"resourceClaimTemplate", klog.KObj(template),
"podgroup", klog.KObj(podGroup),
)
ec.enqueuePodGroup(logger, object, false)
}
}
}
func (ec *Controller) enqueuePod(logger klog.Logger, obj any, deleted bool) {
if d, ok := obj.(cache.DeletedFinalStateUnknown); ok {
obj = d.Obj
}
pod, ok := obj.(*v1.Pod)
if !ok {
// Not a pod?!
logger.Error(nil, "EnqueuePod called for unexpected object", "type", fmt.Sprintf("%T", obj))
return
}
// Check if pod has any resource claims to process.
// Extended resource claims are stored in pod.Status.ExtendedResourceClaimStatus,
// not in pod.Spec.ResourceClaims, so we need to check both locations.
hasResourceClaims := len(pod.Spec.ResourceClaims) > 0
// For cleanup of extended resource claims, we must consider claims present
// in pod status regardless of the current feature gate state. The claim may
// have been created when the feature was enabled and still needs cleanup.
hasExtendedResourceClaims := pod.Status.ExtendedResourceClaimStatus != nil
if !hasResourceClaims && !hasExtendedResourceClaims {
// Nothing to do for it at all.
return
}
if deleted {
logger.V(6).Info("Pod got deleted", "pod", klog.KObj(pod))
ec.deletedObjects.Add(pod.UID)
}
logger.V(6).Info("Pod with resource claims changed", "pod", klog.KObj(pod), "deleted", deleted)
// Release reservations of a deleted or completed pod?
needsClaims, reason := podNeedsClaims(pod, deleted)
if needsClaims {
logger.V(6).Info("Not touching claims", "pod", klog.KObj(pod), "reason", reason)
} else {
for _, podClaim := range pod.Spec.ResourceClaims {
claimName, _, err := resourceclaim.Name(pod, &podClaim)
switch {
case err != nil:
// Either the claim was not created (nothing to do here) or
// the API changed. The later will also get reported elsewhere,
// so here it's just a debug message.
logger.V(6).Info("Nothing to do for claim during pod change", "pod", klog.KObj(pod), "podClaim", podClaim.Name, "err", err, "reason", reason)
case claimName != nil:
key := claimKeyPrefix + pod.Namespace + "/" + *claimName
logger.V(6).Info("Process claim", "pod", klog.KObj(pod), "claim", klog.KRef(pod.Namespace, *claimName), "key", key, "reason", reason)
ec.queue.Add(key)
default:
// Nothing to do, claim wasn't generated.
logger.V(6).Info("Nothing to do for skipped claim during pod change", "pod", klog.KObj(pod), "podClaim", podClaim.Name, "reason", reason)
}
}
// Process extended resource claims for completed/deleted pods.
// Extended resource claims are created by the scheduler and stored in
// pod.Status.ExtendedResourceClaimStatus, not in pod.Spec.ResourceClaims.
// Without this, extended resource claims would never be cleaned up when
// pods complete, causing device resources to remain allocated indefinitely.
if hasExtendedResourceClaims {
claimName := pod.Status.ExtendedResourceClaimStatus.ResourceClaimName
key := claimKeyPrefix + pod.Namespace + "/" + claimName
logger.V(6).Info("Process extended resource claim", "pod", klog.KObj(pod), "claim", klog.KRef(pod.Namespace, claimName), "key", key, "reason", reason)
ec.queue.Add(key)
}
}
needsWork, reason := ec.podNeedsWork(pod)
if needsWork {
logger.V(6).Info("Enqueueing pod", "pod", klog.KObj(pod), "reason", reason)
ec.queue.Add(podKeyPrefix + pod.Namespace + "/" + pod.Name)
return
}
logger.V(6).Info("Not enqueueing pod", "pod", klog.KObj(pod), "reason", reason)
}
func podNeedsClaims(pod *v1.Pod, deleted bool) (bool, string) {
if deleted {
return false, "pod got removed"
}
if podutil.IsPodTerminal(pod) {
return false, "pod has terminated"
}
if pod.DeletionTimestamp != nil && pod.Spec.NodeName == "" {
return false, "pod got deleted before scheduling"
}
// Still needs claims.
return true, "pod might run"
}
// podNeedsWork checks whether a new or modified pod needs to be processed
// further by a worker. It returns a boolean with the result and an explanation
// for it.
func (ec *Controller) podNeedsWork(pod *v1.Pod) (bool, string) {
if pod.DeletionTimestamp != nil {
// Nothing else to do for the pod.
return false, "pod is deleted"
}
var doNothingReasons []string
for _, podClaim := range pod.Spec.ResourceClaims {
claimName, checkOwner, err := resourceclaim.Name(pod, &podClaim)
if err != nil {
return true, err.Error()
}
// If the claimName is nil, then it has been determined before
// that the claim is not needed.
if claimName == nil {
doNothingReasons = append(doNothingReasons, fmt.Sprintf("claim %s is not needed", podClaim.Name))
continue
}
claim, err := ec.claimLister.ResourceClaims(pod.Namespace).Get(*claimName)
if apierrors.IsNotFound(err) {
if podClaim.ResourceClaimTemplateName != nil {
podGroup, err := ec.getPodGroup(pod)
if err != nil {
return true, "ResourceClaim might have to be created from template: " + err.Error()
}
bindTo, err := resourceclaim.BindTo(pod, podGroup, &podClaim)
if err != nil {
doNothingReasons = append(doNothingReasons, fmt.Sprintf("not sure what to do for ResourceClaim for claim %s: %v", podClaim.Name, err))
continue
}
if bindTo.APIGroup == schedulingapi.GroupName && bindTo.Resource == "podgroups" {
doNothingReasons = append(doNothingReasons, fmt.Sprintf("ResourceClaim needs to be created for the PodGroup claim %s", podClaim.Name))
continue
}
return true, "must create ResourceClaim from template"
}
// User needs to create claim.
doNothingReasons = append(doNothingReasons, "ResourceClaim for claim %s is missing and must be created by user", podClaim.Name)
continue
}
if err != nil {
// Shouldn't happen.
return true, fmt.Sprintf("internal error while checking for claim: %v", err)
}
if checkOwner {
if err := resourceclaim.IsForPod(pod, claim, ec.features.WorkloadResourceClaims); err != nil {
// Cannot proceed with the pod unless that other claim gets deleted.
doNothingReasons = append(doNothingReasons, fmt.Sprintf("claim %s: %v", podClaim.Name, err))
continue
}
}
// This check skips over the reasons below that only apply
// when a pod has been scheduled already. We need to keep checking
// for more claims that might need to be created.
if pod.Spec.NodeName == "" {
continue
}
if claim.Status.Allocation != nil &&
!resourceclaim.IsReservedForPod(pod, claim, ec.features.WorkloadResourceClaims) &&
resourceclaim.CanBeReserved(claim) {
// Need to reserve it.
return true, fmt.Sprintf("need to reserve claim %s for pod", klog.KObj(claim))
}
}
return false, "nothing to do for any claim: " + strings.Join(doNothingReasons, ", ")
}
func (ec *Controller) enqueuePodGroup(logger klog.Logger, obj any, deleted bool) {
if d, ok := obj.(cache.DeletedFinalStateUnknown); ok {
obj = d.Obj
}
podGroup, ok := obj.(*schedulingapi.PodGroup)
if !ok {
// Not a PodGroup?!
logger.Error(nil, "enqueuePodGroup called for unexpected object", "type", fmt.Sprintf("%T", obj))
return
}
// Check if PodGroup has any resource claims to process.
hasResourceClaims := len(podGroup.Spec.ResourceClaims) > 0
if !hasResourceClaims {
// Nothing to do for it at all.
return
}
if deleted {
logger.V(6).Info("PodGroup got deleted", "podgroup", klog.KObj(podGroup))
ec.deletedObjects.Add(podGroup.UID)
}
logger.V(6).Info("PodGroup with resource claims changed", "podgroup", klog.KObj(podGroup), "deleted", deleted)
// Release reservations of a deleted PodGroup?
needsClaims, reason := podGroupNeedsClaims(podGroup, deleted)
if needsClaims {
logger.V(6).Info("Not touching claims", "podgroup", klog.KObj(podGroup), "reason", reason)
} else {
for _, podGroupClaim := range podGroup.Spec.ResourceClaims {
claimName, _, err := resourceclaim.NameFromPodGroup(podGroup, &podGroupClaim)
switch {
case err != nil:
// Either the claim was not created (nothing to do here) or
// the API changed. The later will also get reported elsewhere,
// so here it's just a debug message.
logger.V(6).Info("Nothing to do for claim during PodGroup change", "podgroup", klog.KObj(podGroup), "podGroupClaim", podGroupClaim.Name, "err", err, "reason", reason)
case claimName != nil:
key := claimKeyPrefix + podGroup.Namespace + "/" + *claimName
logger.V(6).Info("Process claim", "podgroup", klog.KObj(podGroup), "claim", klog.KRef(podGroup.Namespace, *claimName), "key", key, "reason", reason)
ec.queue.Add(key)
default:
// Nothing to do, claim wasn't generated.
logger.V(6).Info("Nothing to do for skipped claim during PodGroup change", "podgroup", klog.KObj(podGroup), "podGroupClaim", podGroupClaim.Name, "reason", reason)
}
}
}
needsWork, reason := ec.podGroupNeedsWork(podGroup)
if needsWork {
logger.V(6).Info("Enqueueing PodGroup", "podgroup", klog.KObj(podGroup), "reason", reason)
ec.queue.Add(podGroupKeyPrefix + podGroup.Namespace + "/" + podGroup.Name)
} else {
logger.V(6).Info("Not enqueueing PodGroup", "podgroup", klog.KObj(podGroup), "reason", reason)
}
// A PodGroup status update may make ResourceClaims allocated for the
// PodGroup available to the group's Pods. Pods enqueued here will have
// their status updated to reflect the status of their claims which match
// the PodGroup's to bootstrap the ResourceClaim->Pod index.
objects, err := ec.podIndexer.ByIndex(podGroupMembersIndex, podGroup.Namespace+"/"+podGroup.Name)
if err != nil {
runtime.HandleErrorWithLogger(logger, err, "Unable to list Pods for PodGroup", "podgroup", klog.KObj(podGroup))
return
}
if len(objects) == 0 {
logger.V(6).Info("PodGroup change unrelated to any known Pod", "podgroup", klog.KObj(podGroup))
}
for _, object := range objects {
pod, ok := object.(*v1.Pod)
if !ok {
// Not a pod?!
runtime.HandleErrorWithLogger(logger, nil, "unexpected object in Pod indexer", "type", fmt.Sprintf("%T", object))
return
}
logger.V(6).Info(
"Enqueuing Pod due to PodGroup change",
"podgroup", klog.KObj(podGroup),
"pod", klog.KObj(pod),
)
ec.enqueuePod(logger, object, false)
}
}
func podGroupNeedsClaims(_ *schedulingapi.PodGroup, deleted bool) (bool, string) {
if deleted {
return false, "PodGroup got removed"
}
// Still needs claims.
return true, "Pods in the PodGroup might run"
}
// podGroupNeedsWork checks whether a new or modified PodGroup needs to be processed
// further by a worker. It returns a boolean with the result and an explanation
// for it.
func (ec *Controller) podGroupNeedsWork(podGroup *schedulingapi.PodGroup) (bool, string) {
if podGroup.DeletionTimestamp != nil {
// Nothing else to do for the PodGroup.
return false, "PodGroup is deleted"
}
var doNothingReasons []string
for _, podGroupClaim := range podGroup.Spec.ResourceClaims {
claimName, checkOwner, err := resourceclaim.NameFromPodGroup(podGroup, &podGroupClaim)
if err != nil {
return true, err.Error()
}
// If the claimName is nil, then it has been determined before
// that the claim is not needed.
if claimName == nil {
doNothingReasons = append(doNothingReasons, fmt.Sprintf("claim %s is not needed", podGroupClaim.Name))
continue
}
claim, err := ec.claimLister.ResourceClaims(podGroup.Namespace).Get(*claimName)
if apierrors.IsNotFound(err) {
if podGroupClaim.ResourceClaimTemplateName != nil {
return true, "must create ResourceClaim from template"
}
// User needs to create claim.
doNothingReasons = append(doNothingReasons, "ResourceClaim claim %s is missing and must be created by user", *claimName, podGroupClaim.Name)
continue
}
if err != nil {
// Shouldn't happen.
return true, fmt.Sprintf("internal error while checking for claim: %v", err)
}
if checkOwner {
if err := resourceclaim.IsForPodGroup(podGroup, claim); err != nil {
// Cannot proceed with the PodGroup unless that other claim gets deleted.
doNothingReasons = append(doNothingReasons, fmt.Sprintf("claim %s: %v", podGroupClaim.Name, err))
continue
}
}
}
return false, "nothing to do for any claim: " + strings.Join(doNothingReasons, ", ")
}
func (ec *Controller) enqueueResourceClaim(logger klog.Logger, oldObj, newObj any) {
deleted := newObj == nil
if d, ok := oldObj.(cache.DeletedFinalStateUnknown); ok {
oldObj = d.Obj
}
oldClaim, ok := oldObj.(*resourceapi.ResourceClaim)
if oldObj != nil && !ok {
return
}
newClaim, ok := newObj.(*resourceapi.ResourceClaim)
if newObj != nil && !ok {
return
}
// Check if both the old and new claim are nil in case DeletedFinalStateUnknown.Obj can be nil.
if oldClaim == nil && newClaim == nil {
return
}
claim := newClaim
if claim == nil {
claim = oldClaim
}
if !deleted {
// When starting up, we have to check all claims to find those with
// stale pods in ReservedFor. During an update, a pod might get added
// that already no longer exists.
key := claimKeyPrefix + claim.Namespace + "/" + claim.Name
logger.V(6).Info("Enqueueing new or updated claim", "claim", klog.KObj(claim), "key", key)
ec.queue.Add(key)
} else {
logger.V(6).Info("Not enqueueing deleted claim", "claim", klog.KObj(claim))
}
// Also check whether this causes work for any of the currently
// known pods which use the ResourceClaim.
objs, err := ec.podIndexer.ByIndex(podResourceClaimIndex, fmt.Sprintf("%s/%s", claim.Namespace, claim.Name))
if err != nil {
logger.Error(err, "Failed to list pods from cache")
return
}
if len(objs) == 0 {
logger.V(6).Info("ResourceClaim change unrelated to any known pod", "claim", klog.KObj(claim))
}
for _, obj := range objs {
ec.enqueuePod(logger, obj, false)
}
if ec.features.WorkloadResourceClaims {
// Also check whether this causes work for any of the currently
// known PodGroups which use the ResourceClaim.
podGroups, err := ec.podGroupIndexer.ByIndex(podGroupResourceClaimIndex, fmt.Sprintf("%s/%s", claim.Namespace, claim.Name))
if err != nil {
logger.Error(err, "Failed to list PodGroups from cache")
return
}
if len(podGroups) == 0 {
logger.V(6).Info("ResourceClaim change unrelated to any known PodGroup", "claim", klog.KObj(claim))
}
for _, podGroup := range podGroups {
ec.enqueuePodGroup(logger, podGroup, false)
}
}
}
func (ec *Controller) Run(ctx context.Context, workers int) {
defer runtime.HandleCrashWithContext(ctx)
eventBroadcaster := record.NewBroadcaster(record.WithContext(ctx))
eventBroadcaster.StartLogging(klog.Infof)
eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: ec.kubeClient.CoreV1().Events("")})
ec.recorder = eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "resource_claim"})
defer eventBroadcaster.Shutdown()
logger := klog.FromContext(ctx)
logger.Info("Starting resource claim controller")
var wg sync.WaitGroup
defer func() {
logger.Info("Shutting down resource claim controller")
ec.queue.ShutDown()
wg.Wait()
}()
if !cache.WaitForNamedCacheSyncWithContext(ctx, ec.podSynced, ec.podGroupSynced, ec.claimsSynced, ec.templatesSynced) {
return
}
for range workers {
wg.Go(func() {
wait.UntilWithContext(ctx, ec.runWorker, time.Second)
})
}
<-ctx.Done()
}
func (ec *Controller) runWorker(ctx context.Context) {
for ec.processNextWorkItem(ctx) {
}
}
func (ec *Controller) processNextWorkItem(ctx context.Context) bool {
key, shutdown := ec.queue.Get()
if shutdown {
return false
}
defer ec.queue.Done(key)
err := ec.syncHandlerFunc(ctx, key)
_, nonRetryable := errors.AsType[nonRetryableError](err)
if nonRetryable {
runtime.HandleErrorWithContext(ctx, err, "Work item failed, will not retry", "item", key)
}
if err == nil || nonRetryable {
ec.queue.Forget(key)
return true
}
runtime.HandleErrorWithContext(ctx, err, "Work item failed", "item", key)
ec.queue.AddRateLimited(key)
return true
}
// syncHandler is invoked for each work item which might need to be processed.
// If an error is returned from this function, the item will be requeued.
func (ec *Controller) syncHandler(ctx context.Context, key string) error {
sep := strings.Index(key, ":")
if sep < 0 {
return fmt.Errorf("unexpected key: %s", key)
}
prefix, object := key[0:sep+1], key[sep+1:]
namespace, name, err := cache.SplitMetaNamespaceKey(object)
if err != nil {
return err
}
switch prefix {
case podKeyPrefix:
return ec.syncPod(ctx, namespace, name)
case podGroupKeyPrefix:
return ec.syncPodGroup(ctx, namespace, name)
case claimKeyPrefix:
return ec.syncClaim(ctx, namespace, name)
default:
return fmt.Errorf("unexpected key prefix: %s", prefix)
}
}
func (ec *Controller) syncPod(ctx context.Context, namespace, name string) error {
logger := klog.LoggerWithValues(klog.FromContext(ctx), "pod", klog.KRef(namespace, name))
ctx = klog.NewContext(ctx, logger)
pod, err := ec.podLister.Pods(namespace).Get(name)
if err != nil {
if apierrors.IsNotFound(err) {
logger.V(5).Info("Nothing to do for pod, it is gone")
return nil
}
return err
}
// Ignore pods which are already getting deleted.
if pod.DeletionTimestamp != nil {
logger.V(5).Info("Nothing to do for pod, it is marked for deletion")
return nil
}
podGroup, err := ec.getPodGroup(pod)
if err != nil {
return fmt.Errorf("get PodGroup for Pod %s/%s: %w", pod.Namespace, pod.Name, err)
}
if podGroup != nil {
logger = klog.LoggerWithValues(logger, "podgroup", klog.KObj(podGroup))
ctx = klog.NewContext(ctx, logger)
}
var newPodClaims map[string]string
for _, podClaim := range pod.Spec.ResourceClaims {
if err := ec.handleClaim(ctx, pod, podGroup, podClaim, &newPodClaims); err != nil {
if ec.recorder != nil {
ec.recorder.Event(pod, v1.EventTypeWarning, "FailedResourceClaimCreation", fmt.Sprintf("PodResourceClaim %s: %v", podClaim.Name, err))
}
return fmt.Errorf("pod %s/%s, PodResourceClaim %s: %v", namespace, name, podClaim.Name, err)
}
}
if newPodClaims != nil {
// Patch the pod status with the new information about
// generated ResourceClaims.
mergedStatuses := make(map[string]string)
for _, status := range pod.Status.ResourceClaimStatuses {
if status.ResourceClaimName != nil {
mergedStatuses[status.Name] = *status.ResourceClaimName
}
}
maps.Copy(mergedStatuses, newPodClaims)
names := make([]string, 0, len(mergedStatuses))
for name := range mergedStatuses {
names = append(names, name)
}
slices.Sort(names)
statuses := make([]*corev1apply.PodResourceClaimStatusApplyConfiguration, 0, len(names))
for _, name := range names {
statuses = append(statuses, corev1apply.PodResourceClaimStatus().WithName(name).WithResourceClaimName(mergedStatuses[name]))
}
podApply := corev1apply.Pod(name, namespace).WithStatus(corev1apply.PodStatus().WithResourceClaimStatuses(statuses...))
if _, err := ec.kubeClient.CoreV1().Pods(namespace).ApplyStatus(ctx, podApply, metav1.ApplyOptions{FieldManager: fieldManager, Force: true}); err != nil {
return fmt.Errorf("update pod %s/%s ResourceClaimStatuses: %v", namespace, name, err)
}
}
if pod.Spec.NodeName == "" {
// Scheduler will handle reservations.
logger.V(5).Info("Nothing to do for pod, scheduler will deal with it")
return nil
}
for _, podClaim := range pod.Spec.ResourceClaims {
claimName, checkOwner, err := resourceclaim.Name(pod, &podClaim)
if err != nil {
return err
}
// If nil, then it has been determined that the claim is not needed
// and can be skipped.
if claimName == nil {
continue
}
claim, err := ec.claimLister.ResourceClaims(pod.Namespace).Get(*claimName)
if err != nil {
if apierrors.IsNotFound(err) {
return nil
}
return fmt.Errorf("retrieve claim: %v", err)
}
if checkOwner {
if err := resourceclaim.IsForPod(pod, claim, ec.features.WorkloadResourceClaims); err != nil {
return err
}
}
if claim.Status.Allocation != nil &&
!resourceclaim.IsReservedForPod(pod, claim, ec.features.WorkloadResourceClaims) &&
resourceclaim.CanBeReserved(claim) {
bindTo, err := resourceclaim.BindTo(pod, podGroup, &podClaim)
if err != nil {
return err
}
if isPodGroupClaim(bindTo) && !ec.features.WorkloadResourceClaims {
// It's not expected for ResourceClaims to remain allocated but
// unreserved for too long. This message is logged at a lower
// verbosity threshold so cluster admins can more easily
// identify when that happens because of this feature gate in
// normal production clusters.
logger.V(3).Info("Not reserving PodGroup ResourceClaim because feature is disabled", "feature", features.DRAWorkloadResourceClaims, "resourceClaim", klog.KObj(claim))