Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/linters/urunc-dict.txt
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ LOGPIPE
MANDLOCK
Mainas
Mewz
cgroupfs
SECURITYFS
DEBUGFS
TRACEFS
EFIVARFS
PSTOREFS
BINFMTFS
NSFS
configfs
fusectl
mqueue
uapi
Mirred
Mkdev
Mountpoint
Expand Down
137 changes: 137 additions & 0 deletions pkg/unikontainers/bind_mount_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Copyright (c) 2023-2026, Nubificus LTD
//
// 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 unikontainers

import (
"os"
"path/filepath"
"testing"

"github.com/opencontainers/runtime-spec/specs-go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sys/unix"
)

func TestIsBindMount(t *testing.T) {
t.Parallel()

// Docker spells a volume as type bind with an rbind option.
assert.True(t, isBindMount(specs.Mount{Type: "bind", Options: []string{"rbind", "ro"}}))
// nerdctl and containerd spell a volume as type none with an rbind option.
assert.True(t, isBindMount(specs.Mount{Type: "none", Options: []string{"rbind", "rprivate", "rw"}}))
assert.True(t, isBindMount(specs.Mount{Options: []string{"bind"}}))
// The options alone decide: a bind or rbind Type without such an option is
// not a bind mount.
assert.False(t, isBindMount(specs.Mount{Type: "bind"}))
assert.False(t, isBindMount(specs.Mount{Type: "rbind", Options: []string{"rw"}}))
assert.False(t, isBindMount(specs.Mount{Type: "tmpfs", Options: []string{"nosuid"}}))
assert.False(t, isBindMount(specs.Mount{Type: "proc"}))

// rebaseBindMounts re-roots such volumes under the shared rootfs.
dir := t.TempDir()
vol := t.TempDir()
mounts, err := rebaseBindMounts(dir, []specs.Mount{
{Type: "none", Source: vol, Destination: "/data", Options: []string{"rbind", "rw"}},
})
require.NoError(t, err)
require.Len(t, mounts, 1)
assert.Equal(t, vol, mounts[0].Source)
assert.Equal(t, containerRootfsMountPath+"/data", mounts[0].Destination)
}

func TestOnlyBindMounts(t *testing.T) {
t.Parallel()

vol := t.TempDir()
file := filepath.Join(vol, "file")
require.NoError(t, os.WriteFile(file, []byte("data"), 0o600))

mounts := []specs.Mount{
{Type: "bind", Source: vol, Destination: "/data", Options: []string{"rbind"}},
{Type: "none", Source: file, Destination: "/etc/file", Options: []string{"bind", "ro"}},
{Type: "tmpfs", Source: "tmpfs", Destination: "/tmp"},
{Type: "sysfs", Source: "sysfs", Destination: "/sys"},
// Rootless runtimes emit an rbind of the host's /sys in place of sysfs.
{Type: "none", Source: "/sys", Destination: "/sys", Options: []string{"rbind", "nosuid", "noexec", "nodev", "ro"}},
{Type: "bind", Source: "/proc", Destination: "/host/proc", Options: []string{"rbind"}},
{Type: "bind", Source: "/proc/cpuinfo", Destination: "/cpuinfo", Options: []string{"bind"}},
}
// Kernel filesystems mounted on their own, e.g. cgroupfs under /sys, when
// this host has them.
for _, kfs := range []struct {
path string
magic int64
}{
{"/sys/fs/cgroup", unix.CGROUP2_SUPER_MAGIC},
{"/sys/kernel/config", configfsMagic},
{"/sys/fs/fuse/connections", fusectlMagic},
{"/dev/mqueue", mqueueMagic},
{"/sys/fs/selinux", unix.SELINUX_MAGIC},
} {
var st unix.Statfs_t
if unix.Statfs(kfs.path, &st) == nil && int64(st.Type) == kfs.magic {
mounts = append(mounts, specs.Mount{Type: "bind", Source: kfs.path, Destination: "/host" + kfs.path, Options: []string{"rbind"}})
}
}

result, err := onlyBindMounts(mounts)
require.NoError(t, err)
require.Len(t, result, 2)
assert.Equal(t, vol, result[0].Source)
assert.Equal(t, file, result[1].Source)

_, err = onlyBindMounts([]specs.Mount{
{Type: "bind", Source: filepath.Join(vol, "missing"), Destination: "/missing", Options: []string{"rbind"}},
})
assert.Error(t, err)

// A bind or rbind Type without such an option, as `ctr run --mount
// type=bind,...` emits, is an error rather than a silently dropped volume.
for _, typ := range []string{"bind", "rbind"} {
_, err = onlyBindMounts([]specs.Mount{
{Type: typ, Source: vol, Destination: "/data", Options: []string{"rw"}},
})
assert.ErrorContains(t, err, "no bind or rbind option")
}
}

