Repository: kubernetes-sigs/node-feature-discovery (go)

Issue:
Swap misidentified due to trailing newline in file
<!-- Please use this template while reporting a bug and provide as much info as possible. Not doing so may result in your bug not being addressed in a timely manner. Thanks!

If the matter is security related, please disclose it privately via https://kubernetes.io/security/
-->


**What happened**:

While deploying NFD 0.16.0 on a k8s 1.30.2 node (Ubuntu 22.04), I noticed it assigned `memory-swap=true` despite swap not being enabled on this system.

**What you expected to happen**:

I expected NFD to recognize that no swap device is registered

**How to reproduce it (as minimally and precisely as possible)**:

As far as I can tell, the issue is that `/proc/swaps` ends in a newline character `\n`, while the testdata has no such trailing newline. So any system which has `/proc/swaps` with a trailing newline will be misidentified.

**Anything else we need to know?**:

This system is a VM which was initially created with swap which was then removed as part of the k8s provisioning process. `/proc/swaps` contains only the header line and a single `\n` character now.

**Environment**:
- Kubernetes version (use `kubectl version`): v1.30.2
- Cloud provider or hardware configuration: VM on local proxmox instance
- OS (e.g: `cat /etc/os-release`): Ubuntu 22.04
- Kernel (e.g. `uname -a`): 5.15.0-113-generic
- Install tools: 
  - Cluster created with `kubeadm version: &version.Info{Major:"1", Minor:"30", GitVersion:"v1.30.2", GitCommit:"39683505b630ff2121012f3c5b16215a1449d5ed", GitTreeState:"clean", BuildDate:"2024-06-11T20:27:59Z", GoVersion:"go1.22.4", Compiler:"gc", Platform:"linux/amd64"}`
  - Helm: [Terraform provider](https://registry.terraform.io/providers/hashicorp/helm/2.14.0) version 2.14.0

I believe the fix is as simple as ignoring empty lines when checking number of lines in the file, though I won't have time to open a PR until next weekend at the earliest, so someone else is welcome to take this on as well.

Pull request:
fix: take into consideration possibility of having empty line in swap file
Closes #1751 

Patch:
diff --git a/README.md b/README.md
index 5e5c1b98c..52d318d5c 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@ features and system configuration!
 #### Quick-start – the short-short version
 
 ```bash
-$ kubectl apply -k https://github.com/kubernetes-sigs/node-feature-discovery/deployment/overlays/default?ref=v0.16.2
+$ kubectl apply -k https://github.com/kubernetes-sigs/node-feature-discovery/deployment/overlays/default?ref=v0.16.1
   namespace/node-feature-discovery created
   customresourcedefinition.apiextensions.k8s.io/nodefeaturerules.nfd.k8s-sigs.io created
   customresourcedefinition.apiextensions.k8s.io/nodefeatures.nfd.k8s-sigs.io created
diff --git a/cmd/nfd-master/main.go b/cmd/nfd-master/main.go
index 08a35324f..a51309b4a 100644
--- a/cmd/nfd-master/main.go
+++ b/cmd/nfd-master/main.go
@@ -81,6 +81,8 @@ func main() {
 			args.Overrides.ResyncPeriod = overrides.ResyncPeriod
 		case "nfd-api-parallelism":
 			args.Overrides.NfdApiParallelism = overrides.NfdApiParallelism
+		case "enable-nodefeature-api":
+			klog.InfoS("-enable-nodefeature-api is deprecated and will be removed in the next release, use -feature-gate NodeFeatureAPI instead")
 		case "ca-file":
 			klog.InfoS("-ca-file is deprecated, will be removed in a future release along with the deprecated gRPC API")
 		case "cert-file":
@@ -139,6 +141,9 @@ func initFlags(flagset *flag.FlagSet) (*master.Args, *master.ConfigOverrideArgs)
 		"Config file to use.")
 	flagset.StringVar(&args.Kubeconfig, "kubeconfig", "",
 		"Kubeconfig to use")
+	flagset.BoolVar(&args.EnableNodeFeatureApi, "enable-nodefeature-api", true,
+		"Enable the NodeFeature CRD API for receiving node features. This will automatically disable the gRPC communication."+
+			" DEPRECATED: will be removed in NFD v0.17. Use -feature-gate NodeFeatureAPI instead.")
 	flagset.BoolVar(&args.CrdController, "featurerules-controller", true,
 		"Enable NFD CRD API controller. DEPRECATED: use -crd-controller instead")
 	flagset.BoolVar(&args.CrdController, "crd-controller", true,
diff --git a/cmd/nfd-worker/main.go b/cmd/nfd-worker/main.go
index 5c204aea4..20a259381 100644
--- a/cmd/nfd-worker/main.go
+++ b/cmd/nfd-worker/main.go
@@ -69,6 +69,8 @@ func main() {
 			klog.InfoS("-cert-file is deprecated, will be removed in a future release along with the deprecated gRPC API")
 		case "key-file":
 			klog.InfoS("-key-file is deprecated, will be removed in a future release along with the deprecated gRPC API")
+		case "enable-nodefeature-api":
+			klog.InfoS("-enable-nodefeature-api is deprecated and will be removed in the next release, use -feature-gate NodeFeatureAPI instead")
 		case "server":
 			klog.InfoS("-server is deprecated, will be removed in a future release along with the deprecated gRPC API")
 		case "server-name-override":
@@ -132,6 +134,9 @@ func initFlags(flagset *flag.FlagSet) (*worker.Args, *worker.ConfigOverrideArgs)
 	flagset.StringVar(&args.KeyFile, "key-file", "",
 		"Private key matching -cert-file."+
 			" DEPRECATED: will be removed in a future release along with the deprecated gRPC API.")
+	flagset.BoolVar(&args.EnableNodeFeatureApi, "enable-nodefeature-api", true,
+		"Enable the NodeFeature CRD API for communicating with nfd-master. This will automatically disable the gRPC communication."+
+			" DEPRECATED: will be removed in NFD v0.17. Use -feature-gate NodeFeatureAPI instead.")
 	flagset.StringVar(&args.Kubeconfig, "kubeconfig", "",
 		"Kubeconfig to use")
 	flagset.BoolVar(&args.Oneshot, "oneshot", false,
diff --git a/deployment/helm/node-feature-discovery/templates/clusterrole.yaml b/deployment/helm/node-feature-discovery/templates/clusterrole.yaml
index 958f043fe..f935cfe41 100644
--- a/deployment/helm/node-feature-discovery/templates/clusterrole.yaml
+++ b/deployment/helm/node-feature-discovery/templates/clusterrole.yaml
@@ -94,7 +94,7 @@ rules:
   - update
 {{- end }}
 
-{{- if and .Values.gc.enable .Values.gc.rbac.create (or .Values.featureGates.NodeFeatureAPI .Values.topologyUpdater.enable) }}
+{{- if and .Values.gc.enable .Values.gc.rbac.create (or (and .Values.featureGates.NodeFeatureAPI .Values.enableNodeFeatureApi) .Values.topologyUpdater.enable) }}
 ---
 apiVersion: rbac.authorization.k8s.io/v1
 kind: ClusterRole
diff --git a/deployment/helm/node-feature-discovery/templates/clusterrolebinding.yaml b/deployment/helm/node-feature-discovery/templates/clusterrolebinding.yaml
index 8623de606..3f717988b 100644
--- a/deployment/helm/node-feature-discovery/templates/clusterrolebinding.yaml
+++ b/deployment/helm/node-feature-discovery/templates/clusterrolebinding.yaml
@@ -33,7 +33,7 @@ subjects:
   namespace: {{ include "node-feature-discovery.namespace" .  }}
 {{- end }}
 
-{{- if and .Values.gc.enable .Values.gc.rbac.create (or .Values.featureGates.NodeFeatureAPI  .Values.topologyUpdater.enable) }}
+{{- if and .Values.gc.enable .Values.gc.rbac.create (or (and .Values.featureGates.NodeFeatureAPI .Values.enableNodeFeatureApi) .Values.topologyUpdater.enable) }}
 ---
 apiVersion: rbac.authorization.k8s.io/v1
 kind: ClusterRoleBinding
diff --git a/deployment/helm/node-feature-discovery/templates/master.yaml b/deployment/helm/node-feature-discovery/templates/master.yaml
index a15467c83..496a443f9 100644
--- a/deployment/helm/node-feature-discovery/templates/master.yaml
+++ b/deployment/helm/node-feature-discovery/templates/master.yaml
@@ -73,7 +73,7 @@ spec:
             {{- if .Values.master.instance | empty | not }}
             - "-instance={{ .Values.master.instance }}"
             {{- end }}
-            {{- if not .Values.featureGates.NodeFeatureAPI }}
+            {{- if not (and .Values.featureGates.NodeFeatureAPI .Values.enableNodeFeatureApi) }}
             - "-port={{ .Values.master.port | default "8080" }}"
             {{- else if gt (int .Values.master.replicaCount) 1 }}
             - "-enable-leader-election"
diff --git a/deployment/helm/node-feature-discovery/templates/nfd-gc.yaml b/deployment/helm/node-feature-discovery/templates/nfd-gc.yaml
index e23a25ad0..19dd4e192 100644
--- a/deployment/helm/node-feature-discovery/templates/nfd-gc.yaml
+++ b/deployment/helm/node-feature-discovery/templates/nfd-gc.yaml
@@ -1,4 +1,4 @@
-{{- if and .Values.gc.enable (or .Values.featureGates.NodeFeatureAPI .Values.topologyUpdater.enable) -}}
+{{- if and .Values.gc.enable (or (and .Values.featureGates.NodeFeatureAPI .Values.enableNodeFeatureApi) .Values.topologyUpdater.enable) -}}
 apiVersion: apps/v1
 kind: Deployment
 metadata:
diff --git a/deployment/helm/node-feature-discovery/templates/service.yaml b/deployment/helm/node-feature-discovery/templates/service.yaml
index a6e7678fb..7191dca70 100644
--- a/deployment/helm/node-feature-discovery/templates/service.yaml
+++ b/deployment/helm/node-feature-discovery/templates/service.yaml
@@ -1,4 +1,4 @@
-{{- if and (not .Values.featureGates.NodeFeatureAPI) .Values.master.enable }}
+{{- if and (not (and .Values.featureGates.NodeFeatureAPI .Values.enableNodeFeatureApi)) .Values.master.enable }}
 apiVersion: v1
 kind: Service
 metadata:
diff --git a/deployment/helm/node-feature-discovery/templates/serviceaccount.yaml b/deployment/helm/node-feature-discovery/templates/serviceaccount.yaml
index 740160284..59edc5e6c 100644
--- a/deployment/helm/node-feature-discovery/templates/serviceaccount.yaml
+++ b/deployment/helm/node-feature-discovery/templates/serviceaccount.yaml
@@ -27,7 +27,7 @@ metadata:
   {{- end }}
 {{- end }}
 
-{{- if and .Values.gc.enable .Values.gc.serviceAccount.create (or .Values.featureGates.NodeFeatureAPI .Values.topologyUpdater.enable) }}
+{{- if and .Values.gc.enable .Values.gc.serviceAccount.create (or (and .Values.featureGates.NodeFeatureAPI .Values.enableNodeFeatureApi) .Values.topologyUpdater.enable) }}
 ---
 apiVersion: v1
 kind: ServiceAccount
diff --git a/deployment/helm/node-feature-discovery/templates/worker.yaml b/deployment/helm/node-feature-discovery/templates/worker.yaml
index 684681324..d775debca 100644
--- a/deployment/helm/node-feature-discovery/templates/worker.yaml
+++ b/deployment/helm/node-feature-discovery/templates/worker.yaml
@@ -72,7 +72,7 @@ spec:
         command:
         - "nfd-worker"
         args:
-{{- if not .Values.featureGates.NodeFeatureAPI }}
+{{- if not (and .Values.featureGates.NodeFeatureAPI .Values.enableNodeFeatureApi)   }}
         - "-server={{ include "node-feature-discovery.fullname" . }}-master:{{ .Values.master.service.port }}"
 {{- end }}
 {{- if .Values.tls.enable }}
diff --git a/deployment/helm/node-feature-discovery/values.yaml b/deployment/helm/node-feature-discovery/values.yaml
index a5f94df37..e3574ac23 100644
--- a/deployment/helm/node-feature-discovery/values.yaml
+++ b/deployment/helm/node-feature-discovery/values.yaml
@@ -10,6 +10,8 @@ nameOverride: ""
 fullnameOverride: ""
 namespaceOverride: ""
 
+enableNodeFeatureApi: true
+
 featureGates:
   NodeFeatureAPI: true
   NodeFeatureGroupAPI: false
diff --git a/docs/deployment/helm.md b/docs/deployment/helm.md
index de727eae4..2c56e0e54 100644
--- a/docs/deployment/helm.md
+++ b/docs/deployment/helm.md
@@ -101,6 +101,7 @@ Chart parameters are available.
 | `featureGates.NodeFeatureAPI`      | bool | true                         | Enable the [NodeFeature](../usage/custom-resources.md#nodefeature) CRD API for communicating node features. This will automatically disable the gRPC communication. |
 | `featureGates.NodeFeatureGroupAPI` | bool | false                        | Enable the [NodeFeatureGroup](../usage/custom-resources.md#nodefeaturegroup) CRD API. |
 | `featureGates.DisableAutoPrefix`   | bool | false                        | Enable [DisableAutoPrefix](../reference/feature-gates.md#disableautoprefix) feature gate. Disables automatic prefixing of unprefixed labels, annotations and extended resources. |
+| `enableNodeFeatureApi`| bool   | true                                    | Enable the [NodeFeature](../usage/custom-resources.md#nodefeature) CRD API for communicating node features. This will automatically disable the gRPC communication. **DEPRECATED**: will be removed in NFD v0.17, use `featureGates.NodeFeatureAPI` instead.    |
 | `prometheus.enable`   | bool   | false                                   | Specifies whether to expose metrics using prometheus operator                                                                                |
 | `prometheus.labels`   | dict   | {}                                      | Specifies labels for use with the prometheus operator to control how it is selected                                                        |
 | `prometheus.scrapeInterval`    | string   | 10s                                      | Specifies the interval by which metrics are scraped                                                        |
diff --git a/docs/reference/master-commandline-reference.md b/docs/reference/master-commandline-reference.md
index ffdd07e90..a64670e3a 100644
--- a/docs/reference/master-commandline-reference.md
+++ b/docs/reference/master-commandline-reference.md
@@ -175,6 +175,27 @@ nfd-master -verify-node-name -ca-file=/opt/nfd/ca.crt \
     -cert-file=/opt/nfd/master.crt -key-file=/opt/nfd/master.key
 ```
 
+### -enable-nodefeature-api
+
+**DEPRECATED**: will be removed in NFD v0.17. Use'
+[`-feature-gates`](#-feature-gates)
+[NodeFeatureAPI](feature-gates.md#nodefeatureapi) instead.
+
+> **NOTE** the gRPC API is deprecated and will be removed in a future release.
+
+The `-enable-nodefeature-api` flag enables/disables the
+[NodeFeature](../usage/custom-resources.md#nodefeature) CRD API for receiving
+feature requests. This will also automatically disable/enable the gRPC
+interface.
+
+Default: true
+
+Example:
+
+```bash
+nfd-master -enable-nodefeature-api=false
+```
+
 ### -enable-leader-election
 
 The `-enable-leader-election` flag enables leader election for NFD-Master.
diff --git a/pkg/nfd-master/nfd-master.go b/pkg/nfd-master/nfd-master.go
index e34bb3e5f..b9a1de156 100644
--- a/pkg/nfd-master/nfd-master.go
+++ b/pkg/nfd-master/nfd-master.go
@@ -111,15 +111,16 @@ type ConfigOverrideArgs struct {
 
 // Args holds command line arguments
 type Args struct {
-	CaFile        string
-	CertFile      string
-	ConfigFile    string
-	Instance      string
-	KeyFile       string
-	Klog          map[string]*utils.KlogFlagVal
-	Kubeconfig    string
-	CrdController bool
-	Port          int
+	CaFile               string
+	CertFile             string
+	ConfigFile           string
+	Instance             string
+	KeyFile              string
+	Klog                 map[string]*utils.KlogFlagVal
+	Kubeconfig           string
+	CrdController        bool
+	EnableNodeFeatureApi bool
+	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
@@ -336,7 +337,7 @@ func (m *nfdMaster) Run() error {
 	grpcErr := make(chan error)
 	// If the NodeFeature API is enabled, don'tregister the labeler API
 	// server. Otherwise, register the labeler server.
-	if !nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.NodeFeatureAPI) {
+	if !nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.NodeFeatureAPI) || !m.args.EnableNodeFeatureApi {
 		go m.runGrpcServer(grpcErr)
 	}
 
@@ -391,7 +392,7 @@ func (m *nfdMaster) Run() error {
 			m.updaterPool.start(m.config.NfdApiParallelism)
 
 			// Update all nodes when the configuration changes
-			if m.nfdController != nil && nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.NodeFeatureAPI) {
+			if m.nfdController != nil && nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.NodeFeatureAPI) && m.args.EnableNodeFeatureApi {
 				m.nfdController.updateAllNodesChan <- struct{}{}
 			}
 
@@ -489,7 +490,7 @@ func (m *nfdMaster) runGrpcServer(errChan chan<- error) {
 func (m *nfdMaster) nfdAPIUpdateHandler() {
 	// We want to unconditionally update all nodes at startup if gRPC is
 	// disabled (i.e. NodeFeature API is enabled)
-	updateAll := nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.NodeFeatureAPI)
+	updateAll := nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.NodeFeatureAPI) && m.args.EnableNodeFeatureApi
 	updateNodes := make(map[string]struct{})
 	nodeFeatureGroup := make(map[string]struct{})
 	updateAllNodeFeatureGroups := false
@@ -1511,7 +1512,7 @@ func (m *nfdMaster) startNfdApiController() error {
 	}
 	klog.InfoS("starting the nfd api controller")
 	m.nfdController, err = newNfdController(kubeconfig, nfdApiControllerOptions{
-		DisableNodeFeature: !nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.NodeFeatureAPI),
+		DisableNodeFeature: !nfdfeatures.NFDFeatureGate.Enabled(nfdfeatures.NodeFeatureAPI) || !m.args.EnableNodeFeatureApi,
 		ResyncPeriod:       m.config.ResyncPeriod.Duration,
 	})
 	if err != nil {
diff --git a/pkg/nfd-worker/nfd-worker.go b/pkg/nfd-worker/nfd-worker.go
index 460041850..b9bb87f60 100644
--- a/pkg/nfd-worker/nfd-worker.go
+++ b/pkg/nfd-worker/nfd-worker.go
@@ -97,18 +97,19 @@ type Labels map[string]string
 
 // Args are the command line arguments of NfdWorker.
 type Args struct {
-	CaFile             string
-	CertFile           string
-	ConfigFile         string
-	KeyFile            string
-	Klog               map[string]*utils.KlogFlagVal
-	Kubeconfig         string
-	Oneshot            bool
-	Options            string
-	Server             string
-	ServerNameOverride string
-	MetricsPort        int
-	GrpcHealthPort     int
+	CaFile               string
+	CertFile             string
+	ConfigFile           string
+	EnableNodeFeatureApi bool
+	KeyFile              string
+	Klog                 map[string]*utils.KlogFlagVal
+	Kubeconfig           string
+	Oneshot              bool
+	Options              string
+	Server               string
+	ServerNameOverride   string
+	MetricsPort          int
+	GrpcHealthPort       int
 
 	Overrides ConfigOverrideArgs
 }
@@ -390,7 +391,7 @@ func (w *nfdWorker) Run() error {
 				return err
 			}
 			// Manage connection to master
-			if w.config.Core.NoPublish || !features.NFDFeatureGate.Enabled(features.NodeFeatureAPI) {
+			if w.config.Core.NoPublish || !features.NFDFeatureGate.Enabled(features.NodeFeatureAPI) || !w.args.EnableNodeFeatureApi {
 				w.grpcDisconnect()
 			}
 
@@ -734,7 +735,7 @@ func getFeatureLabels(source source.LabelSource, labelWhiteList regexp.Regexp) (
 
 // advertiseFeatures advertises the features of a Kubernetes node
 func (w *nfdWorker) advertiseFeatures(labels Labels) error {
-	if features.NFDFeatureGate.Enabled(features.NodeFeatureAPI) {
+	if features.NFDFeatureGate.Enabled(features.NodeFeatureAPI) && w.args.EnableNodeFeatureApi {
 		// Create/update NodeFeature CR object
 		if err := w.updateNodeFeatureObject(labels); err != nil {
 			return fmt.Errorf("failed to advertise features (via CRD API): %w", err)
diff --git a/source/memory/memory.go b/source/memory/memory.go
index 5c4ce9f61..ab9bc02ed 100644
--- a/source/memory/memory.go
+++ b/source/memory/memory.go
@@ -131,7 +131,7 @@ func (s *memorySource) GetFeatures() *nfdv1alpha1.Features {
 // detectSwap detects Swap node information
 func detectSwap() (map[string]string, error) {
 	procBasePath := hostpath.ProcDir.Path("swaps")
-	lines, err := getNumberOfLinesFromFile(procBasePath)
+	lines, err := getNumberOfNonEmptyLinesFromFile(procBasePath)
 	if err != nil {
 		return nil, fmt.Errorf("failed to read swaps file: %w", err)
 	}
@@ -195,12 +195,18 @@ func readNdDeviceInfo(path string) nfdv1alpha1.InstanceFeature {
 	return *nfdv1alpha1.NewInstanceFeature(attrs)
 }
 
-func getNumberOfLinesFromFile(path string) (int, error) {
+func getNumberOfNonEmptyLinesFromFile(path string) (int, error) {
 	data, err := os.ReadFile(path)
 	if err != nil {
 		return 0, err
 	}
-	return len(strings.Split(string(data), "\n")), nil
+	length := 0
+	for _, line := range strings.Split(string(data), "\n") {
+		if strings.TrimSpace(line) != "" {
+			length++
+		}
+	}
+	return length, nil
 }
 
 func init() {


Test patch:
diff --git a/source/memory/memory_test.go b/source/memory/memory_test.go
index c5edc1b36..535decb03 100644
--- a/source/memory/memory_test.go
+++ b/source/memory/memory_test.go
@@ -54,7 +54,7 @@ func TestGetNumberofLinesFromFile(t *testing.T) {
 		},
 	}
 	for _, tc := range tc {
-		actual, err := getNumberOfLinesFromFile(tc.path)
+		actual, err := getNumberOfNonEmptyLinesFromFile(tc.path)
 		if tc.expectErr {
 			assert.NotNil(t, err, "should get an error")
 		}
diff --git a/source/memory/testdata/noswap b/source/memory/testdata/noswap
index 37a6cc05c..613dce24e 100644
--- a/source/memory/testdata/noswap
+++ b/source/memory/testdata/noswap
@@ -1,1 +1,1 @@
-Filename                          Type        Size     Used    Priority
\ No newline at end of file
+Filename                          Type        Size     Used    Priority
diff --git a/source/memory/testdata/swap b/source/memory/testdata/swap
index 6ffbd4070..8eb673444 100644
--- a/source/memory/testdata/swap
+++ b/source/memory/testdata/swap
@@ -1,2 +1,2 @@
 Filename                          Type        Size     Used    Priority
-dummyfile   partition   65555   0       -1
\ No newline at end of file
+dummyfile   partition   65555   0       -1