osutil

package
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: GPL-3.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const NoChown = sys.FlagID

Variables

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.

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

func CanStat(path string) bool

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

func Environ

func Environ() map[string]string

Environ returns a map representing the environment. It converts the slice from os.Environ() into a map.

func Escape

func Escape(path string) string

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

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 IsCurrent

func IsCurrent(uid, gid int) (bool, error)

IsCurrent reports whether the given user ID and group ID are those of the current user.

func IsDevice

func IsDevice(mode os.FileMode) bool

IsDevice returns true if mode coresponds 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 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 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 MkdirChown

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

MkdirChown is like os.Mkdir but it also calls os.Chown on the directory it creates.

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

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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