systemd.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package containers
  2. import (
  3. "context"
  4. "os"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/coroot/coroot-node-agent/proc"
  9. "github.com/coreos/go-systemd/v22/dbus"
  10. gdbus "github.com/godbus/dbus/v5"
  11. "k8s.io/klog/v2"
  12. )
  13. var (
  14. dbusConn *dbus.Conn
  15. dbusTimeout = time.Second
  16. )
  17. func init() {
  18. var err error
  19. dbusConn, err = dbus.NewConnection(func() (*gdbus.Conn, error) {
  20. c, err := gdbus.Dial("unix:path=" + proc.HostPath("/run/systemd/private"))
  21. if err != nil {
  22. return nil, err
  23. }
  24. methods := []gdbus.Auth{gdbus.AuthExternal(strconv.Itoa(os.Getuid()))}
  25. if err = c.Auth(methods); err != nil {
  26. dbusConn.Close()
  27. return nil, err
  28. }
  29. return c, nil
  30. })
  31. if err != nil {
  32. klog.Warningln("failed to connect to systemd bus:", err)
  33. }
  34. }
  35. func SystemdTriggeredBy(id string) string {
  36. if dbusConn == nil {
  37. return ""
  38. }
  39. ctx, cancel := context.WithTimeout(context.Background(), dbusTimeout)
  40. defer cancel()
  41. parts := strings.Split(id, "/")
  42. unit := parts[len(parts)-1]
  43. if prop, _ := dbusConn.GetUnitPropertyContext(ctx, unit, "TriggeredBy"); prop != nil {
  44. if values, _ := prop.Value.Value().([]string); len(values) > 0 {
  45. return values[0]
  46. }
  47. }
  48. return ""
  49. }