osutil

package
v2.42.5-go-mod+incompa... Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2020 License: GPL-3.0 Imports: 28 Imported by: 0

Documentation

Overview

* Copyright (C) 2017 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *

Index

Constants

View Source
const (
	// from /usr/include/linux/fs.h
	FS_SECRM_FL        = 0x00000001 /* Secure deletion */
	FS_UNRM_FL         = 0x00000002 /* Undelete */
	FS_COMPR_FL        = 0x00000004 /* Compress file */
	FS_SYNC_FL         = 0x00000008 /* Synchronous updates */
	FS_IMMUTABLE_FL    = 0x00000010 /* Immutable file */
	FS_APPEND_FL       = 0x00000020 /* writes to file may only append */
	FS_NODUMP_FL       = 0x00000040 /* do not dump file */
	FS_NOATIME_FL      = 0x00000080 /* do not update atime */
	FS_DIRTY_FL        = 0x00000100
	FS_COMPRBLK_FL     = 0x00000200 /* One or more compressed clusters */
	FS_NOCOMP_FL       = 0x00000400 /* Don't compress */
	FS_ECOMPR_FL       = 0x00000800 /* Compression error */
	FS_BTREE_FL        = 0x00001000 /* btree format dir */
	FS_INDEX_FL        = 0x00001000 /* hash-indexed directory */
	FS_IMAGIC_FL       = 0x00002000 /* AFS directory */
	FS_JOURNAL_DATA_FL = 0x00004000 /* Reserved for ext3 */
	FS_NOTAIL_FL       = 0x00008000 /* file tail should not be merged */
	FS_DIRSYNC_FL      = 0x00010000 /* dirsync behaviour (directories only) */
	FS_TOPDIR_FL       = 0x00020000 /* Top of directory hierarchies*/
	FS_EXTENT_FL       = 0x00080000 /* Extents */
	FS_DIRECTIO_FL     = 0x00100000 /* Use direct i/o */
	FS_NOCOW_FL        = 0x00800000 /* Do not cow file */
	FS_PROJINHERIT_FL  = 0x20000000 /* Create with parents projid */
	FS_RESERVED_FL     = 0x80000000 /* reserved for ext2 lib */
)
View Source
const NoChown = sys.FlagID
View Source
const (
	// ProcSelfMountInfo is a path to the mountinfo table of the current process.
	ProcSelfMountInfo = "/proc/self/mountinfo"
)

Variables

View Source
var ErrAlreadyLocked = errors.New("cannot acquire lock, already locked")
View Source
var ErrCannotCancel = errors.New("cannot cancel: file has already been renamed")

ErrCannotCancel means the Commit operation failed at the last step, and your luck has run out.

View Source
var ErrNoBuildID = errors.New("executable does not contain a build ID")

ErrNoBuildID is returned when an executable does not contain a Build-ID

View Source
var ErrSameState = fmt.Errorf("file state has not changed")

ErrSameState is returned when the state of a file has not changed.

View Source
var IsValidUsername = regexp.MustCompile(`^[a-z0-9][-a-z0-9+._]*$`).MatchString

we check the (user)name ourselves, adduser is a bit too strict (i.e. no `.`) - this regexp is in sync with that SSO allows as valid usernames

View Source
var KernelVersion = kernelVersion

Functions

func AddUser

func AddUser(name string, opts *AddUserOptions) error

AddUser uses the Debian/Ubuntu/derivative 'adduser' command for creating regular login users on Ubuntu Core. 'adduser' is not portable cross-distro but is convenient for creating regular login users.

func AtomicWrite

func AtomicWrite(filename string, reader io.Reader, perm os.FileMode, flags AtomicWriteFlags) (err error)

The AtomicWrite* family of functions work like ioutil.WriteFile(), but the file created is an AtomicWriter, which is Committed before returning.

AtomicWriteChown and AtomicWriteFileChown take an uid and a gid that can be used to specify the ownership of the created file. A special value of 0xffffffff (math.MaxUint32, or NoChown for convenience) can be used to request no change to that attribute.

AtomicWriteFile and AtomicWriteFileChown take the content to be written as a []byte, and so work exactly like io.WriteFile(); AtomicWrite and AtomicWriteChown take an io.Reader which is copied into the file instead, and so are more amenable to streaming.

func AtomicWriteChown

func AtomicWriteChown(filename string, reader io.Reader, perm os.FileMode, flags AtomicWriteFlags, uid sys.UserID, gid sys.GroupID) (err error)

