mount

package module
v0.32.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2023 License: Apache-2.0 Imports: 18 Imported by: 0

README

Purpose

This repository defines an interface to mounting filesystems to be consumed by various Kubernetes and out-of-tree CSI components.

Consumers of this repository can make use of functions like 'Mount' to mount source to target as fstype with given options, 'Unmount' to unmount a target. Other useful functions include 'List' all mounted file systems and find all mount references to a path using 'GetMountRefs'

Community, discussion, contribution, and support

Learn how to engage with the Kubernetes community on the community page.

You can reach the maintainers of this repository at:

Code of Conduct

Participation in the Kubernetes community is governed by the Kubernetes Code of Conduct.

Contibution Guidelines

See CONTRIBUTING.md for more information.

Documentation

Overview

Package mount defines an interface to mounting filesystems.

Index

Constants

View Source
const (
	// FakeActionMount is the string for specifying mount as FakeAction.Action
	FakeActionMount = "mount"
	// FakeActionUnmount is the string for specifying unmount as FakeAction.Action
	FakeActionUnmount = "unmount"
)

Variables

This section is empty.

Functions

func AddSystemdScope

func AddSystemdScope(systemdRunPath, mountName, command string, args []string) (string, []string)

AddSystemdScope adds "system-run --scope" to given command line If args contains sensitive material, use AddSystemdScopeSensitive to construct a safe to log string.

func AddSystemdScopeSensitive

func AddSystemdScopeSensitive(systemdRunPath, mountName, command string, args []string, mountArgsLogStr string) (string, []string, string)

AddSystemdScopeSensitive adds "system-run --scope" to given command line It also accepts takes a sanitized string containing mount arguments, mountArgsLogStr, and returns the string appended to the systemd command for logging.

func CleanupMountPoint

func CleanupMountPoint(mountPath string, mounter Interface, extensiveMountPointCheck bool) error

CleanupMountPoint unmounts the given path and deletes the remaining directory if successful. If extensiveMountPointCheck is true IsNotMountPoint will be called instead of IsLikelyNotMountPoint. IsNotMountPoint is more expensive but properly handles bind mounts within the same fs.

func CleanupMountWithForce

func CleanupMountWithForce(mountPath string, mounter MounterForceUnmounter, extensiveMountPointCheck bool, umountTimeout time.Duration) error

func GetDeviceNameFromMount

func GetDeviceNameFromMount(mounter Interface, mountPath string) (string, int, error)

GetDeviceNameFromMount given a mnt point, find the device from /proc/mounts returns the device name, reference count, and error code.

func IsCorruptedMnt

func IsCorruptedMnt(err error) bool

IsCorruptedMnt return true if err is about corrupted mount point

func IsNotMountPoint deprecated

func IsNotMountPoint(mounter Interface, file string) (bool, error)

IsNotMountPoint determines if a directory is a mountpoint. It should return ErrNotExist when the directory does not exist. IsNotMountPoint is more expensive than IsLikelyNotMountPoint and depends on IsMountPoint.

If an error occurs, it returns true (assuming it is not a mountpoint) when ErrNotExist is returned for callers similar to IsLikelyNotMountPoint.

Deprecated: This function is kept to keep changes backward compatible with previous library version. Callers should prefer mounter.IsMountPoint.

func MakeBindOpts

func MakeBindOpts(options []string) (bool, []string, []string)

MakeBindOpts detects whether a bind mount is being requested and makes the remount options to use in case of bind mount, due to the fact that bind mount doesn't respect mount options. The list equals:

options - 'bind' + 'remount' (no duplicate)

func MakeBindOptsSensitive

func MakeBindOptsSensitive(options []string, sensitiveOptions []string) (bool, []string, []string, []string)

MakeBindOptsSensitive is the same as MakeBindOpts but this method allows sensitiveOptions to be passed in a separate parameter from the normal mount options and ensures the sensitiveOptions are never logged. This method should be used by callers that pass sensitive material (like passwords) as mount options.

func MakeMountArgs

func MakeMountArgs(source, target, fstype string, options []string) (mountArgs []string)

MakeMountArgs makes the arguments to the mount(8) command. options MUST not contain sensitive material (like passwords).

func MakeMountArgsSensitive

func MakeMountArgsSensitive(source, target, fstype string, options []string, sensitiveOptions []string) (mountArgs []string, mountArgsLogStr string)

