Skip to content

Commit

Permalink
Merge pull request #1781 from TessaIO/fix-swap-empty-line
Browse files Browse the repository at this point in the history
fix: take into consideration possibility of having empty line in swap file
  • Loading branch information
k8s-ci-robot committed Jul 12, 2024
2 parents ee7795c + 316fe71 commit 98e9091
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 6 deletions.
12 changes: 9 additions & 3 deletions source/memory/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion source/memory/memory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
2 changes: 1 addition & 1 deletion source/memory/testdata/noswap
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Filename Type Size Used Priority
Filename Type Size Used Priority
2 changes: 1 addition & 1 deletion source/memory/testdata/swap
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
Filename Type Size Used Priority
dummyfile partition 65555 0 -1
dummyfile partition 65555 0 -1

0 comments on commit 98e9091

Please sign in to comment.