From ff1da9655191e658c89ef90fca2d1cbe27379621 Mon Sep 17 00:00:00 2001 From: tomfeigin Date: Wed, 27 Apr 2022 15:10:17 +0300 Subject: [PATCH] Run systemd commands with --user flag (#310) When controlling a user service with systemd supply the --user flag --- .gitignore | 1 + service_systemd_linux.go | 13 ++++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index e69de29..dbe9c82 100644 --- a/.gitignore +++ b/.gitignore @@ -0,0 +1 @@ +.vscode/ \ No newline at end of file diff --git a/service_systemd_linux.go b/service_systemd_linux.go index 3dfcf8a..77dc013 100644 --- a/service_systemd_linux.go +++ b/service_systemd_linux.go @@ -90,7 +90,7 @@ func (s *systemd) unitName() string { } func (s *systemd) getSystemdVersion() int64 { - _, out, err := runWithOutput("systemctl", "--version") + _, out, err := s.runWithOutput("systemctl", "--version") if err != nil { return -1 } @@ -234,7 +234,7 @@ func (s *systemd) Run() (err error) { } func (s *systemd) Status() (Status, error) { - exitCode, out, err := runWithOutput("systemctl", "is-active", s.unitName()) + exitCode, out, err := s.runWithOutput("systemctl", "is-active", s.unitName()) if exitCode == 0 && err != nil { return StatusUnknown, err } @@ -244,7 +244,7 @@ func (s *systemd) Status() (Status, error) { return StatusRunning, nil case strings.HasPrefix(out, "inactive"): // inactive can also mean its not installed, check unit files - exitCode, out, err := runWithOutput("systemctl", "list-unit-files", "-t", "service", s.unitName()) + exitCode, out, err := s.runWithOutput("systemctl", "list-unit-files", "-t", "service", s.unitName()) if exitCode == 0 && err != nil { return StatusUnknown, err } @@ -275,6 +275,13 @@ func (s *systemd) Restart() error { return s.runAction("restart") } +func (s *systemd) runWithOutput(command string, arguments ...string) (int, string, error) { + if s.isUserService() { + arguments = append(arguments, "--user") + } + return runWithOutput(command, arguments...) +} + func (s *systemd) run(action string, args ...string) error { if s.isUserService() { return run("systemctl", append([]string{action, "--user"}, args...)...)