2023-11-21 09:08:49 +00:00
|
|
|
package sdnotify
|
|
|
|
|
|
|
|
import (
|
2024-03-11 14:55:50 +00:00
|
|
|
"errors"
|
2023-11-21 09:08:49 +00:00
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
ReadyEnabled = "READY=1"
|
|
|
|
StoppingEnabled = "STOPPING=1"
|
|
|
|
ReloadingEnabled = "RELOADING=1"
|
|
|
|
)
|
|
|
|
|
2024-03-11 14:55:50 +00:00
|
|
|
var (
|
|
|
|
socket *net.UnixAddr
|
|
|
|
|
|
|
|
errSocketVariableIsNotPresent = errors.New("\"NOTIFY_SOCKET\" environment variable is not present")
|
|
|
|
errSocketIsNotInitialized = errors.New("socket is not initialized")
|
|
|
|
)
|
2023-11-21 09:08:49 +00:00
|
|
|
|
|
|
|
// Initializes socket with provided name of
|
|
|
|
// environment variable.
|
|
|
|
func InitSocket() error {
|
|
|
|
notifySocket := os.Getenv("NOTIFY_SOCKET")
|
|
|
|
if notifySocket == "" {
|
2024-03-11 14:55:50 +00:00
|
|
|
return errSocketVariableIsNotPresent
|
2023-11-21 09:08:49 +00:00
|
|
|
}
|
|
|
|
socket = &net.UnixAddr{
|
|
|
|
Name: notifySocket,
|
|
|
|
Net: "unixgram",
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// FlagAndStatus sends systemd a combination of a
|
|
|
|
// well-known status and STATUS=%s{status}, separated by newline.
|
|
|
|
func FlagAndStatus(status string) error {
|
|
|
|
status += "\nSTATUS=" + strings.TrimSuffix(status, "=1")
|
|
|
|
return Send(status)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Status sends systemd notify STATUS=%s{status}.
|
|
|
|
func Status(status string) error {
|
2024-03-11 14:55:50 +00:00
|
|
|
return Send("STATUS=" + status)
|
2023-11-21 09:08:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Send state through the notify socket if any.
|
|
|
|
// If the notify socket was not detected, it returns an error.
|
|
|
|
func Send(state string) error {
|
|
|
|
if socket == nil {
|
2024-03-11 14:55:50 +00:00
|
|
|
return errSocketIsNotInitialized
|
2023-11-21 09:08:49 +00:00
|
|
|
}
|
|
|
|
conn, err := net.DialUnix(socket.Net, nil, socket)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("can't open unix socket: %v", err)
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
if _, err = conn.Write([]byte(state)); err != nil {
|
|
|
|
return fmt.Errorf("can't write into the unix socket: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|