Files
RenewCMS/internal/infrastructure/update/systemctlControl.go
T

58 lines
1.3 KiB
Go

package update
import (
domain "RenewCMS/internal/domain/update"
"errors"
"fmt"
"os/exec"
"strings"
)
const systemctlCommand = "systemctl"
type SystemctlControl struct {
service string
}
var (
_ domain.ServiceControl = &SystemctlControl{}
_ domain.UnitManager = &SystemctlControl{}
)
func NewSystemctlControl(service string) *SystemctlControl {
return &SystemctlControl{service: service}
}
func (c *SystemctlControl) Restart() error {
return runSystemctl("restart", c.service)
}
func (c *SystemctlControl) Status() (bool, error) {
err := exec.Command(systemctlCommand, "is-active", "--quiet", c.service).Run()
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
return false, nil
}
return err == nil, err
}
func (c *SystemctlControl) DaemonReload() error {
return runSystemctl("daemon-reload")
}
func (c *SystemctlControl) EnableNow(unit string) error {
return runSystemctl("enable", "--now", unit)
}
func (c *SystemctlControl) DisableNow(unit string) error {
return runSystemctl("disable", "--now", unit)
}
func runSystemctl(arguments ...string) error {
output, err := exec.Command(systemctlCommand, arguments...).CombinedOutput()
if err != nil {
return fmt.Errorf("systemctl %s: %w: %s", strings.Join(arguments, " "), err, strings.TrimSpace(string(output)))
}
return nil
}