This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
systemd.go
101 lines (83 loc) · 2.17 KB
/
systemd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package dep
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"github.com/pkg/errors"
"github.com/caos/orbos/mntr"
)
type SystemD struct {
monitor mntr.Monitor
}
func NewSystemD(monitor mntr.Monitor) *SystemD {
return &SystemD{monitor}
}
func (s *SystemD) Disable(binary string) error {
errBuf := new(bytes.Buffer)
defer errBuf.Reset()
cmd := exec.Command("systemctl", "stop", binary)
cmd.Stderr = errBuf
if s.monitor.IsVerbose() {
fmt.Println(strings.Join(cmd.Args, " "))
cmd.Stdout = os.Stdout
}
err := cmd.Run()
if err != nil {
errString := errBuf.String()
if strings.Contains(errString, "not loaded") {
err = nil
} else {
return errors.Wrapf(err, "stopping %s by systemd failed with stderr %s", binary, errString)
}
}
errBuf.Reset()
cmd = exec.Command("systemctl", "disable", binary)
cmd.Stderr = errBuf
if s.monitor.IsVerbose() {
fmt.Println(strings.Join(cmd.Args, " "))
cmd.Stdout = os.Stdout
}
if err := cmd.Run(); err != nil {
errString := errBuf.String()
if strings.Contains(errString, "No such file or directory") {
err = nil
} else {
return errors.Wrapf(err, "disabling %s by systemd failed with stderr %s", binary, errString)
}
}
return nil
}
func (s *SystemD) Start(binary string) error {
errBuf := new(bytes.Buffer)
defer errBuf.Reset()
cmd := exec.Command("systemctl", "restart", binary)
cmd.Stderr = errBuf
return errors.Wrapf(cmd.Run(), "restarting %s from systemd failed with stderr %s", binary, errBuf.String())
}
func (s *SystemD) Enable(binary string) error {
errBuf := new(bytes.Buffer)
defer errBuf.Reset()
cmd := exec.Command("systemctl", "enable", binary)
cmd.Stderr = errBuf
if s.monitor.IsVerbose() {
fmt.Println(strings.Join(cmd.Args, " "))
cmd.Stdout = os.Stdout
}
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "enabling systemd unit %s failed with stderr %s", binary, errBuf.String())
}
if !s.Active(binary) {
return s.Start(binary)
}
return nil
}
func (s *SystemD) Active(binary string) bool {
cmd := exec.Command("systemctl", "is-active", binary)
if s.monitor.IsVerbose() {
fmt.Println(strings.Join(cmd.Args, " "))
cmd.Stdout = os.Stdout
}
return cmd.Run() == nil
}