-
Notifications
You must be signed in to change notification settings - Fork 248
/
nfd-master.go
1448 lines (1261 loc) · 46.1 KB
/
nfd-master.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
/*
Copyright 2019-2021 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 nfdmaster
import (
"encoding/json"
"fmt"
"maps"
"net"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
corev1 "k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
k8sLabels "k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
k8sclient "k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"k8s.io/klog/v2"
controller "k8s.io/kubernetes/pkg/controller"
taintutils "k8s.io/kubernetes/pkg/util/taints"
"sigs.k8s.io/yaml"
nfdclientset "sigs.k8s.io/node-feature-discovery/api/generated/clientset/versioned"
nfdv1alpha1 "sigs.k8s.io/node-feature-discovery/api/nfd/v1alpha1"
"sigs.k8s.io/node-feature-discovery/pkg/apis/nfd/nodefeaturerule"
"sigs.k8s.io/node-feature-discovery/pkg/apis/nfd/validate"
nfdfeatures "sigs.k8s.io/node-feature-discovery/pkg/features"
"sigs.k8s.io/node-feature-discovery/pkg/utils"
klogutils "sigs.k8s.io/node-feature-discovery/pkg/utils/klog"
"sigs.k8s.io/node-feature-discovery/pkg/version"
)
// Labels are a Kubernetes representation of discovered features.
type Labels map[string]string
// ExtendedResources are k8s extended resources which are created from discovered features.
type ExtendedResources map[string]string
// Annotations are used for NFD-related node metadata
type Annotations map[string]string
// Restrictions contains the restrictions on the NF and NFR Crs
type Restrictions struct {
NodeFeatureNamespaceSelector *metav1.LabelSelector
DisableLabels bool
DisableExtendedResources bool
DisableAnnotations bool
DenyNodeFeatureLabels bool
AllowOverwrite bool
}
// NFDConfig contains the configuration settings of NfdMaster.
type NFDConfig struct {
AutoDefaultNs bool
DenyLabelNs utils.StringSetVal
ExtraLabelNs utils.StringSetVal
LabelWhiteList *regexp.Regexp
NoPublish bool
EnableTaints bool
ResyncPeriod utils.DurationVal
LeaderElection LeaderElectionConfig
NfdApiParallelism int
Klog klogutils.KlogConfigOpts
Restrictions Restrictions
}
// LeaderElectionConfig contains the configuration for leader election
type LeaderElectionConfig struct {
LeaseDuration utils.DurationVal
RenewDeadline utils.DurationVal
RetryPeriod utils.DurationVal
}
// ConfigOverrideArgs are args that override config file options
type ConfigOverrideArgs struct {
DenyLabelNs *utils.StringSetVal
ExtraLabelNs *utils.StringSetVal
LabelWhiteList *utils.RegexpVal
EnableTaints *bool
NoPublish *bool
ResyncPeriod *utils.DurationVal
NfdApiParallelism *int
}
// Args holds command line arguments
type Args struct {
ConfigFile string
Instance string
Klog map[string]*utils.KlogFlagVal
Kubeconfig string
Port int
// GrpcHealthPort is only needed to avoid races between tests (by skipping the health server).
// Could be removed when gRPC labler service is dropped (when nfd-worker tests stop running nfd-master).
GrpcHealthPort int
Prune bool
Options string
EnableLeaderElection bool
MetricsPort int
Overrides ConfigOverrideArgs
}
type deniedNs struct {
normal utils.StringSetVal
wildcard utils.StringSetVal
}
type NfdMaster interface {
Run() error
Stop()
WaitForReady(time.Duration) bool
}
type nfdMaster struct {
*nfdController
args Args
namespace string
nodeName string
configFilePath string
server *grpc.Server
healthServer *grpc.Server
stop chan struct{}
ready chan struct{}
kubeconfig *restclient.Config
k8sClient k8sclient.Interface
nfdClient nfdclientset.Interface
updaterPool *updaterPool
deniedNs
config *NFDConfig
}
// NewNfdMaster creates a new NfdMaster server instance.
func NewNfdMaster(opts ...NfdMasterOption) (NfdMaster, error) {
nfd := &nfdMaster{
nodeName: utils.NodeName(),
namespace: utils.GetKubernetesNamespace(),
ready: make(chan struct{}),
stop: make(chan struct{}),
}
for _, o := range opts {
o.apply(nfd)
}
if nfd.args.Instance != "" {
if ok, _ := regexp.MatchString(`^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$`, nfd.args.Instance); !ok {
return nfd, fmt.Errorf("invalid -instance %q: instance name "+
"must start and end with an alphanumeric character and may only contain "+
"alphanumerics, `-`, `_` or `.`", nfd.args.Instance)
}
}
if nfd.args.ConfigFile != "" {
nfd.configFilePath = filepath.Clean(nfd.args.ConfigFile)
}
// k8sClient might've been set via opts by tests
if nfd.k8sClient == nil {
kubeconfig, err := utils.GetKubeconfig(nfd.args.Kubeconfig)
if err != nil {
return nfd, err
}
nfd.kubeconfig = kubeconfig
cli, err := k8sclient.NewForConfig(kubeconfig)
if err != nil {
return nfd, err
}
nfd.k8sClient = cli
}
// nfdClient
if nfd.kubeconfig != nil {
kubeconfig, err := utils.GetKubeconfig(nfd.args.Kubeconfig)
if err != nil {
return nfd, err
}
nfd.kubeconfig = kubeconfig
c, err := nfdclientset.NewForConfig(nfd.kubeconfig)
if err != nil {
return nfd, err
}
nfd.nfdClient = c
}
nfd.updaterPool = newUpdaterPool(nfd)
return nfd, nil
}
// NfdMasterOption sets properties of the NfdMaster instance.
type NfdMasterOption interface {
apply(*nfdMaster)
}
// WithArgs is used for passing settings from command line arguments.
func WithArgs(args *Args) NfdMasterOption {
return &nfdMasterOpt{f: func(n *nfdMaster) { n.args = *args }}
}
// WithKuberneteClient forces to use the given kubernetes client, without
// initializing one from kubeconfig.
func WithKubernetesClient(cli k8sclient.Interface) NfdMasterOption {
return &nfdMasterOpt{f: func(n *nfdMaster) { n.k8sClient = cli }}
}
type nfdMasterOpt struct {
f func(*nfdMaster)
}
func (f *nfdMasterOpt) apply(n *nfdMaster) {
f.f(n)
}
func newDefaultConfig() *NFDConfig {
return &NFDConfig{
DenyLabelNs: utils.StringSetVal{},
ExtraLabelNs: utils.StringSetVal{},
NoPublish: false,
AutoDefaultNs: true,
NfdApiParallelism: 10,
EnableTaints: false,
ResyncPeriod: utils.DurationVal{Duration: time.Duration(1) * time.Hour},
LeaderElection: LeaderElectionConfig{
LeaseDuration: utils.DurationVal{Duration: time.Duration(15) * time.Second},
RetryPeriod: utils.DurationVal{Duration: time.Duration(2) * time.Second},
RenewDeadline: utils.DurationVal{Duration: time.Duration(10) * time.Second},
},
Klog: make(map[string]string),
Restrictions: Restrictions{
DisableLabels: false,
DisableExtendedResources: false,
DisableAnnotations: false,
AllowOverwrite: true,
DenyNodeFeatureLabels: false,
},
}
}
// Run NfdMaster server. The method returns in case of fatal errors or if Stop()
// is called.
func (m *nfdMaster) Run() error {
klog.InfoS("Node Feature Discovery Master", "version", version.Get(), "nodeName", m.nodeName, "namespace", m.namespace)
if m.args.Instance != "" {
klog.InfoS("Master instance", "instance", m.args.Instance)
}
// Read configuration
if err := m.configure(m.configFilePath, m.args.Options); err != nil {
return err
}
if m.args.Prune {
return m.prune()
}
if err := m.startNfdApiController(); err != nil {
return err
}
m.updaterPool.start(m.config.NfdApiParallelism)
if !m.config.NoPublish {
err := m.updateMasterNode()
if err != nil {
return fmt.Errorf("failed to update master node: %w", err)
}
}
// Register to metrics server
if m.args.MetricsPort > 0 {
m := utils.CreateMetricsServer(m.args.MetricsPort,
buildInfo,
nodeUpdateRequests,
nodeUpdates,
nodeUpdateFailures,
nodeLabelsRejected,
nodeERsRejected,
nodeTaintsRejected,
nfrProcessingTime,
nfrProcessingErrors)
go m.Run()
registerVersion(version.Get())
defer m.Stop()
}
// Run updater that handles events from the nfd CRD API.
if m.nfdController != nil {
if m.args.EnableLeaderElection {
go m.nfdAPIUpdateHandlerWithLeaderElection()
} else {
go m.nfdAPIUpdateHandler()
}
}
// Start gRPC server for liveness probe (at this point we're "live")
grpcErr := make(chan error)
if m.args.GrpcHealthPort != 0 {
if err := m.startGrpcHealthServer(grpcErr); err != nil {
return fmt.Errorf("failed to start gRPC health server: %w", err)
}
}
// Notify that we're ready to accept connections
close(m.ready)
// NFD-Master main event loop
for {
select {
case err := <-grpcErr:
return fmt.Errorf("error in serving gRPC: %w", err)
case <-m.stop:
klog.InfoS("shutting down nfd-master")
return nil
}
}
}
// startGrpcHealthServer starts a gRPC health server for Kubernetes readiness/liveness probes.
// TODO: improve status checking e.g. with watchdog in the main event loop and
// cheking that node updater pool is alive.
func (m *nfdMaster) startGrpcHealthServer(errChan chan<- error) error {
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", m.args.GrpcHealthPort))
if err != nil {
return fmt.Errorf("failed to listen: %w", err)
}
s := grpc.NewServer()
grpc_health_v1.RegisterHealthServer(s, health.NewServer())
klog.InfoS("gRPC health server serving", "port", m.args.GrpcHealthPort)
go func() {
defer func() {
lis.Close()
}()
if err := s.Serve(lis); err != nil {
errChan <- fmt.Errorf("gRPC health server exited with an error: %w", err)
}
klog.InfoS("gRPC health server stopped")
}()
m.healthServer = s
return nil
}
// nfdAPIUpdateHandler handles events from the nfd API controller.
func (m *nfdMaster) nfdAPIUpdateHandler() {
// We want to unconditionally update all nodes at startup if gRPC is
// disabled (i.e. NodeFeature API is enabled)
updateAll := true
updateNodes := make(map[string]struct{})
nodeFeatureGroup := make(map[string]struct{})
updateAllNodeFeatureGroups := false
rateLimit := time.After(time.Second)
for {
select {
case <-m.nfdController.updateAllNodesChan:
updateAll = true
case nodeName := <-m.nfdController.updateOneNodeChan:
updateNodes[nodeName] = struct{}{}
case <-m.nfdController.updateAllNodeFeatureGroupsChan:
updateAllNodeFeatureGroups = true
case nodeFeatureGroupName := <-m.nfdController.updateNodeFeatureGroupChan:
nodeFeatureGroup[nodeFeatureGroupName] = struct{}{}
case <-rateLimit:
// NodeFeature
errUpdateAll := false
if updateAll {
if err := m.nfdAPIUpdateAllNodes(); err != nil {
klog.ErrorS(err, "failed to update nodes")
errUpdateAll = true
}
} else {
for nodeName := range updateNodes {
m.updaterPool.addNode(nodeName)
}
}
// NodeFeatureGroup
errUpdateAllNFG := false
if updateAllNodeFeatureGroups {
if err := m.nfdAPIUpdateAllNodeFeatureGroups(); err != nil {
klog.ErrorS(err, "failed to update NodeFeatureGroups")
errUpdateAllNFG = true
}
} else {
for nodeFeatureGroupName := range nodeFeatureGroup {
m.updaterPool.addNodeFeatureGroup(nodeFeatureGroupName)
}
}
// Reset "work queue" and timer
updateAll = errUpdateAll
updateAllNodeFeatureGroups = errUpdateAllNFG
nodeFeatureGroup = map[string]struct{}{}
updateNodes = map[string]struct{}{}
rateLimit = time.After(time.Second)
}
}
}
// Stop NfdMaster
func (m *nfdMaster) Stop() {
if m.server != nil {
m.server.GracefulStop()
}
if m.healthServer != nil {
m.healthServer.GracefulStop()
}
if m.nfdController != nil {
m.nfdController.stop()
}
m.updaterPool.stop()
close(m.stop)
}
// Wait until NfdMaster is able able to accept connections.
func (m *nfdMaster) WaitForReady(timeout time.Duration) bool {
select {
case <-m.ready:
return true
case <-time.After(timeout):
}
return false
}
// Prune erases all NFD related properties from the node objects of the cluster.
func (m *nfdMaster) prune() error {
if m.config.NoPublish {
klog.InfoS("skipping pruning of nodes as noPublish config option is set")
return nil
}
nodes, err := getNodes(m.k8sClient)
if err != nil {
return err
}
for _, node := range nodes.Items {
klog.InfoS("pruning node...", "nodeName", node.Name)
// Prune labels and extended resources
err := m.updateNodeObject(m.k8sClient, &node, Labels{}, Annotations{}, ExtendedResources{}, []corev1.Taint{})
if err != nil {
nodeUpdateFailures.Inc()
return fmt.Errorf("failed to prune node %q: %v", node.Name, err)
}
// Prune annotations
node, err := getNode(m.k8sClient, node.Name)
if err != nil {
return err
}
maps.DeleteFunc(node.Annotations, func(k, v string) bool {
return strings.HasPrefix(k, m.instanceAnnotation(nfdv1alpha1.AnnotationNs))
})
_, err = m.k8sClient.CoreV1().Nodes().Update(context.TODO(), node, metav1.UpdateOptions{})
if err != nil {
return fmt.Errorf("failed to prune annotations from node %q: %v", node.Name, err)
}
}
return nil
}
// Update annotations on the node where nfd-master is running. Currently the
// only function is to remove the deprecated
// "nfd.node.kubernetes.io/master.version" annotation, if it exists.
// TODO: Drop when nfdv1alpha1.MasterVersionAnnotation is removed.
func (m *nfdMaster) updateMasterNode() error {
node, err := getNode(m.k8sClient, m.nodeName)
if err != nil {
return err
}
// Advertise NFD version as an annotation
p := createPatches(sets.New([]string{m.instanceAnnotation(nfdv1alpha1.MasterVersionAnnotation)}...),
node.Annotations,
nil,
"/metadata/annotations", m.config.Restrictions.AllowOverwrite)
err = patchNode(m.k8sClient, node.Name, p)
if err != nil {
return fmt.Errorf("failed to patch node annotations: %w", err)
}
return nil
}
// Filter labels by namespace and name whitelist, and, turn selected labels
// into extended resources. This function also handles proper namespacing of
// labels and ERs, i.e. adds the possibly missing default namespace for labels.
func (m *nfdMaster) filterFeatureLabels(labels Labels, features *nfdv1alpha1.Features) Labels {
outLabels := Labels{}
for name, value := range labels {
if value, err := m.filterFeatureLabel(name, value, features); err != nil {
klog.ErrorS(err, "ignoring label", "labelKey", name, "labelValue", value)
nodeLabelsRejected.Inc()
} else {
outLabels[name] = value
}
}
if len(outLabels) > 0 && m.config.Restrictions.DisableLabels {
klog.V(2).InfoS("node labels are disabled in configuration (restrictions.disableLabels=true)")
outLabels = Labels{}
}
return outLabels
}
func (m *nfdMaster) filterFeatureLabel(name, value string, features *nfdv1alpha1.Features) (string, error) {
// Check if Value is dynamic
var filteredValue string
if strings.HasPrefix(value, "@") {
dynamicValue, err := getDynamicValue(value, features)
if err != nil {
return "", err
}
filteredValue = dynamicValue
} else {
filteredValue = value
}
// Validate
ns, base := splitNs(name)
err := validate.Label(name, filteredValue)
if err == validate.ErrNSNotAllowed || isNamespaceDenied(ns, m.deniedNs.wildcard, m.deniedNs.normal) {
if _, ok := m.config.ExtraLabelNs[ns]; !ok {
return "", fmt.Errorf("namespace %q is not allowed", ns)
}
} else if err != nil {
return "", err
}
// Skip if label doesn't match labelWhiteList
if m.config.LabelWhiteList != nil && !m.config.LabelWhiteList.MatchString(base) {
return "", fmt.Errorf("%s (%s) does not match the whitelist (%s)", base, name, m.config.LabelWhiteList.String())
}
return filteredValue, nil
}
func getDynamicValue(value string, features *nfdv1alpha1.Features) (string, error) {
// value is a string in the form of attribute.featureset.elements
split := strings.SplitN(value[1:], ".", 3)
if len(split) != 3 {
return "", fmt.Errorf("value %s is not in the form of '@domain.feature.element'", value)
}
featureName := split[0] + "." + split[1]
elementName := split[2]
attrFeatureSet, ok := features.Attributes[featureName]
if !ok {
return "", fmt.Errorf("feature %s not found", featureName)
}
element, ok := attrFeatureSet.Elements[elementName]
if !ok {
return "", fmt.Errorf("element %s not found on feature %s", elementName, featureName)
}
return element, nil
}
func filterTaints(taints []corev1.Taint) []corev1.Taint {
outTaints := []corev1.Taint{}
for _, taint := range taints {
if err := validate.Taint(&taint); err != nil {
klog.ErrorS(err, "ignoring taint", "taint", taint)
nodeTaintsRejected.Inc()
} else {
outTaints = append(outTaints, taint)
}
}
return outTaints
}
func isNamespaceDenied(labelNs string, wildcardDeniedNs map[string]struct{}, normalDeniedNs map[string]struct{}) bool {
for deniedNs := range normalDeniedNs {
if labelNs == deniedNs {
return true
}
}
for deniedNs := range wildcardDeniedNs {
if strings.HasSuffix(labelNs, deniedNs) {
return true
}
}
return false
}
func (m *nfdMaster) nfdAPIUpdateAllNodes() error {
klog.InfoS("will process all nodes in the cluster")
nodes, err := getNodes(m.k8sClient)
if err != nil {
return err
}
for _, node := range nodes.Items {
m.updaterPool.addNode(node.Name)
}
return nil
}
// getAndMergeNodeFeatures merges the NodeFeature objects of the given node into a single NodeFeatureSpec.
// The Name field of the returned NodeFeatureSpec contains the node name.
func (m *nfdMaster) getAndMergeNodeFeatures(nodeName string) (*nfdv1alpha1.NodeFeature, error) {
nodeFeatures := &nfdv1alpha1.NodeFeature{
ObjectMeta: metav1.ObjectMeta{
Name: nodeName,
},
}
sel := k8sLabels.SelectorFromSet(k8sLabels.Set{nfdv1alpha1.NodeFeatureObjNodeNameLabel: nodeName})
objs, err := m.nfdController.featureLister.List(sel)
if err != nil {
return &nfdv1alpha1.NodeFeature{}, fmt.Errorf("failed to get NodeFeature resources for node %q: %w", nodeName, err)
}
filteredObjs := []*nfdv1alpha1.NodeFeature{}
for _, obj := range objs {
if m.isNamespaceSelected(obj.Namespace) {
filteredObjs = append(filteredObjs, obj)
}
}
// Node without a running NFD-Worker
if len(filteredObjs) == 0 {
return &nfdv1alpha1.NodeFeature{}, nil
}
// Sort our objects
sort.Slice(filteredObjs, func(i, j int) bool {
// Objects in our nfd namespace gets into the beginning of the list
if filteredObjs[i].Namespace == m.namespace && filteredObjs[j].Namespace != m.namespace {
return true
}
if filteredObjs[i].Namespace != m.namespace && filteredObjs[j].Namespace == m.namespace {
return false
}
// After the nfd namespace, sort objects by their name
if filteredObjs[i].Name != filteredObjs[j].Name {
return filteredObjs[i].Name < filteredObjs[j].Name
}
// Objects with the same name are sorted by their namespace
return filteredObjs[i].Namespace < filteredObjs[j].Namespace
})
if len(filteredObjs) > 0 {
// Merge in features
//
// NOTE: changing the rule api to support handle multiple objects instead
// of merging would probably perform better with lot less data to copy.
features := filteredObjs[0].Spec.DeepCopy()
if m.config.Restrictions.DenyNodeFeatureLabels && m.isThirdPartyNodeFeature(*filteredObjs[0], nodeName, m.namespace) {
klog.V(2).InfoS("node feature labels are disabled in configuration (restrictions.denyNodeFeatureLabels=true)")
features.Labels = nil
}
if !nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.DisableAutoPrefix) && m.config.AutoDefaultNs {
features.Labels = addNsToMapKeys(features.Labels, nfdv1alpha1.FeatureLabelNs)
}
for _, o := range filteredObjs[1:] {
s := o.Spec.DeepCopy()
if m.config.Restrictions.DenyNodeFeatureLabels && m.isThirdPartyNodeFeature(*o, nodeName, m.namespace) {
klog.V(2).InfoS("node feature labels are disabled in configuration (restrictions.denyNodeFeatureLabels=true)")
s.Labels = nil
}
if !nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.DisableAutoPrefix) && m.config.AutoDefaultNs {
s.Labels = addNsToMapKeys(s.Labels, nfdv1alpha1.FeatureLabelNs)
}
s.MergeInto(features)
}
// Set the merged features to the NodeFeature object
nodeFeatures.Spec = *features
klog.V(4).InfoS("merged nodeFeatureSpecs", "newNodeFeatureSpec", utils.DelayedDumper(features))
}
return nodeFeatures, nil
}
// isThirdPartyNodeFeature determines whether a node feature is a third party one or created by nfd-worker
func (m *nfdMaster) isThirdPartyNodeFeature(nodeFeature nfdv1alpha1.NodeFeature, nodeName, namespace string) bool {
return nodeFeature.Namespace != namespace || nodeFeature.Name != nodeName
}
func (m *nfdMaster) nfdAPIUpdateOneNode(cli k8sclient.Interface, node *corev1.Node) error {
if m.nfdController == nil || m.nfdController.featureLister == nil {
return nil
}
// Merge all NodeFeature objects into a single NodeFeatureSpec
nodeFeatures, err := m.getAndMergeNodeFeatures(node.Name)
if err != nil {
return fmt.Errorf("failed to merge NodeFeature objects for node %q: %w", node.Name, err)
}
// Update node labels et al. This may also mean removing all NFD-owned
// labels (et al.), for example in the case no NodeFeature objects are
// present.
if err := m.refreshNodeFeatures(cli, node, nodeFeatures.Spec.Labels, &nodeFeatures.Spec.Features); err != nil {
return err
}
return nil
}
func (m *nfdMaster) nfdAPIUpdateAllNodeFeatureGroups() error {
klog.V(1).InfoS("updating all NodeFeatureGroups")
nodeFeatureGroupsList, err := m.nfdController.featureGroupLister.List(labels.Everything())
if err != nil {
return fmt.Errorf("failed to get NodeFeatureGroup objects: %w", err)
}
if len(nodeFeatureGroupsList) > 0 {
for _, nodeFeatureGroup := range nodeFeatureGroupsList {
m.updaterPool.nfgQueue.Add(nodeFeatureGroup.Name)
}
} else {
klog.V(2).InfoS("no NodeFeatureGroup objects found")
}
return nil
}
func (m *nfdMaster) nfdAPIUpdateNodeFeatureGroup(nfdClient nfdclientset.Interface, nodeFeatureGroup *nfdv1alpha1.NodeFeatureGroup) error {
klog.V(2).InfoS("evaluating NodeFeatureGroup", "nodeFeatureGroup", klog.KObj(nodeFeatureGroup))
if m.nfdController == nil || m.nfdController.featureLister == nil {
return nil
}
// Get all Nodes
nodes, err := getNodes(m.k8sClient)
if err != nil {
return fmt.Errorf("failed to get nodes: %w", err)
}
nodeFeaturesList := make([]*nfdv1alpha1.NodeFeature, 0)
for _, node := range nodes.Items {
// Merge all NodeFeature objects into a single NodeFeatureSpec
nodeFeatures, err := m.getAndMergeNodeFeatures(node.Name)
if err != nil {
return fmt.Errorf("failed to merge NodeFeature objects for node %q: %w", node.Name, err)
}
if nodeFeatures.Name == "" {
// Nothing to do for this node
continue
}
nodeFeaturesList = append(nodeFeaturesList, nodeFeatures)
}
// Execute rules and create matching groups
nodePool := make([]nfdv1alpha1.FeatureGroupNode, 0)
nodeGroupValidator := make(map[string]bool)
for _, rule := range nodeFeatureGroup.Spec.Rules {
for _, feature := range nodeFeaturesList {
match, err := nodefeaturerule.ExecuteGroupRule(&rule, &feature.Spec.Features, true)
if err != nil {
klog.ErrorS(err, "failed to evaluate rule", "ruleName", rule.Name)
continue
}
if match {
klog.ErrorS(err, "failed to evaluate rule", "ruleName", rule.Name, "nodeName", feature.Name)
system := feature.Spec.Features.Attributes["system.name"]
nodeName := system.Elements["nodename"]
if _, ok := nodeGroupValidator[nodeName]; !ok {
nodePool = append(nodePool, nfdv1alpha1.FeatureGroupNode{
Name: nodeName,
})
nodeGroupValidator[nodeName] = true
}
}
}
}
// Update the NodeFeatureGroup object with the updated featureGroupRules
nodeFeatureGroupUpdated := nodeFeatureGroup.DeepCopy()
nodeFeatureGroupUpdated.Status.Nodes = nodePool
if !apiequality.Semantic.DeepEqual(nodeFeatureGroup, nodeFeatureGroupUpdated) {
klog.InfoS("updating NodeFeatureGroup object", "nodeFeatureGroup", klog.KObj(nodeFeatureGroup))
nodeFeatureGroupUpdated, err = nfdClient.NfdV1alpha1().NodeFeatureGroups(m.namespace).UpdateStatus(context.TODO(), nodeFeatureGroupUpdated, metav1.UpdateOptions{})
if err != nil {
return fmt.Errorf("failed to update NodeFeatureGroup object: %w", err)
}
klog.V(4).InfoS("NodeFeatureGroup object updated", "nodeFeatureGroup", utils.DelayedDumper(nodeFeatureGroupUpdated))
} else {
klog.V(1).InfoS("no changes in NodeFeatureGroup, object is up to date", "nodeFeatureGroup", klog.KObj(nodeFeatureGroup))
}
return nil
}
// filterExtendedResources filters extended resources and returns a map
// of valid extended resources.
func (m *nfdMaster) filterExtendedResources(features *nfdv1alpha1.Features, extendedResources ExtendedResources) ExtendedResources {
outExtendedResources := ExtendedResources{}
for name, value := range extendedResources {
capacity, err := filterExtendedResource(name, value, features)
if err != nil {
klog.ErrorS(err, "failed to create extended resources", "extendedResourceName", name, "extendedResourceValue", value)
nodeERsRejected.Inc()
} else {
outExtendedResources[name] = capacity
}
}
return outExtendedResources
}
func filterExtendedResource(name, value string, features *nfdv1alpha1.Features) (string, error) {
// Dynamic Value
var filteredValue string
if strings.HasPrefix(value, "@") {
dynamicValue, err := getDynamicValue(value, features)
if err != nil {
return "", err
}
filteredValue = dynamicValue
} else {
filteredValue = value
}
// Validate
err := validate.ExtendedResource(name, filteredValue)
if err != nil {
return "", err
}
return filteredValue, nil
}
func (m *nfdMaster) refreshNodeFeatures(cli k8sclient.Interface, node *corev1.Node, labels map[string]string, features *nfdv1alpha1.Features) error {
if !nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.DisableAutoPrefix) && m.config.AutoDefaultNs {
labels = addNsToMapKeys(labels, nfdv1alpha1.FeatureLabelNs)
} else if labels == nil {
labels = make(map[string]string)
}
crLabels, crAnnotations, crExtendedResources, crTaints := m.processNodeFeatureRule(node.Name, features)
// Labels
maps.Copy(labels, crLabels)
labels = m.filterFeatureLabels(labels, features)
// Extended resources
extendedResources := m.filterExtendedResources(features, crExtendedResources)
if len(extendedResources) > 0 && m.config.Restrictions.DisableExtendedResources {
klog.V(2).InfoS("extended resources are disabled in configuration (restrictions.disableExtendedResources=true)")
extendedResources = map[string]string{}
}
// Annotations
annotations := m.filterFeatureAnnotations(crAnnotations)
// Taints
var taints []corev1.Taint
if m.config.EnableTaints {
taints = filterTaints(crTaints)
}
if m.config.NoPublish {
klog.V(1).InfoS("node update skipped, NoPublish=true", "nodeName", node.Name)
return nil
}
err := m.updateNodeObject(cli, node, labels, annotations, extendedResources, taints)
if err != nil {
klog.ErrorS(err, "failed to update node", "nodeName", node.Name)
return err
}
return nil
}
// setTaints sets node taints and annotations based on the taints passed via
// nodeFeatureRule custom resorce. If empty list of taints is passed, currently
// NFD owned taints and annotations are removed from the node.
func (m *nfdMaster) setTaints(cli k8sclient.Interface, taints []corev1.Taint, node *corev1.Node) error {
// De-serialize the taints annotation into corev1.Taint type for comparision below.
var err error
oldTaints := []corev1.Taint{}
if val, ok := node.Annotations[nfdv1alpha1.NodeTaintsAnnotation]; ok {
sts := strings.Split(val, ",")
oldTaints, _, err = taintutils.ParseTaints(sts)
if err != nil {
return err
}
}
// Delete old nfd-managed taints that are not found in the set of new taints.
taintsUpdated := false
newNode := node.DeepCopy()
for _, taintToRemove := range oldTaints {
if taintutils.TaintExists(taints, &taintToRemove) {
continue
}
newTaints, removed := taintutils.DeleteTaint(newNode.Spec.Taints, &taintToRemove)
if !removed {
klog.V(1).InfoS("taint already deleted from node", "taint", taintToRemove)
}
taintsUpdated = taintsUpdated || removed
newNode.Spec.Taints = newTaints
}
// Add new taints found in the set of new taints.
for _, taint := range taints {
var updated bool
newNode, updated, err = taintutils.AddOrUpdateTaint(newNode, &taint)
if err != nil {
return fmt.Errorf("failed to add %q taint on node %v", taint, node.Name)
}
taintsUpdated = taintsUpdated || updated
}
if taintsUpdated {
if err := controller.PatchNodeTaints(context.TODO(), cli, node.Name, node, newNode); err != nil {
return fmt.Errorf("failed to patch the node %v", node.Name)
}
klog.InfoS("updated node taints", "nodeName", node.Name)
}
// Update node annotation that holds the taints managed by us
newAnnotations := map[string]string{}
if len(taints) > 0 {
// Serialize the new taints into string and update the annotation
// with that string.
taintStrs := make([]string, 0, len(taints))
for _, taint := range taints {
taintStrs = append(taintStrs, taint.ToString())
}
newAnnotations[nfdv1alpha1.NodeTaintsAnnotation] = strings.Join(taintStrs, ",")
}
patches := createPatches(sets.New([]string{nfdv1alpha1.NodeTaintsAnnotation}...),
node.Annotations, newAnnotations,
"/metadata/annotations",
m.config.Restrictions.AllowOverwrite,
)
if len(patches) > 0 {
if err := patchNode(cli, node.Name, patches); err != nil {
return fmt.Errorf("error while patching node object: %w", err)
}
klog.V(1).InfoS("patched node annotations for taints", "nodeName", node.Name)
}
return nil
}
func (m *nfdMaster) processNodeFeatureRule(nodeName string, features *nfdv1alpha1.Features) (Labels, Annotations, ExtendedResources, []corev1.Taint) {
if m.nfdController == nil {
return nil, nil, nil, nil
}
extendedResources := ExtendedResources{}
labels := make(map[string]string)
annotations := make(map[string]string)
var taints []corev1.Taint
ruleSpecs, err := m.nfdController.ruleLister.List(k8sLabels.Everything())