From 3b9af437380850034e92d5936a49ac8bd68a9493 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Tue, 5 Mar 2024 23:48:47 +0100 Subject: feat(stdlib): began adding systemd services support --- stdlib/os/systemd/systemd.go | 70 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 stdlib/os/systemd/systemd.go diff --git a/stdlib/os/systemd/systemd.go b/stdlib/os/systemd/systemd.go new file mode 100644 index 0000000..782548d --- /dev/null +++ b/stdlib/os/systemd/systemd.go @@ -0,0 +1,70 @@ +package systemd + +import ( + "errors" + "os/exec" + + "git.adyxax.org/adyxax/gonf/v2/gonf" +) + +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 +} -- cgit v1.2.3