Skip to content

Commit 6bdf704

Browse files
author
Dylan Ratcliffe
committed
dbus: add ability to query by pid
Allows users to get the unit name by PID. Similar to `systemctl status {pid}`
1 parent f9f2546 commit 6bdf704

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

dbus/methods.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,24 @@ func (c *Conn) listUnitsInternal(f storeFunc) ([]UnitStatus, error) {
417417
return status, nil
418418
}
419419

420+
func (c *Conn) getUnitInternal(f storeFunc) (string, error) {
421+
var result dbus.ObjectPath
422+
423+
err := f(&result)
424+
425+
// Nothing in this library actually accepts a dbus.ObjectPath, so it's much
426+
// more useful as a name
427+
name := unitName(result)
428+
429+
return name, err
430+
}
431+
432+
// GetUnitByPIDContext returns the unit name for a given PID. The PID must refer
433+
// to an existing system process
434+
func (c *Conn) GetUnitByPIDContext(ctx context.Context, pid uint32) (string, error) {
435+
return c.getUnitInternal(c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.GetUnitByPID", 0, pid).Store)
436+
}
437+
420438
// Deprecated: use ListUnitsContext instead.
421439
func (c *Conn) ListUnits() ([]UnitStatus, error) {
422440
return c.ListUnitsContext(context.Background())

dbus/methods_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,22 @@ func TestReloadOrRestartUnit(t *testing.T) {
450450
}
451451
}
452452

453+
// Ensure that GetUnitByPIDContext works.
454+
func TestGetUnitByPIDContext(t *testing.T) {
455+
conn := setupConn(t)
456+
defer conn.Close()
457+
458+
name, err := conn.GetUnitByPIDContext(context.Background(), 1)
459+
460+
if err != nil {
461+
t.Error(err)
462+
}
463+
464+
if name == "" {
465+
t.Fatal("name is empty")
466+
}
467+
}
468+
453469
// Ensure that ListUnitsByNames works.
454470
func TestListUnitsByNames(t *testing.T) {
455471
target1 := "systemd-journald.service"

0 commit comments

Comments
 (0)