Skip to content

Commit

Permalink
Run commands as user on systemd when using user service (#224)
Browse files Browse the repository at this point in the history
  • Loading branch information
oliverkra committed Nov 16, 2020
1 parent 60dcbae commit 258d7b2
Showing 1 changed file with 23 additions and 22 deletions.
45 changes: 23 additions & 22 deletions service_systemd_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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
}

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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]
Expand Down

0 comments on commit 258d7b2

Please sign in to comment.