summaryrefslogtreecommitdiff
path: root/stdlib/os/systemd/systemd.go
blob: 8e34f28118ab7ba6eb68ba4a607bc9c5669e25c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package systemd

import (
	"fmt"
	"os/exec"

	gonf "git.adyxax.org/adyxax/gonf/pkg"
)

func Promise() {
	gonf.SetServiceFunction(systemdService)
}

func isEnabled(name string) bool {
	return systemctlShow(name, "UnitFileState") == "enabled"
}

func isRunning(name string) bool {
	value := systemctlShow(name, "SubState")
	return value == "running" || value == "waiting"
}

func systemctl(name, operation string) (gonf.Status, error) {
	cmd := exec.Command("systemctl", operation, name)
	if err := cmd.Run(); err != nil {
		return gonf.BROKEN, err
	}
	return gonf.REPAIRED, nil
}

func systemctlShow(name, field string) string {
	ecmd := exec.Command("systemctl", "show", name, "-p", field, "--value")
	out, _ := ecmd.CombinedOutput()
	return string(out[:len(out)-1]) // remove trailing '\n' and convert to string
}

func systemdService(name, state string) (gonf.Status, error) {
	switch state {
	case "disabled":
		if isEnabled(name) {
			return systemctl(name, "disable")
		} else {
			return gonf.KEPT, nil
		}
	case "enabled":
		if isEnabled(name) {
			return gonf.KEPT, nil
		} else {
			return systemctl(name, "enable")
		}
	case "reloaded":
		return systemctl(name, "reloaded")
	case "restarted":
		return systemctl(name, "restart")
	case "started":
		if isRunning(name) {
			return gonf.KEPT, nil
		} else {
			return systemctl(name, "start")
		}
	case "stopped":
		if isRunning(name) {
			return systemctl(name, "stop")
		} else {
			return gonf.KEPT, nil
		}
	default:
		return gonf.BROKEN, fmt.Errorf("unsupported systemctl operation " + state)
	}
}