-
Notifications
You must be signed in to change notification settings - Fork 1
/
systemd.go
115 lines (88 loc) · 2.48 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// +build linux
package initme
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"path"
"text/template"
)
const (
unitStoragePath string = "/etc/systemd/system"
unitTemplate string = `[Unit]
Description={{ .Conf.Description }}
After=network.target
[Service]
TimeoutStartSec={{ .Conf.TimeoutStartSec }}
ExecStart={{ .Conf.ExecStart }}
[Install]
WantedBy={{ .Conf.WantedBy }}`
)
func init() {
if IsSystemD() {
serviceType = SystemD{}
}
}
type SystemD struct {
Conf Config
}
func (self SystemD) New(c Config) Service {
self.Conf = c
return self
}
func (self SystemD) Register() (output string, err error, code int) {
if err = self.createUnitFile(); err != nil {
return
}
return self.Enable()
}
func (self SystemD) Start() (output string, err error, code int) {
return execute(self.Conf.Log, "systemctl", "start", self.Conf.Name+".service")
}
func (self SystemD) Stop() (output string, err error, code int) {
return execute(self.Conf.Log, "systemctl", "stop", self.Conf.Name+".service")
}
func (self SystemD) Status() (output string, err error, code int) {
return execute(self.Conf.Log, "systemctl", "status", self.Conf.Name+".service")
}
func (self SystemD) Enable() (output string, err error, code int) {
return execute(self.Conf.Log, "systemctl", "enable", path.Join(unitStoragePath, self.Conf.Name+".service"))
}
func (self SystemD) Disable() (output string, err error, code int) {
return execute(self.Conf.Log, "systemctl", "disable", self.Conf.Name+".service")
}
func (self SystemD) Delete() (output string, err error, code int) {
if _, err := os.Stat(path.Join(unitStoragePath, self.Conf.Name+".service")); os.IsNotExist(err) {
return output, nil, code
}
err = os.Remove(path.Join(unitStoragePath, self.Conf.Name+".service"))
return
}
func (self SystemD) Run() {
// To fit Service interface
}
func (self SystemD) createUnitFile() (err error) {
var b bytes.Buffer
unitString := bufio.NewWriter(&b)
unitTmpl, err := template.New("unit").Parse(unitTemplate)
if err != nil {
return fmt.Errorf("createUnitFile: %s", err)
}
err = unitTmpl.Execute(unitString, self)
if err != nil {
return fmt.Errorf("createUnitFile: %s", err)
}
unitString.Flush()
unitPath := path.Join(unitStoragePath, self.Conf.Name+".service")
err = ioutil.WriteFile(unitPath, b.Bytes(), os.ModePerm)
if err != nil {
return fmt.Errorf("createUnitFile: %s", err)
}
return nil
}
func (self SystemD) IsAnInteractiveSession() (bool, error) {
// To fit Service interface
return false, nil
}