sdnotify.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package sdnotify
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. )
  11. // Ready and Watchdog talk to systemd via NOTIFY_SOCKET.
  12. // This is a process liveness signal only. It is not a Control Lease and
  13. // not the CPLD/FPGA 30s SET_ALL watchdog.
  14. var (
  15. mu sync.Mutex
  16. conn *net.UnixConn
  17. )
  18. func Enabled() bool {
  19. return os.Getenv("NOTIFY_SOCKET") != ""
  20. }
  21. func WatchdogEnabled() bool {
  22. if os.Getenv("WATCHDOG_USEC") == "" {
  23. return false
  24. }
  25. pid := os.Getenv("WATCHDOG_PID")
  26. if pid != "" && pid != strconv.Itoa(os.Getpid()) {
  27. return false
  28. }
  29. return true
  30. }
  31. func WatchdogInterval() time.Duration {
  32. usec, err := strconv.ParseUint(os.Getenv("WATCHDOG_USEC"), 10, 64)
  33. if err != nil || usec == 0 {
  34. return 0
  35. }
  36. return time.Duration(usec/2) * time.Microsecond
  37. }
  38. func Ready() error {
  39. return send("READY=1")
  40. }
  41. func Stopping() error {
  42. return send("STOPPING=1")
  43. }
  44. func Watchdog() error {
  45. return send("WATCHDOG=1")
  46. }
  47. func Status(msg string) error {
  48. return send("STATUS=" + msg)
  49. }
  50. func notifyAddr(sock string) *net.UnixAddr {
  51. if strings.HasPrefix(sock, "@") {
  52. // Abstract namespace: leading NUL plus the name after '@'.
  53. return &net.UnixAddr{Name: "\x00" + sock[1:], Net: "unixgram"}
  54. }
  55. return &net.UnixAddr{Name: sock, Net: "unixgram"}
  56. }
  57. func send(msg string) error {
  58. sock := os.Getenv("NOTIFY_SOCKET")
  59. if sock == "" {
  60. return nil
  61. }
  62. mu.Lock()
  63. defer mu.Unlock()
  64. if conn == nil {
  65. c, err := net.DialUnix("unixgram", nil, notifyAddr(sock))
  66. if err != nil {
  67. return fmt.Errorf("sdnotify: %w", err)
  68. }
  69. conn = c
  70. }
  71. _, err := conn.Write([]byte(msg))
  72. return err
  73. }
  74. func Close() {
  75. mu.Lock()
  76. defer mu.Unlock()
  77. if conn != nil {
  78. _ = conn.Close()
  79. conn = nil
  80. }
  81. }