service_darwin.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. "regexp"
  13. "strings"
  14. "syscall"
  15. "text/template"
  16. "time"
  17. )
  18. const maxPathSize = 32 * 1024
  19. const version = "darwin-launchd"
  20. type darwinSystem struct{}
  21. func (darwinSystem) String() string {
  22. return version
  23. }
  24. func (darwinSystem) Detect() bool {
  25. return true
  26. }
  27. func (darwinSystem) Interactive() bool {
  28. return interactive
  29. }
  30. func (darwinSystem) New(i Interface, c *Config) (Service, error) {
  31. s := &darwinLaunchdService{
  32. i: i,
  33. Config: c,
  34. userService: c.Option.bool(optionUserService, optionUserServiceDefault),
  35. }
  36. return s, nil
  37. }
  38. func init() {
  39. ChooseSystem(darwinSystem{})
  40. }
  41. var interactive = false
  42. func init() {
  43. var err error
  44. interactive, err = isInteractive()
  45. if err != nil {
  46. panic(err)
  47. }
  48. }
  49. func isInteractive() (bool, error) {
  50. // TODO: The PPID of Launchd is 1. The PPid of a service process should match launchd's PID.
  51. return os.Getppid() != 1, nil
  52. }
  53. type darwinLaunchdService struct {
  54. i Interface
  55. *Config
  56. userService bool
  57. }
  58. func (s *darwinLaunchdService) String() string {
  59. if len(s.DisplayName) > 0 {
  60. return s.DisplayName
  61. }
  62. return s.Name
  63. }
  64. func (s *darwinLaunchdService) Platform() string {
  65. return version
  66. }
  67. func (s *darwinLaunchdService) getHomeDir() (string, error) {
  68. u, err := user.Current()
  69. if err == nil {
  70. return u.HomeDir, nil
  71. }
  72. // alternate methods
  73. homeDir := os.Getenv("HOME") // *nix
  74. if homeDir == "" {
  75. return "", errors.New("User home directory not found.")
  76. }
  77. return homeDir, nil
  78. }
  79. func (s *darwinLaunchdService) getServiceFilePath() (string, error) {
  80. if s.userService {
  81. homeDir, err := s.getHomeDir()
  82. if err != nil {
  83. return "", err
  84. }
  85. return homeDir + "/Library/LaunchAgents/" + s.Name + ".plist", nil
  86. }
  87. return "/Library/LaunchDaemons/" + s.Name + ".plist", nil
  88. }
  89. func (s *darwinLaunchdService) template() *template.Template {
  90. functions := template.FuncMap{
  91. "bool": func(v bool) string {
  92. if v {
  93. return "true"
  94. }
  95. return "false"
  96. },
  97. }
  98. customConfig := s.Option.string(optionLaunchdConfig, "")
  99. if customConfig != "" {
  100. return template.Must(template.New("").Funcs(functions).Parse(customConfig))
  101. } else {
  102. return template.Must(template.New("").Funcs(functions).Parse(launchdConfig))
  103. }
  104. }
  105. func (s *darwinLaunchdService) Install() error {
  106. confPath, err := s.getServiceFilePath()
  107. if err != nil {
  108. return err
  109. }
  110. _, err = os.Stat(confPath)
  111. if err == nil {
  112. return fmt.Errorf("Init already exists: %s", confPath)
  113. }
  114. if s.userService {
  115. // Ensure that ~/Library/LaunchAgents exists.
  116. err = os.MkdirAll(filepath.Dir(confPath), 0700)
  117. if err != nil {
  118. return err
  119. }
  120. }
  121. f, err := os.Create(confPath)
  122. if err != nil {
  123. return err
  124. }
  125. defer f.Close()
  126. path, err := s.execPath()
  127. if err != nil {
  128. return err
  129. }
  130. var to = &struct {
  131. *Config
  132. Path string
  133. KeepAlive, RunAtLoad bool
  134. SessionCreate bool
  135. StandardOut bool
  136. StandardError bool
  137. }{
  138. Config: s.Config,
  139. Path: path,
  140. KeepAlive: s.Option.bool(optionKeepAlive, optionKeepAliveDefault),
  141. RunAtLoad: s.Option.bool(optionRunAtLoad, optionRunAtLoadDefault),
  142. SessionCreate: s.Option.bool(optionSessionCreate, optionSessionCreateDefault),
  143. }
  144. return s.template().Execute(f, to)
  145. }
  146. func (s *darwinLaunchdService) Uninstall() error {
  147. s.Stop()
  148. confPath, err := s.getServiceFilePath()
  149. if err != nil {
  150. return err
  151. }
  152. return os.Remove(confPath)
  153. }
  154. func (s *darwinLaunchdService) Status() (Status, error) {
  155. exitCode, out, err := runWithOutput("launchctl", "list", s.Name)
  156. if exitCode == 0 && err != nil {
  157. if !strings.Contains(err.Error(), "failed with StandardError") {
  158. return StatusUnknown, err
  159. }
  160. }
  161. re := regexp.MustCompile(`"PID" = ([0-9]+);`)
  162. matches := re.FindStringSubmatch(out)
  163. if len(matches) == 2 {
  164. return StatusRunning, nil
  165. }
  166. confPath, err := s.getServiceFilePath()
  167. if err != nil {
  168. return StatusUnknown, err
  169. }
  170. if _, err = os.Stat(confPath); err == nil {
  171. return StatusStopped, nil
  172. }
  173. return StatusUnknown, ErrNotInstalled
  174. }
  175. func (s *darwinLaunchdService) Start() error {
  176. confPath, err := s.getServiceFilePath()
  177. if err != nil {
  178. return err
  179. }
  180. return run("launchctl", "load", confPath)
  181. }
  182. func (s *darwinLaunchdService) Stop() error {
  183. confPath, err := s.getServiceFilePath()
  184. if err != nil {
  185. return err
  186. }
  187. return run("launchctl", "unload", confPath)
  188. }
  189. func (s *darwinLaunchdService) Restart() error {
  190. err := s.Stop()
  191. if err != nil {
  192. return err
  193. }
  194. time.Sleep(50 * time.Millisecond)
  195. return s.Start()
  196. }
  197. func (s *darwinLaunchdService) Run() error {
  198. var err error
  199. err = s.i.Start(s)
  200. if err != nil {
  201. return err
  202. }
  203. s.Option.funcSingle(optionRunWait, func() {
  204. var sigChan = make(chan os.Signal, 3)
  205. signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt)
  206. <-sigChan
  207. })()
  208. return s.i.Stop(s)
  209. }
  210. func (s *darwinLaunchdService) Logger(errs chan<- error) (Logger, error) {
  211. if interactive {
  212. return ConsoleLogger, nil
  213. }
  214. return s.SystemLogger(errs)
  215. }
  216. func (s *darwinLaunchdService) SystemLogger(errs chan<- error) (Logger, error) {
  217. return newSysLogger(s.Name, errs)
  218. }
  219. var launchdConfig = `<?xml version='1.0' encoding='UTF-8'?>
  220. <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
  221. "http://www.apple.com/DTDs/PropertyList-1.0.dtd" >
  222. <plist version='1.0'>
  223. <dict>
  224. <key>Label</key>
  225. <string>{{html .Name}}</string>
  226. <key>ProgramArguments</key>
  227. <array>
  228. <string>{{html .Path}}</string>
  229. {{range .Config.Arguments}}
  230. <string>{{html .}}</string>
  231. {{end}}
  232. </array>
  233. {{if .UserName}}<key>UserName</key>
  234. <string>{{html .UserName}}</string>{{end}}
  235. {{if .ChRoot}}<key>RootDirectory</key>
  236. <string>{{html .ChRoot}}</string>{{end}}
  237. {{if .WorkingDirectory}}<key>WorkingDirectory</key>
  238. <string>{{html .WorkingDirectory}}</string>{{end}}
  239. <key>SessionCreate</key>
  240. <{{bool .SessionCreate}}/>
  241. <key>KeepAlive</key>
  242. <{{bool .KeepAlive}}/>
  243. <key>RunAtLoad</key>
  244. <{{bool .RunAtLoad}}/>
  245. <key>Disabled</key>
  246. <false/>
  247. <key>StandardOutPath</key>
  248. <string>/usr/local/var/log/{{html .Name}}.out.log</string>
  249. <key>StandardErrorPath</key>
  250. <string>/usr/local/var/log/{{html .Name}}.err.log</string>
  251. </dict>
  252. </plist>
  253. `