systemctl

package module
v0.0.0-...-291c849 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2024 License: 0BSD Imports: 10 Imported by: 0

README

PkgGoDev

systemctl

This library aims at providing idiomatic systemctl bindings for go developers, in order to make it easier to write system tooling using golang. This tool tries to take guesswork out of arbitrarily shelling out to systemctl by providing a structured, thoroughly-tested wrapper for the systemctl functions most-likely to be used in a system program.

If your system isn't running (or targeting another system running) systemctl, this library will be of little use to you.

What is systemctl

systemctl is a command-line program which grants the user control over the systemd system and service manager.

systemctl may be used to introspect and control the state of the "systemd" system and service manager. Please refer to systemd(1) for an introduction into the basic concepts and functionality this tool manages.

Supported systemctl functions

  • systemctl daemon-reload
  • systemctl disable
  • systemctl enable
  • systemctl reenable
  • systemctl is-active
  • systemctl is-enabled
  • systemctl is-failed
  • systemctl mask
  • systemctl restart
  • systemctl show
  • systemctl start
  • systemctl status
  • systemctl stop
  • systemctl unmask

Helper functionality

  • Get start time of a service (ExecMainStartTimestamp) as a Time type
  • Get current memory in bytes (MemoryCurrent) an an int
  • Get the PID of the main process (MainPID) as an int
  • Get the restart count of a unit (NRestarts) as an int

Useful errors

All functions return a predefined error type, and it is highly recommended these errors are handled properly.

Context support

All calls into this library support go's context functionality. Therefore, blocking calls can time out according to the caller's needs, and the returned error should be checked to see if a timeout occurred (ErrExecTimeout).

Simple example

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/taigrr/systemctl"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    // Equivalent to `systemctl enable nginx` with a 10 second timeout
    opts := systemctl.Options{ UserMode: false }
    unit := "nginx"
    err := systemctl.Enable(ctx, unit, opts)
    if err != nil {
        log.Fatalf("unable to enable unit %s: %v", "nginx", err)
    }
}

License

This project is licensed under the 0BSD License, written by Rob Landley. As such, you may use this library without restriction or attribution, but please don't pass it off as your own. Attribution, though not required, is appreciated.

By contributing, you agree all code submitted also falls under the License.

External resources

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR were not defined
	// This usually is the result of running in usermode as root
	ErrBusFailure = errors.New("bus connection failure")
	// The unit specified doesn't exist or can't be found
	ErrDoesNotExist = errors.New("unit does not exist")
	// The provided context was cancelled before the command finished execution
	ErrExecTimeout = errors.New("command timed out")
	// The executable was invoked without enough permissions to run the selected command
	// Running as superuser or adding the correct PolicyKit definitions can fix this
	// See https://wiki.debian.org/PolicyKit for more information
	ErrInsufficientPermissions = errors.New("insufficient permissions")
	// Selected unit file resides outside of the unit file search path
	ErrLinked = errors.New("unit file linked")
	// Masked units can only be unmasked, but something else was attempted
	// Unmask the unit before enabling or disabling it
	ErrMasked = errors.New("unit masked")
	// Make sure systemctl is in the PATH before calling again
	ErrNotInstalled = errors.New("systemctl not in $PATH")
	// A unit was expected to be running but was found inactive
	// This can happen when calling GetStartTime on a dead unit, for example
	ErrUnitNotActive = errors.New("unit not active")
	// A unit was expected to be loaded, but was not.
	// This can happen when trying to Stop a unit which does not exist, for example
	ErrUnitNotLoaded = errors.New("unit not loaded")
	// An expected value is unavailable, but the unit may be running
	// This can happen when calling GetMemoryUsage on systemd itself, for example
	ErrValueNotSet = errors.New("value not set")

	// Something in the stderr output contains the word `Failed`, but it is not a known case
	// This is a catch-all, and if it's ever seen in the wild, please submit a PR
	ErrUnspecified = errors.New("unknown error, please submit an issue at github.com/CloudAceEmma/systemctl")
)

Functions

func DaemonReload

func DaemonReload(ctx context.Context, opts Options) error

Reload systemd manager configuration.

This will rerun all generators (see systemd. generator(7)), reload all unit files, and recreate the entire dependency tree. While the daemon is being reloaded, all sockets systemd listens on behalf of user configuration will stay accessible.

func Disable

func Disable(ctx context.Context, unit string, opts Options) error

Disables one or more units.

This removes all symlinks to the unit files backing the specified units from the unit configuration directory, and hence undoes any changes made by enable or link.

func Enable

func Enable(ctx context.Context, unit string, opts Options) error

Enable one or more units or unit instances.

This will create a set of symlinks, as encoded in the [Install] sections of the indicated unit files. After the symlinks have been created, the system manager configuration is reloaded (in a way equivalent to daemon-reload), in order to ensure the changes are taken into account immediately.

Example
unit := "syncthing"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

err := Enable(ctx, unit, Options{UserMode: true})
switch {
case errors.Is(err, ErrMasked):
	fmt.Printf("%s is masked, unmask it before enabling\n", unit)
case errors.Is(err, ErrDoesNotExist):
	fmt.Printf("%s does not exist\n", unit)
case errors.Is(err, ErrInsufficientPermissions):
	fmt.Printf("permission to enable %s denied\n", unit)
case errors.Is(err, ErrBusFailure):
	fmt.Printf("Cannot communicate with the bus\n")
case err == nil:
	fmt.Printf("%s enabled successfully\n", unit)
default:
	fmt.Printf("Error: %v", err)
}
Output:

func GetMaskedUnits

func GetMaskedUnits(ctx context.Context, opts Options) ([]string, error)

func GetMemoryUsage

func GetMemoryUsage(ctx context.Context, unit string, opts Options) (int, error)

Get current memory in bytes (`systemctl show [unit] --property MemoryCurrent`) an an int

func GetNumRestarts

func GetNumRestarts(ctx context.Context, unit string, opts Options) (int, error)

Get the number of times a process restarted (`systemctl show [unit] --property NRestarts`) as an int

func GetPID

func GetPID(ctx context.Context, unit string, opts Options) (int, error)

Get the PID of the main process (`systemctl show [unit] --property MainPID`) as an int

func GetStartTime

func GetStartTime(ctx context.Context, unit string, opts Options) (time.Time, error)

Get start time of a service (`systemctl show [unit] --property ExecMainStartTimestamp`) as a `Time` type

func IsActive

func IsActive(ctx context.Context, unit string, opts Options) (bool, error)

Check whether any of the specified units are active (i.e. running).

Returns true if the unit is active, false if inactive or failed. Also returns false in an error case.

func IsEnabled

func IsEnabled(ctx context.Context, unit string, opts Options) (bool, error)

Checks whether any of the specified unit files are enabled (as with enable).

Returns true if the unit is enabled, aliased, static, indirect, generated or transient.

Returns false if disabled. Also returns an error if linked, masked, or bad.

See https://www.freedesktop.org/software/systemd/man/systemctl.html#is-enabled%20UNIT%E2%80%A6 for more information

func IsFailed

func IsFailed(ctx context.Context, unit string, opts Options) (bool, error)

Check whether any of the specified units are in a "failed" state.

func IsMasked

func IsMasked(ctx context.Context, unit string, opts Options) (bool, error)

check if a service is masked

func IsRunning

func IsRunning(ctx context.Context, unit string, opts Options) (bool, error)

check if a service is running https://unix.stackexchange.com/a/396633

func Mask

func Mask(ctx context.Context, unit string, opts Options) error

Mask one or more units, as specified on the command line. This will link these unit files to /dev/null, making it impossible to start them.

Notably, Mask may return ErrDoesNotExist if a unit doesn't exist, but it will continue masking anyway. Calling Mask on a non-existing masked unit does not return an error. Similarly, see Unmask.

func Reenable

func Reenable(ctx context.Context, unit string, opts Options) error

Reenables one or more units.

This removes all symlinks to the unit files backing the specified units from the unit configuration directory, then recreates the symlink to the unit again, atomically. Can be used to change the symlink target.

func Reload

func Reload(ctx context.Context, unit string, opts Options) error

Reload one or more units specified on the command line.

func Restart

func Restart(ctx context.Context, unit string, opts Options) error

Stop and then start one or more units specified on the command line. If the units are not running yet, they will be started.

func Show

func Show(ctx context.Context, unit string, property properties.Property, opts Options) (string, error)

Show a selected property of a unit. Accepted properties are predefined in the properties subpackage to guarantee properties are valid and assist code-completion.

func Start

func Start(ctx context.Context, unit string, opts Options) error

Start (activate) a given unit

func Status

func Status(ctx context.Context, unit string, opts Options) (string, error)

Get back the status string which would be returned by running `systemctl status [unit]`.

Generally, it makes more sense to programatically retrieve the properties using Show, but this command is provided for the sake of completeness

func Stop

func Stop(ctx context.Context, unit string, opts Options) error

Stop (deactivate) a given unit

func Unmask

func Unmask(ctx context.Context, unit string, opts Options) error

Unmask one or more unit files, as specified on the command line. This will undo the effect of Mask.

In line with systemd, Unmask will return ErrDoesNotExist if the unit doesn't exist, but only if it's not already masked. If the unit doesn't exist but it's masked anyway, no error will be returned. Gross, I know. Take it up with Poettering.

Types

type Options

type Options struct {
	UserMode bool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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