-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
96 lines (84 loc) · 1.69 KB
/
util.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
package master
import (
"net"
"os"
"runtime"
)
var (
booted bool
workerEntity *worker
)
func Listeners(resolveAddrFunc func() []string) []*Listener {
if booted {
panic("this package is only allowed to be called once")
}
booted = true
var (
err error
listeners = getParentListeners()
)
if len(listeners) == 0 && runtime.GOOS == "linux" {
masterEntity := newMaster(resolveAddrFunc)
masterEntity.run()
}
if len(listeners) == 0 {
addresses := resolveAddrFunc()
if len(addresses) == 0 {
panic("getAddrFunc resolve empty addr")
}
if listeners, err = createListenersWithAddr(addresses); err != nil {
panic(err)
}
}
workerEntity = newWorker(listeners)
go workerEntity.run()
return workerEntity.listeners()
}
func Wait() {
if workerEntity != nil {
workerEntity.waitQuit()
}
}
func RegisterExitEvent(event func()) {
if workerEntity != nil {
workerEntity.registerExitEvent(event)
}
}
func createListenersWithAddr(addresses []string) (lns []*Listener, err error) {
var (
ln net.Listener
tcpAddr *net.TCPAddr
)
defer func() {
if err != nil {
for _, ln = range lns {
_ = ln.Close()
}
}
}()
for _, v := range addresses {
if tcpAddr, err = net.ResolveTCPAddr("tcp", v); err != nil {
return nil, err
}
if ln, err = net.ListenTCP("tcp", tcpAddr); err != nil {
return nil, err
}
lns = append(lns, &Listener{Listener: ln})
}
return
}
func getParentListeners() (lns []*Listener) {
var (
err error
file *os.File
ln net.Listener
)
for i := 3; ; i++ {
file = os.NewFile(uintptr(i), "")
if ln, err = net.FileListener(file); err != nil {
break
}
lns = append(lns, &Listener{Listener: ln, file: file})
}
return
}