osutil

package
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: GPL-3.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const CommandNotFound = 127

Well-known exit status.

View Source
const NoChown = sys.FlagID

Variables

View Source
var (
	UserCurrent       = user.Current
	UserLookup        = user.Lookup
	UserLookupGroup   = user.LookupGroup
	UserEnv           = userEnvironment
	CurrentUserAndEnv = currentUserAndEnv
	Timezone          = timezone
)
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 KernelVersion = kernelVersion

Functions

func AtomicWrite

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

The AtomicWrite* family of functions work like os.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 os.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 CopyAllChown

func CopyAllChown(src, dst string, uid sys.UserID, gid sys.GroupID) error

CopyAllChown copies a directory's contents to a new location, owned by the provided user. Preserves permissions and symlinks, but ignores other non-regular files. Syncs to disk. On failure the target directory is left in an unspecified state. FIXME: the chown behaviour is not currently tested. The plan is to simplify this function and run it as the actual user, once we have decided on a uniform approach for this.

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 DirInfos

func DirInfos(entries []os.DirEntry) ([]os.FileInfo, error)

DirInfos converts directory entries into file info.

func Escape

func Escape(path string) string

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

func Exchange

func Exchange(olddir, newdir string) error

func ExistsIsDir

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

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

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 FakeCurrentUserAndEnv

func FakeCurrentUserAndEnv(f func() (*user.User, map[string]string, error)) func()

func FakeTimezone

func FakeTimezone(f func() (string, error)) func()

func FakeUserCurrent

func FakeUserCurrent(f func() (*user.User, error)) func()

func FakeUserEnvironment

func FakeUserEnvironment(f func(user *user.User) (map[string]string, error)) func()

func FakeUserLookup

func FakeUserLookup(f func(name string) (*user.User, error)) func()

func FakeUserLookupGroup

func FakeUserLookupGroup(f func(name string) (*user.Group, error)) func()

func FileExists

func FileExists(path string) bool

FileExists returns true if stat succeeds on the given path. It may return false on permission issues.

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 HashDirEntries

func HashDirEntries(hash hash.Cloner, path string) ([]byte, error)

Updates hash with entry metadata for the given directory, and returns the resulting digest. Based on git, but allows any hashing algorithm and takes all permission bits into account.

func IsDevice

func IsDevice(mode os.FileMode) bool

IsDevice returns true if mode corresponds to a device (char/block).

func IsDir

func IsDir(path string) bool

IsDir returns true if the given path is a directory. It may return false on permission issues.

func IsDirNotExist

func IsDirNotExist(err error) bool

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

func IsExec

func IsExec(path string) bool

IsExec returns true if path points to an executable file.

func IsExecInPath

func IsExecInPath(name string) bool

IsExecInPath returns true if name is an executable in $PATH.

func IsMounted

func IsMounted(baseDir string) (bool, error)

IsMounted checks if a given directory is a mount point.

func IsSymlink(path string) bool

IsSymlink returns true if path is a symlink.

func IsTestBinary

func IsTestBinary() bool

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

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 key is missing from the kernel command line, it is omitted from the returned map, but it is added if present even if it has no value.

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 MockKernelVersion

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

MockKernelVersion replaces the function that returns the kernel version string.

func MockProcCmdline

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

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

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 NormalizeUidGid

func NormalizeUidGid(uid, gid *int, username, group string) (*int, *int, error)

NormalizeUidGid returns the "normalized" UID and GID for the given IDs and names. If both uid and username are specified, the username's UID must match the given uid (similar for gid and group), otherwise an error is returned.

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

func Rename(olddir, newdir string) error

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 RunCmd

func RunCmd(c *exec.Cmd) ([]byte, []byte, error)

RunCmd runs a command and returns separately stdout and stderr output, and an error.

func SaveMountProfileText

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

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

func UserAndEnv(name string) (*user.User, map[string]string, error)

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 WriteDirEntries

func WriteDirEntries(hash hash.Cloner, path string) error

Updates hash with entry metadata for the given directory. Based on git, but allows any hashing algorithm and takes all permission bits into account.

Types

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
	// AtomicWriteChmod performs an explicit chmod to file permissions after
	// creation for e.g. overcoming any umask modifications.
	AtomicWriteChmod
)

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

func ParseEnvironment(raw []string) (Environment, error)

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 KernelArgument

type KernelArgument struct {
	Param  string
	Value  string
	Quoted bool
}

KernelArgument represents a parsed kernel argument.

func ParseKernelCommandline

func ParseKernelCommandline(cmdline string) (args []KernelArgument)

ParseKernelCommandline parses a kernel command line, returning a slice with the arguments in the same order as in cmdline. Note that kernel arguments can be repeated. We follow the same algorithm as in linux kernel's function lib/cmdline.c:next_arg as far as possible. TODO Replace KernelCommandLineSplit with this eventually

func (*KernelArgument) UnmarshalYAML

func (ka *KernelArgument) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements the Unmarshaler interface.

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

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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