-
Notifications
You must be signed in to change notification settings - Fork 79
/
server.go
executable file
·216 lines (181 loc) · 4.57 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
205
206
207
208
209
210
211
212
213
214
215
216
package gracehttp
import (
"context"
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)
const (
GRACEFUL_ENVIRON_KEY = "IS_GRACEFUL"
GRACEFUL_ENVIRON_STRING = GRACEFUL_ENVIRON_KEY + "=1"
GRACEFUL_LISTENER_FD = 3
)
// HTTP server that supported graceful shutdown or restart
type Server struct {
*http.Server
listener net.Listener
isGraceful bool
signalChan chan os.Signal
shutdownChan chan bool
}
func NewServer(addr string, handler http.Handler, readTimeout, writeTimeout time.Duration) *Server {
isGraceful := false
if os.Getenv(GRACEFUL_ENVIRON_KEY) != "" {
isGraceful = true
}
return &Server{
Server: &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
},
isGraceful: isGraceful,
signalChan: make(chan os.Signal),
shutdownChan: make(chan bool),
}
}
func (srv *Server) ListenAndServe() error {
addr := srv.Addr
if addr == "" {
addr = ":http"
}
ln, err := srv.getNetListener(addr)
if err != nil {
return err
}
srv.listener = ln
return srv.Serve()
}
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
addr := srv.Addr
if addr == "" {
addr = ":https"
}
config := &tls.Config{}
if srv.TLSConfig != nil {
*config = *srv.TLSConfig
}
if config.NextProtos == nil {
config.NextProtos = []string{"http/1.1"}
}
var err error
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
ln, err := srv.getNetListener(addr)
if err != nil {
return err
}
srv.listener = tls.NewListener(ln, config)
return srv.Serve()
}
func (srv *Server) Serve() error {
go srv.handleSignals()
err := srv.Server.Serve(srv.listener)
srv.logf("waiting for connections closed.")
<-srv.shutdownChan
srv.logf("all connections closed.")
return err
}
func (srv *Server) getNetListener(addr string) (net.Listener, error) {
var ln net.Listener
var err error
if srv.isGraceful {
file := os.NewFile(GRACEFUL_LISTENER_FD, "")
ln, err = net.FileListener(file)
if err != nil {
err = fmt.Errorf("net.FileListener error: %v", err)
return nil, err
}
} else {
ln, err = net.Listen("tcp", addr)
if err != nil {
err = fmt.Errorf("net.Listen error: %v", err)
return nil, err
}
}
return ln, nil
}
func (srv *Server) handleSignals() {
var sig os.Signal
signal.Notify(
srv.signalChan,
syscall.SIGTERM,
syscall.SIGUSR2,
)
for {
sig = <-srv.signalChan
switch sig {
case syscall.SIGTERM:
srv.logf("received SIGTERM, graceful shutting down HTTP server.")
srv.shutdownHTTPServer()
case syscall.SIGUSR2:
srv.logf("received SIGUSR2, graceful restarting HTTP server.")
if pid, err := srv.startNewProcess(); err != nil {
srv.logf("start new process failed: %v, continue serving.", err)
} else {
srv.logf("start new process successed, the new pid is %d.", pid)
srv.shutdownHTTPServer()
}
default:
}
}
}
func (srv *Server) shutdownHTTPServer() {
if err := srv.Shutdown(context.Background()); err != nil {
srv.logf("HTTP server shutdown error: %v", err)
} else {
srv.logf("HTTP server shutdown success.")
srv.shutdownChan <- true
}
}
// start new process to handle HTTP Connection
func (srv *Server) startNewProcess() (uintptr, error) {
listenerFd, err := srv.getTCPListenerFd()
if err != nil {
return 0, fmt.Errorf("failed to get socket file descriptor: %v", err)
}
// set graceful restart env flag
envs := []string{}
for _, value := range os.Environ() {
if value != GRACEFUL_ENVIRON_STRING {
envs = append(envs, value)
}
}
envs = append(envs, GRACEFUL_ENVIRON_STRING)
execSpec := &syscall.ProcAttr{
Env: envs,
Files: []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), listenerFd},
}
fork, err := syscall.ForkExec(os.Args[0], os.Args, execSpec)
if err != nil {
return 0, fmt.Errorf("failed to forkexec: %v", err)
}
return uintptr(fork), nil
}
func (srv *Server) getTCPListenerFd() (uintptr, error) {
file, err := srv.listener.(*net.TCPListener).File()
if err != nil {
return 0, err
}
return file.Fd(), nil
}
func (srv *Server) logf(format string, args ...interface{}) {
pids := strconv.Itoa(os.Getpid())
format = "[pid " + pids + "] " + format
if srv.ErrorLog != nil {
srv.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}