Skip to content

Commit 0d7fdc1

Browse files
davidcassanyfgiudici
authored andcommitted
Add fstab package
This package includes utilities to create and update fstab file. Signed-off-by: David Cassany <dcassany@suse.com> Co-authored-by: Francesco Giudici <francesco.giudici@gmail.com>
1 parent 966ac0e commit 0d7fdc1

File tree

2 files changed

+329
-0
lines changed

2 files changed

+329
-0
lines changed

pkg/fstab/fstab.go

+198
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
/*
2+
Copyright © 2025 SUSE LLC
3+
SPDX-License-Identifier: Apache-2.0
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
*/
17+
18+
package fstab
19+
20+
import (
21+
"bufio"
22+
"fmt"
23+
"io"
24+
"os"
25+
"slices"
26+
"strconv"
27+
"text/tabwriter"
28+
29+
"strings"
30+
31+
"github.com/suse/elemental/v3/pkg/sys"
32+
"github.com/suse/elemental/v3/pkg/sys/vfs"
33+
)
34+
35+
const File = "/etc/fstab"
36+
37+
type Line struct {
38+
Device string
39+
MountPoint string
40+
FileSystem string
41+
Options []string
42+
DumpFreq int
43+
FsckOrder int
44+
}
45+
46+
// WriteFstab writes an fstab file at the given location including the given fstab lines
47+
func WriteFstab(s *sys.System, fstabFile string, fstabLines []Line) (err error) {
48+
fstab, err := s.FS().Create(fstabFile)
49+
if err != nil {
50+
s.Logger().Error("could not create fstab file %s", fstabFile)
51+
return err
52+
}
53+
defer func() {
54+
e := fstab.Close()
55+
if err == nil && e != nil {
56+
err = e
57+
}
58+
}()
59+
60+
err = writeFstabLines(fstab, fstabLines)
61+
if err != nil {
62+
s.Logger().Error("failed writing fstab lines")
63+
return err
64+
}
65+
66+
return nil
67+
}
68+
69+
// UpdateFstab updates the given fstab file by replacing each oldLine with its newLine.
70+
func UpdateFstab(s *sys.System, fstabFile string, oldLines, newLines []Line) (err error) {
71+
if len(oldLines) != len(newLines) {
72+
return fmt.Errorf("length of new and old lines must match")
73+
}
74+
75+
fstab, err := s.FS().OpenFile(fstabFile, os.O_RDWR, vfs.FilePerm)
76+
if err != nil {
77+
s.Logger().Error("could not open fstab file %s", fstabFile)
78+
return err
79+
}
80+
defer func() {
81+
e := fstab.Close()
82+
if err == nil && e != nil {
83+
err = e
84+
}
85+
}()
86+
87+
scanner := bufio.NewScanner(fstab)
88+
89+
var fstabLines []Line
90+
for scanner.Scan() {
91+
line := scanner.Text()
92+
fstabLine, err := fstabLineFromFields(strings.Fields(line))
93+
if err != nil {
94+
s.Logger().Error("invalid fstab line '%s'", line)
95+
return err
96+
}
97+
fstabLines = append(fstabLines, fstabLine)
98+
}
99+
100+
fstabLines = updateFstabLines(fstabLines, oldLines, newLines)
101+
102+
_, err = fstab.Seek(0, 0)
103+
if err != nil {
104+
s.Logger().Error("failed to reset fstab file cursor")
105+
return err
106+
}
107+
108+
err = fstab.Truncate(0)
109+
if err != nil {
110+
s.Logger().Error("failed truncating fstab file '%s'", fstabFile)
111+
return err
112+
}
113+
114+
err = writeFstabLines(fstab, fstabLines)
115+
if err != nil {
116+
s.Logger().Error("failed writing fstab lines")
117+
return err
118+
}
119+
120+
return nil
121+
}
122+
123+
func updateFstabLines(lines []Line, oldLines, newLines []Line) []Line {
124+
var fstabLines []Line
125+
for _, line := range lines {
126+
if i := matchFstabLine(line, oldLines); i >= 0 {
127+
fstabLines = append(fstabLines, newLines[i])
128+
} else {
129+
fstabLines = append(fstabLines, line)
130+
}
131+
}
132+
return fstabLines
133+
}
134+
135+
func writeFstabLines(w io.Writer, fstabLines []Line) (err error) {
136+
tw := tabwriter.NewWriter(w, 1, 4, 1, ' ', 0)
137+
for _, fLine := range fstabLines {
138+
_, err = fmt.Fprintf(
139+
tw, "%s\t%s\t%s\t%s\t%d\t%d\n",
140+
fLine.Device, fLine.MountPoint, fLine.FileSystem,
141+
strings.Join(fLine.Options, ","), fLine.DumpFreq, fLine.FsckOrder,
142+
)
143+
if err != nil {
144+
return err
145+
}
146+
}
147+
err = tw.Flush()
148+
if err != nil {
149+
return err
150+
}
151+
152+
return nil
153+
}
154+
155+
// matchFstabLine compares device, mountpoint, filesystem and options of the given fstab line, with the
156+
// lines in the match list. If parameters match returns the index of the list or -1 if no match. Any empty
157+
// field in match lines matches any value.
158+
func matchFstabLine(line Line, matchLines []Line) int {
159+
for i, mLine := range matchLines {
160+
if mLine.Device != "" && mLine.Device != line.Device {
161+
continue
162+
}
163+
if mLine.MountPoint != "" && mLine.MountPoint != line.MountPoint {
164+
continue
165+
}
166+
if mLine.FileSystem != "" && mLine.FileSystem != line.FileSystem {
167+
continue
168+
}
169+
if len(mLine.Options) > 0 && !slices.Equal(mLine.Options, line.Options) {
170+
continue
171+
}
172+
return i
173+
}
174+
return -1
175+
}
176+
177+
func fstabLineFromFields(fields []string) (Line, error) {
178+
var fstabLine Line
179+
if len(fields) != 6 {
180+
return fstabLine, fmt.Errorf("invalid number of fields for fstab line")
181+
}
182+
dumpFreq, err := strconv.Atoi(fields[4])
183+
if err != nil {
184+
return fstabLine, fmt.Errorf("invalid dump frequency value in fstab line '%s'", fields[4])
185+
}
186+
fsckOrder, err := strconv.Atoi(fields[5])
187+
if err != nil {
188+
return fstabLine, fmt.Errorf("invalid filesystem check order value in fstab line '%s'", fields[5])
189+
}
190+
fstabLine.Device = fields[0]
191+
fstabLine.MountPoint = fields[1]
192+
fstabLine.FileSystem = fields[2]
193+
fstabLine.Options = strings.Split(fields[3], ",")
194+
fstabLine.DumpFreq = dumpFreq
195+
fstabLine.FsckOrder = fsckOrder
196+
197+
return fstabLine, nil
198+
}

