-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_systemd_linux.go
274 lines (234 loc) · 6.04 KB
/
service_systemd_linux.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Copyright 2015 Daniel Theophanes.
// Use of this source code is governed by a zlib-style
// license that can be found in the LICENSE file.
package service
import (
"bytes"
"errors"
"fmt"
"os"
"os/signal"
"regexp"
"strconv"
"strings"
"syscall"
"text/template"
)
func isSystemd() bool {
if _, err := os.Stat("/run/systemd/system"); err == nil {
return true
}
if _, err := os.Stat("/proc/1/comm"); err == nil {
filerc, err := os.Open("/proc/1/comm")
if err != nil {
return false
}
defer filerc.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(filerc)
contents := buf.String()
if strings.Trim(contents, " \r\n") == "systemd" {
return true
}
}
return false
}
type systemd struct {
i Interface
platform string
*Config
}
func newSystemdService(i Interface, platform string, c *Config) (Service, error) {
s := &systemd{
i: i,
platform: platform,
Config: c,
}
return s, nil
}
func (s *systemd) String() string {
if len(s.DisplayName) > 0 {
return s.DisplayName
}
return s.Name
}
func (s *systemd) Platform() string {
return s.platform
}
// Systemd services should be supported, but are not currently.
var errNoUserServiceSystemd = errors.New("User services are not supported on systemd.")
func (s *systemd) configPath() (cp string, err error) {
if s.Option.bool(optionUserService, optionUserServiceDefault) {
err = errNoUserServiceSystemd
return
}
cp = "/etc/systemd/system/" + s.Config.Name + ".service"
return
}
func (s *systemd) getSystemdVersion() int64 {
_, out, err := runWithOutput("systemctl", "--version")
if err != nil {
return -1
}
re := regexp.MustCompile(`systemd ([0-9]+)`)
matches := re.FindStringSubmatch(out)
if len(matches) != 2 {
return -1
}
v, err := strconv.ParseInt(matches[1], 10, 64)
if err != nil {
return -1
}
return v
}
func (s *systemd) hasOutputFileSupport() bool {
defaultValue := true
version := s.getSystemdVersion()
if version == -1 {
return defaultValue
}
if version < 236 {
return false
}
return defaultValue
}
func (s *systemd) template() *template.Template {
customScript := s.Option.string(optionSystemdScript, "")
if customScript != "" {
return template.Must(template.New("").Funcs(tf).Parse(customScript))
} else {
return template.Must(template.New("").Funcs(tf).Parse(systemdScript))
}
}
func (s *systemd) Install() error {
confPath, err := s.configPath()
if err != nil {
return err
}
_, err = os.Stat(confPath)
if err == nil {
return fmt.Errorf("Init already exists: %s", confPath)
}
f, err := os.Create(confPath)
if err != nil {
return err
}
defer f.Close()
path, err := s.execPath()
if err != nil {
return err
}
var to = &struct {
*Config
Path string
HasOutputFileSupport bool
ReloadSignal string
PIDFile string
Restart string
SuccessExitStatus string
LogOutput bool
}{
s.Config,
path,
s.hasOutputFileSupport(),
s.Option.string(optionReloadSignal, ""),
s.Option.string(optionPIDFile, ""),
s.Option.string(optionRestart, "always"),
s.Option.string(optionSuccessExitStatus, ""),
s.Option.bool(optionLogOutput, optionLogOutputDefault),
}
err = s.template().Execute(f, to)
if err != nil {
return err
}
err = run("systemctl", "enable", s.Name+".service")
if err != nil {
return err
}
return run("systemctl", "daemon-reload")
}
func (s *systemd) Uninstall() error {
err := run("systemctl", "disable", s.Name+".service")
if err != nil {
return err
}
cp, err := s.configPath()
if err != nil {
return err
}
if err := os.Remove(cp); err != nil {
return err
}
return nil
}
func (s *systemd) Logger(errs chan<- error) (Logger, error) {
if system.Interactive() {
return ConsoleLogger, nil
}
return s.SystemLogger(errs)
}
func (s *systemd) SystemLogger(errs chan<- error) (Logger, error) {
return newSysLogger(s.Name, errs)
}
func (s *systemd) Run() (err error) {
err = s.i.Start(s)
if err != nil {
return err
}
s.Option.funcSingle(optionRunWait, func() {
var sigChan = make(chan os.Signal, 3)
signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt)
<-sigChan
})()
return s.i.Stop(s)
}
func (s *systemd) Status() (Status, error) {
exitCode, out, err := runWithOutput("systemctl", "is-active", s.Name)
if exitCode == 0 && err != nil {
return StatusUnknown, err
}
switch {
case strings.HasPrefix(out, "active"):
return StatusRunning, nil
case strings.HasPrefix(out, "inactive"):
return StatusStopped, nil
case strings.HasPrefix(out, "failed"):
return StatusUnknown, errors.New("service in failed state")
default:
return StatusUnknown, ErrNotInstalled
}
}
func (s *systemd) Start() error {
return run("systemctl", "start", s.Name+".service")
}
func (s *systemd) Stop() error {
return run("systemctl", "stop", s.Name+".service")
}
func (s *systemd) Restart() error {
return run("systemctl", "restart", s.Name+".service")
}
const systemdScript = `[Unit]
Description={{.Description}}
ConditionFileIsExecutable={{.Path|cmdEscape}}
{{range $i, $dep := .Dependencies}}
{{$dep}} {{end}}
[Service]
StartLimitInterval=5
StartLimitBurst=10
ExecStart={{.Path|cmdEscape}}{{range .Arguments}} {{.|cmd}}{{end}}
{{if .ChRoot}}RootDirectory={{.ChRoot|cmd}}{{end}}
{{if .WorkingDirectory}}WorkingDirectory={{.WorkingDirectory|cmdEscape}}{{end}}
{{if .UserName}}User={{.UserName}}{{end}}
{{if .ReloadSignal}}ExecReload=/bin/kill -{{.ReloadSignal}} "$MAINPID"{{end}}
{{if .PIDFile}}PIDFile={{.PIDFile|cmd}}{{end}}
{{if and .LogOutput .HasOutputFileSupport -}}
StandardOutput=file:/var/log/{{.Name}}.out
StandardError=file:/var/log/{{.Name}}.err
{{- end}}
{{if .Restart}}Restart={{.Restart}}{{end}}
{{if .SuccessExitStatus}}SuccessExitStatus={{.SuccessExitStatus}}{{end}}
RestartSec=120
EnvironmentFile=-/etc/sysconfig/{{.Name}}
[Install]
WantedBy=multi-user.target
`