Debian Codegraph @

daemon.go

raw symbols SCIP
1 // +build darwin freebsd linux
2
3 // Package godaemon runs a program as a Unix daemon.
4 package godaemon
5
6 // Copyright (c) 2013-2015 VividCortex, Inc. All rights reserved.
7 // Please see the LICENSE file for applicable license terms.
8
9 import (
10 "bytes"
11 "crypto/sha1"
12 "encoding/hex"
13 "fmt"
14 "io"
15 "os"
16 "strconv"
17 "strings"
18 "syscall"
19 "time"
20 )
21
22 // Environment variables to support this process
23 const (
24 stageVar = "__DAEMON_STAGE"
25 fdVarPrefix = "__DAEMON_FD_"
26 )
27
28 // DaemonAttr describes the options that apply to daemonization
29 type DaemonAttr struct {
30 ProgramName string // child's os.Args[0]; copied from parent if empty
31 CaptureOutput bool // whether to capture stdout/stderr
32 Files []**os.File // files to keep open in the daemon
33 }
34
35 /*
36 MakeDaemon turns the process into a daemon. But given the lack of Go's
37 support for fork(), MakeDaemon() is forced to run the process all over again,
38 from the start. Hence, this should probably be your first call after main
39 begins, unless you understand the effects of calling from somewhere else.
40 Keep in mind that the PID changes after this function is called, given
41 that it only returns in the child; the parent will exit without returning.
42
43 Options are provided as a DaemonAttr structure. In particular, setting the
44 CaptureOutput member to true will make the function return two io.Reader
45 streams to read the process' standard output and standard error, respectively.
46 That's useful if you want to capture things you'd normally lose given the
47 lack of console output for a daemon. Some libraries can write error conditions
48 to standard error or make use of Go's log package, that defaults to standard
49 error too. Having these streams allows you to capture them as required. (Note
50 that this function takes no action whatsoever on any of the streams.)
51
52 NOTE: If you use them, make sure NOT to take one of these readers and write
53 the data back again to standard output/error, or you'll end up with a loop.
54 Also, note that data will be flushed on a line-by-line basis; i.e., partial
55 lines will be buffered until an end-of-line is seen.
56
57 By using the Files member of DaemonAttr you can inherit open files that will
58 still be open once the program is running as a daemon. This may be convenient in
59 general, but it's primarily intended to avoid race conditions while forking, in
60 case a lock (flock) was held on that file. Repeatedly releasing and re-locking
61 while forking is subject to race conditions, cause a different process could
62 lock the file in between. But locks held on files declared at DaemonAttr.Files
63 are guaranteed NOT to be released during the whole process, and still be held by
64 the daemon. To use this feature you should open the file(s), lock if required
65 and then call MakeDaemon using pointers to that *os.File objects; i.e., you'd be
66 passing **os.File objects to MakeDaemon(). However, opening the files (and
67 locking if required) should only be attempted at the parent. (Recall that
68 MakeDaemon() will run the code coming "before" it three times; see the
69 explanation above.) You can filter that by calling Stage() and looking for a
70 godaemon.StageParent result. The last call to MakeDaemon() at the daemon itself
71 will actually *load* the *os.File objects for you; that's why you need to
72 provide a pointer to them. So here's how you'd use it:
73
74 var (
75 f *os.File
76 err error
77 )
78
79 if godaemon.Stage() == godaemon.StageParent {
80 f, err = os.OpenFile(name, opts, perm)
81 if err != nil {
82 os.Exit(1)
83 }
84 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
85 if err != nil {
86 os.Exit(1)
87 }
88 }
89
90 _, _, err = godaemon.MakeDaemon(&godaemon.DaemonAttr{
91 Files: []**os.File{&f},
92 })
93
94 // Only the daemon will reach this point, where f will be a valid descriptor
95 // pointing to your file "name", still holding the lock (which will have
96 // never been released during successive forks). You can operate on f as you
97 // normally would, like:
98 f.Close()
99
100 NOTE: Do not abuse this feature. Even though you could, it's obviously not a
101 good idea to use this mechanism to keep a terminal device open, for instance.
102 Otherwise, what you get is not strictly a daemon.
103
104
105 Daemonizing is a 3-stage process. In stage 0, the program increments the
106 magical environment variable and starts a copy of itself that's a session
107 leader, with its STDIN, STDOUT, and STDERR disconnected from any tty. It
108 then exits.
109
110 In stage 1, the (new copy of) the program starts another copy that's not
111 a session leader, and then exits.
112
113 In stage 2, the (new copy of) the program chdir's to /, then sets the umask
114 and reestablishes the original value for the environment variable.
115 */
116 func MakeDaemon(attrs *DaemonAttr) (io.Reader, io.Reader, error) {
117 stage, advanceStage, resetEnv := getStage()
118
119 // This is a handy wrapper to do the proper thing in case of fatal
120 // conditions. For the first stage you may want to recover, so it will
121 // return the error. Otherwise it will exit the process, cause you'll be
122 // half-way with some descriptors already changed. There's no chance to
123 // write to stdout or stderr in the later case; they'll be already closed.
124 fatal := func(err error) (io.Reader, io.Reader, error) {
125 if stage > 0 {
126 os.Exit(1)
127 }
128 resetEnv()
129 return nil, nil, err
130 }
131
132 fileCount := 3 + len(attrs.Files)
133 files := make([]*os.File, fileCount, fileCount+2)
134
135 if stage == 0 {
136 // Descriptors 0, 1 and 2 are fixed in the "os" package. If we close
137 // them, the process may choose to open something else there, with bad
138 // consequences if some write to os.Stdout or os.Stderr follows (even
139 // from Go's library itself, through the default log package). We thus
140 // reserve these descriptors to avoid that.
141 nullDev, err := os.OpenFile("/dev/null", 0, 0)
142 if err != nil {
143 return fatal(err)
144 }
145 files[0], files[1], files[2] = nullDev, nullDev, nullDev
146
147 fd := 3
148 for _, fPtr := range attrs.Files {
149 files[fd] = *fPtr
150 saveFileName(fd, (*fPtr).Name())
151 fd++
152 }
153 } else {
154 files[0], files[1], files[2] = os.Stdin, os.Stdout, os.Stderr
155
156 fd := 3
157 for _, fPtr := range attrs.Files {
158 *fPtr = os.NewFile(uintptr(fd), getFileName(fd))
159 syscall.CloseOnExec(fd)
160 files[fd] = *fPtr
161 fd++
162 }
163 }
164
165 if stage < 2 {
166 procName, err := os.Executable()
167 if err != nil {
168 return fatal(fmt.Errorf("can't determine full path to executable: %s", err))
169 }
170
171 // If Executable() returns "" but no error, determinating the
172 // executable path is not implemented on the host OS, so daemonization
173 // is not supported.
174 if len(procName) == 0 {
175 return fatal(fmt.Errorf("can't determine full path to executable"))
176 }
177
178 if stage == 1 && attrs.CaptureOutput {
179 files = files[:fileCount+2]
180
181 // stdout: write at fd:1, read at fd:fileCount
182 if files[fileCount], files[1], err = os.Pipe(); err != nil {
183 return fatal(err)
184 }
185 // stderr: write at fd:2, read at fd:fileCount+1
186 if files[fileCount+1], files[2], err = os.Pipe(); err != nil {
187 return fatal(err)
188 }
189 }
190
191 if err := advanceStage(); err != nil {
192 return fatal(err)
193 }
194 dir, _ := os.Getwd()
195 osAttrs := os.ProcAttr{Dir: dir, Env: os.Environ(), Files: files}
196
197 if stage == 0 {
198 sysattrs := syscall.SysProcAttr{Setsid: true}
199 osAttrs.Sys = &sysattrs
200 }
201
202 progName := attrs.ProgramName
203 if len(progName) == 0 {
204 progName = os.Args[0]
205 }
206 args := append([]string{progName}, os.Args[1:]...)
207 proc, err := os.StartProcess(procName, args, &osAttrs)
208 if err != nil {
209 return fatal(fmt.Errorf("can't create process %s: %s", procName, err))
210 }
211 proc.Release()
212 os.Exit(0)
213 }
214
215 os.Chdir("/")
216 syscall.Umask(0)
217 resetEnv()
218
219 for fd := 3; fd < fileCount; fd++ {
220 resetFileName(fd)
221 }
222 currStage = DaemonStage(stage)
223
224 var stdout, stderr *os.File
225 if attrs.CaptureOutput {
226 stdout = os.NewFile(uintptr(fileCount), "stdout")
227 stderr = os.NewFile(uintptr(fileCount+1), "stderr")
228 }
229 return stdout, stderr, nil
230 }
231
232 func saveFileName(fd int, name string) {
233 // We encode in hex to avoid issues with filename encoding, and to be able
234 // to separate it from the original variable value (if set) that we want to
235 // keep. Otherwise, all non-zero characters are valid in the name, and we
236 // can't insert a zero in the var as a separator.
237 fdVar := fdVarPrefix + fmt.Sprint(fd)
238 value := fmt.Sprintf("%s:%s",
239 hex.EncodeToString([]byte(name)), os.Getenv(fdVar))
240
241 if err := os.Setenv(fdVar, value); err != nil {
242 fmt.Fprintf(os.Stderr, "can't set %s: %s\n", fdVar, err)
243 os.Exit(1)
244 }
245 }
246
247 func getFileName(fd int) string {
248 fdVar := fdVarPrefix + fmt.Sprint(fd)
249 value := os.Getenv(fdVar)
250 sep := bytes.IndexByte([]byte(value), ':')
251
252 if sep < 0 {
253 fmt.Fprintf(os.Stderr, "bad fd var %s\n", fdVar)
254 os.Exit(1)
255 }
256 name, err := hex.DecodeString(value[:sep])
257 if err != nil {
258 fmt.Fprintf(os.Stderr, "error decoding %s\n", fdVar)
259 os.Exit(1)
260 }
261 return string(name)
262 }
263
264 func resetFileName(fd int) {
265 fdVar := fdVarPrefix + fmt.Sprint(fd)
266 value := os.Getenv(fdVar)
267 sep := bytes.IndexByte([]byte(value), ':')
268
269 if sep < 0 {
270 fmt.Fprintf(os.Stderr, "bad fd var %s\n", fdVar)
271 os.Exit(1)
272 }
273 if err := os.Setenv(fdVar, value[sep+1:]); err != nil {
274 fmt.Fprintf(os.Stderr, "can't reset %s\n", fdVar)
275 os.Exit(1)
276 }
277 }
278
279 // Daemonize is equivalent to MakeDaemon(&DaemonAttr{}). It is kept only for
280 // backwards API compatibility, but it's usage is otherwise discouraged. Use
281 // MakeDaemon() instead. The child parameter, previously used to tell whether
282 // to reset the environment or not (see MakeDaemon()), is currently ignored.
283 // The environment is reset in all cases.
284 func Daemonize(child ...bool) {
285 MakeDaemon(&DaemonAttr{})
286 }
287
288 // DaemonStage tells in what stage in the process we are. See Stage().
289 type DaemonStage int
290
291 // Stages in the daemonizing process.
292 const (
293 StageParent = DaemonStage(iota) // Original process
294 StageChild // MakeDaemon() called once: first child
295 StageDaemon // MakeDaemon() run twice: final daemon
296
297 stageUnknown = DaemonStage(-1)
298 )
299
300 // currStage keeps the current stage. This is used only as a cache for Stage(),
301 // in order to extend a valid result after MakeDaemon() has returned, where the
302 // environment variable would have already been reset. (Also, this is faster
303 // than repetitive calls to getStage().) Note that this approach is valid cause
304 // the stage doesn't change throughout any single process execution. It does
305 // only for the next process after the MakeDaemon() call.
306 var currStage = stageUnknown
307
308 // Stage returns the "stage of daemonizing", i.e., it allows you to know whether
309 // you're currently working in the parent, first child, or the final daemon.
310 // This is useless after the call to MakeDaemon(), cause that call will only
311 // return for the daemon stage. However, you can still use Stage() to tell
312 // whether you've daemonized or not, in case you have a running path that may
313 // exclude the call to MakeDaemon().
314 func Stage() DaemonStage {
315 if currStage == stageUnknown {
316 s, _, _ := getStage()
317 currStage = DaemonStage(s)
318 }
319 return currStage
320 }
321
322 // String returns a humanly readable daemonization stage.
323 func (s DaemonStage) String() string {
324 switch s {
325 case StageParent:
326 return "parent"
327 case StageChild:
328 return "first child"
329 case StageDaemon:
330 return "daemon"
331 default:
332 return "unknown"
333 }
334 }
335
336 // Returns the current stage in the "daemonization process", that's kept in
337 // an environment variable. The variable is instrumented with a digital
338 // signature, to avoid misbehavior if it was present in the user's
339 // environment. The original value is restored after the last stage, so that
340 // there's no final effect on the environment the application receives.
341 func getStage() (stage int, advanceStage func() error, resetEnv func() error) {
342 var origValue string
343 stage = 0
344
345 daemonStage := os.Getenv(stageVar)
346 stageTag := strings.SplitN(daemonStage, ":", 2)
347 stageInfo := strings.SplitN(stageTag[0], "/", 3)
348
349 if len(stageInfo) == 3 {
350 stageStr, tm, check := stageInfo[0], stageInfo[1], stageInfo[2]
351
352 hash := sha1.New()
353 hash.Write([]byte(stageStr + "/" + tm + "/"))
354
355 if check != hex.EncodeToString(hash.Sum([]byte{})) {
356 // This whole chunk is original data
357 origValue = daemonStage
358 } else {
359 stage, _ = strconv.Atoi(stageStr)
360
361 if len(stageTag) == 2 {
362 origValue = stageTag[1]
363 }
364 }
365 } else {
366 origValue = daemonStage
367 }
368
369 advanceStage = func() error {
370 base := fmt.Sprintf("%d/%09d/", stage+1, time.Now().Nanosecond())
371 hash := sha1.New()
372 hash.Write([]byte(base))
373 tag := base + hex.EncodeToString(hash.Sum([]byte{}))
374
375 if err := os.Setenv(stageVar, tag+":"+origValue); err != nil {
376 return fmt.Errorf("can't set %s: %s", stageVar, err)
377 }
378 return nil
379 }
380 resetEnv = func() error {
381 return os.Setenv(stageVar, origValue)
382 }
383
384 return stage, advanceStage, resetEnv
385 }