func AtomicWriteFile

func AtomicWriteFile(filename string, data []byte, perm os.FileMode, flags AtomicWriteFlags) (err error)

func AtomicWriteFileChown

func AtomicWriteFileChown(filename string, data []byte, perm os.FileMode, flags AtomicWriteFlags, uid sys.UserID, gid sys.GroupID) (err error)

func BootID

func BootID() (string, error)

BootID returns the unique system-generated boot identifier.

func ChDir

func ChDir(newDir string, f func() error) (err error)

ChDir runs runs "f" inside the given directory Note that this will only work reliable in a single-threaded context.

func ContextWriter

func ContextWriter(ctx context.Context) io.Writer

ContextWriter returns a discarding io.Writer which Write method returns an error once the context is done.

func CopyFile

func CopyFile(src, dst string, flags CopyFlag) (err error)

CopyFile copies src to dst

func CopySpecialFile

func CopySpecialFile(path, dest string) error

CopySpecialFile is used to copy all the things that are not files (like device nodes, named pipes etc)

func DirExists

func DirExists(fn string) (exists bool, isDir bool, err error)

DirExists checks whether a given path exists, and if so whether it is a directory.

func EnsureDirState

func EnsureDirState(dir string, glob string, content map[string]*FileState) (changed, removed []string, err error)

EnsureDirState ensures that directory content matches expectations.

This is like EnsureDirStateGlobs but it only supports one glob at a time.

func EnsureDirStateGlobs

func EnsureDirStateGlobs(dir string, globs []string, content map[string]*FileState) (changed, removed []string, err error)

EnsureDirStateGlobs ensures that directory content matches expectations.

EnsureDirStateGlobs enumerates all the files in the specified directory that match the provided set of pattern (globs). Each enumerated file is checked to ensure that the contents, permissions are what is desired. Unexpected files are removed. Missing files are created and differing files are corrected. Files not matching any pattern are ignored.

Note that EnsureDirStateGlobs only checks for permissions and content. Other security mechanisms, including file ownership and extended attributes are *not* supported.

The content map describes each of the files that are intended to exist in the directory. Map keys must be file names relative to the directory. Sub-directories in the name are not allowed.

If writing any of the files fails, EnsureDirStateGlobs switches to erase mode where *all* of the files managed by the glob pattern are removed (including those that may have been already written). The return value is an empty list of changed files, the real list of removed files and the first error.

If an error happens while removing files then such a file is not removed but the removal continues until the set of managed files matching the glob is exhausted.

In all cases, the function returns the first error it has encountered.

func EnsureFileState

func EnsureFileState(filePath string, fileState *FileState) error

EnsureFileState ensures that the file is in the expected state. It will not attempt to remove the file if no content is provided.

func EnsureTreeState

func EnsureTreeState(baseDir string, globs []string, content map[string]map[string]*FileState) (changed, removed []string, err error)

EnsureTreeState ensures that a directory tree content matches expectations.

EnsureTreeState walks subdirectories of the base directory, and uses EnsureDirStateGlobs to synchronise content with the corresponding entry in the content map. Any non-existent subdirectories in the content map will be created.

After synchronising all subdirectories, any subdirectories where files were removed that are now empty will itself be removed, plus its parent directories up to but not including the base directory.

While there is a sanity check to prevent creation of directories that match the file glob pattern, it is the caller's responsibility to not create directories that may match globs passed to other invocations.

For example, if the glob "snap.$SNAP_NAME.*" is used then the caller should avoid trying to populate any directories matching "snap.*".

If an error occurs, all matching files are removed from the tree.

A list of changed and removed files is returned, as relative paths to the base directory.

func EnsureUserGroup

func EnsureUserGroup(name string, id uint32, extraUsers bool) error

EnsureUserGroup uses the standard shadow utilities' 'useradd' and 'groupadd' commands for creating non-login system users and groups that is portable cross-distro. It will create the group with groupname 'name' and gid 'id' as well as the user with username 'name' and uid 'id'. Importantly, 'useradd' and 'groupadd' will use NSS to determine if a uid/gid is already assigned (so LDAP, etc are consulted), but will themselves only add to local files, which is exactly what we want since we don't want snaps to be blocked on LDAP, etc when performing lookups.

func EnvMap

func EnvMap(env []string) map[string]string

