From 16c07fde4b42101f016661d2406186b7d3394d17 Mon Sep 17 00:00:00 2001 From: Tim Serong Date: Wed, 21 Aug 2024 16:23:06 +1000 Subject: [PATCH] feat: Add TryRestartService() This is just like the existing RestartService() function, except it only applies to services that are already running. Related issue: https://github.com/harvester/harvester/issues/5274 Signed-off-by: Tim Serong --- sys/systemd-dbus.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/sys/systemd-dbus.go b/sys/systemd-dbus.go index 0e00c68..b5e580f 100644 --- a/sys/systemd-dbus.go +++ b/sys/systemd-dbus.go @@ -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) @@ -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 +}