MakeMountArgsSensitive makes the arguments to the mount(8) command. sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material)

func MakeMountArgsSensitiveWithMountFlags

func MakeMountArgsSensitiveWithMountFlags(source, target, fstype string, options []string, sensitiveOptions []string, mountFlags []string) (mountArgs []string, mountArgsLogStr string)

MakeMountArgsSensitiveWithMountFlags makes the arguments to the mount(8) command. sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material) mountFlags are additional mount flags that are not related with the fstype and mount options

func NewMountError

func NewMountError(mountErrorValue MountErrorType, format string, args ...interface{}) error

func PathExists

func PathExists(path string) (bool, error)

PathExists returns true if the specified path exists. TODO: clean this up to use pkg/util/file/FileExists

func PathWithinBase

func PathWithinBase(fullPath, basePath string) bool

PathWithinBase checks if give path is within given base directory.

func SearchMountPoints

func SearchMountPoints(hostSource, mountInfoPath string) ([]string, error)

SearchMountPoints finds all mount references to the source, returns a list of mountpoints. The source can be a mount point or a normal directory (bind mount). We didn't support device because there is no use case by now. Some filesystems may share a source name, e.g. tmpfs. And for bind mounting, it's possible to mount a non-root path of a filesystem, so we need to use root path and major:minor to represent mount source uniquely. This implementation is shared between Linux and NsEnterMounter

func StartsWithBackstep

func StartsWithBackstep(rel string) bool

StartsWithBackstep checks if the given path starts with a backstep segment.

Types

type FakeAction

type FakeAction struct {
	Action string // "mount" or "unmount"
	Target string // applies to both mount and unmount actions
	Source string // applies only to "mount" actions
	FSType string // applies only to "mount" actions
}

FakeAction objects are logged every time a fake mount or unmount is called.

type FakeMounter

type FakeMounter struct {
	MountPoints []MountPoint

	// Error to return for a path when calling IsLikelyNotMountPoint
	MountCheckErrors map[string]error

	UnmountFunc UnmountFunc
	// contains filtered or unexported fields
}

FakeMounter implements mount.Interface for tests.

func NewFakeMounter

func NewFakeMounter(mps []MountPoint) *FakeMounter

NewFakeMounter returns a FakeMounter struct that implements Interface and is suitable for testing purposes.

func (*FakeMounter) CanSafelySkipMountPointCheck

func (f *FakeMounter) CanSafelySkipMountPointCheck() bool

func (*FakeMounter) GetLog

func (f *FakeMounter) GetLog() []FakeAction

GetLog returns the slice of FakeActions taken by the mounter

func (*FakeMounter) GetMountRefs

func (f *FakeMounter) GetMountRefs(pathname string) ([]string, error)

GetMountRefs finds all mount references to the path, returns a list of paths.

func (*FakeMounter) IsLikelyNotMountPoint

func (f *FakeMounter) IsLikelyNotMountPoint(file string) (bool, error)

IsLikelyNotMountPoint determines whether a path is a mountpoint by checking if the absolute path to file is in the in-memory mountpoints

func (*FakeMounter) IsMountPoint

func (f *FakeMounter) IsMountPoint(file string) (bool, error)

func (*FakeMounter) List

func (f *FakeMounter) List() ([]MountPoint, error)

List returns all the in-memory mountpoints for FakeMounter

func (*FakeMounter) Mount

func (f *FakeMounter) Mount(source string, target string, fstype string, options []string) error

Mount records the mount event and updates the in-memory mount points for FakeMounter

func (*FakeMounter) MountSensitive