EnvMap takes a list of "key=value" strings and transforms them into a map.

func Escape

func Escape(path string) string

Escape returns the given path with space, tab, newline and forward slash escaped.

func ExecutableExists

func ExecutableExists(name string) bool

ExecutableExists returns whether there an exists an executable with the given name somewhere on $PATH.

func ExitCode

func ExitCode(runErr error) (e int, err error)

ExitCode extract the exit code from the error of a failed cmd.Run() or the original error if its not a exec.ExitError

func FileDigest

func FileDigest(filename string, hash crypto.Hash) ([]byte, uint64, error)

FileDigest computes a hash digest of the file using the given hash. It also returns the file size.

func FileExists

func FileExists(path string) bool

FileExists return true if given path can be stat()ed by us. Note that it may return false on e.g. permission issues.

func FilesAreEqual

func FilesAreEqual(a, b string) bool

FilesAreEqual compares the two files' contents and returns whether they are the same.

func FindGid

func FindGid(groupname string) (uint64, error)

FindGid returns the identifier of the given UNIX group name. It will automatically fallback to use "getent" if needed.

func FindGidOwning

func FindGidOwning(path string) (uint64, error)

FindGidOwning obtains UNIX group ID and name owning file `path`.

func FindUid

func FindUid(username string) (uint64, error)

FindUid returns the identifier of the given UNIX user name. It will automatically fallback to use "getent" if needed.

func GetAttr

func GetAttr(f *os.File) (int32, error)

GetAttr retrieves the attributes of a file on a linux filesystem

func GetenvBool

func GetenvBool(key string, dflt ...bool) bool

GetenvBool returns whether the given key may be considered "set" in the environment (i.e. it is set to one of "1", "true", etc).

An optional second argument can be provided, which determines how to treat missing or unparsable values; default is to treat them as false.

func GetenvInt64

func GetenvInt64(key string, dflt ...int64) int64

GetenvInt64 interprets the value of the given environment variable as an int64 and returns the corresponding value. The base can be implied via the prefix (0x for 16, 0 for 8; otherwise 10).

An optional second argument can be provided, which determines how to treat missing or unparsable values; default is to treat them as 0.

func IsDevice

func IsDevice(mode os.FileMode) bool

IsDevice checks if the given os.FileMode coresponds to a device (char/block)

func IsDirNotExist

func IsDirNotExist(err error) bool

IsDirNotExist tells you whether the given error is due to a directory not existing.

func IsDirectory

func IsDirectory(path string) bool

IsDirectory return true if the given path can be stat()ed by us and is a directory. Note that it may return false on e.g. permission issues.

func IsExecutable

func IsExecutable(path string) bool

IsExecutable returns true when given path points to an executable file

func IsHomeUsingNFS

func IsHomeUsingNFS() (bool, error)

IsHomeUsingNFS returns true if NFS mounts are defined or mounted under /home.

Internally /proc/self/mountinfo and /etc/fstab are interrogated (for current and possible mounted filesystems). If either of those describes NFS filesystem mounted under or beneath /home/ then the return value is true.

func IsMounted

func IsMounted(baseDir string) (bool, error)

IsMounted checks if a given directory is a mount point.

func IsRootWritableOverlay

func IsRootWritableOverlay() (string, error)

IsRootWritableOverlay detects if the current '/' is a writable overlay (fstype is 'overlay' and 'upperdir' is specified) and returns upperdir or the empty string if not used.

Debian-based LiveCD systems use 'casper' to setup the mounts, and part of this setup involves running mount commands to mount / on /cow as overlay and results in AppArmor seeing '/upper' as the upperdir rather than '/cow/upper' as seen in mountinfo. By the time snapd is run, we don't have enough information to discover /cow through mount parent ID or st_dev (maj:min). While overlay doesn't use the mount source for anything itself, casper sets the mount source ('/cow' with the above) for its own purposes and we can leverage this by stripping the mount source from the beginning of upperdir.

https://www.kernel.org/doc/Documentation/filesystems/overlayfs.txt man 5 proc

Currently uses variables and Mock functions from nfs.go

func IsSymlink(path string) bool

IsSymlink returns true if the given file is a symlink

func IsUnknownGroup

func IsUnknownGroup(err error) bool

func IsUnknownUser

func IsUnknownUser(err error) bool

func IsWritable

func IsWritable(path string) bool

IsWritable checks if the given file/directory can be written by the current user

