http-server-status/internal/pkg/checks/systemd.go

64 lines
1.1 KiB
Go
Raw Normal View History

2021-10-21 10:15:55 +00:00
package checks
import (
"github.com/rs/zerolog/log"
"os/exec"
"strings"
)
type SystemdConf struct {
Services []string `yaml:"services"`
2021-11-29 05:02:41 +00:00
Enabled bool `yaml:"enabled"`
2021-10-21 10:15:55 +00:00
}
type Systemd struct {
Config SystemdConf
}
func (h Systemd) Execute() (ok bool, data interface{}, err error) {
2021-11-29 05:02:41 +00:00
if h.Config.Enabled == false {
return true, nil, nil
}
2021-10-21 10:15:55 +00:00
success := true
servicelist := make(map[string]bool)
for _, service := range h.Config.Services {
res, err := h.getStatus(service)
if err != nil {
return false, nil, err
}
if res == false {
success = false
}
servicelist[service] = res
}
return success, servicelist,nil
}
func (h Systemd) Name() string {
2021-11-25 01:01:27 +00:00
return "SystemdStatus"
2021-10-21 10:15:55 +00:00
}
func (h Systemd) getStatus(name string) (bool, error) {
cmd := exec.Command("systemctl", "check", name)
out, err := cmd.CombinedOutput()
if err != nil {
log.Debug().Err(err).Msg("Error in systemd communication")
if exitErr, ok := err.(*exec.ExitError); ok {
if exitErr.ExitCode() == 3 {
return false, nil
}
}
return false, err
}
s := string(out)
s = strings.Trim(s, "\n")
if s == "active" {
return true, nil
}
return false, nil
}