Skip to content

Commit

Permalink
Add mount command
Browse files Browse the repository at this point in the history
The mount command mounts the system and is meant to run in an initrd to
actually mount the root filesystem and use systemd to switch-root into
it.

It also optionally writes an /etc/fstab file to the newly mounted
system so that systemd will mount the system after switching root.

The command is used in the new dracut module elemental-rootfs, which
will coexist with immutable-rootfs (they are functionally the same)
until immutable-rootfs can be deprecated.

Signed-off-by: Fredrik Lönnegren <fredrik.lonnegren@suse.com>
  • Loading branch information
frelon committed Sep 27, 2023
1 parent 2717827 commit cbecf85
Show file tree
Hide file tree
Showing 15 changed files with 445 additions and 12 deletions.
18 changes: 18 additions & 0 deletions cmd/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,24 @@ func ReadInitSpec(r *v1.RunConfig, flags *pflag.FlagSet) (*v1.InitSpec, error) {
return init, err
}

func ReadMountSpec(r *v1.RunConfig, flags *pflag.FlagSet) (*v1.MountSpec, error) {
mount := config.NewMountSpec()
vp := viper.Sub("mount")
if vp == nil {
vp = viper.New()
}
// Bind install cmd flags
bindGivenFlags(vp, flags)
// Bind install env vars
viperReadEnv(vp, "MOUNT", constants.GetInitKeyEnvMap())

err := vp.Unmarshal(mount, setDecoder, decodeHook)
if err != nil {
r.Logger.Warnf("error unmarshalling MountSpec: %s", err)
}
return mount, err
}

func ReadResetSpec(r *v1.RunConfig, flags *pflag.FlagSet) (*v1.ResetSpec, error) {
reset, err := config.NewResetSpec(r.Config)
if err != nil {
Expand Down
59 changes: 59 additions & 0 deletions cmd/mount.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
Copyright © 2022 - 2023 SUSE LLC
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 cmd

import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
"k8s.io/mount-utils"

"github.com/rancher/elemental-toolkit/cmd/config"
"github.com/rancher/elemental-toolkit/pkg/action"
"github.com/rancher/elemental-toolkit/pkg/constants"
elementalError "github.com/rancher/elemental-toolkit/pkg/error"
)

func MountCmd(root *cobra.Command) *cobra.Command {
c := &cobra.Command{
Use: "mount DEVICE SYSROOT",
Short: "Mount an elemental system from a device into the specified sysroot",
Args: cobra.MaximumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
mounter := mount.New(constants.MountBinary)

cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), mounter)
if err != nil {
cfg.Logger.Errorf("Error reading config: %s\n", err)
return elementalError.NewFromError(err, elementalError.ReadingRunConfig)
}

cmd.SilenceUsage = true
spec, err := config.ReadMountSpec(cfg, cmd.Flags())
if err != nil {
cfg.Logger.Errorf("Error reading spec: %s\n", err)
return elementalError.NewFromError(err, elementalError.ReadingSpecConfig)
}

cfg.Logger.Infof("Mounting system...")
return action.RunMount(cfg, spec)
},
}
root.AddCommand(c)
return c
}

var _ = MountCmd(rootCmd)
21 changes: 21 additions & 0 deletions config.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,27 @@ upgrade:
# grub menu entry, this is the string that will be displayed
grub-entry-name: Elemental

# configuration used for the 'mount' command
mount:
read-kernel-cmdline: true # read and parse /proc/cmdline for arguments
sysroot: /sysroot
write-fstab: true
write-sentinel: true
rw-paths:
- /var
- /etc
- /srv
persistent:
mode: overlay # overlay|bind
paths:
- /etc/systemd
- /etc/ssh
- /home
- /opt
- /root
- /usr/libexec
- /var/log

# use cosign to validate images from container registries
cosign: true
# cosign key to used for validation
Expand Down
132 changes: 132 additions & 0 deletions pkg/action/mount.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
Copyright © 2022 - 2023 SUSE LLC
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 action

import (
"fmt"
"path/filepath"
"strings"

"github.com/rancher/elemental-toolkit/pkg/constants"
"github.com/rancher/elemental-toolkit/pkg/elemental"
v1 "github.com/rancher/elemental-toolkit/pkg/types/v1"
"github.com/rancher/elemental-toolkit/pkg/utils"
)

func RunMount(cfg *v1.RunConfig, spec *v1.MountSpec) error {
cfg.Logger.Info("Running mount command")

e := elemental.NewElemental(&cfg.Config)

err := e.MountPartitions(spec.Partitions.PartitionsByMountPoint(false))
if err != nil {
return err
}

if err := e.MountImage(spec.Image); err != nil {
cfg.Logger.Errorf("Error mounting image %s: %s", spec.Image.File, err.Error())
return err
}

for _, path := range spec.RwPaths {
cfg.Logger.Debugf("Mounting path %s into %s", path, spec.Sysroot)
if err := MountRwPath(cfg, spec.Sysroot, path); err != nil {
cfg.Logger.Errorf("Error mounting path %s: %s", path, err.Error())
return err
}
}

if err := WriteFstab(cfg, spec); err != nil {
cfg.Logger.Errorf("Error writing new fstab: %s", err.Error())
return err
}

cfg.Logger.Info("Mount command finished successfully")
return nil
}

func MountRwPath(cfg *v1.RunConfig, sysroot, path string) error {
cfg.Logger.Debugf("Mounting Path")

lower := filepath.Join(sysroot, path)
if err := utils.MkdirAll(cfg.Config.Fs, lower, constants.DirPerm); err != nil {
cfg.Logger.Errorf("Error creating directory %s: %s", path, err.Error())
return err
}

trimmed := strings.TrimPrefix(path, "/")
pathName := strings.ReplaceAll(trimmed, "/", "-")
upper := fmt.Sprintf("%s/%s/upper", constants.OverlayDir, pathName)
if err := utils.MkdirAll(cfg.Config.Fs, upper, constants.DirPerm); err != nil {
cfg.Logger.Errorf("Error creating upperdir %s: %s", upper, err.Error())
return err
}

work := fmt.Sprintf("%s/%s/work", constants.OverlayDir, pathName)
if err := utils.MkdirAll(cfg.Config.Fs, work, constants.DirPerm); err != nil {
cfg.Logger.Errorf("Error creating workdir %s: %s", work, err.Error())
return err
}

cfg.Logger.Debugf("Mounting overlay %s", lower)
options := []string{"defaults"}
options = append(options, fmt.Sprintf("lowerdir=%s", lower))
options = append(options, fmt.Sprintf("upperdir=%s", upper))
options = append(options, fmt.Sprintf("workdir=%s", work))

if err := cfg.Mounter.Mount("overlay", lower, "overlay", options); err != nil {
cfg.Logger.Errorf("Error mounting overlay: %s", err.Error())
return err
}

return nil
}

// /dev/loop0 / auto ro 0 0
// overlay /etc overlay defaults,lowerdir=/etc,upperdir=/run/elemental/overlay/etc.overlay/upper,workdir=/run/elemental/overlay/etc.overlay/work,x-systemd.requires-mounts-for=/run/elemental/overlay
// /dev/disk/by-label/COS_OEM /oem auto defaults 0 0
// overlay /srv overlay defaults,lowerdir=/srv,upperdir=/run/elemental/overlay/srv.overlay/upper,workdir=/run/elemental/overlay/srv.overlay/work,x-systemd.requires-mounts-for=/run/elemental/overlay
// /dev/disk/by-label/COS_PERSISTENT /run/elemental/persistent auto defaults 0 0
// overlay /var overlay defaults,lowerdir=/var,upperdir=/run/elemental/overlay/var.overlay/upper,workdir=/run/elemental/overlay/var.overlay/work,x-systemd.requires-mounts-for=/run/elemental/overlay
func WriteFstab(cfg *v1.RunConfig, spec *v1.MountSpec) error {
if !spec.WriteFstab {
cfg.Logger.Debug("Skipping writing fstab")
return nil
}

data := fmt.Sprintf("%s\t/\tauto\tro\t0 0\n", spec.Image.LoopDevice)

for _, part := range spec.Partitions.PartitionsByMountPoint(false) {
data = data + fmt.Sprintf("%s\t%s\t%s\t%s\n", part.Path, part.MountPoint, part.FS, "")
}

for _, rw := range spec.RwPaths {
trimmed := strings.TrimPrefix(rw, "/")
pathName := strings.ReplaceAll(trimmed, "/", "-")
upper := fmt.Sprintf("%s/%s/upper", constants.OverlayDir, pathName)
work := fmt.Sprintf("%s/%s/work", constants.OverlayDir, pathName)

options := []string{"defaults"}
options = append(options, fmt.Sprintf("lowerdir=%s", rw))
options = append(options, fmt.Sprintf("upperdir=%s", upper))
options = append(options, fmt.Sprintf("workdir=%s", work))
options = append(options, fmt.Sprintf("x-systemd.requires-mounts-for=%s", constants.OverlayDir))
data = data + fmt.Sprintf("%s\t%s\t%s\t%s\n", "overlay", rw, "overlay", strings.Join(options, ","))
}

return cfg.Config.Fs.WriteFile(filepath.Join(spec.Sysroot, "/etc/fstab"), []byte(data), 0644)
}
71 changes: 71 additions & 0 deletions pkg/action/mount_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package action_test

