Skip to content

Commit

Permalink
Merge pull request coreos#385 from dylanratcliffe/get-unit-pid
Browse files Browse the repository at this point in the history
dbus: add support for querying unit by PID
  • Loading branch information
Luca Bruno committed Dec 13, 2021
2 parents f9f2546 + fd56b73 commit f5a75de
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
23 changes: 23 additions & 0 deletions dbus/methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,29 @@ func (c *Conn) listUnitsInternal(f storeFunc) ([]UnitStatus, error) {
return status, nil
}

// 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 := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.GetUnitByPID", 0, pid).Store(&result)

return result, err
}

// 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.
func (c *Conn) ListUnits() ([]UnitStatus, error) {
return c.ListUnitsContext(context.Background())
Expand Down
32 changes: 32 additions & 0 deletions dbus/methods_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,38 @@ func TestReloadOrRestartUnit(t *testing.T) {
}
}

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

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)
}

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

// Ensure that ListUnitsByNames works.
func TestListUnitsByNames(t *testing.T) {
target1 := "systemd-journald.service"
Expand Down

0 comments on commit f5a75de

Please sign in to comment.