systemd

package
v0.0.0-...-f890545 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2024 License: GPL-3.0 Imports: 25 Imported by: 207

Documentation

Index

Constants

View Source
const (
	// the default target for systemd units that we generate
	ServicesTarget = "multi-user.target"

	// the target prerequisite for systemd units we generate
	PrerequisiteTarget = "network.target"

	// the default target for systemd socket units that we generate
	SocketsTarget = "sockets.target"

	// the default target for systemd timer units that we generate
	TimersTarget = "timers.target"

	// the target for systemd user session units that we generate
	UserServicesTarget = "default.target"
)

Variables

View Source
var (

	// allow mocking the systemd version
	Version = getVersion
)

Functions

func Available

func Available() error

func EnsureAtLeast

func EnsureAtLeast(requiredVersion int) error

EnsureAtLeast checks whether the installed version of systemd is greater or equal than the given one. An error is returned if the required version is not matched, and also if systemd is not installed or not working

func EscapeUnitNamePath

func EscapeUnitNamePath(in string) string

EscapeUnitNamePath works like systemd-escape --path FIXME: we could use github.com/coreos/go-systemd/unit/escape.go and EscapePath from it. But that's not in the archive and it won't work with go1.3

func ExistingMountUnitPath

func ExistingMountUnitPath(mountPointDir string) string

ExistingMountUnitPath finds the location of an existing mount unit

func HostFsTypeAndMountOptions

func HostFsTypeAndMountOptions(fstype string) (hostFsType string, options []string)

HostFsTypeAndMountOptions returns filesystem type and options to actually mount the given fstype at runtime, i.e. it determines if fuse should be used for squashfs.

func IsSystemdTooOld

func IsSystemdTooOld(err error) bool

IsSystemdTooOld returns true if the error is a result of a failed check whether systemd version is at least what was asked for.

func MockJournalctl

func MockJournalctl(f func(svcs []string, n int, follow, namespaces bool) (io.ReadCloser, error)) func()

func MockNewSystemd

func MockNewSystemd(f func(be Backend, rootDir string, mode InstanceMode, rep Reporter) Systemd) func()

MockNewSystemd can be used to replace the constructor of the Systemd types with a function that returns a mock object.

func MockStopDelays

func MockStopDelays(checkDelay, notifyDelay time.Duration) func()

MockStopDelays is used from tests so that Stop can be less forgiving there.

func MockSystemctl

func MockSystemctl(f func(args ...string) ([]byte, error)) func()

MockSystemctl allows to mock the systemctl invocations. The provided function will be called when systemctl would be invoked. The function can return the output and an error.

func MockSystemctlWithDelay

func MockSystemctlWithDelay(f func(args ...string) ([]byte, time.Duration, error)) func()

MockSystemctlWithDelay allows to mock the systemctl invocations. The provided function will be called when systemctl would be invoked. The function can return the output and an error. Also the function can return a delay that will be respected before completing the mocked invocation.

func MockSystemdSysctl

func MockSystemdSysctl(f func(args ...string) error) func()

MockSystemdSysctl lets mock and intercept calls to systemd-sysctl from the package.

func MockSystemdVersion

func MockSystemdVersion(version int, injectedError error) (restore func())

func MountUnitPath

func MountUnitPath(baseDir string) string

MountUnitPath returns the path of a {,auto}mount unit

func NewJournalStreamFile

func NewJournalStreamFile(identifier string, priority syslog.Priority, levelPrefix bool) (*os.File, error)

NewJournalStreamFile creates log stream file descriptor to the journal. The semantics is identical to that of sd_journal_stream_fd(3) call.

func SdNotify

func SdNotify(notifyState string) error

SdNotify sends the given state string notification to systemd.

inspired by libsystemd/sd-daemon/sd-daemon.c from the systemd source

func SecurityTagToUnitName

func SecurityTagToUnitName(tag string) (string, error)

SecurityTagToUnitName converts a security tag to a unit name. It also verifies that no unhandled characters are present in the security tag. Valid characters are: a-z, A-Z, 0-9, '_', '-', '.' and '+'. All characters are passed through, except for the '+' character, which is converted to '\x2b'.

Note that this is not the same as systemd-escape, since systemd-escape escapes the '-' character. Due to historical reasons, snapd uses the '-' character in unit names. Note that these are still valid unit names, since '-' is used by systemd-escape to represent the '/' character.