import (
"bytes"
"path/filepath"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/sirupsen/logrus"
"github.com/twpayne/go-vfs"
"github.com/twpayne/go-vfs/vfst"
"k8s.io/mount-utils"

"github.com/rancher/elemental-toolkit/pkg/action"
"github.com/rancher/elemental-toolkit/pkg/config"
"github.com/rancher/elemental-toolkit/pkg/constants"
v1 "github.com/rancher/elemental-toolkit/pkg/types/v1"
"github.com/rancher/elemental-toolkit/pkg/utils"
)

var _ = Describe("Mount Action", func() {
var cfg *v1.RunConfig
var mounter *mount.FakeMounter
var fs vfs.FS
var logger v1.Logger
var cleanup func()
var memLog *bytes.Buffer

BeforeEach(func() {
mounter = &mount.FakeMounter{}
memLog = &bytes.Buffer{}
logger = v1.NewBufferLogger(memLog)
logger.SetLevel(logrus.DebugLevel)
fs, cleanup, _ = vfst.NewTestFS(map[string]interface{}{})
cfg = config.NewRunConfig(
config.WithFs(fs),
config.WithMounter(mounter),
config.WithLogger(logger),
)
})
AfterEach(func() {
cleanup()
})
Describe("Write fstab", Label("mount", "fstab"), func() {
It("Writes a simple fstab", func() {
spec := &v1.MountSpec{
WriteFstab: true,
Image: &v1.Image{
LoopDevice: "/dev/loop0",
},
}
utils.MkdirAll(fs, filepath.Join(spec.Sysroot, "/etc"), constants.DirPerm)
err := action.WriteFstab(cfg, spec)
Expect(err).To(BeNil())

fstab, err := cfg.Config.Fs.ReadFile(filepath.Join(spec.Sysroot, "/etc/fstab"))
Expect(err).To(BeNil())
Expect(string(fstab)).To(Equal("/dev/loop0\t/\tauto\tro\t0 0\n"))
})
})
// Describe("Mount image", Label("mount", "image"), func() {
// It("Mounts an image", func() {
// spec := &v1.MountSpec{
// Image: &v1.Image{},
// }

// err := action.RunMount(cfg, spec)
// Expect(err).To(BeNil())
// })
// })
})
42 changes: 42 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,48 @@ func NewInitSpec() *v1.InitSpec {
}
}

func NewMountSpec() *v1.MountSpec {
return &v1.MountSpec{
Sysroot: "/sysroot",
WriteFstab: true,
WriteSentinel: true,
Image: &v1.Image{
Label: constants.ActiveLabel,
FS: constants.LinuxImgFs,
File: filepath.Join(constants.RunningStateDir, "cOS", constants.ActiveImgFile),
Source: v1.NewFileSrc(filepath.Join(constants.RunningStateDir, "cOS", constants.ActiveImgFile)),
MountPoint: "/sysroot",
},
Partitions: v1.ElementalPartitions{
State: &v1.Partition{
FilesystemLabel: constants.StateLabel,
Size: constants.StateSize,
Name: constants.StatePartName,
FS: constants.LinuxFs,
MountPoint: constants.RunningStateDir,
Flags: []string{},
},
Persistent: &v1.Partition{
FilesystemLabel: constants.PersistentLabel,
Size: constants.PersistentSize,
Name: constants.PersistentPartName,
FS: constants.LinuxFs,
MountPoint: constants.PersistentDir,
Flags: []string{},
},
OEM: &v1.Partition{
FilesystemLabel: constants.OEMLabel,
Size: constants.OEMSize,
Name: constants.OEMPartName,
FS: constants.LinuxFs,
MountPoint: constants.OEMPath,
Flags: []string{},
},
},
RwPaths: []string{"/var", "/etc", "/srv"},
}
}

func NewInstallElementalPartitions() v1.ElementalPartitions {
partitions := v1.ElementalPartitions{}
partitions.OEM = &v1.Partition{
Expand Down
Loading

0 comments on commit cbecf85

Please sign in to comment.