func TestCopyMountfilesSkipsSpecialFiles(t *testing.T) {
t.Parallel()

src := t.TempDir()
file := filepath.Join(src, "file")
require.NoError(t, os.WriteFile(file, []byte("data"), 0o600))
fifo := filepath.Join(src, "fifo")
require.NoError(t, unix.Mkfifo(fifo, 0o600))

assert.ErrorIs(t, fileFromHost(t.TempDir(), fifo, "/fifo"), ErrNotRegularFile)
assert.ErrorIs(t, fileFromHost(t.TempDir(), "/dev/null", "/dev/null"), ErrNotRegularFile)
assert.ErrorIs(t, fileFromHost(t.TempDir(), src, "/data"), ErrNotRegularFile)

target := t.TempDir()
require.NoError(t, copyMountfiles(target, []specs.Mount{
{Type: "none", Source: file, Destination: "/etc/file", Options: []string{"rbind"}},
{Type: "none", Source: fifo, Destination: "/run/fifo", Options: []string{"rbind"}},
{Type: "bind", Source: "/dev/null", Destination: "/dev/null", Options: []string{"rbind"}},
{Type: "none", Source: src, Destination: "/data", Options: []string{"rbind"}},
}))

content, err := os.ReadFile(filepath.Join(target, "etc/file"))
require.NoError(t, err)
assert.Equal(t, "data", string(content))
assert.NoFileExists(t, filepath.Join(target, "run/fifo"))
assert.NoFileExists(t, filepath.Join(target, "dev/null"))
}
18 changes: 7 additions & 11 deletions pkg/unikontainers/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,13 @@ func extractBootFiles(rootfsPath string, newRootfsPath string, unikernel string,
return nil
}

