Dmitrii Stepanov
d433b49265
All checks were successful
DCO action / DCO (pull_request) Successful in 2m40s
Vulncheck / Vulncheck (pull_request) Successful in 3m41s
Build / Build Components (1.20) (pull_request) Successful in 4m27s
Build / Build Components (1.21) (pull_request) Successful in 5m6s
Tests and linters / Staticcheck (pull_request) Successful in 6m16s
Tests and linters / gopls check (pull_request) Successful in 6m23s
Tests and linters / Lint (pull_request) Successful in 6m48s
Tests and linters / Tests (1.20) (pull_request) Successful in 9m4s
Tests and linters / Tests with -race (pull_request) Successful in 9m9s
Tests and linters / Tests (1.21) (pull_request) Successful in 9m23s
`fmt.Errorf can be replaced with errors.New` and `fmt.Sprintf can be replaced with string addition` Signed-off-by: Dmitrii Stepanov <d.stepanov@yadro.com>
65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
package sdnotify
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
const (
|
|
ReadyEnabled = "READY=1"
|
|
StoppingEnabled = "STOPPING=1"
|
|
ReloadingEnabled = "RELOADING=1"
|
|
)
|
|
|
|
var (
|
|
socket *net.UnixAddr
|
|
|
|
errSocketVariableIsNotPresent = errors.New("\"NOTIFY_SOCKET\" environment variable is not present")
|
|
errSocketIsNotInitialized = errors.New("socket is not initialized")
|
|
)
|
|
|
|
// Initializes socket with provided name of
|
|
// environment variable.
|
|
func InitSocket() error {
|
|
notifySocket := os.Getenv("NOTIFY_SOCKET")
|
|
if notifySocket == "" {
|
|
return errSocketVariableIsNotPresent
|
|
}
|
|
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 {
|
|
return Send("STATUS=" + status)
|
|
}
|
|
|
|
// 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 {
|
|
return errSocketIsNotInitialized
|
|
}
|
|
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
|
|
}
|