osutil

package
Version: v0.0.0-...-c7fba9c Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2021 License: GPL-3.0 Imports: 30 Imported by: 0

Documentation

Overview

Package osutil offers utilities related to the operating system or i/o, mainly for files, filesystems and mounts, and also users and processes.

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

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 FindGid = findGid

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

View Source
var FindUid = findUid

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

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 AtomicRename

func AtomicRename(oldName, newName string) error

AtomicRename attempts to rename a path from oldName to newName atomically.

func AtomicSymlink(target, linkPath string) error

AtomicSymlink attempts to atomically create a symlink at linkPath, pointing to a given target. The process creates a temporary symlink object pointing to the target, and then proceeds to rename it atomically, replacing the linkPath.

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 AtomicWriteFileCopy

func AtomicWriteFileCopy(dst, src string, flags AtomicWriteFlags) (err error)

AtomicWriteFileCopy writes to dst a copy of src using AtomicFile internally to create the destination. The destination path is always overwritten. The destination and the owning directory are synced after copy completes. Pass additional flags for AtomicFile wrapping the destination.

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 CheckFreeSpace

func CheckFreeSpace(path string, minSize uint64) error

CheckFreeSpace checks if there is enough disk space for the given path

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 DelUser

func DelUser(name string, opts *DelUserOptions) error