// copyMountfiles copies the sources of the bind mounts passed to the guest, as
// selected by onlyBindMounts, into targetPath.
func copyMountfiles(targetPath string, mounts []specs.Mount) error {
var err error
for _, m := range mounts {
if m.Type != "bind" {
continue
}
err := fileFromHost(targetPath, m.Source, m.Destination)
if (err != nil) && !errors.Is(err, ErrCopyDir) {
err = fileFromHost(targetPath, m.Source, m.Destination)
if (err != nil) && !errors.Is(err, ErrNotRegularFile) {
return err
}
}
Expand Down Expand Up @@ -206,15 +206,11 @@ func handleExplicitBlockImage(blockImg string, mountPoint string) (types.BlockDe
}, nil
}

// Search all the mount entries in the container's config and
// find the ones that come from a block.
// Search the bind mounts passed to the guest, as selected by onlyBindMounts,
// and find the ones that come from a block.
func getBlockVolumes(mounts []specs.Mount, ukernel types.Unikernel) ([]types.BlockDevParams, error) {
blkImgs := []types.BlockDevParams{}
for i, m := range mounts {
// We check only bind mounts
if m.Type != "bind" {
continue
}
// Get the information of the source path
// from /proc/thread-self/mountinfo
mInfo, err := getMountInfo(m.Source)
Expand Down
10 changes: 3 additions & 7 deletions pkg/unikontainers/initrd/initrd.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ func copyFileToInitrdWithInode(w *cpio.Writer, srcFile string, destFile string,
return nil
}

// CopyFileMountsToInitrd appends the files of the given mounts to the initrd
// as a new archive member. The caller should pass only bind mounts.
func CopyFileMountsToInitrd(oldInitrd string, mounts []specs.Mount) error {
f, err := os.OpenFile(oldInitrd, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
Expand All @@ -125,9 +127,6 @@ func CopyFileMountsToInitrd(oldInitrd string, mounts []specs.Mount) error {

w := cpio.NewWriter(f)
for _, m := range mounts {
if m.Type != "bind" {
continue
}
err = CopyFileToInitrd(w, m.Source, m.Destination)
if err != nil {
return fmt.Errorf("could not add file %s to initrd: %w", m.Source, err)
Expand All @@ -143,7 +142,7 @@ func CopyFileMountsToInitrd(oldInitrd string, mounts []specs.Mount) error {

// MergeFileMountsIntoInitrd adds regular-file bind mounts before the trailer
// of an uncompressed newc archive. The archive is fully parsed before the
// disposable initrd is updated in place.
// disposable initrd is updated in place. The caller should pass only bind mounts.
func MergeFileMountsIntoInitrd(oldInitrd string, mounts []specs.Mount) (retErr error) {
fileMounts, err := regularFileBindMounts(mounts)
if err != nil {
Expand Down Expand Up @@ -208,9 +207,6 @@ func MergeFileMountsIntoInitrd(oldInitrd string, mounts []specs.Mount) (retErr e
func regularFileBindMounts(mounts []specs.Mount) ([]specs.Mount, error) {
var fileMounts []specs.Mount
for _, mount := range mounts {
if mount.Type != "bind" {
continue
}
info, err := os.Stat(mount.Source)
if err != nil {
return nil, fmt.Errorf("could not stat file %s: %w", mount.Source, err)
Expand Down
1 change: 0 additions & 1 deletion pkg/unikontainers/initrd/initrd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,6 @@ func TestMergeFileMountsIntoInitrdWithoutRegularBindMountsDoesNotRewrite(t *test
require.NoError(t, err)

require.NoError(t, MergeFileMountsIntoInitrd(initrdPath, []specs.Mount{
{Type: "tmpfs", Source: "tmpfs", Destination: "/tmp"},
{Type: "bind", Source: dir, Destination: "/directory"},
}))

Expand Down
1 change: 1 addition & 0 deletions pkg/unikontainers/initrd_rootfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ func (i initrdRootfs) postSetup() error {
return fmt.Errorf("failed to resolve guest's initrd path: %w", err)
}

// i.mounts holds only bind mounts, as the initrd package expects.
if i.guestType == unikernels.UnikraftUnikernel {
err = initrd.MergeFileMountsIntoInitrd(initrdHostFullPath, i.mounts)
} else {
Expand Down
51 changes: 49 additions & 2 deletions pkg/unikontainers/initrd_rootfs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,59 @@ func TestNewRootfsBuilderPassesGuestTypeToInitrd(t *testing.T) {
Spec: &specs.Spec{},
}

builder := u.newRootfsBuilder("", types.RootfsParams{Type: "initrd"}, nil, "", "", 0)
builder, err := u.newRootfsBuilder("", types.RootfsParams{Type: "initrd"}, nil, "", "", 0)
require.NoError(t, err)
rfs, ok := builder.(initrdRootfs)
require.True(t, ok)
require.Equal(t, unikernels.UnikraftUnikernel, rfs.guestType)
}

func TestNewRootfsBuilderSelectsBindMounts(t *testing.T) {
t.Parallel()

vol := t.TempDir()
u := &Unikontainer{
State: &specs.State{Annotations: map[string]string{}},
UruncCfg: defaultUruncConfig(),
Spec: &specs.Spec{Mounts: []specs.Mount{
{Type: "bind", Source: vol, Destination: "/data", Options: []string{"rbind"}},
{Type: "tmpfs", Source: "tmpfs", Destination: "/tmp"},
{Type: "none", Source: "/sys", Destination: "/sys", Options: []string{"rbind", "ro"}},
}},
}
guestRootfs := []string{"block", "initrd", "virtiofs", "9pfs"}

// Each guest rootfs gets the bind mounts passed to the guest, selected once.
for _, typ := range guestRootfs {
builder, err := u.newRootfsBuilder("", types.RootfsParams{Type: typ}, nil, "", "", 0)
require.NoError(t, err)
var mounts []specs.Mount
switch rfs := builder.(type) {
case blockRootfs:
mounts = rfs.mounts
case initrdRootfs:
mounts = rfs.mounts
case sharedfsRootfs:
mounts = rfs.mounts
default:
t.Fatalf("unexpected builder %T for %q", builder, typ)
}
require.Len(t, mounts, 1, typ)
require.Equal(t, vol, mounts[0].Source, typ)
}

// The mounts are selected only for a guest rootfs, so a bind or rbind Type
// without such an option fails only there.
u.Spec.Mounts = []specs.Mount{{Type: "bind", Source: vol, Destination: "/data"}}
for _, typ := range guestRootfs {
_, err := u.newRootfsBuilder("", types.RootfsParams{Type: typ}, nil, "", "", 0)
require.ErrorContains(t, err, "no bind or rbind option", typ)
}
builder, err := u.newRootfsBuilder("", types.RootfsParams{}, nil, "", "", 0)
require.NoError(t, err)
require.IsType(t, noRootfs{}, builder)
}

func TestInitrdRootfsPostSetupSelectsUpdateByGuestType(t *testing.T) {
tests := []struct {
name string
Expand Down Expand Up @@ -67,7 +114,7 @@ func TestInitrdRootfsPostSetupSelectsUpdateByGuestType(t *testing.T) {
initrdPath: "initrd.cpio",
guestType: tt.guestType,
mounts: []specs.Mount{
{Type: "bind", Source: source, Destination: "/mounted"},
{Type: "none", Source: source, Destination: "/mounted", Options: []string{"rbind", "rw"}},
},
}

Expand Down
Loading