Skip to content

Commit

Permalink
dbus: add options for name & path
Browse files Browse the repository at this point in the history
PID-based queries can now return either a name or a path
  • Loading branch information
dylanratcliffe committed Dec 13, 2021
1 parent 6bdf704 commit fd56b73
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
27 changes: 16 additions & 11 deletions dbus/methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -417,22 +417,27 @@ func (c *Conn) listUnitsInternal(f storeFunc) ([]UnitStatus, error) {
return status, nil
}

func (c *Conn) getUnitInternal(f storeFunc) (string, error) {
// GetUnitByPID returns the unit object path of the unit a process ID
// belongs to. It takes a UNIX PID and returns the object path. The PID must
// refer to an existing system process
func (c *Conn) GetUnitByPID(ctx context.Context, pid uint32) (dbus.ObjectPath, error) {
var result dbus.ObjectPath

err := f(&result)

// Nothing in this library actually accepts a dbus.ObjectPath, so it's much
// more useful as a name
name := unitName(result)
err := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.GetUnitByPID", 0, pid).Store(&result)

return name, err
return result, err
}

// GetUnitByPIDContext returns the unit name for a given PID. The PID must refer
// to an existing system process
func (c *Conn) GetUnitByPIDContext(ctx context.Context, pid uint32) (string, error) {
return c.getUnitInternal(c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.GetUnitByPID", 0, pid).Store)
// GetUnitNameByPID returns the name of the unit a process ID belongs to. It
// takes a UNIX PID and returns the object path. The PID must refer to an
// existing system process
func (c *Conn) GetUnitNameByPID(ctx context.Context, pid uint32) (string, error) {
path, err := c.GetUnitByPID(ctx, pid)
if err != nil {
return "", err
}

return unitName(path), nil
}

// Deprecated: use ListUnitsContext instead.
Expand Down
22 changes: 19 additions & 3 deletions dbus/methods_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,12 +450,28 @@ func TestReloadOrRestartUnit(t *testing.T) {
}
}

// Ensure that GetUnitByPIDContext works.
func TestGetUnitByPIDContext(t *testing.T) {
// Ensure that GetUnitByPID works.
func TestGetUnitByPID(t *testing.T) {
conn := setupConn(t)
defer conn.Close()

name, err := conn.GetUnitByPIDContext(context.Background(), 1)
path, err := conn.GetUnitByPID(context.Background(), 1)

if err != nil {
t.Error(err)
}

if path == "" {
t.Fatal("path is empty")
}
}

// Ensure that GetUnitNameByPID works.
func TestGetUnitNameByPID(t *testing.T) {
conn := setupConn(t)
defer conn.Close()

name, err := conn.GetUnitNameByPID(context.Background(), 1)

if err != nil {
t.Error(err)
Expand Down

0 comments on commit fd56b73

Please sign in to comment.