Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add TryRestartService() #19

Merged
merged 1 commit into from
Aug 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions sys/systemd-dbus.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/sirupsen/logrus"
)

// RestartService restarts a service. If the service isn't already running it will be started.
func RestartService(unit string) error {
ctx := context.Background()
conn, err := dbus.NewWithContext(ctx)
Expand All @@ -21,3 +22,20 @@ func RestartService(unit string) error {
}
return nil
}

// TryRestartService will restart a service, but only if it's currently running.
// A service that isn't running won't be affected.
func TryRestartService(unit string) error {
ctx := context.Background()
conn, err := dbus.NewWithContext(ctx)
if err != nil {
logrus.Errorf("Failed to create new connection for systemd. err: %v", err)
return err
}
responseChan := make(chan string, 1)
if _, err := conn.TryRestartUnitContext(ctx, unit, "fail", responseChan); err != nil {
logrus.Errorf("Failed to restart service %s. err: %v", unit, err)
return err
}
return nil
}
Loading