service_systemd_linux.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. "bytes"
  7. "errors"
  8. "fmt"
  9. "os"
  10. "os/signal"
  11. "path/filepath"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "syscall"
  16. "text/template"
  17. )
  18. func isSystemd() bool {
  19. if _, err := os.Stat("/run/systemd/system"); err == nil {
  20. return true
  21. }
  22. if _, err := os.Stat("/proc/1/comm"); err == nil {
  23. filerc, err := os.Open("/proc/1/comm")
  24. if err != nil {
  25. return false
  26. }
  27. defer filerc.Close()
  28. buf := new(bytes.Buffer)
  29. buf.ReadFrom(filerc)
  30. contents := buf.String()
  31. if strings.Trim(contents, " \r\n") == "systemd" {
  32. return true
  33. }
  34. }
  35. return false
  36. }
  37. type systemd struct {
  38. i Interface
  39. platform string
  40. *Config
  41. }
  42. func newSystemdService(i Interface, platform string, c *Config) (Service, error) {
  43. s := &systemd{
  44. i: i,
  45. platform: platform,
  46. Config: c,
  47. }
  48. return s, nil
  49. }
  50. func (s *systemd) String() string {
  51. if len(s.DisplayName) > 0 {
  52. return s.DisplayName
  53. }
  54. return s.Name
  55. }
  56. func (s *systemd) Platform() string {
  57. return s.platform
  58. }
  59. func (s *systemd) configPath() (cp string, err error) {
  60. if !s.isUserService() {
  61. cp = "/etc/systemd/system/" + s.Config.Name + ".service"
  62. return
  63. }
  64. homeDir, err := os.UserHomeDir()
  65. if err != nil {
  66. return
  67. }
  68. systemdUserDir := filepath.Join(homeDir, ".config/systemd/user")
  69. err = os.MkdirAll(systemdUserDir, os.ModePerm)
  70. if err != nil {
  71. return
  72. }
  73. cp = filepath.Join(systemdUserDir, s.Config.Name+".service")
  74. return
  75. }
  76. func (s *systemd) getSystemdVersion() int64 {
  77. _, out, err := runWithOutput("systemctl", "--version")
  78. if err != nil {
  79. return -1
  80. }
  81. re := regexp.MustCompile(`systemd ([0-9]+)`)
  82. matches := re.FindStringSubmatch(out)
  83. if len(matches) != 2 {
  84. return -1
  85. }
  86. v, err := strconv.ParseInt(matches[1], 10, 64)
  87. if err != nil {
  88. return -1
  89. }
  90. return v
  91. }
  92. func (s *systemd) hasOutputFileSupport() bool {
  93. defaultValue := true
  94. version := s.getSystemdVersion()
  95. if version == -1 {
  96. return defaultValue
  97. }
  98. if version < 236 {
  99. return false
  100. }
  101. return defaultValue
  102. }
  103. func (s *systemd) template() *template.Template {
  104. customScript := s.Option.string(optionSystemdScript, "")
  105. if customScript != "" {
  106. return template.Must(template.New("").Funcs(tf).Parse(customScript))
  107. } else {
  108. return template.Must(template.New("").Funcs(tf).Parse(systemdScript))
  109. }
  110. }
  111. func (s *systemd) isUserService() bool {
  112. return s.Option.bool(optionUserService, optionUserServiceDefault)
  113. }
  114. func (s *systemd) Install() error {
  115. confPath, err := s.configPath()
  116. if err != nil {
  117. return err
  118. }
  119. _, err = os.Stat(confPath)
  120. if err == nil {
  121. return fmt.Errorf("Init already exists: %s", confPath)
  122. }
  123. f, err := os.OpenFile(confPath, os.O_WRONLY|os.O_CREATE, 0644)
  124. if err != nil {
  125. return err
  126. }
  127. defer f.Close()
  128. path, err := s.execPath()
  129. if err != nil {
  130. return err
  131. }
  132. var to = &struct {
  133. *Config
  134. Path string
  135. HasOutputFileSupport bool
  136. ReloadSignal string
  137. PIDFile string
  138. LimitNOFILE int
  139. Restart string
  140. SuccessExitStatus string
  141. LogOutput bool
  142. }{
  143. s.Config,
  144. path,
  145. s.hasOutputFileSupport(),
  146. s.Option.string(optionReloadSignal, ""),
  147. s.Option.string(optionPIDFile, ""),
  148. s.Option.int(optionLimitNOFILE, optionLimitNOFILEDefault),
  149. s.Option.string(optionRestart, "always"),
  150. s.Option.string(optionSuccessExitStatus, ""),
  151. s.Option.bool(optionLogOutput, optionLogOutputDefault),
  152. }
  153. err = s.template().Execute(f, to)
  154. if err != nil {
  155. return err
  156. }
  157. err = s.runAction("enable")
  158. if err != nil {
  159. return err
  160. }
  161. return s.run("daemon-reload")
  162. }
  163. func (s *systemd) Uninstall() error {
  164. err := s.runAction("disable")
  165. if err != nil {
  166. return err
  167. }
  168. cp, err := s.configPath()
  169. if err != nil {
  170. return err
  171. }
  172. if err := os.Remove(cp); err != nil {
  173. return err
  174. }
  175. return nil
  176. }
  177. func (s *systemd) Logger(errs chan<- error) (Logger, error) {
  178. if system.Interactive() {
  179. return ConsoleLogger, nil
  180. }
  181. return s.SystemLogger(errs)
  182. }
  183. func (s *systemd) SystemLogger(errs chan<- error) (Logger, error) {
  184. return newSysLogger(s.Name, errs)
  185. }
  186. func (s *systemd) Run() (err error) {
  187. err = s.i.Start(s)
  188. if err != nil {
  189. return err
  190. }
  191. s.Option.funcSingle(optionRunWait, func() {
  192. var sigChan = make(chan os.Signal, 3)
  193. signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt)
  194. <-sigChan
  195. })()
  196. return s.i.Stop(s)
  197. }
  198. func (s *systemd) Status() (Status, error) {
  199. exitCode, out, err := runWithOutput("systemctl", "is-active", s.Name)
  200. if exitCode == 0 && err != nil {
  201. return StatusUnknown, err
  202. }
  203. switch {
  204. case strings.HasPrefix(out, "active"):
  205. return StatusRunning, nil
  206. case strings.HasPrefix(out, "inactive"):
  207. // inactive can also mean its not installed, check unit files
  208. exitCode, out, err := runWithOutput("systemctl", "list-unit-files", "-t", "service", s.Name)
  209. if exitCode == 0 && err != nil {
  210. return StatusUnknown, err
  211. }
  212. if strings.Contains(out, s.Name) {
  213. // unit file exists, installed but not running
  214. return StatusStopped, nil
  215. }
  216. // no unit file
  217. return StatusUnknown, ErrNotInstalled
  218. case strings.HasPrefix(out, "activating"):
  219. return StatusRunning, nil
  220. case strings.HasPrefix(out, "failed"):
  221. return StatusUnknown, errors.New("service in failed state")
  222. default:
  223. return StatusUnknown, ErrNotInstalled
  224. }
  225. }
  226. func (s *systemd) Start() error {
  227. return s.runAction("start")
  228. }
  229. func (s *systemd) Stop() error {
  230. return s.runAction("stop")
  231. }
  232. func (s *systemd) Restart() error {
  233. return s.runAction("restart")
  234. }
  235. func (s *systemd) run(action string, args ...string) error {
  236. if s.isUserService() {
  237. return run("systemctl", append([]string{action, "--user"}, args...)...)
  238. }
  239. return run("systemctl", append([]string{action}, args...)...)
  240. }
  241. func (s *systemd) runAction(action string) error {
  242. return s.run(action, s.Name+".service")
  243. }
  244. const systemdScript = `[Unit]
  245. Description={{.Description}}
  246. ConditionFileIsExecutable={{.Path|cmdEscape}}
  247. {{range $i, $dep := .Dependencies}}
  248. {{$dep}} {{end}}
  249. [Service]
  250. StartLimitInterval=5
  251. StartLimitBurst=10
  252. ExecStart={{.Path|cmdEscape}}{{range .Arguments}} {{.|cmd}}{{end}}
  253. {{if .ChRoot}}RootDirectory={{.ChRoot|cmd}}{{end}}
  254. {{if .WorkingDirectory}}WorkingDirectory={{.WorkingDirectory|cmdEscape}}{{end}}
  255. {{if .UserName}}User={{.UserName}}{{end}}
  256. {{if .ReloadSignal}}ExecReload=/bin/kill -{{.ReloadSignal}} "$MAINPID"{{end}}
  257. {{if .PIDFile}}PIDFile={{.PIDFile|cmd}}{{end}}
  258. {{if and .LogOutput .HasOutputFileSupport -}}
  259. StandardOutput=file:/var/log/{{.Name}}.out
  260. StandardError=file:/var/log/{{.Name}}.err
  261. {{- end}}
  262. {{if gt .LimitNOFILE -1 }}LimitNOFILE={{.LimitNOFILE}}{{end}}
  263. {{if .Restart}}Restart={{.Restart}}{{end}}
  264. {{if .SuccessExitStatus}}SuccessExitStatus={{.SuccessExitStatus}}{{end}}
  265. RestartSec=120
  266. EnvironmentFile=-/etc/sysconfig/{{.Name}}
  267. [Install]
  268. WantedBy=multi-user.target
  269. `