Skip to content
Draft
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
4 changes: 3 additions & 1 deletion mountinfo/go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module github.com/moby/sys/mountinfo

go 1.18
go 1.26.0

require golang.org/x/sys v0.1.0

replace golang.org/x/sys => ../../../golang/x/sys
2 changes: 0 additions & 2 deletions mountinfo/go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +0,0 @@
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
44 changes: 44 additions & 0 deletions mountinfo/mounted_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package mountinfo

import (
"fmt"
"os"
"path/filepath"

Expand Down Expand Up @@ -50,3 +51,46 @@ func mountedByMountinfo(path string) (bool, error) {

return len(entries) > 0, nil
}

// mountOfByParentsSlow is like mountOfByParents, but does not require path
// to be normalized.
func mountOfByParentsSlow(path string) (*Info, error) {
path, err := normalizePath(path)
if err != nil {
return nil, err
}
return mountOfByParents(path)
}

// mountOfByParents finds the mount which path belongs to, by looking for the
// longest mount point which is a parent of path. The path must be normalized.
func mountOfByParents(path string) (*Info, error) {
mounts, err := GetMounts(ParentsFilter(path))
if err != nil {
return nil, err
}
var res *Info
for _, m := range mounts {
// Several mounts can be stacked on the same mount point, and the
// last one is the topmost one (well, unless MOVE_MOUNT_BENEATH was
// used, which can only be figured out by statx + mount ID).
if res == nil || len(m.Mountpoint) >= len(res.Mountpoint) {
res = m
}
}
if res == nil {
// Should not happen, as / is always mounted.
return nil, fmt.Errorf("no mount found for %q", path)
}
return res, nil
}

// submountsByPrefixSlow returns all mounts on path or under it,
// using PrefixFilter. The path does not have to be normalized.
func submountsByPrefixSlow(path string) ([]*Info, error) {
path, err := normalizePath(path)
if err != nil {
return nil, err
}
return GetMounts(PrefixFilter(path))
}
111 changes: 110 additions & 1 deletion mountinfo/mountinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package mountinfo

import (
"os"
"strconv"
"strings"
)

// GetMounts retrieves a list of mounts for the current running process,
Expand All @@ -24,8 +26,43 @@ func Mounted(path string) (bool, error) {
return mounted(path)
}

// MountOf returns information about the mount which path belongs to (i.e.
// the mount containing the file or directory the path refers to, after
// resolving all symlinks). If several mounts are stacked on the same mount
// point, the topmost (i.e. visible) one is returned.
//
// This is a more efficient and correct alternative to calling GetMounts with
// ParentsFilter and choosing an entry with the longest mount point. On Linux
// 6.13+, it uses statx(2) and statmount(2) and avoids reading mountinfo.
//
// If a non-existent path is specified, an appropriate error is returned,
// which can be checked using errors.Is(err, fs.ErrNotExist).
//
// This function is not implemented on Windows.
func MountOf(path string) (*Info, error) {
return mountOf(path)
}

// Submounts returns information about all mounts on path (including those
// stacked on the same mount point) and under it, after resolving all symlinks
// in path. The mounts are returned in the same order as GetMounts does.
//
// This is equivalent to GetMounts(PrefixFilter(path)), except path does not
// have to be normalized. On Linux 6.13+, if path is a mount point, it uses
// statx(2), listmount(2) and statmount(2) and avoids reading mountinfo,
// which is much faster when there are many mounts in the system.
//
// If a non-existent path is specified, an appropriate error is returned,
// which can be checked using errors.Is(err, fs.ErrNotExist).
//
// This function is not implemented on Windows.
func Submounts(path string) ([]*Info, error) {
return submounts(path)
}

// Info reveals information about a particular mounted filesystem. This
// struct is populated from the content in the /proc/<pid>/mountinfo file.
// struct is populated from the content in the /proc/<pid>/mountinfo file,
// or using statmount(2).
type Info struct {
// ID is a unique identifier of the mount (may be reused after umount).
ID int
Expand Down Expand Up @@ -64,4 +101,76 @@ type Info struct {

// VFSOptions is a comma-separated list of superblock options.
VFSOptions string

// UniqueID is a unique identifier of the mount (never reused), as
// returned by statmount(2) and statx(2) with STATX_MNT_ID_UNIQUE
// (Linux 6.8+). Note that it differs from ID.
//
// It is 0 when not available (e.g. when Info is parsed from mountinfo).
UniqueID uint64

// ParentUniqueID is a unique identifier of the parent mount (or of
// self for the root of this mount namespace's mount tree).
//
// It is 0 when not available (e.g. when Info is parsed from mountinfo).
ParentUniqueID uint64
}

// optionalField returns the value of a tag from the Optional field
// (e.g. "1" for tag "shared" if Optional is "shared:1 master:2"),
// and whether the tag is present.
func (i *Info) optionalField(tag string) (string, bool) {
for f := range strings.FieldsSeq(i.Optional) {
name, val, _ := strings.Cut(f, ":")
if name == tag {
return val, true
}
}
return "", false
}

// optionalID is like optionalField, but parses the value as an integer ID.
func (i *Info) optionalID(tag string) (int, bool) {
val, ok := i.optionalField(tag)
if !ok {
return 0, false
}
id, err := strconv.Atoi(val)
if err != nil {
return 0, false
}
return id, true
}

// PeerGroup returns the ID of the peer group, and true, if the mount is
// shared (i.e. its Optional field contains "shared:ID"). Otherwise, it
// returns 0 and false.
//
// For more information on mount propagation, see mount_namespaces(7).
func (i *Info) PeerGroup() (int, bool) {
return i.optionalID("shared")
}

// Master returns the ID of the peer group from which the mount receives
// propagation events, and true, if the mount is a slave (i.e. its Optional
// field contains "master:ID"). Otherwise, it returns 0 and false.
//
// Note that a mount can be both a slave and shared, in which case both
// PeerGroup and Master return true.
func (i *Info) Master() (int, bool) {
return i.optionalID("master")
}

// PropagateFrom returns the ID of the closest dominant peer group under the
// process's root directory, and true, if it differs from the one returned
// by Master (i.e. its Optional field contains "propagate_from:ID").
// Otherwise, it returns 0 and false.
func (i *Info) PropagateFrom() (int, bool) {
return i.optionalID("propagate_from")
}

// Unbindable reports whether the mount is unbindable.
func (i *Info) Unbindable() bool {
_, ok := i.optionalField("unbindable")
return ok
}
8 changes: 8 additions & 0 deletions mountinfo/mountinfo_bsd.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,11 @@ func mounted(path string) (bool, error) {
// Fallback to parsing mountinfo
return mountedByMountinfo(path)
}

func mountOf(path string) (*Info, error) {
return mountOfByParentsSlow(path)
}

func submounts(path string) ([]*Info, error) {
return submountsByPrefixSlow(path)
}
47 changes: 47 additions & 0 deletions mountinfo/mountinfo_optional_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package mountinfo

import "testing"

func TestInfoOptional(t *testing.T) {
type idOK struct {
id int
ok bool
}
for _, tc := range []struct {
optional string
peerGroup idOK
master idOK
propagateFrom idOK
unbindable bool
}{
{optional: ""},
{optional: "shared:1", peerGroup: idOK{1, true}},
// Make sure "shared:12" is not treated as "shared:1".
{optional: "shared:12", peerGroup: idOK{12, true}},
{optional: "master:3", master: idOK{3, true}},
{optional: "master:3 propagate_from:5", master: idOK{3, true}, propagateFrom: idOK{5, true}},
{optional: "shared:2 master:3", peerGroup: idOK{2, true}, master: idOK{3, true}},
{optional: "unbindable", unbindable: true},
// Malformed or unknown fields.
{optional: "shared"},
{optional: "shared:x"},
{optional: "shared: master:1", master: idOK{1, true}},
{optional: "sharedx:1 unbindablex foo:7"},
} {
i := Info{Optional: tc.optional}
check := func(name string, got, want idOK) {
if got != want {
t.Errorf("%q: %s: got %+v, want %+v", tc.optional, name, got, want)
}
}
id, ok := i.PeerGroup()
check("PeerGroup", idOK{id, ok}, tc.peerGroup)
id, ok = i.Master()
check("Master", idOK{id, ok}, tc.master)
id, ok = i.PropagateFrom()
check("PropagateFrom", idOK{id, ok}, tc.propagateFrom)
if got := i.Unbindable(); got != tc.unbindable {
t.Errorf("%q: Unbindable: got %v, want %v", tc.optional, got, tc.unbindable)
}
}
}
8 changes: 8 additions & 0 deletions mountinfo/mountinfo_unsupported.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,11 @@ func parseMountTable(_ FilterFunc) ([]*Info, error) {
func mounted(path string) (bool, error) {
return false, errNotImplemented
}

func mountOf(_ string) (*Info, error) {
return nil, errNotImplemented
}

func submounts(_ string) ([]*Info, error) {
return nil, errNotImplemented
}
10 changes: 10 additions & 0 deletions mountinfo/mountinfo_windows.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package mountinfo

import "errors"

func parseMountTable(_ FilterFunc) ([]*Info, error) {
// Do NOT return an error!
return nil, nil
Expand All @@ -8,3 +10,11 @@ func parseMountTable(_ FilterFunc) ([]*Info, error) {
func mounted(_ string) (bool, error) {
return false, nil
}

func mountOf(_ string) (*Info, error) {
return nil, errors.ErrUnsupported
}

func submounts(_ string) ([]*Info, error) {
return nil, errors.ErrUnsupported
}
64 changes: 64 additions & 0 deletions mountinfo/mountof_linux.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package mountinfo

import (
"errors"
"fmt"
"os"
"runtime"

"golang.org/x/sys/unix"
)

func mountOf(path string) (*Info, error) {
// Make sure the mount namespace does not change in between the calls.
runtime.LockOSThread()
defer runtime.UnlockOSThread()

// Use AT_NO_AUTOMOUNT to be consistent with Mounted.
const flags = unix.AT_NO_AUTOMOUNT
var st unix.Statx_t
err := unix.Statx(unix.AT_FDCWD, path, flags, unix.STATX_MNT_ID_UNIQUE, &st)
if err != nil {
if !isUnsupported(err) {
return nil, &os.PathError{Op: "statx", Path: path, Err: err}
}
// No statx (or blocked by seccomp).
return mountOfByParentsSlow(path)
}

// Fast path: statx + statmount (Linux 6.8+, all Info fields need 6.13+).
if st.Mask&unix.STATX_MNT_ID_UNIQUE != 0 {
info, err := statmount(st.Mnt_id)
if !errors.Is(err, errStatmountUnsupported) {
return info, err
}
// Get the old (non-unique) mount ID which is used in mountinfo.
err = unix.Statx(unix.AT_FDCWD, path, flags, unix.STATX_MNT_ID, &st)
if err != nil {
return nil, &os.PathError{Op: "statx", Path: path, Err: err}
}
}

// Slower path: statx + mountinfo by mount ID (Linux 5.8+).
if st.Mask&unix.STATX_MNT_ID != 0 {
return mountOfByID(int(st.Mnt_id))
}

// Slowest path.
return mountOfByParentsSlow(path)
}

// mountOfByID returns Info of a mount with a given (non-unique) mount ID.
func mountOfByID(id int) (*Info, error) {
mounts, err := GetMounts(func(m *Info) (skip, stop bool) {
return m.ID != id, m.ID == id
})
if err != nil {
return nil, err
}
if len(mounts) == 0 {
// Unmounted since statx.
return nil, fmt.Errorf("mount ID %d: %w", id, unix.ENOENT)
}
return mounts[0], nil
}
Loading
Loading