| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- package sdnotify
- import (
- "fmt"
- "net"
- "os"
- "strconv"
- "strings"
- "sync"
- "time"
- )
- // Ready and Watchdog talk to systemd via NOTIFY_SOCKET.
- // This is a process liveness signal only. It is not a Control Lease and
- // not the CPLD/FPGA 30s SET_ALL watchdog.
- var (
- mu sync.Mutex
- conn *net.UnixConn
- )
- func Enabled() bool {
- return os.Getenv("NOTIFY_SOCKET") != ""
- }
- func WatchdogEnabled() bool {
- if os.Getenv("WATCHDOG_USEC") == "" {
- return false
- }
- pid := os.Getenv("WATCHDOG_PID")
- if pid != "" && pid != strconv.Itoa(os.Getpid()) {
- return false
- }
- return true
- }
- func WatchdogInterval() time.Duration {
- usec, err := strconv.ParseUint(os.Getenv("WATCHDOG_USEC"), 10, 64)
- if err != nil || usec == 0 {
- return 0
- }
- return time.Duration(usec/2) * time.Microsecond
- }
- func Ready() error {
- return send("READY=1")
- }
- func Stopping() error {
- return send("STOPPING=1")
- }
- func Watchdog() error {
- return send("WATCHDOG=1")
- }
- func Status(msg string) error {
- return send("STATUS=" + msg)
- }
- func notifyAddr(sock string) *net.UnixAddr {
- if strings.HasPrefix(sock, "@") {
- // Abstract namespace: leading NUL plus the name after '@'.
- return &net.UnixAddr{Name: "\x00" + sock[1:], Net: "unixgram"}
- }
- return &net.UnixAddr{Name: sock, Net: "unixgram"}
- }
- func send(msg string) error {
- sock := os.Getenv("NOTIFY_SOCKET")
- if sock == "" {
- return nil
- }
- mu.Lock()
- defer mu.Unlock()
- if conn == nil {
- c, err := net.DialUnix("unixgram", nil, notifyAddr(sock))
- if err != nil {
- return fmt.Errorf("sdnotify: %w", err)
- }
- conn = c
- }
- _, err := conn.Write([]byte(msg))
- return err
- }
- func Close() {
- mu.Lock()
- defer mu.Unlock()
- if conn != nil {
- _ = conn.Close()
- conn = nil
- }
- }
|