DelUser removes a "regular login user" from the system, including their home. Unlike AddUser, it does this by calling userdel(8) directly (deluser doesn't support extrausers). Additionally this will remove the user from sudoers if found.

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, state 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 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 FindGidOwning

func FindGidOwning(path string) (uint64, error)

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

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 IsTestBinary

func IsTestBinary() bool

IsTestBinary checks whether the current process is a go test binary.

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 KernelCommandLine

func KernelCommandLine() (string, error)

KernelCommandLine returns the command line reported by the running kernel.

func KernelCommandLineKeyValues

func KernelCommandLineKeyValues(keys ...string) (map[string]string, error)

KernelCommandLineKeyValues returns a map of the specified keys to the values set for them in the kernel command line (eg. panic=-1). If the value is missing from the kernel command line or it has no value (eg. quiet), the key is omitted from the returned map.

func KernelCommandLineSplit

func KernelCommandLineSplit(s string) (out []string, err error)

KernelCommandLineSplit tries to split the string comprising full or a part of a kernel command line into a list of individual arguments. Returns an error when the input string is incorrectly formatted.

See https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html for details.

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 MockFindGid

func MockFindGid(f func(string) (uint64, error)) (restore func())

func MockFindUid

func MockFindUid(f func(string) (uint64, error)) (restore func())

func MockKernelVersion

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

MockKernelVersion replaces the function that returns the kernel version string.

func MockMountInfo

func MockMountInfo(content string) (restore func())

MockMountInfo is meant for tests to mock the content of /proc/self/mountinfo.

func MockProcCmdline

func MockProcCmdline(newPath string) (restore func())

MockProcCmdline overrides the path to /proc/cmdline. For use in tests.

func MockProcMeminfo

func MockProcMeminfo(newPath string) (restore func())

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 MustBeTestBinary

func MustBeTestBinary(panicMsg string)

MustBeTestBinary checks whether the executing process is a go test binary, panics otherwise.

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 RegularFileExists

func RegularFileExists(fn string) (exists, isReg bool, err error)

RegularFileExists checks whether a given path exists, and if so whether it is a regular file.

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 SetTime

func SetTime(t time.Time) error

SetTime sets the time of the system using settimeofday(). This syscall needs to be performed as root or with CAP_SYS_TIME.

func Shred

func Shred(fileName string) error

This function opens the file and overwrites it 10 times with random data obtained from /dev/urandom device, then deletes it

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 Symlinkat

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

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

func TotalUsableMemory

func TotalUsableMemory() (totalMem uint64, err error)

TotalUsableMemory returns the total usable memory in the system in bytes.

Usable means (MemTotal - CmaTotal), i.e. the total amount of memory minus the space reserved for the CMA (Contiguous Memory Allocator).

CMA memory is taken up by e.g. the framebuffer on the Raspberry Pi or by DSPs on specific boards.

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 UserMaybeSudoUser

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

UserMaybeSudoUser finds the user behind a sudo invocation when root, if applicable and possible. Otherwise the current user is returned.

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 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.

func (*AtomicFile) CommitAs

func (aw *AtomicFile) CommitAs(filename string) error

CommitAs commits the file under a new target name, following the same rules as Commit. The new target name must be located in the same directory as the original filename provided when creating AtomicFile.

The call is useful when the target name is not known until the end (eg. it may depend on data being written to the file), in which case one can create AtomicFile using a temporary name and later override the actual name by calling CommitAs.

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 DelUserOptions

type DelUserOptions struct {
	ExtraUsers bool
}

type Environment

type Environment map[string]string

Environment is an unordered map of key=value strings.

Environment can be manipulated with available methods and eventually converted to low-level representation necessary when executing programs. This approach discourages operations that could result in duplicate environment variable definitions from being constructed.

func OSEnvironment

func OSEnvironment() (Environment, error)

OSEnvironment returns the environment of the calling process.

func OSEnvironmentUnescapeUnsafe

func OSEnvironmentUnescapeUnsafe(unsafeEscapePrefix string) (Environment, error)

OSEnvironmentUnescapeUnsafe returns the environment of the calling process. It will also strip unsafeEscapePrefix from any variable starting with it. Use-case/assumption is that ForExecEscapeUnsafe was used previously along the exec chain.

func (*Environment) ExtendWithExpanded

func (env *Environment) ExtendWithExpanded(eenv ExpandableEnv)

ExtendWithExpanded extends the environment with eenv.

Environment is modified in place. Each variable defined by eenv is expanded according to os.Expand, using the environment itself as it gets extended. Undefined variables expand to an empty string.

func (Environment) ForExec

func (env Environment) ForExec() []string

ForExec returns the environment in a form suitable for using with the exec family of functions.

The returned environment is sorted lexicographically by variable name.

func (Environment) ForExecEscapeUnsafe

func (env Environment) ForExecEscapeUnsafe(unsafeEscapePrefix string) []string

ForExecEscapeUnsafe returns the environment in a form suitable for using with the exec family of functions.

Further variables that are usually stripped out by ld.so when starting a setuid process are renamed by prepending unsafeEscapePrefix to them.

Unlikely variables already starting with the prefix will be dropped, they would be mishandled down chain.

The returned environment is sorted lexicographically by final variable name.

type ExpandableEnv

type ExpandableEnv struct {
	*strutil.OrderedMap
}

ExpandableEnv represents alterations to an environment as ordered key, value entries.

Values can refer to predefined entries by using shell-like syntax $KEY or ${KEY}.

func NewExpandableEnv

func NewExpandableEnv(pairs ...string) ExpandableEnv

NewExpandableEnv returns a new expandable environment comprised of given pairs.

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" with mode 0600.

func NewFileLockWithMode

func NewFileLockWithMode(path string, mode os.FileMode) (*FileLock, error)

NewFileLockWithMode creates and opens the lock file given by "path" with the given mode.

func OpenExistingLockForReading

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

OpenExistingLockForReading opens an existing lock file given by "path". The lock is opened in read-only mode.

func (*FileLock) Close

func (l *FileLock) Close() error

Close closes the lock, unlocking it automatically if needed.

func (*FileLock) File

func (l *FileLock) File() *os.File

File returns the underlying file.

func (*FileLock) Lock

func (l *FileLock) Lock() error

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

Only one process can acquire an exclusive lock at a given time, preventing shared or exclusive locks from being acquired.

func (*FileLock) Path

func (l *FileLock) Path() string

Path returns the path of the lock file.

func (*FileLock) ReadLock

func (l *FileLock) ReadLock() error

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

Multiple processes can acquire a shared lock at the same time, unless an exclusive lock is held.

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 FileReference

type FileReference struct {
	Path string
}

FileReference describes the desired content by referencing an existing file.

func (FileReference) State

func (fref FileReference) State() (io.ReadCloser, int64, os.FileMode, error)

State returns a reader of the referenced file, along with other meta-data.

type FileReferencePlusMode

type FileReferencePlusMode struct {
	FileReference
	Mode os.FileMode
}

FileReferencePlusMode describes the desired content by referencing an existing file and providing custom mode.

func (FileReferencePlusMode) State

State returns a reader of the referenced file, substituting the mode.

type FileState

type FileState interface {
	State() (reader io.ReadCloser, size int64, mode os.FileMode, err error)
}

FileState is an interface for conveying the desired state of a some file.

type MemoryFileState

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

MemoryFileState describes the desired content by providing an in-memory copy.

func (*MemoryFileState) State

func (blob *MemoryFileState) State() (io.ReadCloser, int64, os.FileMode, error)

State returns a reader of the in-memory contents of a file, along with other meta-data.

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() ([]*MountInfoEntry, error)

LoadMountInfo loads list of mounted entries from /proc/self/mountinfo. This can be mocked by using osutil.MockMountInfo to hard-code a specific mountinfo file content to be loaded by this function

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 NotEnoughDiskSpaceError

type NotEnoughDiskSpaceError struct {
	Path  string
	Delta int64
}

func (*NotEnoughDiskSpaceError) Error

func (e *NotEnoughDiskSpaceError) Error() string

type Sizer

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

func (*Sizer) Reset

func (sz *Sizer) Reset()

func (*Sizer) Size

func (sz *Sizer) Size() int64

func (*Sizer) Write

func (sz *Sizer) Write(data []byte) (n int, err error)

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL