service_darwin.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. // Copyright 2015 Daniel Theophanes.
  2. // Use of this source code is governed by a zlib-style
  3. // license that can be found in the LICENSE file.
  4. package service
  5. import (
  6. "errors"
  7. "fmt"
  8. "os"
  9. "os/signal"
  10. "os/user"
  11. "path/filepath"
  12. "syscall"
  13. "text/template"
  14. "time"
  15. )
  16. const maxPathSize = 32 * 1024
  17. const version = "darwin-launchd"
  18. type darwinSystem struct{}
  19. func (darwinSystem) String() string {
  20. return version
  21. }
  22. func (darwinSystem) Detect() bool {
  23. return true
  24. }
  25. func (darwinSystem) Interactive() bool {
  26. return interactive
  27. }
  28. func (darwinSystem) New(i Interface, c *Config) (Service, error) {
  29. s := &darwinLaunchdService{
  30. i: i,
  31. Config: c,
  32. userService: c.Option.bool(optionUserService, optionUserServiceDefault),
  33. }
  34. return s, nil
  35. }
  36. func init() {
  37. ChooseSystem(darwinSystem{})
  38. }
  39. var interactive = false
  40. func init() {
  41. var err error
  42. interactive, err = isInteractive()
  43. if err != nil {
  44. panic(err)
  45. }
  46. }
  47. func isInteractive() (bool, error) {
  48. // TODO: The PPID of Launchd is 1. The PPid of a service process should match launchd's PID.
  49. return os.Getppid() != 1, nil
  50. }
  51. type darwinLaunchdService struct {
  52. i Interface
  53. *Config
  54. userService bool
  55. }
  56. func (s *darwinLaunchdService) String() string {
  57. if len(s.DisplayName) > 0 {
  58. return s.DisplayName
  59. }
  60. return s.Name
  61. }
  62. func (s *darwinLaunchdService) getHomeDir() (string, error) {
  63. u, err := user.Current()
  64. if err == nil {
  65. return u.HomeDir, nil
  66. }
  67. // alternate methods
  68. homeDir := os.Getenv("HOME") // *nix
  69. if homeDir == "" {
  70. return "", errors.New("User home directory not found.")
  71. }
  72. return homeDir, nil
  73. }
  74. func (s *darwinLaunchdService) getServiceFilePath() (string, error) {
  75. if s.userService {
  76. homeDir, err := s.getHomeDir()
  77. if err != nil {
  78. return "", err
  79. }
  80. return homeDir + "/Library/LaunchAgents/" + s.Name + ".plist", nil
  81. }
  82. return "/Library/LaunchDaemons/" + s.Name + ".plist", nil
  83. }
  84. func (s *darwinLaunchdService) Install() error {
  85. confPath, err := s.getServiceFilePath()
  86. if err != nil {
  87. return err
  88. }
  89. _, err = os.Stat(confPath)
  90. if err == nil {
  91. return fmt.Errorf("Init already exists: %s", confPath)
  92. }
  93. if s.userService {
  94. // Ensure that ~/Library/LaunchAgents exists.
  95. err = os.MkdirAll(filepath.Dir(confPath), 0700)
  96. if err != nil {
  97. return err
  98. }
  99. }
  100. f, err := os.Create(confPath)
  101. if err != nil {
  102. return err
  103. }
  104. defer f.Close()
  105. path, err := s.execPath()
  106. if err != nil {
  107. return err
  108. }
  109. var to = &struct {
  110. *Config
  111. Path string
  112. KeepAlive, RunAtLoad bool
  113. SessionCreate bool
  114. }{
  115. Config: s.Config,
  116. Path: path,
  117. KeepAlive: s.Option.bool(optionKeepAlive, optionKeepAliveDefault),
  118. RunAtLoad: s.Option.bool(optionRunAtLoad, optionRunAtLoadDefault),
  119. SessionCreate: s.Option.bool(optionSessionCreate, optionSessionCreateDefault),
  120. }
  121. functions := template.FuncMap{
  122. "bool": func(v bool) string {
  123. if v {
  124. return "true"
  125. }
  126. return "false"
  127. },
  128. }
  129. t := template.Must(template.New("launchdConfig").Funcs(functions).Parse(launchdConfig))
  130. return t.Execute(f, to)
  131. }
  132. func (s *darwinLaunchdService) Uninstall() error {
  133. s.Stop()
  134. confPath, err := s.getServiceFilePath()
  135. if err != nil {
  136. return err
  137. }
  138. return os.Remove(confPath)
  139. }
  140. func (s *darwinLaunchdService) Start() error {
  141. confPath, err := s.getServiceFilePath()
  142. if err != nil {
  143. return err
  144. }
  145. return run("launchctl", "load", confPath)
  146. }
  147. func (s *darwinLaunchdService) Stop() error {
  148. confPath, err := s.getServiceFilePath()
  149. if err != nil {
  150. return err
  151. }
  152. return run("launchctl", "unload", confPath)
  153. }
  154. func (s *darwinLaunchdService) Restart() error {
  155. err := s.Stop()
  156. if err != nil {
  157. return err
  158. }
  159. time.Sleep(50 * time.Millisecond)
  160. return s.Start()
  161. }
  162. func (s *darwinLaunchdService) Run() error {
  163. var err error
  164. err = s.i.Start(s)
  165. if err != nil {
  166. return err
  167. }
  168. s.Option.funcSingle(optionRunWait, func() {
  169. var sigChan = make(chan os.Signal, 3)
  170. signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt)
  171. <-sigChan
  172. })()
  173. return s.i.Stop(s)
  174. }
  175. func (s *darwinLaunchdService) Logger(errs chan<- error) (Logger, error) {
  176. if interactive {
  177. return ConsoleLogger, nil
  178. }
  179. return s.SystemLogger(errs)
  180. }
  181. func (s *darwinLaunchdService) SystemLogger(errs chan<- error) (Logger, error) {
  182. return newSysLogger(s.Name, errs)
  183. }
  184. var launchdConfig = `<?xml version='1.0' encoding='UTF-8'?>
  185. <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
  186. "http://www.apple.com/DTDs/PropertyList-1.0.dtd" >
  187. <plist version='1.0'>
  188. <dict>
  189. <key>Label</key><string>{{html .Name}}</string>
  190. <key>ProgramArguments</key>
  191. <array>
  192. <string>{{html .Path}}</string>
  193. {{range .Config.Arguments}}
  194. <string>{{html .}}</string>
  195. {{end}}
  196. </array>
  197. {{if .UserName}}<key>UserName</key><string>{{html .UserName}}</string>{{end}}
  198. {{if .ChRoot}}<key>RootDirectory</key><string>{{html .ChRoot}}</string>{{end}}
  199. {{if .WorkingDirectory}}<key>WorkingDirectory</key><string>{{html .WorkingDirectory}}</string>{{end}}
  200. <key>SessionCreate</key><{{bool .SessionCreate}}/>
  201. <key>KeepAlive</key><{{bool .KeepAlive}}/>
  202. <key>RunAtLoad</key><{{bool .RunAtLoad}}/>
  203. <key>Disabled</key><false/>
  204. </dict>
  205. </plist>
  206. `