From 91ed3d4fbf1772284141179088ba8d153aa84e94 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Wed, 1 Mar 2017 16:50:09 -0800 Subject: [PATCH] Add a utility to run a pid in a systemd scope Signed-off-by: Mrunal Patel --- utils/utils.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/utils/utils.go b/utils/utils.go index 0db64aaf..b5d29a4f 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -7,6 +7,9 @@ import ( "os/exec" "strings" "syscall" + + systemdDbus "github.com/coreos/go-systemd/dbus" + "github.com/godbus/dbus" ) // ExecCmd executes a command with args and returns its output as a string along @@ -54,3 +57,27 @@ func Prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) { func StatusToExitCode(status int) int { return ((status) & 0xff00) >> 8 } + +// RunUnderSystemdScope adds the specified pid to a systemd scope +func RunUnderSystemdScope(pid int, slice string, unitName string) error { + var properties []systemdDbus.Property + conn, err := systemdDbus.New() + if err != nil { + return err + } + properties = append(properties, systemdDbus.PropSlice(slice)) + properties = append(properties, newProp("PIDs", []uint32{uint32(pid)})) + properties = append(properties, newProp("Delegate", true)) + properties = append(properties, newProp("DefaultDependencies", false)) + if _, err := conn.StartTransientUnit(unitName, "replace", properties, nil); err != nil { + return err + } + return nil +} + +func newProp(name string, units interface{}) systemdDbus.Property { + return systemdDbus.Property{ + Name: name, + Value: dbus.MakeVariant(units), + } +}