/
daemon.go
97 lines (78 loc) · 1.51 KB
/
daemon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package sd
import "net"
import "os"
import "strconv"
import "strings"
import "syscall"
const START_FD int = 3
type FileDescriptor struct {
fd int
name string
}
type FD interface {
FD() int
Name() string
Listener() (net.Listener, error)
}
func (l FileDescriptor) FD() int {
return l.fd
}
func (l FileDescriptor) Name() string {
return l.name
}
func (l FileDescriptor) Listener() (net.Listener, error) {
return net.FileListener(os.NewFile(uintptr(l.fd), l.name))
}
func ListenPID() int {
pid, err := strconv.ParseInt(os.Getenv("LISTEN_PID"), 10, 16)
if err != nil {
return 0
} else {
return int(pid)
}
}
func ListenFDs() int {
if ListenPID() != os.Getpid() {
return 0
}
fds, err := strconv.ParseInt(os.Getenv("LISTEN_FDS"), 10, 16)
if err != nil {
return 0
} else {
return int(fds)
}
}
func ListenFDNames() []string {
return strings.Split(os.Getenv("LISTEN_FDNAMES"), ":")
}
func Listeners() []FileDescriptor {
fds := ListenFDs()
names := ListenFDNames()
ls := make([]FileDescriptor, fds)
for i := 0; i < fds; i++ {
ls[i].fd = START_FD + i
ls[i].name = names[i]
}
return ls
}
func Notify(state string, fds ...int) {
ns := os.Getenv("NOTIFY_SOCKET")
if ns == "" {
return
}
addr := &net.UnixAddr{
Name: ns,
Net: "unixgram",
}
conn, err := net.DialUnix("unixgram", nil, addr)
if err != nil {
return
}
defer conn.Close()
if len(fds) > 0 {
rights := syscall.UnixRights(fds...)
conn.WriteMsgUnix([]byte(state), rights, nil)
} else {
conn.Write([]byte(state))
}
}