systemd.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. klog "github.com/sirupsen/logrus"
  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. if dbusConn != nil { // 添加这个非空检查
  27. dbusConn.Close()
  28. }
  29. return nil, err
  30. }
  31. return c, nil
  32. })
  33. if err != nil {
  34. klog.Warningln("failed to connect to systemd bus:", err)
  35. }
  36. }
  37. func SystemdTriggeredBy(id string) string {
  38. if dbusConn == nil {
  39. return ""
  40. }
  41. ctx, cancel := context.WithTimeout(context.Background(), dbusTimeout)
  42. defer cancel()
  43. parts := strings.Split(id, "/")
  44. unit := parts[len(parts)-1]
  45. if prop, _ := dbusConn.GetUnitPropertyContext(ctx, unit, "TriggeredBy"); prop != nil {
  46. if values, _ := prop.Value.Value().([]string); len(values) > 0 {
  47. return values[0]
  48. }
  49. }
  50. return ""
  51. }