Documentation
¶
Index ¶
- Constants
- Variables
- func AtomicWrite(filename string, reader io.Reader, perm os.FileMode, flags AtomicWriteFlags) (err error)
- func AtomicWriteChown(filename string, reader io.Reader, perm os.FileMode, flags AtomicWriteFlags, ...) (err error)
- func AtomicWriteFile(filename string, data []byte, perm os.FileMode, flags AtomicWriteFlags) (err error)
- func AtomicWriteFileChown(filename string, data []byte, perm os.FileMode, flags AtomicWriteFlags, ...) (err error)
- func BootID() (string, error)
- func CopyAllChown(src, dst string, uid sys.UserID, gid sys.GroupID) error
- func CopyFile(src, dst string, flags CopyFlag) (err error)
- func CopySpecialFile(path, dest string) error
- func DirInfos(entries []os.DirEntry) ([]os.FileInfo, error)
- func Escape(path string) string
- func Exchange(olddir, newdir string) error
- func ExistsIsDir(fn string) (exists bool, isDir bool, err error)
- func ExitCode(runErr error) (e int, err error)
- func FakeCurrentUserAndEnv(f func() (*user.User, map[string]string, error)) func()
- func FakeTimezone(f func() (string, error)) func()
- func FakeUserCurrent(f func() (*user.User, error)) func()
- func FakeUserEnvironment(f func(user *user.User) (map[string]string, error)) func()
- func FakeUserLookup(f func(name string) (*user.User, error)) func()
- func FakeUserLookupGroup(f func(name string) (*user.Group, error)) func()
- func FileExists(path string) bool
- func GetenvBool(key string, dflt ...bool) bool
- func GetenvInt64(key string, dflt ...int64) int64
- func HashDirEntries(hash hash.Cloner, path string) ([]byte, error)
- func IsDevice(mode os.FileMode) bool
- func IsDir(path string) bool
- func IsDirNotExist(err error) bool
- func IsExec(path string) bool
- func IsExecInPath(name string) bool
- func IsMounted(baseDir string) (bool, error)
- func IsSymlink(path string) bool
- func IsTestBinary() bool
- func IsWritable(path string) bool
- func KernelCommandLine() (string, error)
- func KernelCommandLineKeyValues(keys ...string) (map[string]string, error)
- func KernelCommandLineSplit(s string) (out []string, err error)
- func KillProcessGroup(cmd *exec.Cmd) error
- func LookPathDefault(name string, defaultPath string) string
- func MachineName() string
- func MkdirAllChown(path string, perm os.FileMode, uid sys.UserID, gid sys.GroupID) error
- func MockKernelVersion(version string) (restore func())
- func MockProcCmdline(newPath string) (restore func())
- func MountOptsToCommonFlags(opts []string) (flags int, unparsed []string)
- func MountOptsToFlags(opts []string) (flags int, err error)
- func MustBeTestBinary(panicMsg string)
- func NormalizeUidGid(uid, gid *int, username, group string) (*int, *int, error)
- func OutputErr(output []byte, err error) error
- func RealUser() (*user.User, error)
- func Rename(olddir, newdir string) error
- func RunAndWait(argv []string, env []string, timeout time.Duration, tomb *tomb.Tomb) ([]byte, error)
- func RunCmd(c *exec.Cmd) ([]byte, []byte, error)
- func SaveMountProfileText(p *MountProfile) (string, error)
- func StreamCommand(name string, args ...string) (io.ReadCloser, error)
- func UidGid(u *user.User) (sys.UserID, sys.GroupID, error)
- func Unescape(path string) string
- func UserAndEnv(name string) (*user.User, map[string]string, error)
- func UserMaybeSudoUser() (*user.User, error)
- func WriteDirEntries(hash hash.Cloner, path string) error
- type AtomicFile
- type AtomicWriteFlags
- type CopyFlag
- type CopySpecialFileError
- type Environment
- type ExpandableEnv
- type FileLock
- type KernelArgument
- type MountEntry
- type MountInfoEntry
- type MountProfile
Constants ¶
const CommandNotFound = 127
Well-known exit status.
const NoChown = sys.FlagID
Variables ¶
var ( UserCurrent = user.Current UserLookup = user.Lookup UserLookupGroup = user.LookupGroup UserEnv = userEnvironment CurrentUserAndEnv = currentUserAndEnv Timezone = timezone )
var ErrAlreadyLocked = errors.New("cannot acquire lock, already locked")
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.
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 AtomicWriteFile ¶
func AtomicWriteFileChown ¶
func CopyAllChown ¶
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 CopySpecialFile ¶
CopySpecialFile is used to copy all the things that are not files (like device nodes, named pipes etc)
func ExistsIsDir ¶
ExistIsDir checks whether a given path exists, and if so whether it is a directory.
func ExitCode ¶
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 FakeTimezone ¶
func FakeUserCurrent ¶
func FakeUserEnvironment ¶
func FakeUserLookupGroup ¶
func FileExists ¶
FileExists returns true if stat succeeds on the given path. It may return false on permission issues.
func GetenvBool ¶
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 ¶
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 ¶
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 IsDir ¶
IsDir returns true if the given path is a directory. It may return false on permission issues.
func IsDirNotExist ¶
IsDirNotExist tells you whether the given error is due to a directory not existing.
func IsExecInPath ¶
IsExecInPath returns true if name is an executable in $PATH.
func IsTestBinary ¶
func IsTestBinary() bool
IsTestBinary checks whether the current process is a go test binary.
func IsWritable ¶
IsWritable checks if the given file/directory can be written by the current user
func KernelCommandLine ¶
KernelCommandLine returns the command line reported by the running kernel.
func KernelCommandLineKeyValues ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
OutputErr formats an error based on output if its length is not zero, or returns err otherwise.
func RealUser ¶
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 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 ¶
UidGid returns the uid and gid of the given user, as uint32s
XXX this should go away soon
func Unescape ¶
Unescape returns the given path with space, tab, newline and forward slash unescaped.
func UserMaybeSudoUser ¶
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
Types ¶
type AtomicFile ¶
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 ¶
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 ¶
NewFileLock creates and opens the lock file given by "path" with mode 0600.
func NewFileLockWithMode ¶
NewFileLockWithMode creates and opens the lock file given by "path" with the given mode.
func OpenExistingLockForReading ¶
OpenExistingLockForReading opens an existing lock file given by "path". The lock is opened in read-only mode.
func (*FileLock) Lock ¶
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) ReadLock ¶
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.
type KernelArgument ¶
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.