Debian Codegraph @

service.go

raw symbols SCIP
1 // Package service wraps all the complexity of writing daemons while enabling
2 // seamless integration with OS service management facilities.
3 package service // import "gopkg.in/hlandau/service.v2"
4
5 import (
6 "expvar"
7 "fmt"
8 "gopkg.in/hlandau/easyconfig.v1/cflag"
9 "gopkg.in/hlandau/service.v2/gsptcall"
10 "gopkg.in/hlandau/svcutils.v1/exepath"
11 "io"
12 "net/http"
13 _ "net/http/pprof" // register pprof handler for debug server
14 "os"
15 "os/signal"
16 "runtime/pprof"
17 "sync"
18 "syscall"
19 "time"
20 )
21
22 // Flags
23
24 var (
25 fg = cflag.NewGroup(nil, "service")
26 cpuProfileFlag = cflag.String(fg, "cpuprofile", "", "Write CPU profile to file")
27 debugServerAddrFlag = cflag.String(fg, "debugserveraddr", "", "Address for debug server to listen on (do not specify a public address) (default: disabled)")
28 )
29
30 type nullWriter struct{}
31
32 func (nw nullWriter) Write(p []byte) (n int, err error) {
33 return len(p), nil
34 }
35
36 func init() {
37 expvar.NewString("service.startTime").Set(time.Now().String())
38 }
39
40 // This function should typically be called directly from func main(). It takes
41 // care of all housekeeping for running services and handles service lifecycle.
42 func Main(info *Info) {
43 info.main()
44 }
45
46 // The interface between the service library and the application-specific code.
47 // The application calls the methods in the provided instance of this interface
48 // at various stages in its lifecycle.
49 type Manager interface {
50 // Must be called when the service is ready to drop privileges.
51 // This must be called before SetStarted().
52 DropPrivileges() error
53
54 // Must be called by a service payload when it has finished starting.
55 SetStarted()
56
57 // A service payload must stop when this channel is closed.
58 StopChan() <-chan struct{}
59
60 // Called by a service payload to provide a single line of information on the
61 // current status of that service.
62 SetStatus(status string)
63 }
64
65 // Used only by the NewFunc interface.
66 type Runnable interface {
67 // Start the runnable. Any initialization requiring root privileges must
68 // already have been obtained as this will be called after dropping
69 // privileges. Must return.
70 Start() error
71
72 // Stop the runnable. Must return.
73 Stop() error
74 }
75
76 // An upgrade interface for Runnable, implementation of which is optional.
77 type StatusSource interface {
78 // Return a channel on which status messages will be sent. If a Runnable
79 // implements this, it is guaranteed that the channel will be consumed until
80 // Stop is called.
81 StatusChan() <-chan string
82 }
83
84 // An instantiable service.
85 type Info struct {
86 // Recommended. Codename for the service, e.g. "foobar"
87 //
88 // If this is not set, exepath.ProgramName is used, which by default is the
89 // program's binary basename (e.g. "FooBar.exe" would become "foobar").
90 Name string
91
92 // Required unless NewFunc is specified instead. Starts the service. Must not
93 // return until the service has stopped. Must call smgr.SetStarted() to
94 // indicate when it has finished starting and use smgr.StopChan() to
95 // determine when to stop.
96 //
97 // Should call SetStatus() periodically with a status string.
98 RunFunc func(smgr Manager) error
99
100 // Optional. An alternative to RunFunc. If this is provided, RunFunc must not
101 // be specified, and this package will provide its own implementation of
102 // RunFunc.
103 //
104 // The NewFunc will be called to instantiate the runnable service.
105 // Privileges will then be dropped and Start will be called. Start must
106 // return. When the service is to be stopped, Stop will be called. Stop must
107 // return.
108 //
109 // To implement status notification, implement also the StatusSource interface.
110 NewFunc func() (Runnable, error)
111
112 Title string // Optional. Friendly name for the service, e.g. "Foobar Web Server"
113 Description string // Optional. Single line description for the service
114
115 AllowRoot bool // May the service run as root? If false, the service will refuse to run as root unless privilege dropping is set.
116 DefaultChroot string // Default path to chroot to. Use this if the service can be chrooted without consequence.
117 NoBanSuid bool // Set to true if the ability to execute suid binaries must be retained.
118
119 // Are we being started by systemd with [Service] Type=notify?
120 // If so, we can issue service status notifications to systemd.
121 systemd bool
122
123 // Path to created PID file.
124 pidFileName string
125 pidFile io.Closer
126 }
127
128 func (info *Info) main() {
129 err := info.maine()
130 if err != nil {
131 fmt.Fprintf(os.Stderr, "Error in service: %+v\n", err)
132 os.Exit(1)
133 }
134 }
135
136 func (info *Info) maine() error {
137 if info.Name == "" {
138 info.Name = exepath.ProgramName
139 } else if exepath.ProgramNameSetter == "default" {
140 exepath.ProgramName = info.Name
141 exepath.ProgramNameSetter = "service"
142 }
143
144 if info.Name == "" {
145 panic("service name must be specified")
146 }
147 if info.Title == "" {
148 info.Title = info.Name
149 }
150 if info.Description == "" {
151 info.Description = info.Title
152 }
153
154 err := info.commonPre()
155 if err != nil {
156 return err
157 }
158
159 err = info.setRunFunc()
160 if err != nil {
161 return err
162 }
163
164 // profiling
165 if cpuProfileFlag.Value() != "" {
166 f, err := os.Create(cpuProfileFlag.Value())
167 if err != nil {
168 return err
169 }
170 pprof.StartCPUProfile(f)
171 defer f.Close()
172 defer pprof.StopCPUProfile()
173 }
174
175 err = info.serviceMain()
176
177 return err
178 }
179
180 func (info *Info) commonPre() error {
181 if debugServerAddrFlag != nil && debugServerAddrFlag.Value() != "" {
182 go func() {
183 err := http.ListenAndServe(debugServerAddrFlag.Value(), nil)
184 if err != nil {
185 fmt.Fprintf(os.Stderr, "Couldn't start debug server: %+v\n", err)
186 }
187 }()
188 }
189 return nil
190 }
191
192 func (info *Info) setRunFunc() error {
193 if info.RunFunc != nil {
194 return nil
195 }
196
197 if info.NewFunc == nil {
198 panic("either RunFunc or NewFunc must be specified")
199 }
200
201 info.RunFunc = func(smgr Manager) error {
202 // instantiate runnable
203 r, err := info.NewFunc()
204 if err != nil {
205 return err
206 }
207
208 // setup status channel
209 getStatusChan := func() <-chan string {
210 return nil
211 }
212 if ss, ok := r.(StatusSource); ok {
213 getStatusChan = func() <-chan string {
214 return ss.StatusChan()
215 }
216 }
217
218 // drop privileges
219 err = smgr.DropPrivileges()
220 if err != nil {
221 return err
222 }
223
224 // start
225 err = r.Start()
226 if err != nil {
227 return err
228 }
229
230 //
231 smgr.SetStarted()
232 smgr.SetStatus(info.Name + ": running ok")
233
234 // wait for status messages or stop requests
235 loop:
236 for {
237 select {
238 case statusMsg := <-getStatusChan():
239 smgr.SetStatus(info.Name + ": " + statusMsg)
240
241 case <-smgr.StopChan():
242 break loop
243 }
244 }
245
246 // stop
247 return r.Stop()
248 }
249
250 return nil
251 }
252
253 type ihandler struct {
254 info *Info
255 stopChan chan struct{}
256 statusMutex sync.Mutex
257 statusNotifyChan chan struct{}
258 startedChan chan struct{}
259 status string
260 started bool
261 stopping bool
262 dropped bool
263 }
264
265 func (h *ihandler) SetStarted() {
266 if !h.dropped {
267 panic("service must call DropPrivileges before calling SetStarted")
268 }
269
270 select {
271 case h.startedChan <- struct{}{}:
272 default:
273 }
274 }
275
276 func (h *ihandler) StopChan() <-chan struct{} {
277 return h.stopChan
278 }
279
280 func (h *ihandler) SetStatus(status string) {
281 h.statusMutex.Lock()
282 h.status = status
283 h.statusMutex.Unlock()
284
285 select {
286 case <-h.statusNotifyChan:
287 default:
288 }
289 }
290
291 func (h *ihandler) updateStatus() {
292 // systemd
293 if h.info.systemd {
294 s := ""
295 if h.started {
296 s += "READY=1\n"
297 }
298 if h.status != "" {
299 s += "STATUS=" + h.status + "\n"
300 }
301 systemdUpdateStatus(s)
302 // ignore error
303 }
304
305 if h.status != "" {
306 gsptcall.SetProcTitle(h.status)
307 }
308 }
309
310 func (info *Info) runInteractively() error {
311 smgr := ihandler{
312 info: info,
313 stopChan: make(chan struct{}),
314 statusNotifyChan: make(chan struct{}, 1),
315 startedChan: make(chan struct{}, 1),
316 }
317
318 doneChan := make(chan error)
319 go func() {
320 err := info.RunFunc(&smgr)
321 doneChan <- err
322 }()
323
324 sig := make(chan os.Signal, 1)
325 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
326
327 var exitErr error
328
329 loop:
330 for {
331 select {
332 case <-sig:
333 if !smgr.stopping {
334 smgr.stopping = true
335 close(smgr.stopChan)
336 smgr.updateStatus()
337 }
338 case <-smgr.startedChan:
339 if !smgr.started {
340 smgr.started = true
341 smgr.updateStatus()
342 }
343 case <-smgr.statusNotifyChan:
344 smgr.updateStatus()
345 case exitErr = <-doneChan:
346 break loop
347 }
348 }
349
350 return exitErr
351 }
352
353 // © 2015 Hugo Landau <[email protected]> ISC License