func KillProcessGroup

func KillProcessGroup(cmd *exec.Cmd) error

KillProcessGroup kills the process group associated with the given command.

If the command hasn't had Setpgid set in its SysProcAttr, you'll probably end up killing yourself.

func LookPathDefault

func LookPathDefault(name string, defaultPath string) string

LookPathDefault searches for a given command name in all directories listed in the environment variable PATH and returns the found path or the provided default path.

func MachineName

func MachineName() string

func MkdirAllChown

func MkdirAllChown(path string, perm os.FileMode, uid sys.UserID, gid sys.GroupID) error

MkdirAllChown is like os.MkdirAll but it calls os.Chown on any directories it creates.

func MockKernelVersion

func MockKernelVersion(version string) (restore func())

MockKernelVersion replaces the function that returns the kernel version string.

func MountOptsToCommonFlags

func MountOptsToCommonFlags(opts []string) (flags int, unparsed []string)

MountOptsToCommonFlags converts mount options strings to a mount flag, returning unparsed flags. The unparsed flags will not contain any snapd- specific mount option, those starting with the string "x-snapd."

func MountOptsToFlags

func MountOptsToFlags(opts []string) (flags int, err error)

MountOptsToFlags converts mount options strings to a mount flag.

func MyBuildID

func MyBuildID() (string, error)

MyBuildID return the build-id of the currently running executable

func OutputErr

func OutputErr(output []byte, err error) error

OutputErr formats an error based on output if its length is not zero, or returns err otherwise.

func ReadBuildID

func ReadBuildID(fname string) (string, error)

ReadBuildID returns the build ID of a given binary. GNU BuildID is is preferred over Go BuildID. Returns an error when neither is found.

func Readlinkat

func Readlinkat(dirfd int, path string, buf []byte) (n int, err error)

Readlinkat is a direct pass-through to the readlinkat(2) system call.

func RealUser

func RealUser() (*user.User, error)

RealUser finds the user behind a sudo invocation when root, if applicable and possible.

Don't check SUDO_USER when not root and simply return the current uid to properly support sudo'ing from root to a non-root user

func RunAndWait

func RunAndWait(argv []string, env []string, timeout time.Duration, tomb *tomb.Tomb) ([]byte, error)

RunAndWait runs a command for the given argv with the given environ added to os.Environ, killing it if it reaches timeout, or if the tomb is dying.

func RunWithContext

func RunWithContext(ctx context.Context, cmd *exec.Cmd) error

RunWithContext runs the given command, but kills it if the context becomes done before the command finishes.

func SaveMountProfileText

func SaveMountProfileText(p *MountProfile) (string, error)

func SetAttr

func SetAttr(f *os.File, attr int32) error

SetAttr sets the attributes of a file on a linux filesystem to the given value

func StreamCommand

func StreamCommand(name string, args ...string) (io.ReadCloser, error)

StreamCommand runs a the named program with the given arguments, streaming its standard output over the returned io.ReadCloser.

The program will run until EOF is reached (at which point the ReadCloser is closed), or until the ReadCloser is explicitly closed.

func StreamsEqual

func StreamsEqual(a, b io.Reader) bool

StreamsEqual compares two streams and returns true if both have the same content.

func SubstituteEnv

func SubstituteEnv(env []string) []string

SubstituteEnv takes a list of environment strings like: - K1=BAR - K2=$K1 - K3=${K2} and substitutes them top-down from the given environment and from the os environment.

Input strings that do not have the form "k=v" will be dropped from the output.

The result will be a list of environment strings in the same order as the input.

func Symlinkat

func Symlinkat(target string, dirfd int, linkpath string) error

Symlinkat is a direct pass-through to the symlinkat(2) system call.

func UidGid

func UidGid(u *user.User) (sys.UserID, sys.GroupID, error)

UidGid returns the uid and gid of the given user, as uint32s

XXX this should go away soon

func Unescape

func Unescape(path string) string

Unescape returns the given path with space, tab, newline and forward slash unescaped.

func UnlinkMany

func UnlinkMany(dirname string, filenames []string) error

UnlinkMany removes multiple files from a single directory.

If dirname is not a directory, this will fail.

This will abort at the first removal error (but ENOENT is ignored).

Filenames must refer to files. They don't necessarily have to be relative paths to the given dirname, but if they aren't why are you using this function?

Errors are *os.PathError, for convenience

func UnlinkManyAt

