summaryrefslogtreecommitdiff
path: root/stdlib/os/systemd/systemd.go
blob: 5af1e91bab7eca8308152c3136172b80967ff61b (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 (
	"errors"
	"os/exec"

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

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

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

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

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 systemd_service(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, errors.New("unsupported systemctl operation " + state)
	}
	return gonf.KEPT, nil
}