-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathservice_linux.go
125 lines (96 loc) · 2.24 KB
/
service_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
package service
import (
"fmt"
"log/syslog"
"os"
"os/signal"
"text/template"
)
func newService(name, displayName, description string) (s *linuxUpstartService, err error) {
s = &linuxUpstartService{
name: name,
displayName: displayName,
description: description,
}
s.logger, err = syslog.New(syslog.LOG_INFO, name)
if err != nil {
return nil, err
}
return s, nil
}
type linuxUpstartService struct {
name, displayName, description string
logger *syslog.Writer
}
func (s *linuxUpstartService) Install() error {
var confPath = "/etc/init/" + s.name + ".conf"
_, 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 := getExePath()
if err != nil {
return err
}
var to = &struct {
Display string
Description string
Path string
}{
s.displayName,
s.description,
path,
}
t := template.Must(template.New("upstartScript").Parse(upstartScript))
err = t.Execute(f, to)
if err != nil {
return err
}
return nil
}
func (s *linuxUpstartService) Remove() error {
return os.Remove("/etc/init/" + s.name + ".conf")
}
func (s *linuxUpstartService) Run(onStart, onStop func() error) error {
var err error
err = onStart()
if err != nil {
return err
}
var sigChan = make(chan os.Signal, 3)
signal.Notify(sigChan, os.Interrupt, os.Kill)
<-sigChan
return onStop()
}
func (s *linuxUpstartService) LogError(format string, a ...interface{}) error {
return s.logger.Err(fmt.Sprintf(format, a...))
}
func (s *linuxUpstartService) LogWarning(format string, a ...interface{}) error {
return s.logger.Warning(fmt.Sprintf(format, a...))
}
func (s *linuxUpstartService) LogInfo(format string, a ...interface{}) error {
return s.logger.Info(fmt.Sprintf(format, a...))
}
func getExePath() (exePath string, err error) {
return os.Readlink(`/proc/self/exe`)
}
var upstartScript = `# {{.Description}}
description "{{.Display}}"
start on filesystem or runlevel [2345]
stop on runlevel [!2345]
kill signal INT
respawn
respawn limit 10 5
umask 022
console none
pre-start script
test -x {{.Path}} || { stop; exit 0; }
end script
# Start
exec {{.Path}}
`