-
Notifications
You must be signed in to change notification settings - Fork 2
/
fork.go
141 lines (112 loc) · 2.36 KB
/
fork.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package forker
import (
"flag"
"github.com/valyala/fasthttp/reuseport"
"net"
"os"
"os/exec"
"runtime"
)
const (
childFlag = "-child"
_defaultNetwork = TCP4
)
type processSignal struct {
pid int
err error
}
func init() {
flag.Bool(childFlag[1:], false, "is forker child process")
}
func (f *Fork) forker(address string) (err error) {
if !f.ReusePort {
if runtime.GOOS == "windows" {
return ErrReuseportOnWindows
}
if err = f.setTCPListenerFiles(address); err != nil {
return
}
defer func() {
if e := f.ln.Close(); e != nil {
err = e
}
}()
}
goMaxProcess := runtime.GOMAXPROCS(0)
sigCh := make(chan processSignal, goMaxProcess)
childProcess := make(map[int]*exec.Cmd)
defer func() {
for _, proc := range childProcess {
_ = proc.Process.Kill()
}
}()
for i := 0; i < goMaxProcess; i++ {
var cmd *exec.Cmd
cmd, err = f.doCmd()
if err != nil {
return err
}
pid := cmd.Process.Pid
childProcess[pid] = cmd
f.childsPid = append(f.childsPid, pid)
go func() {
sigCh <- processSignal{cmd.Process.Pid, cmd.Wait()}
}()
}
var exitedProcess int
for sig := range sigCh {
delete(childProcess, sig.pid)
if exitedProcess++; exitedProcess > f.recoverChild {
err = ErrOverRecovery
break
}
var cmd *exec.Cmd
if cmd, err = f.doCmd(); err != nil {
break
}
childProcess[cmd.Process.Pid] = cmd
go func() {
sigCh <- processSignal{cmd.Process.Pid, cmd.Wait()}
}()
}
return nil
}
func (f *Fork) listen(address string) (net.Listener, error) {
runtime.GOMAXPROCS(1)
if f.ReusePort {
return reuseport.Listen(f.Network.String(), address)
}
return net.FileListener(os.NewFile(3, ""))
}
func (f *Fork) setTCPListenerFiles(address string) error {
tcpAddr, err := net.ResolveTCPAddr(f.Network.String(), address)
if err != nil {
return err
}
tcpListener, err := net.ListenTCP(f.Network.String(), tcpAddr)
if err != nil {
return err
}
f.ln = tcpListener
file, err := tcpListener.File()
if err != nil {
return err
}
f.files = []*os.File{file}
return nil
}
func (f *Fork) doCmd() (*exec.Cmd, error) {
cmd := exec.Command(os.Args[0], append(os.Args[1:], childFlag)...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.ExtraFiles = f.files
return cmd, cmd.Start()
}
func isChild() bool {
for _, arg := range os.Args[1:] {
if arg == childFlag {
return true
}
}
return false
}