pkg/fstab/fstab_test.go

+131
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
/*
2+
Copyright © 2025 SUSE LLC
3+
SPDX-License-Identifier: Apache-2.0
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
*/
17+
18+
package fstab_test
19+
20+
import (
21+
"testing"
22+
23+
. "github.com/onsi/ginkgo/v2"
24+
. "github.com/onsi/gomega"
25+
"github.com/onsi/gomega/format"
26+
27+
"github.com/suse/elemental/v3/pkg/fstab"
28+
"github.com/suse/elemental/v3/pkg/log"
29+
"github.com/suse/elemental/v3/pkg/sys"
30+
sysmock "github.com/suse/elemental/v3/pkg/sys/mock"
31+
"github.com/suse/elemental/v3/pkg/sys/vfs"
32+
)
33+
34+
func TestFstabSuite(t *testing.T) {
35+
RegisterFailHandler(Fail)
36+
RunSpecs(t, "Fstab test suite")
37+
}
38+
39+
const fstabFile = `/dev/device / ext2 ro,defaults 0 1
40+
LABEL=mylabel /data btrfs defaults,subvol=/@/data 0 0
41+
UUID=afadf /etc btrfs defaults,subvol=/@/etc 0 0
42+
`
43+
44+
const updatedFstab = `/dev/device / ext2 ro,defaults 0 1
45+
UUID=uuid /data btrfs defaults,subvol=/@/new/data 0 0
46+
UUID=afadf /etc btrfs defaults,subvol=/@/new/path/etc 0 0
47+
`
48+
49+
var _ = Describe("DirectoryUnpacker", Label("directory"), func() {
50+
var tfs vfs.FS
51+
var s *sys.System
52+
var cleanup func()
53+
var err error
54+
var lines []fstab.Line
55+
BeforeEach(func() {
56+
tfs, cleanup, err = sysmock.TestFS(nil)
57+
Expect(err).NotTo(HaveOccurred())
58+
s, err = sys.NewSystem(sys.WithFS(tfs), sys.WithLogger(log.New(log.WithDiscardAll())))
59+
Expect(err).NotTo(HaveOccurred())
60+
Expect(vfs.MkdirAll(tfs, "/etc", vfs.DirPerm)).To(Succeed())
61+
62+
lines = []fstab.Line{{
63+
Device: "/dev/device",
64+
MountPoint: "/",
65+
FileSystem: "ext2",
66+
Options: []string{"ro", "defaults"},
67+
FsckOrder: 1,
68+
}, {
69+
Device: "LABEL=mylabel",
70+
MountPoint: "/data",
71+
FileSystem: "btrfs",
72+
Options: []string{"defaults", "subvol=/@/data"},
73+
}, {
74+
Device: "UUID=afadf",
75+
MountPoint: "/etc",
76+
FileSystem: "btrfs",
77+
Options: []string{"defaults", "subvol=/@/etc"},
78+
}}
79+
format.TruncatedDiff = false
80+
})
81+
AfterEach(func() {
82+
cleanup()
83+
})
84+
It("creates an fstab file with the given lines", func() {
85+
Expect(fstab.WriteFstab(s, fstab.File, lines)).To(Succeed())
86+
data, err := tfs.ReadFile(fstab.File)
87+
Expect(err).NotTo(HaveOccurred())
88+
Expect(string(data)).To(Equal(fstabFile))
89+
})
90+
It("fails to write fstab file on a read-only filesystem", func() {
91+
tfs, err := sysmock.ReadOnlyTestFS(tfs)
92+
Expect(err).NotTo(HaveOccurred())
93+
s, err = sys.NewSystem(sys.WithFS(tfs), sys.WithLogger(log.New(log.WithDiscardAll())))
94+
Expect(err).NotTo(HaveOccurred())
95+
96+
Expect(fstab.WriteFstab(s, fstab.File, lines)).NotTo(Succeed())
97+
})
98+
It("updates the fstab file with a new line", func() {
99+
Expect(fstab.WriteFstab(s, fstab.File, lines)).To(Succeed())
100+
Expect(fstab.UpdateFstab(
101+
s, fstab.File, []fstab.Line{
102+
{MountPoint: "/etc"}, {MountPoint: "/data"},
103+
}, []fstab.Line{
104+
{
105+
Device: "UUID=afadf",
106+
MountPoint: "/etc",
107+
FileSystem: "btrfs",
108+
Options: []string{"defaults", "subvol=/@/new/path/etc"},
109+
},
110+
{
111+
Device: "UUID=uuid",
112+
MountPoint: "/data",
113+
FileSystem: "btrfs",
114+
Options: []string{"defaults", "subvol=/@/new/data"},
115+
},
116+
},
117+
)).To(Succeed())
118+
data, err := tfs.ReadFile(fstab.File)
119+
Expect(err).NotTo(HaveOccurred())
120+
Expect(string(data)).To(Equal(updatedFstab))
121+
})
122+
It("fails to update fstab file on a read-only filesystem", func() {
123+
Expect(fstab.WriteFstab(s, fstab.File, lines)).To(Succeed())
124+
tfs, err := sysmock.ReadOnlyTestFS(tfs)
125+
Expect(err).NotTo(HaveOccurred())
126+
s, err = sys.NewSystem(sys.WithFS(tfs), sys.WithLogger(log.New(log.WithDiscardAll())))
127+
Expect(err).NotTo(HaveOccurred())
128+
129+
Expect(fstab.WriteFstab(s, fstab.File, lines)).NotTo(Succeed())
130+
})
131+
})

0 commit comments

Comments
 (0)