create generic service manager (systemd only, TODO:init)

This commit is contained in:
xdrm-brackets 2018-11-08 13:42:13 +01:00
parent 274d8af1f7
commit 85ecf2d20a
4 changed files with 92 additions and 0 deletions

9
internal/ser/common.go Normal file
View File

@ -0,0 +1,9 @@
package ser
// ServiceManager is the common interface for service managers (systemd, init.d)
type ServiceManager interface {
// Name of executable (to check if installed and for debug)
Name() string
// Exec a specific action on a service
Exec(action, service string) error
}

7
internal/ser/errors.go Normal file
View File

@ -0,0 +1,7 @@
package ser
import (
"errors"
)
var ErrUnknownAction = errors.New("unknown action")

45
internal/ser/loader.go Normal file
View File

@ -0,0 +1,45 @@
package ser
import (
"errors"
"os/exec"
)
var ErrUnknownManager = errors.New("unknown service manager")
var ErrNoCandidateInstalled = errors.New("no package-manager candidate installed")
// available service managers
// var available = []string{"systemd", "init"}
var available = []string{"systemd"}
func Load(_manager string) (ServiceManager, error) {
// 1. fail if unknown manager
known := false
for _, mgr := range available {
if _manager == mgr {
known = true
break
}
}
if !known {
return nil, ErrUnknownManager
}
// 2. Create manager accordingly
var manager ServiceManager
switch _manager {
case "systemd":
manager = new(Systemd)
default:
return nil, ErrUnknownManager
}
// 2. fail if not installed
if exec.Command("which", manager.Name()).Run() == nil {
return nil, ErrNoCandidateInstalled
}
return manager, nil
}

31
internal/ser/systemd.go Normal file
View File

@ -0,0 +1,31 @@
package ser
import (
"os/exec"
)
type Systemd struct{}
// available actions
var actions = []string{"enable", "disable", "start", "stop", "reload", "restart"}
func (d Systemd) Name() string { return "systemctl" }
func (d Systemd) Exec(action, service string) error {
// 1. fail if unknown action
known := false
for _, act := range actions {
if action == act {
known = true
break
}
}
if !known {
return ErrUnknownAction
}
// 2. execute command
return exec.Command("systemctl", action, service).Run()
}