Skip to content

Commit 586b8f6

Browse files
committed
dbus: add GetUnitFileState method
1 parent 87511f3 commit 586b8f6

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

dbus/methods.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -830,3 +830,18 @@ func (c *Conn) listJobsInternal(ctx context.Context) ([]JobStatus, error) {
830830

831831
return status, nil
832832
}
833+
834+
// GetUnitFileStateContext returns UnitFileState
835+
func (c *Conn) GetUnitFileStateContext(ctx context.Context, name string) (string, error) {
836+
var prop dbus.Variant
837+
obj := c.sysconn.Object("org.freedesktop.systemd1", "/org/freedesktop/systemd1")
838+
err := obj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.GetUnitFileState", 0, name).Store(&prop)
839+
if err != nil {
840+
return "", err
841+
}
842+
state, ok := prop.Value().(string)
843+
if !ok {
844+
return "", fmt.Errorf("failed to cast UnitFileState prop to string")
845+
}
846+
return state, nil
847+
}

dbus/methods_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@
1515
package dbus
1616

1717
import (
18+
"context"
1819
"fmt"
1920
"os"
2021
"os/exec"
2122
"path"
2223
"path/filepath"
2324
"reflect"
25+
"strings"
2426
"syscall"
2527
"testing"
2628
"time"
@@ -1600,3 +1602,28 @@ func TestUnitName(t *testing.T) {
16001602
}
16011603
}
16021604
}
1605+
1606+
// TestGetUnitFileState reads the `systemd-udevd.service` which should exist on all systemd
1607+
// systems and ensures that UnitFileState property is valid.
1608+
func TestGetUnitFileState(t *testing.T) {
1609+
conn := setupConn(t)
1610+
defer conn.Close()
1611+
service := "systemd-udevd.service"
1612+
got, err := conn.GetUnitFileStateContext(context.Background(), service)
1613+
if err != nil {
1614+
t.Fatal(err)
1615+
}
1616+
ok := false
1617+
// valid UnitFileState values
1618+
validUnitFileStates := []string{"enabled", "disabled", "static", "bad"}
1619+
for _, v := range validUnitFileStates {
1620+
if got == v {
1621+
ok = true
1622+
break
1623+
}
1624+
}
1625+
if !ok {
1626+
t.Errorf("invalid UnitFileState returned from GetUnitFileState(%s): got %s, want one of [%s]",
1627+
service, got, strings.Join(validUnitFileStates, ", "))
1628+
}
1629+
}

0 commit comments

Comments
 (0)