Skip to content

Commit ada3e13

Browse files
committed
feat(dbus): add GetUnitProperty interface
1 parent 3207a34 commit ada3e13

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

dbus/methods.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,28 @@ func (c *Conn) GetUnitProperties(unit string) (map[string]interface{}, error) {
167167
return c.getProperties(unit, "org.freedesktop.systemd1.Unit")
168168
}
169169

170+
func (c *Conn) getProperty(unit string, dbusInterface string, propertyName string) (*Property, error) {
171+
var err error
172+
var prop dbus.Variant
173+
174+
path := ObjectPath("/org/freedesktop/systemd1/unit/" + unit)
175+
if !path.IsValid() {
176+
return nil, errors.New("invalid unit name: " + unit)
177+
}
178+
179+
obj := c.sysconn.Object("org.freedesktop.systemd1", path)
180+
err = obj.Call("org.freedesktop.DBus.Properties.Get", 0, dbusInterface, propertyName).Store(&prop)
181+
if err != nil {
182+
return nil, err
183+
}
184+
185+
return &Property{Name: propertyName, Value: prop}, nil
186+
}
187+
188+
func (c *Conn) GetUnitProperty(unit string, propertyName string) (*Property, error) {
189+
return c.getProperty(unit, "org.freedesktop.systemd1.Unit", propertyName)
190+
}
191+
170192
// GetUnitTypeProperties returns the extra properties for a unit, specific to the unit type.
171193
// Valid values for unitType: Service, Socket, Target, Device, Mount, Automount, Snapshot, Timer, Swap, Path, Slice, Scope
172194
// return "dbus.Error: Unknown interface" if the unitType is not the correct type of the unit

dbus/methods_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"math/rand"
2222
"os"
2323
"path/filepath"
24+
"reflect"
2425
"testing"
2526
)
2627

@@ -142,6 +143,20 @@ func TestGetUnitProperties(t *testing.T) {
142143
if names[0] != "system.slice" {
143144
t.Fatal("unexpected wants for /")
144145
}
146+
147+
prop, err := conn.GetUnitProperty(unit, "Wants")
148+
if err != nil {
149+
t.Fatal(err)
150+
}
151+
152+
if prop.Name != "Wants" {
153+
t.Fatal("unexpected property name")
154+
}
155+
156+
val := prop.Value.Value().([]string)
157+
if !reflect.DeepEqual(val, names) {
158+
t.Fatal("unexpected property value")
159+
}
145160
}
146161

147162
// TestGetUnitPropertiesRejectsInvalidName attempts to get the properties for a
@@ -153,7 +168,11 @@ func TestGetUnitPropertiesRejectsInvalidName(t *testing.T) {
153168
unit := "//invalid#$^/"
154169

155170
_, err := conn.GetUnitProperties(unit)
171+
if err == nil {
172+
t.Fatal("Expected an error, got nil")
173+
}
156174

175+
_, err = conn.GetUnitProperty(unit, "Wants")
157176
if err == nil {
158177
t.Fatal("Expected an error, got nil")
159178
}

0 commit comments

Comments
 (0)