-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
204 lines (187 loc) · 4.12 KB
/
server.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package graceful
import (
"context"
"errors"
"fmt"
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
type serverInfo struct {
network string
address string
server Server
listener net.Listener
}
var (
// ErrStarted means the servers already started
ErrStarted = errors.New("already started")
// ErrConflict means the current server already added
ErrConflict = errors.New("address conflict")
// ErrUnsupported means the listener type is not supported
ErrUnsupported = errors.New("unsupported listener type")
)
var (
servers []serverInfo
started bool
lock sync.Mutex
)
// AddServer adds a server's info to the servers
func AddServer(network, address string, server Server) error {
lock.Lock()
defer lock.Unlock()
// must not add a server after servers started
if started {
return ErrStarted
}
var found bool
for _, svr := range servers {
if svr.network == network && svr.address == address {
found = true
}
}
if !found {
servers = append(servers, serverInfo{
network: network,
address: address,
server: server,
})
} else {
return ErrConflict
}
return nil
}
// RunServers runs all servers added in the global "servers"
func RunServers(startWait, shutdownWait time.Duration) (err error) {
if err = Init(nil); err != nil {
return
}
lock.Lock()
defer lock.Unlock()
started = true
// get listeners from inherited files or create them
if isGraceful {
if len(inheritedFiles) < len(servers) {
return fmt.Errorf("inherited files not enough, need %d but got %d", len(servers), len(inheritedFiles))
}
for idx := range servers {
servers[idx].listener, err = net.FileListener(inheritedFiles[idx])
if err != nil {
return
}
}
} else {
for idx := range servers {
info := &servers[idx]
info.listener, err = net.Listen(info.network, info.address)
if err != nil {
return
}
}
}
var wg sync.WaitGroup
// run servers each in a goroutine
for idx := range servers {
wg.Add(1)
go func(i int) {
info := &servers[i]
err := info.server.Serve(info.listener)
if err != nil {
lg.Printf("server [%d] serve error: %v", i, err)
}
wg.Done()
}(idx)
}
CommandChannel = make(chan CtrlCommand)
// run the signal handler goroutine
sch := make(chan os.Signal)
signal.Notify(sch, syscall.SIGHUP, syscall.SIGINT)
go func() {
for {
sig := <-sch
switch sig {
case syscall.SIGINT:
CommandChannel <- CtrlCommand{Command: CommandShutdown}
case syscall.SIGHUP:
CommandChannel <- CtrlCommand{Command: CommandRestart}
}
}
}()
// process control commands in a separate goroutine
wg.Add(1)
go func() {
defer wg.Done()
for {
cmd := <-CommandChannel
switch cmd.Command {
case CommandShutdown:
shutdownServers(shutdownWait)
return
case CommandRestart:
err := startProcess(startWait)
if cmd.ErrorChannel != nil {
cmd.ErrorChannel <- err
}
if err != nil {
lg.Printf("restart error: %v", err)
continue
}
go func() {
CommandChannel <- CtrlCommand{Command: CommandShutdown}
}()
}
}
}()
// wait until all finished
wg.Wait()
return
}
func shutdownServers(wait time.Duration) {
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
nch := make(chan struct{})
// call each server's shutdown, each in a goroutine
for idx := range servers {
go func(i int) {
info := &servers[i]
err := info.server.Shutdown(ctx)
if err != nil {
lg.Printf("server [%d] shutdown error: %v", i, err)
}
nch <- struct{}{}
}(idx)
}
var cnt int
// wait until all finished or timeout
for cnt < len(servers) {
select {
case <-ctx.Done():
return
case <-nch:
cnt++
}
}
}
func startProcess(wait time.Duration) (err error) {
// convert net.Listener to *os.File
files := make([]*os.File, len(servers))
for idx := range servers {
switch listener := servers[idx].listener.(type) {
case *net.TCPListener:
files[idx], err = listener.File()
case *net.UnixListener:
files[idx], err = listener.File()
default:
err = ErrUnsupported
}
if err != nil {
return
}
}
// start the new process with extra files
err = startAndWait(files, wait)
return
}