From 258d7b252b5a4cf34f17709a7f73aa78e7db4df9 Mon Sep 17 00:00:00 2001 From: Oliver Kraemer Date: Mon, 16 Nov 2020 11:55:05 -0300 Subject: [PATCH] Run commands as user on systemd when using user service (#224) --- service_systemd_linux.go | 45 ++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/service_systemd_linux.go b/service_systemd_linux.go index bfb7a99..36fb265 100644 --- a/service_systemd_linux.go +++ b/service_systemd_linux.go @@ -68,7 +68,7 @@ func (s *systemd) Platform() string { } func (s *systemd) configPath() (cp string, err error) { - if !s.Option.bool(optionUserService, optionUserServiceDefault) { + if !s.isUserService() { cp = "/etc/systemd/system/" + s.Config.Name + ".service" return } @@ -81,7 +81,7 @@ func (s *systemd) configPath() (cp string, err error) { if err != nil { return } - cp = filepath.Join(systemdUserDir, s.Config.Name + ".service") + cp = filepath.Join(systemdUserDir, s.Config.Name+".service") return } @@ -129,6 +129,10 @@ func (s *systemd) template() *template.Template { } } +func (s *systemd) isUserService() bool { + return s.Option.bool(optionUserService, optionUserServiceDefault) +} + func (s *systemd) Install() error { confPath, err := s.configPath() if err != nil { @@ -177,30 +181,16 @@ func (s *systemd) Install() error { return err } - if s.Option.bool(optionUserService, optionUserServiceDefault) { - err = run("systemctl", "enable", "--user", s.Name+".service") - } else { - err = run("systemctl", "enable", s.Name+".service") - } + err = s.runAction("enable") if err != nil { return err } - if s.Option.bool(optionUserService, optionUserServiceDefault) { - err = run("systemctl", "daemon-reload", "--user") - } else { - err = run("systemctl", "daemon-reload") - } - return err + return s.run("daemon-reload") } func (s *systemd) Uninstall() error { - var err error - if s.Option.bool(optionUserService, optionUserServiceDefault) { - err = run("systemctl", "disable", "--user", s.Name+".service") - } else { - err = run("systemctl", "disable", s.Name+".service") - } + err := s.runAction("disable") if err != nil { return err } @@ -270,15 +260,26 @@ func (s *systemd) Status() (Status, error) { } func (s *systemd) Start() error { - return run("systemctl", "start", s.Name+".service") + return s.runAction("start") } func (s *systemd) Stop() error { - return run("systemctl", "stop", s.Name+".service") + return s.runAction("stop") } func (s *systemd) Restart() error { - return run("systemctl", "restart", s.Name+".service") + return s.runAction("restart") +} + +func (s *systemd) run(action string, args ...string) error { + if s.isUserService() { + return run("systemctl", append([]string{action, "--user"}, args...)...) + } + return run("systemctl", append([]string{action}, args...)...) +} + +func (s *systemd) runAction(action string) error { + return s.run(action, s.Name+".service") } const systemdScript = `[Unit]