To allow us to correctly convert between security tags and unit names (and to maintain snapd's usage of '-' in unit names), this implementation only escapes the '+' character, which was introduced with snap components.

Examples of conversion:

  • "snap.name.app" -> "snap.name.app"
  • "snap.some-name.some-app" -> "snap.some-name.some-app"
  • "snap.name+comp.hook.install" -> "snap.name\x2bcomp.hook.install"

func Sysctl

func Sysctl(prefixes []string) error

Sysctl invokes systemd-sysctl to configure sysctl(8) kernel parameters from disk configuration. A set of prefixes can be passed to limit which settings are (re)configured.

func UnitNameToSecurityTag

func UnitNameToSecurityTag(unitName string) string

UnitNameToSecurityTag converts a unit name to a security tag. Currently, the only character that is unescaped is the '+' character.

See UnitNameFromSecurityTag for more information.

Examples of conversion:

  • "snap.name.app" -> "snap.name.app"
  • "snap.name\x2bcomp.hook.install" -> "snap.name+comp.hook.install"

Types

type Backend

type Backend int

Backend identifies the implementation backend in use by a Systemd instance.

const (
	// RunningSystemdBackend identifies the implementation backend
	// talking to the running system systemd daemon.
	RunningSystemdBackend Backend = iota
	// EmulationModeBackend identifies the implementation backend
	// emulating a subset of systemd against a filesystem.
	EmulationModeBackend
)

type EnsureMountUnitFlags

type EnsureMountUnitFlags struct {
	// PreventRestartIfModified is set if we do not want to restart the
	// mount unit if even though it was modified
	PreventRestartIfModified bool
	// StartBeforeDriversLoad is set if the unit is needed before
	// udevd starts to run rules
	StartBeforeDriversLoad bool
}

EnsureMountUnitFlags contains flags that modify behavior of EnsureMountUnitFile TODO should we call directly EnsureMountUnitFileWithOptions and remove this type instead?

type Error

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

Error is returned if the systemd action failed

func (*Error) Error

func (e *Error) Error() string

func (*Error) ExitCode

func (e *Error) ExitCode() int

func (*Error) Msg

func (e *Error) Msg() []byte

type InstanceMode

type InstanceMode int

InstanceMode determines which instance of systemd to control.

SystemMode refers to the system instance (i.e. pid 1). UserMode refers to the instance launched to manage the user's desktop session. GlobalUserMode controls configuration respected by all user instances on the system.

As GlobalUserMode does not refer to a single instance of systemd, some operations are not supported such as starting and stopping daemons.

const (
	SystemMode InstanceMode = iota
	UserMode
	GlobalUserMode
)

type KeyringMode

type KeyringMode string

KeyringMode describes how the kernel keyring is setup, see systemd.exec(5)

const (
	KeyringModeInherit KeyringMode = "inherit"
	KeyringModePrivate KeyringMode = "private"
	KeyringModeShared  KeyringMode = "shared"
)

type Log

type Log map[string]*json.RawMessage

A Log is a single entry in the systemd journal. In almost all cases, the strings map to a single string value, but as per the manpage for journalctl, under the json format,

Journal entries permit non-unique fields within the same log entry. JSON
does not allow non-unique fields within objects. Due to this, if a
non-unique field is encountered a JSON array is used as field value,
listing all field values as elements.

and this snippet as well,

Fields containing non-printable or non-UTF8 bytes are
encoded as arrays containing the raw bytes individually
formatted as unsigned numbers.

as such, we sometimes get array values which need to be handled differently, so we manually try to decode the json for each message into different types.

func (Log) Message

func (l Log) Message() string

Message of the Log, if any; otherwise, "-".

func (Log) PID

func (l Log) PID() string

PID is the pid of the client pid, if any; otherwise, "-".

func (Log) SID

func (l Log) SID() string

SID is the syslog identifier of the Log, if any; otherwise, "-".

func (Log) Time

func (l Log) Time() (time.Time, error)

Time returns the time the Log was received by the journal.

type MountUnitOptions

type MountUnitOptions struct {
	// MountUnitType is the type of mount unit we want
	MountUnitType MountUnitType
	// Whether the unit is transient or persistent across reboots
	Lifetime    UnitLifetime
	Description string
	What        string
	Where       string
	Fstype      string
	Options     []string
	Origin      string
	// RootDir is the root of the filesystem where the unit will be created
	RootDir string
	// PreventRestartIfModified is set if we do not want to restart the
	// mount unit if modified
	PreventRestartIfModified bool
}

type MountUnitType

type MountUnitType int

MountUnitType is an enum for the supported mount unit types.

const (
	// RegularMountUnit is a mount with the usual dependencies
	RegularMountUnit MountUnitType = iota
	// BeforeDriversLoadMountUnit mounts things before kernel modules are
	// loaded either by udevd or by systemd-modules-load.service.
	BeforeDriversLoadMountUnit
)

type MountUpdateStatus

type MountUpdateStatus int
const (
	MountUnchanged MountUpdateStatus = iota
	MountUpdated
	MountCreated
)

func EnsureMountUnitFileContent

func EnsureMountUnitFileContent(u *MountUnitOptions) (mountUnitName string, modified MountUpdateStatus, err error)

EnsureMountUnitFileContent creates a mount unit file.

type Reporter

type Reporter interface {
	Notify(string)
}

type RunOptions

type RunOptions struct {
	// XXX: alternative we could just have `Propertes []string` here
	//      and let the caller do the keyring setup but feels a bit loose
	KeyringMode KeyringMode
	Stdin       io.Reader
	Properties  []string
}

RunOptions can be passed to systemd.Run()

type Systemd

type Systemd interface {
	// Backend returns the underlying implementation backend.
	Backend() Backend
	// DaemonReload reloads systemd's configuration.
	DaemonReload() error
	// DaemonRexec reexecutes systemd's system manager, should be
	// only necessary to apply manager's configuration like
	// watchdog.
	DaemonReexec() error
	// EnableNoReload the given services, do not reload systemd.
	EnableNoReload(services []string) error
	// DisableNoReload the given services, do not reload system.
	DisableNoReload(services []string) error
	// Start the given service or services.
	Start(service []string) error
	// StartNoBlock starts the given service or services non-blocking.
	StartNoBlock(service []string) error
	// Stop the given service, and wait until it has stopped.
	Stop(services []string) error
	// Kill all processes of the unit with the given signal.
	Kill(service, signal, who string) error
	// Restart the service, waiting for it to stop before starting it again.
	Restart(services []string) error
	// Reload or restart the service via 'systemctl reload-or-restart'
	ReloadOrRestart(services []string) error
	// RestartNoWaitForStop restarts the given services using systemctl restart,
	// with no snapd specific logic to wait for the services to stop.
	RestartNoWaitForStop(services []string) error
	// Status fetches the status of given units. Statuses are
	// returned in the same order as unit names passed in
	// argument.
	Status(units []string) ([]*UnitStatus, error)
	// InactiveEnterTimestamp returns the time that the given unit entered the
	// inactive state as defined by the systemd docs. Specifically, this time is
	// the most recent time in which the unit transitioned from deactivating
	// ("Stopping") to dead ("Stopped"). It may be the zero time if this has
	// never happened during the current boot, since this property is only
	// tracked during the current boot. It specifically does not return a time
	// that is monotonic, so the time returned here may be subject to bugs if
	// there was a discontinuous time jump on the system before or during the
	// unit's transition to inactive.
	// TODO: incorporate this result into Status instead?
	InactiveEnterTimestamp(unit string) (time.Time, error)
	// IsEnabled checks whether the given service is enabled.
	IsEnabled(service string) (bool, error)
	// IsActive checks whether the given service is Active
	IsActive(service string) (bool, error)
	// LogReader returns a reader for the given services' log.
	// If follow is set to true, the reader returned will follow the log
	// as it grows.
	// If namespaces is set to true, the log reader will include journal namespace
	// logs, and is required to get logs for services which are in journal namespaces.
	LogReader(services []string, n int, follow, namespaces bool) (io.ReadCloser, error)
	// EnsureMountUnitFile adds/enables/starts a mount unit.
	EnsureMountUnitFile(description, what, where, fstype string, flags EnsureMountUnitFlags) (string, error)
	// EnsureMountUnitFileWithOptions adds/enables/starts a mount unit with options.
	EnsureMountUnitFileWithOptions(unitOptions *MountUnitOptions) (string, error)
	// RemoveMountUnitFile unmounts/stops/disables/removes a mount unit.
	RemoveMountUnitFile(baseDir string) error
	// ListMountUnits gets the list of targets of the mount units created by
	// the `origin` module for the given snap
	ListMountUnits(snapName, origin string) ([]string, error)
	// Mask the given service.
	Mask(service string) error
	// Unmask the given service.
	Unmask(service string) error
	// Mount requests a mount of what under where with options.
	Mount(what, where string, options ...string) error
	// Umount requests a mount from what or at where to be unmounted.
	Umount(whatOrWhere string) error
	// CurrentMemoryUsage returns the current memory usage for the specified
	// unit.
	CurrentMemoryUsage(unit string) (quantity.Size, error)
	// CurrentTasksCount returns the number of tasks (processes, threads, kernel
	// threads if enabled, etc) part of the unit, which can be a service or a
	// slice.
	CurrentTasksCount(unit string) (uint64, error)
	// Run a command
	Run(command []string, opts *RunOptions) ([]byte, error)
	// Set log level for the system
	SetLogLevel(logLevel string) error
}

Systemd exposes a minimal interface to manage systemd via the systemctl command.

func New

func New(mode InstanceMode, rep Reporter) Systemd

New returns a Systemd that uses the default root directory and omits --root argument when executing systemctl.

func NewEmulationMode

func NewEmulationMode(rootDir string) Systemd

NewEmulationMode returns a Systemd that runs in emulation mode where systemd is not really called, but instead its functions are emulated by other means.

func NewUnderRoot

func NewUnderRoot(rootDir string, mode InstanceMode, rep Reporter) Systemd

NewUnderRoot returns a Systemd that operates on the given rootdir.

type UnitLifetime

type UnitLifetime int
const (
	Persistent UnitLifetime = iota
	Transient
)

type UnitStatus

type UnitStatus struct {
	Daemon string
	// This is the real name ('Id') as returned by systemd.
	Id string
	// This is the name as used by the status requester (which could
	// be a name alias). We always return the requester unit name as
	// the actual unit name, in order to not confuse users.
	Name string
	// This is the actual list of unit names returned by systemd. This
	// list always include the real name ('Id') as well as all the
	// aliases for the unit.
	Names   []string
	Enabled bool
	Active  bool
	// Installed is false if the queried unit doesn't exist.
	Installed bool
	// NeedDaemonReload is true when systemd reports that the unit on disk
	// has been modified and may differ from systemd's internal state, thus
	// a daemon-reload is needed.
	NeedDaemonReload bool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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