func UnlinkManyAt(dir *os.File, filenames []string) error

UnlinkManyAt is like UnlinkMany but takes an open directory *os.File instead of a dirname.

func XSnapdDetach

func XSnapdDetach() string

XSnapdDetach returns the string "x-snapd.detach".

func XSnapdGroup

func XSnapdGroup(gid uint32) string

XSnapdGroup returns the string "x-snapd.group=%d".

func XSnapdIgnoreMissing

func XSnapdIgnoreMissing() string

XSnapdIgnoreMissing returns the string "x-snapd.ignore-missing".

func XSnapdKindFile

func XSnapdKindFile() string

XSnapdKindFile returns the string "x-snapd.kind=file".

func XSnapdKindSymlink() string

XSnapdKindSymlink returns the string "x-snapd.kind=symlink".

func XSnapdMode

func XSnapdMode(mode uint32) string

XSnapdMode returns the string "x-snapd.mode=%#o".

func XSnapdNeededBy

func XSnapdNeededBy(path string) string

XSnapdNeededBy returns the string "x-snapd.needed-by=..." with the given path appended.

func XSnapdOriginLayout

func XSnapdOriginLayout() string

XSnapdOriginLayout returns the string "x-snapd.origin=layout"

func XSnapdOriginOvername

func XSnapdOriginOvername() string

XSnapdOriginOvername returns the string "x-snapd.origin=overname"

func XSnapdSymlink(oldname string) string

XSnapdSymlink returns the string "x-snapd.symlink=%s".

func XSnapdSynthetic

func XSnapdSynthetic() string

XSnapdSynthetic returns the string "x-snapd.synthetic".

func XSnapdUser

func XSnapdUser(uid uint32) string

XSnapdUser returns the string "x-snapd.user=%d".

Types

type AddUserOptions

type AddUserOptions struct {
	Sudoer     bool
	ExtraUsers bool
	Gecos      string
	SSHKeys    []string
	// crypt(3) compatible password of the form $id$salt$hash
	Password string
	// force a password change by the user on login
	ForcePasswordChange bool
}

type AtomicFile

type AtomicFile struct {
	*os.File
	// contains filtered or unexported fields
}

An AtomicFile is similar to an os.File but it has an additional Commit() method that does whatever needs to be done so the modification is "atomic": an AtomicFile will do its best to leave either the previous content or the new content in permanent storage. It also has a Cancel() method to abort and clean up.

func NewAtomicFile

func NewAtomicFile(filename string, perm os.FileMode, flags AtomicWriteFlags, uid sys.UserID, gid sys.GroupID) (aw *AtomicFile, err error)

NewAtomicFile builds an AtomicFile backed by an *os.File that will have the given filename, permissions and uid/gid when Committed.

It _might_ be implemented using O_TMPFILE (see open(2)).

Note that it won't follow symlinks and will replace existing symlinks with the real file, unless the AtomicWriteFollow flag is specified.

It is the caller's responsibility to clean up on error, by calling Cancel().

It is also the caller's responsibility to coordinate access to this, if it is used from different goroutines.

Also note that there are a number of scenarios where Commit fails and then Cancel also fails. In all these scenarios your filesystem was probably in a rather poor state. Good luck.

func (*AtomicFile) Cancel

func (aw *AtomicFile) Cancel() error

Cancel closes the AtomicWriter, and cleans up any artifacts. Cancel can fail if Commit() was (even partially) successful, but calling Cancel after a successful Commit does nothing beyond returning error--so it's always safe to defer a Cancel().

func (*AtomicFile) Close

func (aw *AtomicFile) Close() error

func (*AtomicFile) Commit

func (aw *AtomicFile) Commit() error

Commit the modification; make it permanent.

If Commit succeeds, the writer is closed and further attempts to write will fail. If Commit fails, the writer _might_ be closed; Cancel() needs to be called to clean up.

type AtomicWriteFlags

type AtomicWriteFlags uint

AtomicWriteFlags are a bitfield of flags for AtomicWriteFile

const (
	// AtomicWriteFollow makes AtomicWriteFile follow symlinks
	AtomicWriteFollow AtomicWriteFlags = 1 << iota
)

type CopyFlag

type CopyFlag uint8

CopyFlag is used to tweak the behaviour of CopyFile

