From 523f1ea67f990d4fbaba4a7adb216735d1784e6c Mon Sep 17 00:00:00 2001 From: igophper <34326532+igophper@users.noreply.github.com> Date: Mon, 23 Oct 2023 10:37:35 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=E5=88=A4=E6=96=ADsys?= =?UTF-8?q?temctl=E7=9A=84service=E6=96=87=E4=BB=B6=E6=98=AF=E5=90=A6?= =?UTF-8?q?=E5=AD=98=E5=9C=A8=E5=87=BD=E6=95=B0=20(#2615)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/utils/systemctl/systemctl.go | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/backend/utils/systemctl/systemctl.go b/backend/utils/systemctl/systemctl.go index 7d370cc0a..ee981880f 100644 --- a/backend/utils/systemctl/systemctl.go +++ b/backend/utils/systemctl/systemctl.go @@ -2,10 +2,8 @@ package systemctl import ( "fmt" - "os/exec" - "strings" - "github.com/pkg/errors" + "os/exec" ) func RunSystemCtl(args ...string) (string, error) { @@ -33,12 +31,21 @@ func IsEnable(serviceName string) (bool, error) { return out == "enabled\n", nil } +// IsExist checks if a service exists. func IsExist(serviceName string) (bool, error) { - out, err := RunSystemCtl("list-unit-files") + cmd := exec.Command("systemctl", "is-enabled", serviceName) + output, err := cmd.CombinedOutput() if err != nil { - return false, err + // If the command fails, check if the output indicates that the service does not exist. + if string(output) == fmt.Sprintf("Failed to get unit file state for %s.service: No such file or directory\n", serviceName) { + // Return false if the service does not exist. + return false, nil + } + // Return an error if the command fails. + return false, fmt.Errorf("failed to run command: %w", err) } - return strings.Contains(out, serviceName+".service"), nil + // Return true if the service exists. + return true, nil } func handlerErr(out string, err error) error {