daemon_unix.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // +build darwin dragonfly freebsd linux netbsd openbsd plan9 solaris
  2. package daemon
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "syscall"
  9. )
  10. // A Context describes daemon context.
  11. type Context struct {
  12. // If PidFileName is non-empty, parent process will try to create and lock
  13. // pid file with given name. Child process writes process id to file.
  14. PidFileName string
  15. // Permissions for new pid file.
  16. PidFilePerm os.FileMode
  17. // If LogFileName is non-empty, parent process will create file with given name
  18. // and will link to fd 2 (stderr) for child process.
  19. LogFileName string
  20. // Permissions for new log file.
  21. LogFilePerm os.FileMode
  22. // If WorkDir is non-empty, the child changes into the directory before
  23. // creating the process.
  24. WorkDir string
  25. // If Chroot is non-empty, the child changes root directory
  26. Chroot string
  27. // If Env is non-nil, it gives the environment variables for the
  28. // daemon-process in the form returned by os.Environ.
  29. // If it is nil, the result of os.Environ will be used.
  30. Env []string
  31. // If Args is non-nil, it gives the command-line args for the
  32. // daemon-process. If it is nil, the result of os.Args will be used.
  33. Args []string
  34. // Credential holds user and group identities to be assumed by a daemon-process.
  35. Credential *syscall.Credential
  36. // If Umask is non-zero, the daemon-process call Umask() func with given value.
  37. Umask int
  38. // Struct contains only serializable public fields (!!!)
  39. abspath string
  40. pidFile *LockFile
  41. logFile *os.File
  42. nullFile *os.File
  43. rpipe, wpipe *os.File
  44. }
  45. func (d *Context) reborn() (child *os.Process, err error) {
  46. if !WasReborn() {
  47. child, err = d.parent()
  48. } else {
  49. err = d.child()
  50. }
  51. return
  52. }
  53. func (d *Context) search() (daemon *os.Process, err error) {
  54. if len(d.PidFileName) > 0 {
  55. var pid int
  56. if pid, err = ReadPidFile(d.PidFileName); err != nil {
  57. return
  58. }
  59. daemon, err = os.FindProcess(pid)
  60. }
  61. return
  62. }
  63. func (d *Context) parent() (child *os.Process, err error) {
  64. if err = d.prepareEnv(); err != nil {
  65. return
  66. }
  67. defer d.closeFiles()
  68. if err = d.openFiles(); err != nil {
  69. return
  70. }
  71. attr := &os.ProcAttr{
  72. Dir: d.WorkDir,
  73. Env: d.Env,
  74. Files: d.files(),
  75. Sys: &syscall.SysProcAttr{
  76. //Chroot: d.Chroot,
  77. Credential: d.Credential,
  78. Setsid: true,
  79. },
  80. }
  81. if child, err = os.StartProcess(d.abspath, d.Args, attr); err != nil {
  82. if d.pidFile != nil {
  83. d.pidFile.Remove()
  84. }
  85. return
  86. }
  87. d.rpipe.Close()
  88. encoder := json.NewEncoder(d.wpipe)
  89. if err = encoder.Encode(d); err != nil {
  90. return
  91. }
  92. _, err = fmt.Fprint(d.wpipe, "\n\n")
  93. return
  94. }
  95. func (d *Context) openFiles() (err error) {
  96. if d.PidFilePerm == 0 {
  97. d.PidFilePerm = FILE_PERM
  98. }
  99. if d.LogFilePerm == 0 {
  100. d.LogFilePerm = FILE_PERM
  101. }
  102. if d.nullFile, err = os.Open(os.DevNull); err != nil {
  103. return
  104. }
  105. if len(d.PidFileName) > 0 {
  106. if d.PidFileName, err = filepath.Abs(d.PidFileName); err != nil {
  107. return err
  108. }
  109. if d.pidFile, err = OpenLockFile(d.PidFileName, d.PidFilePerm); err != nil {
  110. return
  111. }
  112. if err = d.pidFile.Lock(); err != nil {
  113. return
  114. }
  115. if len(d.Chroot) > 0 {
  116. // Calculate PID-file absolute path in child's environment
  117. if d.PidFileName, err = filepath.Rel(d.Chroot, d.PidFileName); err != nil {
  118. return err
  119. }
  120. d.PidFileName = "/" + d.PidFileName
  121. }
  122. }
  123. if len(d.LogFileName) > 0 {
  124. if d.logFile, err = os.OpenFile(d.LogFileName,
  125. os.O_WRONLY|os.O_CREATE|os.O_APPEND, d.LogFilePerm); err != nil {
  126. return
  127. }
  128. }
  129. d.rpipe, d.wpipe, err = os.Pipe()
  130. return
  131. }
  132. func (d *Context) closeFiles() (err error) {
  133. cl := func(file **os.File) {
  134. if *file != nil {
  135. (*file).Close()
  136. *file = nil
  137. }
  138. }
  139. cl(&d.rpipe)
  140. cl(&d.wpipe)
  141. cl(&d.logFile)
  142. cl(&d.nullFile)
  143. if d.pidFile != nil {
  144. d.pidFile.Close()
  145. d.pidFile = nil
  146. }
  147. return
  148. }
  149. func (d *Context) prepareEnv() (err error) {
  150. if d.abspath, err = osExecutable(); err != nil {
  151. return
  152. }
  153. if len(d.Args) == 0 {
  154. d.Args = os.Args
  155. }
  156. mark := fmt.Sprintf("%s=%s", MARK_NAME, MARK_VALUE)
  157. if len(d.Env) == 0 {
  158. d.Env = os.Environ()
  159. }
  160. d.Env = append(d.Env, mark)
  161. return
  162. }
  163. func (d *Context) files() (f []*os.File) {
  164. log := d.nullFile
  165. if d.logFile != nil {
  166. log = d.logFile
  167. }
  168. f = []*os.File{
  169. d.rpipe, // (0) stdin
  170. log, // (1) stdout
  171. log, // (2) stderr
  172. d.nullFile, // (3) dup on fd 0 after initialization
  173. }
  174. if d.pidFile != nil {
  175. f = append(f, d.pidFile.File) // (4) pid file
  176. }
  177. return
  178. }
  179. var initialized = false
  180. func (d *Context) child() (err error) {
  181. if initialized {
  182. return os.ErrInvalid
  183. }
  184. initialized = true
  185. decoder := json.NewDecoder(os.Stdin)
  186. if err = decoder.Decode(d); err != nil {
  187. return
  188. }
  189. // create PID file after context decoding to know PID file full path.
  190. if len(d.PidFileName) > 0 {
  191. d.pidFile = NewLockFile(os.NewFile(4, d.PidFileName))
  192. if err = d.pidFile.WritePid(); err != nil {
  193. return
  194. }
  195. defer func() {
  196. if err != nil {
  197. d.pidFile.Remove()
  198. }
  199. }()
  200. }
  201. if err = syscallDup(3, 0); err != nil {
  202. return
  203. }
  204. if d.Umask != 0 {
  205. syscall.Umask(int(d.Umask))
  206. }
  207. if len(d.Chroot) > 0 {
  208. err = syscall.Chroot(d.Chroot)
  209. if err != nil {
  210. return
  211. }
  212. }
  213. return
  214. }
  215. func (d *Context) release() (err error) {
  216. if !initialized {
  217. return
  218. }
  219. if d.pidFile != nil {
  220. err = d.pidFile.Remove()
  221. }
  222. return
  223. }