const (
	// CopyFlagDefault is the default behaviour
	CopyFlagDefault CopyFlag = 0
	// CopyFlagSync does a sync after copying the files
	CopyFlagSync CopyFlag = 1 << iota
	// CopyFlagOverwrite overwrites the target if it exists
	CopyFlagOverwrite
	// CopyFlagPreserveAll preserves mode,owner,time attributes
	CopyFlagPreserveAll
)

type CopySpecialFileError

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

CopySpecialFileError is returned if a special file copy fails

func (CopySpecialFileError) Error

func (e CopySpecialFileError) Error() string

type FileLock

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

FileLock describes a file system lock

func NewFileLock

func NewFileLock(path string) (*FileLock, error)

NewFileLock creates and opens the lock file given by "path"

func (*FileLock) Close

func (l *FileLock) Close() error

Close closes the lock, unlocking it automatically if needed.

func (*FileLock) Lock

func (l *FileLock) Lock() error

Lock acquires an exclusive lock and blocks until the lock is free.

func (*FileLock) Path

func (l *FileLock) Path() string

Path returns the path of the lock file.

func (*FileLock) TryLock

func (l *FileLock) TryLock() error

TryLock acquires an exclusive lock and errors if the lock cannot be acquired.

func (*FileLock) Unlock

func (l *FileLock) Unlock() error

Unlock releases an acquired lock.

type FileState

type FileState struct {
	Content []byte
	Mode    os.FileMode
}

FileState describes the expected content and meta data of a single file.

func (*FileState) Equals

func (fileState *FileState) Equals(filePath string) (bool, error)

Equals returns whether the file exists in the expected state.

type MountEntry

type MountEntry struct {
	Name    string
	Dir     string
	Type    string
	Options []string

	DumpFrequency   int
	CheckPassNumber int
}

MountEntry describes an /etc/fstab-like mount entry.

Fields are named after names in struct returned by getmntent(3).

struct mntent {
    char *mnt_fsname;   /* name of mounted filesystem */
    char *mnt_dir;      /* filesystem path prefix */
    char *mnt_type;     /* mount type (see Mntent.h) */
    char *mnt_opts;     /* mount options (see Mntent.h) */
    int   mnt_freq;     /* dump frequency in days */
    int   mnt_passno;   /* pass number on parallel fsck */
};

func ParseMountEntry

func ParseMountEntry(s string) (MountEntry, error)

ParseMountEntry parses a fstab-like entry.

func (*MountEntry) Equal

func (e *MountEntry) Equal(o *MountEntry) bool

Equal checks if one entry is equal to another

func (*MountEntry) OptBool

func (e *MountEntry) OptBool(name string) bool

OptBool returns true if a given mount option is present.

func (*MountEntry) OptStr

func (e *MountEntry) OptStr(name string) (string, bool)

OptStr returns the value part of a key=value mount option. The name of the option must not contain the trailing "=" character.

func (MountEntry) String

func (e MountEntry) String() string

func (*MountEntry) XSnapdDetach

func (e *MountEntry) XSnapdDetach() bool

XSnapdDetach returns true if a mount entry should be detached rather than unmounted.

Whenever we create a recursive bind mount we don't want to just unmount it as it may have replicated additional mount entries. For simplicity and race-free behavior we just detach such mount entries and let the kernel do the rest.

func (*MountEntry) XSnapdEntryID

func (e *MountEntry) XSnapdEntryID() string

XSnapdEntryID returns the identifier of a given mount enrty.

Identifiers are kept in the x-snapd.id mount option. The value is a string that identifies a mount entry and is stable across invocations of snapd. In absence of that identifier the entry mount point is returned.

func (*MountEntry) XSnapdGID

func (e *MountEntry) XSnapdGID() (gid uint64, err error)

XSnapdGID returns the user associated with x-snapd-user mount option. If the mode is not specified explicitly then a default "root" use is returned.

func (*MountEntry) XSnapdIgnoreMissing

func (e *MountEntry) XSnapdIgnoreMissing() bool

XSnapdIgnoreMissing returns true if a mount entry should be ignored if the source or target are missing.

By default, snap-update-ns will try to create missing source and target paths when processing a mount entry. In some cases, this behaviour is not desired and it would be better to ignore the mount entry when the source or target are missing.

func (*MountEntry) XSnapdKind

func (e *MountEntry) XSnapdKind() string

XSnapdKind returns the kind of a given mount entry.

There are three kinds of mount entries today: one for directories, one for files and one for symlinks. The values are "", "file" and "symlink" respectively.