func (f *FakeMounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error

Mount records the mount event and updates the in-memory mount points for FakeMounter sensitiveOptions to be passed in a separate parameter from the normal mount options and ensures the sensitiveOptions are never logged. This method should be used by callers that pass sensitive material (like passwords) as mount options.

func (*FakeMounter) MountSensitiveWithoutSystemd

func (f *FakeMounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error

func (*FakeMounter) MountSensitiveWithoutSystemdWithMountFlags

func (f *FakeMounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error

func (*FakeMounter) ResetLog

func (f *FakeMounter) ResetLog()

ResetLog clears all the log entries in FakeMounter

func (*FakeMounter) Unmount

func (f *FakeMounter) Unmount(target string) error

Unmount records the unmount event and updates the in-memory mount points for FakeMounter

func (*FakeMounter) WithSkipMountPointCheck

func (f *FakeMounter) WithSkipMountPointCheck() *FakeMounter

type Interface

type Interface interface {
	// Mount mounts source to target as fstype with given options.
	// options MUST not contain sensitive material (like passwords).
	Mount(source string, target string, fstype string, options []string) error
	// MountSensitive is the same as Mount() but this method allows
	// sensitiveOptions to be passed in a separate parameter from the normal
	// mount options and ensures the sensitiveOptions are never logged. This
	// method should be used by callers that pass sensitive material (like
	// passwords) as mount options.
	MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error
	// MountSensitiveWithoutSystemd is the same as MountSensitive() but this method disable using systemd mount.
	MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error
	// MountSensitiveWithoutSystemdWithMountFlags is the same as MountSensitiveWithoutSystemd() with additional mount flags
	MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error
	// Unmount unmounts given target.
	Unmount(target string) error
	// List returns a list of all mounted filesystems.  This can be large.
	// On some platforms, reading mounts directly from the OS is not guaranteed
	// consistent (i.e. it could change between chunked reads). This is guaranteed
	// to be consistent.
	List() ([]MountPoint, error)
	// IsLikelyNotMountPoint uses heuristics to determine if a directory
	// is not a mountpoint.
	// It should return ErrNotExist when the directory does not exist.
	// IsLikelyNotMountPoint does NOT properly detect all mountpoint types
	// most notably linux bind mounts and symbolic link. For callers that do not
	// care about such situations, this is a faster alternative to calling List()
	// and scanning that output.
	IsLikelyNotMountPoint(file string) (bool, error)
	// CanSafelySkipMountPointCheck indicates whether this mounter returns errors on
	// operations for targets that are not mount points. If this returns true, no such
	// errors will be returned.
	CanSafelySkipMountPointCheck() bool
	// IsMountPoint determines if a directory is a mountpoint.
	// It should return ErrNotExist when the directory does not exist.
	// IsMountPoint is more expensive than IsLikelyNotMountPoint.
	// IsMountPoint detects bind mounts in linux.
	// IsMountPoint may enumerate all the mountpoints using List() and
	// the list of mountpoints may be large, then it uses
	// isMountPointMatch to evaluate whether the directory is a mountpoint.
	IsMountPoint(file string) (bool, error)
	// GetMountRefs finds all mount references to pathname, returning a slice of
	// paths. Pathname can be a mountpoint path or a normal	directory
	// (for bind mount). On Linux, pathname is excluded from the slice.
	// For example, if /dev/sdc was mounted at /path/a and /path/b,
	// GetMountRefs("/path/a") would return ["/path/b"]
	// GetMountRefs("/path/b") would return ["/path/a"]
	// On Windows there is no way to query all mount points; as long as pathname is
	// a valid mount, it will be returned.
	GetMountRefs(pathname string) ([]string, error)
}

Interface defines the set of methods to allow for mount operations on a system.

func New

func New(mounterPath string) Interface

New returns a mount.Interface for the current system. It provides options to override the default mounter behavior. mounterPath allows using an alternative to `/bin/mount` for mounting.

func NewWithoutSystemd

func NewWithoutSystemd(mounterPath string) Interface

NewWithoutSystemd returns a Linux specific mount.Interface for the current system. It provides options to override the default mounter behavior. mounterPath allows using an alternative to `/bin/mount` for mounting. Any detection for systemd functionality is disabled with this Mounter.

type MountError

type MountError struct {
	Type    MountErrorType
	Message string
}

func (MountError) Error

func (mountError MountError) Error() string

func (MountError) String

func (mountError MountError) String() string

type MountErrorType

type MountErrorType string // nolint: golint
const (
	FilesystemMismatch  MountErrorType = "FilesystemMismatch"
	HasFilesystemErrors MountErrorType = "HasFilesystemErrors"
	UnformattedReadOnly MountErrorType = "UnformattedReadOnly"
	FormatFailed        MountErrorType = "FormatFailed"
	GetDiskFormatFailed MountErrorType = "GetDiskFormatFailed"
	UnknownMountError   MountErrorType = "UnknownMountError"
)

type MountInfo

type MountInfo struct {
	// Unique ID for the mount (maybe reused after umount).
	ID int
	// The ID of the parent mount (or of self for the root of this mount namespace's mount tree).
	ParentID int
	// Major indicates one half of the device ID which identifies the device class
	// (parsed from `st_dev` for files on this filesystem).
	Major int
	// Minor indicates one half of the device ID which identifies a specific
	// instance of device (parsed from `st_dev` for files on this filesystem).
	Minor int
	// The pathname of the directory in the filesystem which forms the root of this mount.
	Root string
	// Mount source, filesystem-specific information. e.g. device, tmpfs name.
	Source string
	// Mount point, the pathname of the mount point.
	MountPoint string
	// Optional fieds, zero or more fields of the form "tag[:value]".
	OptionalFields []string
	// The filesystem type in the form "type[.subtype]".
	FsType string
	// Per-mount options.
	MountOptions []string
	// Per-superblock options.
	SuperOptions []string
}

MountInfo represents a single line in /proc/<pid>/mountinfo.

func ParseMountInfo

func ParseMountInfo(filename string) ([]MountInfo, error)

ParseMountInfo parses /proc/xxx/mountinfo.

type MountPoint

type MountPoint struct {
	Device string
	Path   string
	Type   string
	Opts   []string // Opts may contain sensitive mount options (like passwords) and MUST be treated as such (e.g. not logged).
	Freq   int
	Pass   int
}

MountPoint represents a single line in /proc/mounts or /etc/fstab.

func ListProcMounts

func ListProcMounts(mountFilePath string) ([]MountPoint, error)

ListProcMounts is shared with NsEnterMounter

type Mounter

type Mounter struct {
	// contains filtered or unexported fields
}

Mounter provides the default implementation of mount.Interface for the linux platform. This implementation assumes that the kubelet is running in the host's root mount namespace.

func (*Mounter) CanSafelySkipMountPointCheck

func (mounter *Mounter) CanSafelySkipMountPointCheck() bool

CanSafelySkipMountPointCheck relies on the detected behavior of umount when given a target that is not a mount point.

func (*Mounter) GetMountRefs

func (mounter *Mounter) GetMountRefs(pathname string) ([]string, error)

GetMountRefs finds all mount references to pathname, returns a list of paths. Path could be a mountpoint or a normal directory (for bind mount).

func (*Mounter) IsLikelyNotMountPoint

func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error)

IsLikelyNotMountPoint determines if a directory is not a mountpoint. It is fast but not necessarily ALWAYS correct. If the path is in fact a bind mount from one part of a mount to another it will not be detected. It also can not distinguish between mountpoints and symbolic links. mkdir /tmp/a /tmp/b; mount --bind /tmp/a /tmp/b; IsLikelyNotMountPoint("/tmp/b") will return true. When in fact /tmp/b is a mount point. If this situation is of interest to you, don't use this function...

func (*Mounter) IsMountPoint

func (mounter *Mounter) IsMountPoint(file string) (bool, error)

IsMountPoint determines if a file is a mountpoint. It first detects bind & any other mountpoints using MountedFast function. If the MountedFast function returns sure as true and err as nil, then a mountpoint is detected successfully. When an error is returned by MountedFast, the following is true: 1. All errors are returned with IsMountPoint as false except os.IsPermission. 2. When os.IsPermission is returned by MountedFast, List() is called to confirm if the given file is a mountpoint are not.

os.ErrNotExist should always be returned if a file does not exist as callers have in past relied on this error and not fallback.

When MountedFast returns sure as false and err as nil (eg: in case of bindmounts on kernel version 5.10- ); mounter.List() endpoint is called to enumerate all the mountpoints and check if it is mountpoint match or not.

func (*Mounter) List

func (*Mounter) List() ([]MountPoint, error)

List returns a list of all mounted filesystems.

func (*Mounter) Mount

func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error

Mount mounts source to target as fstype with given options. 'source' and 'fstype' must be an empty string in case it's not required, e.g. for remount, or for auto filesystem type, where kernel handles fstype for you. The mount 'options' is a list of options, currently come from mount(8), e.g. "ro", "remount", "bind", etc. If no more option is required, call Mount with an empty string list or nil.

func (*Mounter) MountSensitive

func (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error

MountSensitive is the same as Mount() but this method allows sensitiveOptions to be passed in a separate parameter from the normal mount options and ensures the sensitiveOptions are never logged. This method should be used by callers that pass sensitive material (like passwords) as mount options.

func (*Mounter) MountSensitiveWithoutSystemd

func (mounter *Mounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error

MountSensitiveWithoutSystemd is the same as MountSensitive() but disable using systemd mount.

func (*Mounter) MountSensitiveWithoutSystemdWithMountFlags

func (mounter *Mounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error

MountSensitiveWithoutSystemdWithMountFlags is the same as MountSensitiveWithoutSystemd with additional mount flags.

func (*Mounter) Unmount

func (mounter *Mounter) Unmount(target string) error

Unmount unmounts the target. If the mounter has safe "not mounted" behavior, no error will be returned when the target is not a mount point.

func (*Mounter) UnmountWithForce

func (mounter *Mounter) UnmountWithForce(target string, umountTimeout time.Duration) error

UnmountWithForce unmounts given target but will retry unmounting with force option after given timeout.

type MounterForceUnmounter

type MounterForceUnmounter interface {
	Interface
	// UnmountWithForce unmounts given target but will retry unmounting with force option
	// after given timeout.
	UnmountWithForce(target string, umountTimeout time.Duration) error
}

type Option

type Option func(*SafeFormatAndMount)

func WithMaxConcurrentFormat

func WithMaxConcurrentFormat(n int, timeout time.Duration) Option

WithMaxConcurrentFormat sets the maximum number of concurrent format operations executed by the mounter. The timeout controls the maximum duration of a format operation before its concurrency token is released. Once a token is released, it can be acquired by another concurrent format operation. The original operation is allowed to complete. If n < 1, concurrency is set to unlimited.

type ResizeFs

type ResizeFs struct {
	// contains filtered or unexported fields
}

ResizeFs Provides support for resizing file systems

func NewResizeFs

func NewResizeFs(exec utilexec.Interface) *ResizeFs

NewResizeFs returns new instance of resizer

func (*ResizeFs) NeedResize

func (resizefs *ResizeFs) NeedResize(devicePath string, deviceMountPath string) (bool, error)

func (*ResizeFs) Resize

func (resizefs *ResizeFs) Resize(devicePath string, deviceMountPath string) (bool, error)

Resize perform resize of file system

type SafeFormatAndMount

type SafeFormatAndMount struct {
	Interface
	Exec utilexec.Interface
	// contains filtered or unexported fields
}

SafeFormatAndMount probes a device to see if it is formatted. Namely it checks to see if a file system is present. If so it mounts it otherwise the device is formatted first then mounted.

func NewSafeFormatAndMount

func NewSafeFormatAndMount(mounter Interface, exec utilexec.Interface, opts ...Option) *SafeFormatAndMount

func (*SafeFormatAndMount) FormatAndMount

func (mounter *SafeFormatAndMount) FormatAndMount(source string, target string, fstype string, options []string) error

FormatAndMount formats the given disk, if needed, and mounts it. That is if the disk is not formatted and it is not being mounted as read-only it will format it first then mount it. Otherwise, if the disk is already formatted or it is being mounted as read-only, it will be mounted without formatting. options MUST not contain sensitive material (like passwords).

func (*SafeFormatAndMount) FormatAndMountSensitive

func (mounter *SafeFormatAndMount) FormatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error

FormatAndMountSensitive is the same as FormatAndMount but this method allows sensitiveOptions to be passed in a separate parameter from the normal mount options and ensures the sensitiveOptions are never logged. This method should be used by callers that pass sensitive material (like passwords) as mount options.

func (*SafeFormatAndMount) FormatAndMountSensitiveWithFormatOptions

func (mounter *SafeFormatAndMount) FormatAndMountSensitiveWithFormatOptions(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error

FormatAndMountSensitiveWithFormatOptions behaves exactly the same as FormatAndMountSensitive, but allows for options to be passed when the disk is formatted. These options are NOT validated in any way and should never come directly from untrusted user input as that would be an injection risk.

func (*SafeFormatAndMount) GetDiskFormat

func (mounter *SafeFormatAndMount) GetDiskFormat(disk string) (string, error)

GetDiskFormat uses 'blkid' to see if the given disk is unformatted

type UnmountFunc

type UnmountFunc func(path string) error

UnmountFunc is a function callback to be executed during the Unmount() call.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL