mirror of
https://github.com/taigrr/systemctl.git
synced 2026-04-02 02:28:50 -07:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a82f845b84 | |||
| c9e7f79f8c | |||
| 0075dc6b4d | |||
|
5da4924315
|
|||
|
33828cf7b9
|
|||
|
e44344ee7d
|
|||
|
c8050d2258
|
|||
|
ae23e6ecb9
|
|||
|
c9dec8a0b7
|
@@ -5,7 +5,6 @@ This library aims at providing idiomatic `systemctl` bindings for go developers,
|
||||
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.
|
||||
In fact, if `systemctl` isn't found in the `PATH`, this library will panic.
|
||||
|
||||
## What is systemctl
|
||||
|
||||
@@ -18,6 +17,7 @@ In fact, if `systemctl` isn't found in the `PATH`, this library will panic.
|
||||
- [x] `systemctl daemon-reload`
|
||||
- [x] `systemctl disable`
|
||||
- [x] `systemctl enable`
|
||||
- [x] `systemctl reenable`
|
||||
- [x] `systemctl is-active`
|
||||
- [x] `systemctl is-enabled`
|
||||
- [x] `systemctl is-failed`
|
||||
@@ -65,10 +65,9 @@ func main() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
// Equivalent to `systemctl enable nginx` with a 10 second timeout
|
||||
opts := Options{
|
||||
usermode: false,
|
||||
}
|
||||
err := Enable(ctx, unit, opts)
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ var (
|
||||
// Masked units can only be unmasked, but something else was attempted
|
||||
// Unmask the unit before enabling or disabling it
|
||||
ErrMasked = errors.New("unit masked")
|
||||
// If this error occurs, the library isn't entirely useful, as it causes a panic
|
||||
// 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
|
||||
@@ -36,5 +35,5 @@ var (
|
||||
|
||||
// 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/taigrr/systemctl")
|
||||
ErrUnspecified = errors.New("unknown error, please submit an issue at github.com/taigrr/systemctl")
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ package systemctl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"runtime"
|
||||
@@ -53,7 +54,6 @@ func TestErrorFuncs(t *testing.T) {
|
||||
fName := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
|
||||
fName = strings.TrimPrefix(fName, "github.com/taigrr/")
|
||||
t.Run(fmt.Sprintf("Errorcheck %s", fName), func(t *testing.T) {
|
||||
|
||||
for _, tc := range errCases {
|
||||
t.Run(fmt.Sprintf("%s as %s", tc.unit, userString), func(t *testing.T) {
|
||||
if (userString == "root" || userString == "system") && tc.runAsUser {
|
||||
@@ -64,7 +64,7 @@ func TestErrorFuncs(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
err := f(ctx, tc.unit, tc.opts)
|
||||
if err != tc.err {
|
||||
if !errors.Is(err, tc.err) {
|
||||
t.Errorf("error is %v, but should have been %v", err, tc.err)
|
||||
}
|
||||
})
|
||||
|
||||
53
helpers.go
53
helpers.go
@@ -2,7 +2,9 @@ package systemctl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/taigrr/systemctl/properties"
|
||||
@@ -13,7 +15,6 @@ const dateFormat = "Mon 2006-01-02 15:04:05 MST"
|
||||
// Get start time of a service (`systemctl show [unit] --property ExecMainStartTimestamp`) as a `Time` type
|
||||
func GetStartTime(ctx context.Context, unit string, opts Options) (time.Time, error) {
|
||||
value, err := Show(ctx, unit, properties.ExecMainStartTimestamp, opts)
|
||||
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
@@ -53,3 +54,53 @@ func GetPID(ctx context.Context, unit string, opts Options) (int, error) {
|
||||
}
|
||||
return strconv.Atoi(value)
|
||||
}
|
||||
|
||||
func GetMaskedUnits(ctx context.Context, opts Options) ([]string, error) {
|
||||
args := []string{"list-unit-files", "--state=masked"}
|
||||
if opts.UserMode {
|
||||
args = append(args, "--user")
|
||||
}
|
||||
stdout, stderr, _, err := execute(ctx, args)
|
||||
if err != nil {
|
||||
return []string{}, errors.Join(err, filterErr(stderr))
|
||||
}
|
||||
lines := strings.Split(stdout, "\n")
|
||||
units := []string{}
|
||||
for _, line := range lines {
|
||||
if !strings.Contains(line, "masked") {
|
||||
continue
|
||||
}
|
||||
entry := strings.Split(line, " ")
|
||||
if len(entry) < 3 {
|
||||
continue
|
||||
}
|
||||
if entry[1] == "masked" {
|
||||
unit := entry[0]
|
||||
uName := strings.Split(unit, ".")
|
||||
unit = uName[0]
|
||||
units = append(units, unit)
|
||||
}
|
||||
}
|
||||
return units, nil
|
||||
}
|
||||
|
||||
// check if a service is masked
|
||||
func IsMasked(ctx context.Context, unit string, opts Options) (bool, error) {
|
||||
units, err := GetMaskedUnits(ctx, opts)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, u := range units {
|
||||
if u == unit {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// check if a service is running
|
||||
// https://unix.stackexchange.com/a/396633
|
||||
func IsRunning(ctx context.Context, unit string, opts Options) (bool, error) {
|
||||
status, err := Show(ctx, unit, properties.SubState, opts)
|
||||
return status == "running", err
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package systemctl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"syscall"
|
||||
"testing"
|
||||
@@ -58,13 +59,13 @@ func TestGetStartTime(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
_, err := GetStartTime(ctx, tc.unit, tc.opts)
|
||||
if err != tc.err {
|
||||
if !errors.Is(err, tc.err) {
|
||||
t.Errorf("error is %v, but should have been %v", err, tc.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
// Prove start time changes after a restart
|
||||
t.Run(fmt.Sprintf("prove start time changes"), func(t *testing.T) {
|
||||
t.Run("prove start time changes", func(t *testing.T) {
|
||||
if userString != "root" && userString != "system" {
|
||||
t.Skip("skipping superuser test while running as user")
|
||||
}
|
||||
@@ -90,15 +91,16 @@ func TestGetStartTime(t *testing.T) {
|
||||
t.Errorf("Expected start diff to be positive, but got: %d", int(diff))
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestGetNumRestarts(t *testing.T) {
|
||||
testCases := []struct {
|
||||
type testCase struct {
|
||||
unit string
|
||||
err error
|
||||
opts Options
|
||||
runAsUser bool
|
||||
}{
|
||||
}
|
||||
testCases := []testCase{
|
||||
// Run these tests only as a user
|
||||
|
||||
// try nonexistant unit in user mode as user
|
||||
@@ -118,6 +120,7 @@ func TestGetNumRestarts(t *testing.T) {
|
||||
{"nginx", nil, Options{UserMode: false}, false},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
func(tc testCase) {
|
||||
t.Run(fmt.Sprintf("%s as %s", tc.unit, userString), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if (userString == "root" || userString == "system") && tc.runAsUser {
|
||||
@@ -128,13 +131,14 @@ func TestGetNumRestarts(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
_, err := GetNumRestarts(ctx, tc.unit, tc.opts)
|
||||
if err != tc.err {
|
||||
if !errors.Is(err, tc.err) {
|
||||
t.Errorf("error is %v, but should have been %v", err, tc.err)
|
||||
}
|
||||
})
|
||||
}(tc)
|
||||
}
|
||||
// Prove restart count increases by one after a restart
|
||||
t.Run(fmt.Sprintf("prove restart count increases by one after a restart"), func(t *testing.T) {
|
||||
t.Run("prove restart count increases by one after a restart", func(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping in short mode")
|
||||
}
|
||||
@@ -154,9 +158,9 @@ func TestGetNumRestarts(t *testing.T) {
|
||||
}
|
||||
syscall.Kill(pid, syscall.SIGKILL)
|
||||
for {
|
||||
running, err := IsActive(ctx, "nginx", Options{UserMode: false})
|
||||
if err != nil {
|
||||
t.Errorf("error asserting nginx is up: %v", err)
|
||||
running, errIsActive := IsActive(ctx, "nginx", Options{UserMode: false})
|
||||
if errIsActive != nil {
|
||||
t.Errorf("error asserting nginx is up: %v", errIsActive)
|
||||
break
|
||||
} else if running {
|
||||
break
|
||||
@@ -170,16 +174,16 @@ func TestGetNumRestarts(t *testing.T) {
|
||||
t.Errorf("Expected restart count to differ by one, but difference was: %d", secondRestarts-restarts)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestGetMemoryUsage(t *testing.T) {
|
||||
testCases := []struct {
|
||||
type testCase struct {
|
||||
unit string
|
||||
err error
|
||||
opts Options
|
||||
runAsUser bool
|
||||
}{
|
||||
}
|
||||
testCases := []testCase{
|
||||
// Run these tests only as a user
|
||||
|
||||
// try nonexistant unit in user mode as user
|
||||
@@ -199,6 +203,7 @@ func TestGetMemoryUsage(t *testing.T) {
|
||||
{"nginx", nil, Options{UserMode: false}, false},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
func(tc testCase) {
|
||||
t.Run(fmt.Sprintf("%s as %s", tc.unit, userString), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if (userString == "root" || userString == "system") && tc.runAsUser {
|
||||
@@ -209,13 +214,14 @@ func TestGetMemoryUsage(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
_, err := GetMemoryUsage(ctx, tc.unit, tc.opts)
|
||||
if err != tc.err {
|
||||
if !errors.Is(err, tc.err) {
|
||||
t.Errorf("error is %v, but should have been %v", err, tc.err)
|
||||
}
|
||||
})
|
||||
}(tc)
|
||||
}
|
||||
// Prove memory usage values change across services
|
||||
t.Run(fmt.Sprintf("prove memory usage values change across services"), func(t *testing.T) {
|
||||
t.Run("prove memory usage values change across services", func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
bytes, err := GetMemoryUsage(ctx, "nginx", Options{UserMode: false})
|
||||
@@ -230,15 +236,17 @@ func TestGetMemoryUsage(t *testing.T) {
|
||||
t.Errorf("Expected memory usage between nginx and user.slice to differ, but both were: %d", bytes)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestGetPID(t *testing.T) {
|
||||
testCases := []struct {
|
||||
type testCase struct {
|
||||
unit string
|
||||
err error
|
||||
opts Options
|
||||
runAsUser bool
|
||||
}{
|
||||
}
|
||||
|
||||
testCases := []testCase{
|
||||
// Run these tests only as a user
|
||||
|
||||
// try nonexistant unit in user mode as user
|
||||
@@ -258,6 +266,7 @@ func TestGetPID(t *testing.T) {
|
||||
{"nginx", nil, Options{UserMode: false}, false},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
func(tc testCase) {
|
||||
t.Run(fmt.Sprintf("%s as %s", tc.unit, userString), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if (userString == "root" || userString == "system") && tc.runAsUser {
|
||||
@@ -268,12 +277,13 @@ func TestGetPID(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
_, err := GetPID(ctx, tc.unit, tc.opts)
|
||||
if err != tc.err {
|
||||
if !errors.Is(err, tc.err) {
|
||||
t.Errorf("error is %v, but should have been %v", err, tc.err)
|
||||
}
|
||||
})
|
||||
}(tc)
|
||||
}
|
||||
t.Run(fmt.Sprintf("prove pid changes"), func(t *testing.T) {
|
||||
t.Run("prove pid changes", func(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping in short mode")
|
||||
}
|
||||
@@ -296,7 +306,5 @@ func TestGetPID(t *testing.T) {
|
||||
if pid == secondPid {
|
||||
t.Errorf("Expected pid != secondPid, but both were: %d", pid)
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
40
systemctl.go
40
systemctl.go
@@ -15,7 +15,21 @@ import (
|
||||
// reloaded, all sockets systemd listens on behalf of user configuration will
|
||||
// stay accessible.
|
||||
func DaemonReload(ctx context.Context, opts Options) error {
|
||||
var args = []string{"daemon-reload", "--system"}
|
||||
args := []string{"daemon-reload", "--system"}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
_, _, _, err := execute(ctx, args)
|
||||
return err
|
||||
}
|
||||
|
||||
// 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 Reenable(ctx context.Context, unit string, opts Options) error {
|
||||
args := []string{"reenable", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -29,7 +43,7 @@ func DaemonReload(ctx context.Context, opts Options) error {
|
||||
// the unit configuration directory, and hence undoes any changes made by
|
||||
// enable or link.
|
||||
func Disable(ctx context.Context, unit string, opts Options) error {
|
||||
var args = []string{"disable", "--system", unit}
|
||||
args := []string{"disable", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -44,7 +58,7 @@ func Disable(ctx context.Context, unit string, opts Options) error {
|
||||
// manager configuration is reloaded (in a way equivalent to daemon-reload),
|
||||
// in order to ensure the changes are taken into account immediately.
|
||||
func Enable(ctx context.Context, unit string, opts Options) error {
|
||||
var args = []string{"enable", "--system", unit}
|
||||
args := []string{"enable", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -57,7 +71,7 @@ func Enable(ctx context.Context, unit string, opts Options) error {
|
||||
// Returns true if the unit is active, false if inactive or failed.
|
||||
// Also returns false in an error case.
|
||||
func IsActive(ctx context.Context, unit string, opts Options) (bool, error) {
|
||||
var args = []string{"is-active", "--system", unit}
|
||||
args := []string{"is-active", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -87,7 +101,7 @@ func IsActive(ctx context.Context, unit string, opts Options) (bool, error) {
|
||||
// See https://www.freedesktop.org/software/systemd/man/systemctl.html#is-enabled%20UNIT%E2%80%A6
|
||||
// for more information
|
||||
func IsEnabled(ctx context.Context, unit string, opts Options) (bool, error) {
|
||||
var args = []string{"is-enabled", "--system", unit}
|
||||
args := []string{"is-enabled", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -127,7 +141,7 @@ func IsEnabled(ctx context.Context, unit string, opts Options) (bool, error) {
|
||||
|
||||
// Check whether any of the specified units are in a "failed" state.
|
||||
func IsFailed(ctx context.Context, unit string, opts Options) (bool, error) {
|
||||
var args = []string{"is-failed", "--system", unit}
|
||||
args := []string{"is-failed", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -149,7 +163,7 @@ func IsFailed(ctx context.Context, unit string, opts Options) (bool, error) {
|
||||
// continue masking anyway. Calling Mask on a non-existing masked unit does not
|
||||
// return an error. Similarly, see Unmask.
|
||||
func Mask(ctx context.Context, unit string, opts Options) error {
|
||||
var args = []string{"mask", "--system", unit}
|
||||
args := []string{"mask", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -160,7 +174,7 @@ func Mask(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 Restart(ctx context.Context, unit string, opts Options) error {
|
||||
var args = []string{"restart", "--system", unit}
|
||||
args := []string{"restart", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -171,7 +185,7 @@ func Restart(ctx context.Context, unit string, opts Options) 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 Show(ctx context.Context, unit string, property properties.Property, opts Options) (string, error) {
|
||||
var args = []string{"show", "--system", unit, "--property", string(property)}
|
||||
args := []string{"show", "--system", unit, "--property", string(property)}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -183,7 +197,7 @@ func Show(ctx context.Context, unit string, property properties.Property, opts O
|
||||
|
||||
// Start (activate) a given unit
|
||||
func Start(ctx context.Context, unit string, opts Options) error {
|
||||
var args = []string{"start", "--system", unit}
|
||||
args := []string{"start", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -197,7 +211,7 @@ func Start(ctx context.Context, unit string, opts Options) error {
|
||||
// Generally, it makes more sense to programatically retrieve the properties
|
||||
// using Show, but this command is provided for the sake of completeness
|
||||
func Status(ctx context.Context, unit string, opts Options) (string, error) {
|
||||
var args = []string{"status", "--system", unit}
|
||||
args := []string{"status", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -207,7 +221,7 @@ func Status(ctx context.Context, unit string, opts Options) (string, error) {
|
||||
|
||||
// Stop (deactivate) a given unit
|
||||
func Stop(ctx context.Context, unit string, opts Options) error {
|
||||
var args = []string{"stop", "--system", unit}
|
||||
args := []string{"stop", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
@@ -223,7 +237,7 @@ func Stop(ctx context.Context, unit string, opts Options) error {
|
||||
// If the unit doesn't exist but it's masked anyway, no error will be
|
||||
// returned. Gross, I know. Take it up with Poettering.
|
||||
func Unmask(ctx context.Context, unit string, opts Options) error {
|
||||
var args = []string{"unmask", "--system", unit}
|
||||
args := []string{"unmask", "--system", unit}
|
||||
if opts.UserMode {
|
||||
args[1] = "--user"
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package systemctl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
@@ -38,6 +39,7 @@ func TestMain(m *testing.M) {
|
||||
}
|
||||
os.Exit(retCode)
|
||||
}
|
||||
|
||||
func TestDaemonReload(t *testing.T) {
|
||||
testCases := []struct {
|
||||
unit string
|
||||
@@ -72,14 +74,14 @@ func TestDaemonReload(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
err := DaemonReload(ctx, tc.opts)
|
||||
if err != tc.err {
|
||||
if !errors.Is(err, tc.err) {
|
||||
t.Errorf("error is %v, but should have been %v", err, tc.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisable(t *testing.T) {
|
||||
t.Run(fmt.Sprintf(""), func(t *testing.T) {
|
||||
if userString != "root" && userString != "system" {
|
||||
t.Skip("skipping superuser test while running as user")
|
||||
}
|
||||
@@ -92,7 +94,7 @@ func TestDisable(t *testing.T) {
|
||||
t.Errorf("Unable to mask %s", unit)
|
||||
}
|
||||
err = Disable(ctx, unit, Options{UserMode: false})
|
||||
if err != ErrMasked {
|
||||
if !errors.Is(err, ErrMasked) {
|
||||
Unmask(ctx, unit, Options{UserMode: false})
|
||||
t.Errorf("error is %v, but should have been %v", err, ErrMasked)
|
||||
}
|
||||
@@ -100,12 +102,32 @@ func TestDisable(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Errorf("Unable to unmask %s", unit)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
func TestEnable(t *testing.T) {
|
||||
|
||||
t.Run(fmt.Sprintf(""), func(t *testing.T) {
|
||||
func TestReenable(t *testing.T) {
|
||||
if userString != "root" && userString != "system" {
|
||||
t.Skip("skipping superuser test while running as user")
|
||||
}
|
||||
unit := "nginx"
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
err := Mask(ctx, unit, Options{UserMode: false})
|
||||
if err != nil {
|
||||
Unmask(ctx, unit, Options{UserMode: false})
|
||||
t.Errorf("Unable to mask %s", unit)
|
||||
}
|
||||
err = Reenable(ctx, unit, Options{UserMode: false})
|
||||
if !errors.Is(err, ErrMasked) {
|
||||
Unmask(ctx, unit, Options{UserMode: false})
|
||||
t.Errorf("error is %v, but should have been %v", err, ErrMasked)
|
||||
}
|
||||
err = Unmask(ctx, unit, Options{UserMode: false})
|
||||
if err != nil {
|
||||
t.Errorf("Unable to unmask %s", unit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnable(t *testing.T) {
|
||||
if userString != "root" && userString != "system" {
|
||||
t.Skip("skipping superuser test while running as user")
|
||||
}
|
||||
@@ -118,7 +140,7 @@ func TestEnable(t *testing.T) {
|
||||
t.Errorf("Unable to mask %s", unit)
|
||||
}
|
||||
err = Enable(ctx, unit, Options{UserMode: false})
|
||||
if err != ErrMasked {
|
||||
if !errors.Is(err, ErrMasked) {
|
||||
Unmask(ctx, unit, Options{UserMode: false})
|
||||
t.Errorf("error is %v, but should have been %v", err, ErrMasked)
|
||||
}
|
||||
@@ -126,25 +148,24 @@ func TestEnable(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Errorf("Unable to unmask %s", unit)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func ExampleEnable() {
|
||||
unit := "syncthing"
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
err := Enable(ctx, unit, Options{UserMode: true})
|
||||
switch err {
|
||||
case ErrMasked:
|
||||
switch {
|
||||
case errors.Is(err, ErrMasked):
|
||||
fmt.Printf("%s is masked, unmask it before enabling\n", unit)
|
||||
case ErrDoesNotExist:
|
||||
case errors.Is(err, ErrDoesNotExist):
|
||||
fmt.Printf("%s does not exist\n", unit)
|
||||
case ErrInsufficientPermissions:
|
||||
case errors.Is(err, ErrInsufficientPermissions):
|
||||
fmt.Printf("permission to enable %s denied\n", unit)
|
||||
case ErrBusFailure:
|
||||
case errors.Is(err, ErrBusFailure):
|
||||
fmt.Printf("Cannot communicate with the bus\n")
|
||||
case nil:
|
||||
case err == nil:
|
||||
fmt.Printf("%s enabled successfully\n", unit)
|
||||
default:
|
||||
fmt.Printf("Error: %v", err)
|
||||
@@ -153,7 +174,7 @@ func ExampleEnable() {
|
||||
|
||||
func TestIsActive(t *testing.T) {
|
||||
unit := "nginx"
|
||||
t.Run(fmt.Sprintf("check active"), func(t *testing.T) {
|
||||
t.Run("check active", func(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping in short mode")
|
||||
}
|
||||
@@ -169,10 +190,10 @@ func TestIsActive(t *testing.T) {
|
||||
time.Sleep(time.Second)
|
||||
isActive, err := IsActive(ctx, unit, Options{UserMode: false})
|
||||
if !isActive {
|
||||
t.Errorf("IsActive didn't return true for %s", unit)
|
||||
t.Errorf("IsActive didn't return true for %s: %v", unit, err)
|
||||
}
|
||||
})
|
||||
t.Run(fmt.Sprintf("check masked"), func(t *testing.T) {
|
||||
t.Run("check masked", func(t *testing.T) {
|
||||
if userString != "root" && userString != "system" {
|
||||
t.Skip("skipping superuser test while running as user")
|
||||
}
|
||||
@@ -188,7 +209,7 @@ func TestIsActive(t *testing.T) {
|
||||
}
|
||||
Unmask(ctx, unit, Options{UserMode: false})
|
||||
})
|
||||
t.Run(fmt.Sprintf("check masked"), func(t *testing.T) {
|
||||
t.Run("check masked", func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
_, err := IsActive(ctx, "nonexistant", Options{UserMode: false})
|
||||
@@ -196,7 +217,6 @@ func TestIsActive(t *testing.T) {
|
||||
t.Errorf("error is %v, but should have been %v", err, ErrDoesNotExist)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestIsEnabled(t *testing.T) {
|
||||
@@ -206,7 +226,7 @@ func TestIsEnabled(t *testing.T) {
|
||||
userMode = true
|
||||
unit = "syncthing"
|
||||
}
|
||||
t.Run(fmt.Sprintf("check enabled"), func(t *testing.T) {
|
||||
t.Run("check enabled", func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
err := Enable(ctx, unit, Options{UserMode: userMode})
|
||||
@@ -215,10 +235,10 @@ func TestIsEnabled(t *testing.T) {
|
||||
}
|
||||
isEnabled, err := IsEnabled(ctx, unit, Options{UserMode: userMode})
|
||||
if !isEnabled {
|
||||
t.Errorf("IsEnabled didn't return true for %s", unit)
|
||||
t.Errorf("IsEnabled didn't return true for %s: %v", unit, err)
|
||||
}
|
||||
})
|
||||
t.Run(fmt.Sprintf("check disabled"), func(t *testing.T) {
|
||||
t.Run("check disabled", func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
err := Disable(ctx, unit, Options{UserMode: userMode})
|
||||
@@ -234,7 +254,7 @@ func TestIsEnabled(t *testing.T) {
|
||||
}
|
||||
Enable(ctx, unit, Options{UserMode: false})
|
||||
})
|
||||
t.Run(fmt.Sprintf("check masked"), func(t *testing.T) {
|
||||
t.Run("check masked", func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
err := Mask(ctx, unit, Options{UserMode: userMode})
|
||||
@@ -251,7 +271,6 @@ func TestIsEnabled(t *testing.T) {
|
||||
Unmask(ctx, unit, Options{UserMode: userMode})
|
||||
Enable(ctx, unit, Options{UserMode: userMode})
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestMask(t *testing.T) {
|
||||
@@ -296,13 +315,13 @@ func TestMask(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
err := Mask(ctx, tc.unit, tc.opts)
|
||||
if err != tc.err {
|
||||
if !errors.Is(err, tc.err) {
|
||||
t.Errorf("error is %v, but should have been %v", err, tc.err)
|
||||
}
|
||||
Unmask(ctx, tc.unit, tc.opts)
|
||||
})
|
||||
}
|
||||
t.Run(fmt.Sprintf("test double masking existing"), func(t *testing.T) {
|
||||
t.Run("test double masking existing", func(t *testing.T) {
|
||||
unit := "nginx"
|
||||
userMode := false
|
||||
if userString != "root" && userString != "system" {
|
||||
@@ -321,19 +340,16 @@ func TestMask(t *testing.T) {
|
||||
t.Errorf("error on second masking is %v, but should have been %v", err, nil)
|
||||
}
|
||||
Unmask(ctx, unit, opts)
|
||||
|
||||
})
|
||||
t.Run(fmt.Sprintf("test double masking nonexisting"), func(t *testing.T) {
|
||||
t.Run("test double masking nonexisting", func(t *testing.T) {
|
||||
unit := "nonexistant"
|
||||
userMode := false
|
||||
if userString != "root" && userString != "system" {
|
||||
userMode = true
|
||||
}
|
||||
userMode := userString != "root" && userString != "system"
|
||||
|
||||
opts := Options{UserMode: userMode}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
err := Mask(ctx, unit, opts)
|
||||
if err != ErrDoesNotExist {
|
||||
if !errors.Is(err, ErrDoesNotExist) {
|
||||
t.Errorf("error on initial masking is %v, but should have been %v", err, ErrDoesNotExist)
|
||||
}
|
||||
err = Mask(ctx, unit, opts)
|
||||
@@ -342,7 +358,6 @@ func TestMask(t *testing.T) {
|
||||
}
|
||||
Unmask(ctx, unit, opts)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestRestart(t *testing.T) {
|
||||
@@ -366,9 +381,9 @@ func TestRestart(t *testing.T) {
|
||||
}
|
||||
syscall.Kill(pid, syscall.SIGKILL)
|
||||
for {
|
||||
running, err := IsActive(ctx, unit, opts)
|
||||
if err != nil {
|
||||
t.Errorf("error asserting %s is up: %v", unit, err)
|
||||
running, errIsActive := IsActive(ctx, unit, opts)
|
||||
if errIsActive != nil {
|
||||
t.Errorf("error asserting %s is up: %v", unit, errIsActive)
|
||||
break
|
||||
} else if running {
|
||||
break
|
||||
@@ -381,7 +396,6 @@ func TestRestart(t *testing.T) {
|
||||
if restarts+1 != secondRestarts {
|
||||
t.Errorf("Expected restart count to differ by one, but difference was: %d", secondRestarts-restarts)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Runs through all defined Properties in parallel and checks for error cases
|
||||
@@ -394,6 +408,7 @@ func TestShow(t *testing.T) {
|
||||
UserMode: false,
|
||||
}
|
||||
for _, x := range properties.Properties {
|
||||
func(x properties.Property) {
|
||||
t.Run(fmt.Sprintf("show property %s", string(x)), func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
@@ -403,6 +418,7 @@ func TestShow(t *testing.T) {
|
||||
t.Errorf("error is %v, but should have been %v", err, nil)
|
||||
}
|
||||
})
|
||||
}(x)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,7 +455,6 @@ func TestStart(t *testing.T) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestStatus(t *testing.T) {
|
||||
@@ -452,7 +467,6 @@ func TestStatus(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Errorf("error: %v", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestStop(t *testing.T) {
|
||||
@@ -488,7 +502,6 @@ func TestStop(t *testing.T) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestUnmask(t *testing.T) {
|
||||
@@ -533,13 +546,13 @@ func TestUnmask(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
err := Mask(ctx, tc.unit, tc.opts)
|
||||
if err != tc.err {
|
||||
if !errors.Is(err, tc.err) {
|
||||
t.Errorf("error is %v, but should have been %v", err, tc.err)
|
||||
}
|
||||
Unmask(ctx, tc.unit, tc.opts)
|
||||
})
|
||||
}
|
||||
t.Run(fmt.Sprintf("test double unmasking existing"), func(t *testing.T) {
|
||||
t.Run("test double unmasking existing", func(t *testing.T) {
|
||||
unit := "nginx"
|
||||
userMode := false
|
||||
if userString != "root" && userString != "system" {
|
||||
@@ -558,14 +571,11 @@ func TestUnmask(t *testing.T) {
|
||||
t.Errorf("error on second unmasking is %v, but should have been %v", err, nil)
|
||||
}
|
||||
Unmask(ctx, unit, opts)
|
||||
|
||||
})
|
||||
t.Run(fmt.Sprintf("test double unmasking nonexisting"), func(t *testing.T) {
|
||||
t.Run("test double unmasking nonexisting", func(t *testing.T) {
|
||||
unit := "nonexistant"
|
||||
userMode := false
|
||||
if userString != "root" && userString != "system" {
|
||||
userMode = true
|
||||
}
|
||||
userMode := userString != "root" && userString != "system"
|
||||
|
||||
opts := Options{UserMode: userMode}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
@@ -575,9 +585,8 @@ func TestUnmask(t *testing.T) {
|
||||
t.Errorf("error on initial unmasking is %v, but should have been %v", err, nil)
|
||||
}
|
||||
err = Unmask(ctx, unit, opts)
|
||||
if err != ErrDoesNotExist {
|
||||
if !errors.Is(err, ErrDoesNotExist) {
|
||||
t.Errorf("error on second unmasking is %v, but should have been %v", err, ErrDoesNotExist)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
61
util.go
61
util.go
@@ -3,10 +3,10 @@ package systemctl
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var systemctl string
|
||||
@@ -14,12 +14,7 @@ var systemctl string
|
||||
const killed = 130
|
||||
|
||||
func init() {
|
||||
path, err := exec.LookPath("systemctl")
|
||||
if err != nil {
|
||||
log.Printf("%v", ErrNotInstalled)
|
||||
systemctl = ""
|
||||
return
|
||||
}
|
||||
path, _ := exec.LookPath("systemctl")
|
||||
systemctl = path
|
||||
}
|
||||
|
||||
@@ -34,7 +29,7 @@ func execute(ctx context.Context, args []string) (string, string, int, error) {
|
||||
)
|
||||
|
||||
if systemctl == "" {
|
||||
panic(ErrNotInstalled)
|
||||
return "", "", 1, ErrNotInstalled
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, systemctl, args...)
|
||||
cmd.Stdout = &stdout
|
||||
@@ -56,32 +51,26 @@ func execute(ctx context.Context, args []string) (string, string, int, error) {
|
||||
}
|
||||
|
||||
func filterErr(stderr string) error {
|
||||
if matched, _ := regexp.MatchString(`does not exist`, stderr); matched {
|
||||
return ErrDoesNotExist
|
||||
}
|
||||
if matched, _ := regexp.MatchString(`not found.`, stderr); matched {
|
||||
return ErrDoesNotExist
|
||||
}
|
||||
if matched, _ := regexp.MatchString(`not loaded.`, stderr); matched {
|
||||
return ErrUnitNotLoaded
|
||||
}
|
||||
if matched, _ := regexp.MatchString(`No such file or directory`, stderr); matched {
|
||||
return ErrDoesNotExist
|
||||
}
|
||||
if matched, _ := regexp.MatchString(`Interactive authentication required`, stderr); matched {
|
||||
return ErrInsufficientPermissions
|
||||
}
|
||||
if matched, _ := regexp.MatchString(`Access denied`, stderr); matched {
|
||||
return ErrInsufficientPermissions
|
||||
}
|
||||
if matched, _ := regexp.MatchString(`DBUS_SESSION_BUS_ADDRESS`, stderr); matched {
|
||||
return ErrBusFailure
|
||||
}
|
||||
if matched, _ := regexp.MatchString(`is masked`, stderr); matched {
|
||||
return ErrMasked
|
||||
}
|
||||
if matched, _ := regexp.MatchString(`Failed`, stderr); matched {
|
||||
return ErrUnspecified
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(`does not exist`, stderr):
|
||||
return errors.Join(ErrDoesNotExist, fmt.Errorf("stderr: %s", stderr))
|
||||
case strings.Contains(`not found.`, stderr):
|
||||
return errors.Join(ErrDoesNotExist, fmt.Errorf("stderr: %s", stderr))
|
||||
case strings.Contains(`not loaded.`, stderr):
|
||||
return errors.Join(ErrUnitNotLoaded, fmt.Errorf("stderr: %s", stderr))
|
||||
case strings.Contains(`No such file or directory`, stderr):
|
||||
return errors.Join(ErrDoesNotExist, fmt.Errorf("stderr: %s", stderr))
|
||||
case strings.Contains(`Interactive authentication required`, stderr):
|
||||
return errors.Join(ErrInsufficientPermissions, fmt.Errorf("stderr: %s", stderr))
|
||||
case strings.Contains(`Access denied`, stderr):
|
||||
return errors.Join(ErrInsufficientPermissions, fmt.Errorf("stderr: %s", stderr))
|
||||
case strings.Contains(`DBUS_SESSION_BUS_ADDRESS`, stderr):
|
||||
return errors.Join(ErrBusFailure, fmt.Errorf("stderr: %s", stderr))
|
||||
case strings.Contains(`is masked`, stderr):
|
||||
return errors.Join(ErrMasked, fmt.Errorf("stderr: %s", stderr))
|
||||
case strings.Contains(`Failed`, stderr):
|
||||
return errors.Join(ErrUnspecified, fmt.Errorf("stderr: %s", stderr))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user