Directories use the empty string (in fact they don't need the option at all) as this was the default and is retained for backwards compatibility.

func (*MountEntry) XSnapdMode

func (e *MountEntry) XSnapdMode() (os.FileMode, error)

XSnapdMode returns the file mode associated with x-snapd.mode mount option. If the mode is not specified explicitly then a default mode of 0755 is assumed.

func (*MountEntry) XSnapdNeededBy

func (e *MountEntry) XSnapdNeededBy() string

XSnapdNeededBy the identifier of an entry which needs this entry to function.

The "needed by" identifiers are kept in the x-snapd.needed-by mount option. The value is a string that identifies another mount entry which, in order to be feasible, has spawned one or more additional support entries. Each such entry contains the needed-by attribute.

func (*MountEntry) XSnapdOrigin

func (e *MountEntry) XSnapdOrigin() string

XSnapdOrigin returns the origin of a given mount entry.

Currently only "layout" entries are identified with a unique origin string.

func (e *MountEntry) XSnapdSymlink() string

XSnapdSymlink returns the target for a symlink mount entry.

For non-symlinks an empty string is returned.

func (*MountEntry) XSnapdSynthetic

func (e *MountEntry) XSnapdSynthetic() bool

XSnapdSynthetic returns true of a given mount entry is synthetic.

Synthetic mount entries are created by snap-update-ns itself, separately from what snapd instructed. Such entries are needed to make other things possible. They are identified by having the "x-snapd.synthetic" mount option.

func (*MountEntry) XSnapdUID

func (e *MountEntry) XSnapdUID() (uid uint64, err error)

XSnapdUID returns the user associated with x-snapd-user mount option. If the mode is not specified explicitly then a default "root" use is returned.

type MountInfoEntry

type MountInfoEntry struct {
	MountID        int
	ParentID       int
	DevMajor       int
	DevMinor       int
	Root           string
	MountDir       string
	MountOptions   map[string]string
	OptionalFields []string
	FsType         string
	MountSource    string
	SuperOptions   map[string]string
}

MountInfoEntry contains data from /proc/$PID/mountinfo

For details please refer to mountinfo documentation at https://www.kernel.org/doc/Documentation/filesystems/proc.txt

func LoadMountInfo

func LoadMountInfo(fname string) ([]*MountInfoEntry, error)

LoadMountInfo loads list of mounted entries from a given file.

The file is typically ProcSelfMountInfo but any other process mount table can be read the same way.

func ParseMountInfoEntry

func ParseMountInfoEntry(s string) (*MountInfoEntry, error)

ParseMountInfoEntry parses a single line of /proc/$PID/mountinfo file.

func ReadMountInfo

func ReadMountInfo(reader io.Reader) ([]*MountInfoEntry, error)

ReadMountInfo reads and parses a mountinfo file.

func (*MountInfoEntry) String

func (mi *MountInfoEntry) String() string

type MountProfile

type MountProfile struct {
	Entries []MountEntry
}

MountProfile represents an array of mount entries.

func LoadMountProfile

func LoadMountProfile(fname string) (*MountProfile, error)

LoadMountProfile loads a mount profile from a given file.

The file may be absent, in such case an empty profile is returned without errors.

func LoadMountProfileText

func LoadMountProfileText(fstab string) (*MountProfile, error)

LoadMountProfileText loads a mount profile from a given string.

func ReadMountProfile

func ReadMountProfile(reader io.Reader) (*MountProfile, error)

ReadMountProfile reads and parses a mount profile.

The supported format is described by fstab(5).

func (*MountProfile) Save

func (p *MountProfile) Save(fname string) error

Save saves a mount profile (fstab-like) to a given file. The profile is saved with an atomic write+rename+sync operation.

func (*MountProfile) WriteTo

func (p *MountProfile) WriteTo(writer io.Writer) (int64, error)

WriteTo writes a mount profile to the given writer.

The supported format is described by fstab(5). Note that there is no support for comments.

type Winsize

type Winsize struct {
	Row uint16
	Col uint16

	Ypixel uint16 // unused
	// contains filtered or unexported fields
}

Winsize is from tty_ioctl(4)

func GetTermWinsize

func GetTermWinsize() (*Winsize, error)

GetTermWinsize performs the TIOCGWINSZ ioctl on stdout

Directories

Path Synopsis
udev

Jump to

Keyboard shortcuts

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