diff options
author | Julien Dessaux | 2024-03-05 23:48:47 +0100 |
---|---|---|
committer | Julien Dessaux | 2024-03-07 01:02:23 +0100 |
commit | 3b9af437380850034e92d5936a49ac8bd68a9493 (patch) | |
tree | 78a042cd0d799e5fe1b86d7a1d3c4d92effd5612 /stdlib | |
parent | feat(stdlib): disable apt package recommendations by default (diff) | |
download | gonf-3b9af437380850034e92d5936a49ac8bd68a9493.tar.gz gonf-3b9af437380850034e92d5936a49ac8bd68a9493.tar.bz2 gonf-3b9af437380850034e92d5936a49ac8bd68a9493.zip |
feat(stdlib): began adding systemd services support
Diffstat (limited to 'stdlib')
-rw-r--r-- | stdlib/os/systemd/systemd.go | 70 |
1 files changed, 70 insertions, 0 deletions
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 +} |