A cross-platform service manager
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

serviceman.go 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. //go:generate go run -mod=vendor git.rootprojects.org/root/go-gitver
  2. package main
  3. import (
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "strings"
  11. "time"
  12. "git.rootprojects.org/root/go-serviceman/manager"
  13. "git.rootprojects.org/root/go-serviceman/runner"
  14. "git.rootprojects.org/root/go-serviceman/service"
  15. )
  16. var GitRev = "000000000"
  17. var GitVersion = "v0.0.0"
  18. var GitTimestamp = time.Now().Format(time.RFC3339)
  19. func usage() {
  20. fmt.Println("Usage:")
  21. fmt.Println("\tserviceman <command> --help")
  22. fmt.Println("\tserviceman add ./foo-app -- --foo-arg")
  23. fmt.Println("\tserviceman run --config ./foo-app.json")
  24. fmt.Println("\tserviceman start <name>")
  25. fmt.Println("\tserviceman stop <name>")
  26. }
  27. func main() {
  28. if len(os.Args) < 2 {
  29. fmt.Fprintf(os.Stderr, "Too few arguments: %s\n", strings.Join(os.Args, " "))
  30. usage()
  31. os.Exit(1)
  32. }
  33. top := os.Args[1]
  34. os.Args = append(os.Args[:1], os.Args[2:]...)
  35. switch top {
  36. case "version":
  37. fmt.Println(GitVersion, GitTimestamp, GitRev)
  38. case "run":
  39. run()
  40. case "add":
  41. add()
  42. case "start":
  43. start()
  44. case "stop":
  45. stop()
  46. default:
  47. fmt.Fprintf(os.Stderr, "Unknown argument %s\n", top)
  48. usage()
  49. os.Exit(1)
  50. }
  51. }
  52. func add() {
  53. conf := &service.Service{
  54. Restart: true,
  55. }
  56. args := []string{}
  57. for i := range os.Args {
  58. if "--" == os.Args[i] {
  59. if len(os.Args) > i+1 {
  60. args = os.Args[i+1:]
  61. }
  62. os.Args = os.Args[:i]
  63. break
  64. }
  65. }
  66. conf.Argv = args
  67. force := false
  68. forUser := false
  69. forSystem := false
  70. flag.StringVar(&conf.Title, "title", "", "a human-friendly name for the service")
  71. flag.StringVar(&conf.Desc, "desc", "", "a human-friendly description of the service (ex: Foo App)")
  72. flag.StringVar(&conf.Name, "name", "", "a computer-friendly name for the service (ex: foo-app)")
  73. flag.StringVar(&conf.URL, "url", "", "the documentation on home page of the service")
  74. //flag.StringVar(&conf.Workdir, "workdir", "", "the directory in which the service should be started")
  75. flag.StringVar(&conf.ReverseDNS, "rdns", "", "a plist-friendly Reverse DNS name for launchctl (ex: com.example.foo-app)")
  76. flag.BoolVar(&forSystem, "system", false, "attempt to add system service as an unprivileged/unelevated user")
  77. flag.BoolVar(&forUser, "user", false, "add user space / user mode service even when admin/root/sudo/elevated")
  78. flag.BoolVar(&force, "force", false, "if the interpreter or executable doesn't exist, or things don't make sense, try anyway")
  79. flag.StringVar(&conf.User, "username", "", "run the service as this user")
  80. flag.StringVar(&conf.Group, "groupname", "", "run the service as this group")
  81. flag.BoolVar(&conf.PrivilegedPorts, "cap-net-bind", false, "this service should have access to privileged ports")
  82. flag.Parse()
  83. args = flag.Args()
  84. if forUser && forSystem {
  85. fmt.Println("Pfff! You can't --user AND --system! What are you trying to pull?")
  86. os.Exit(1)
  87. return
  88. }
  89. if forUser {
  90. conf.System = false
  91. } else if forSystem {
  92. conf.System = true
  93. } else {
  94. conf.System = manager.IsPrivileged()
  95. }
  96. n := len(args)
  97. if 0 == n {
  98. fmt.Println("Usage: serviceman add ./foo-app -- --foo-arg")
  99. os.Exit(2)
  100. return
  101. }
  102. execpath, err := manager.WhereIs(args[0])
  103. if nil != err {
  104. fmt.Fprintf(os.Stderr, "Error: '%s' could not be found in PATH or working directory.\n", args[0])
  105. if !force {
  106. os.Exit(3)
  107. return
  108. }
  109. } else {
  110. args[0] = execpath
  111. }
  112. conf.Exec = args[0]
  113. args = args[1:]
  114. if n >= 2 {
  115. conf.Interpreter = conf.Exec
  116. conf.Exec = args[0]
  117. conf.Argv = append(args[1:], conf.Argv...)
  118. }
  119. conf.Normalize(force)
  120. //fmt.Printf("\n%#v\n\n", conf)
  121. if conf.System && !manager.IsPrivileged() {
  122. fmt.Fprintf(os.Stderr, "Warning: You may need to use 'sudo' to add %q as a privileged system service.\n", conf.Name)
  123. }
  124. err = manager.Install(conf)
  125. switch e := err.(type) {
  126. case nil:
  127. // do nothing
  128. case *manager.ErrDaemonize:
  129. runAsDaemon(e.DaemonArgs[0], e.DaemonArgs[1:]...)
  130. default:
  131. fmt.Fprintf(os.Stderr, "%s\n", err)
  132. }
  133. printLogMessage(conf)
  134. fmt.Println()
  135. }
  136. func start() {
  137. forUser := false
  138. forSystem := false
  139. flag.BoolVar(&forSystem, "system", false, "attempt to add system service as an unprivileged/unelevated user")
  140. flag.BoolVar(&forUser, "user", false, "add user space / user mode service even when admin/root/sudo/elevated")
  141. flag.Parse()
  142. args := flag.Args()
  143. if 1 != len(args) {
  144. fmt.Println("Usage: serviceman start <name>")
  145. os.Exit(1)
  146. }
  147. if forUser && forSystem {
  148. fmt.Println("Pfff! You can't --user AND --system! What are you trying to pull?")
  149. os.Exit(1)
  150. return
  151. }
  152. conf := &service.Service{
  153. Name: args[0],
  154. Restart: false,
  155. }
  156. if forUser {
  157. conf.System = false
  158. } else if forSystem {
  159. conf.System = true
  160. } else {
  161. conf.System = manager.IsPrivileged()
  162. }
  163. conf.NormalizeWithoutPath()
  164. err := manager.Start(conf)
  165. switch e := err.(type) {
  166. case nil:
  167. // do nothing
  168. case *manager.ErrDaemonize:
  169. runAsDaemon(e.DaemonArgs[0], e.DaemonArgs[1:]...)
  170. default:
  171. fmt.Println(err)
  172. os.Exit(127)
  173. }
  174. }
  175. func stop() {
  176. forUser := false
  177. forSystem := false
  178. flag.BoolVar(&forSystem, "system", false, "attempt to add system service as an unprivileged/unelevated user")
  179. flag.BoolVar(&forUser, "user", false, "add user space / user mode service even when admin/root/sudo/elevated")
  180. flag.Parse()
  181. args := flag.Args()
  182. if 1 != len(args) {
  183. fmt.Println("Usage: serviceman stop <name>")
  184. os.Exit(1)
  185. }
  186. if forUser && forSystem {
  187. fmt.Println("Pfff! You can't --user AND --system! What are you trying to pull?")
  188. os.Exit(1)
  189. return
  190. }
  191. conf := &service.Service{
  192. Name: args[0],
  193. Restart: false,
  194. }
  195. if forUser {
  196. conf.System = false
  197. } else if forSystem {
  198. conf.System = true
  199. } else {
  200. conf.System = manager.IsPrivileged()
  201. }
  202. conf.NormalizeWithoutPath()
  203. if err := manager.Stop(conf); nil != err {
  204. fmt.Println(err)
  205. os.Exit(127)
  206. }
  207. }
  208. func run() {
  209. var confpath string
  210. var daemonize bool
  211. flag.StringVar(&confpath, "config", "", "path to a config file to run")
  212. flag.BoolVar(&daemonize, "daemon", false, "spawn a child process that lives in the background, and exit")
  213. flag.Parse()
  214. if "" == confpath {
  215. fmt.Fprintf(os.Stderr, "%s", strings.Join(flag.Args(), " "))
  216. fmt.Fprintf(os.Stderr, "--config /path/to/config.json is required\n")
  217. usage()
  218. os.Exit(1)
  219. }
  220. b, err := ioutil.ReadFile(confpath)
  221. if nil != err {
  222. fmt.Fprintf(os.Stderr, "Couldn't read config file: %s\n", err)
  223. os.Exit(400)
  224. }
  225. s := &service.Service{}
  226. err = json.Unmarshal(b, s)
  227. if nil != err {
  228. fmt.Fprintf(os.Stderr, "Couldn't JSON parse config file: %s\n", err)
  229. os.Exit(400)
  230. }
  231. m := map[string]interface{}{}
  232. err = json.Unmarshal(b, &m)
  233. if nil != err {
  234. fmt.Fprintf(os.Stderr, "Couldn't JSON parse config file: %s\n", err)
  235. os.Exit(400)
  236. }
  237. // default Restart to true
  238. if _, ok := m["restart"]; !ok {
  239. s.Restart = true
  240. }
  241. if "" == s.Exec {
  242. fmt.Fprintf(os.Stderr, "Missing exec\n")
  243. os.Exit(400)
  244. }
  245. force := false
  246. s.Normalize(force)
  247. fmt.Printf("All output will be directed to the logs at:\n\t%s\n", s.Logdir)
  248. err = os.MkdirAll(s.Logdir, 0755)
  249. if nil != err {
  250. fmt.Fprintf(os.Stderr, "%s\n", err)
  251. return
  252. }
  253. if !daemonize {
  254. //fmt.Fprintf(os.Stdout, "Running %s %s %s\n", s.Interpreter, s.Exec, strings.Join(s.Argv, " "))
  255. if err := runner.Start(s); nil != err {
  256. fmt.Println("Error:", err)
  257. }
  258. return
  259. }
  260. runAsDaemon(os.Args[0], "run", "--config", confpath)
  261. }
  262. func runAsDaemon(bin string, args ...string) {
  263. cmd := exec.Command(bin, args...)
  264. // for debugging
  265. /*
  266. out, err := cmd.CombinedOutput()
  267. if nil != err {
  268. fmt.Println(err)
  269. }
  270. fmt.Println(string(out))
  271. */
  272. err := cmd.Start()
  273. if nil != err {
  274. fmt.Fprintf(os.Stderr, "%s\n", err)
  275. os.Exit(500)
  276. }
  277. }