-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.go
563 lines (468 loc) · 13.3 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
package pgo2
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/pinguo/pgo2/core"
"github.com/pinguo/pgo2/iface"
"github.com/pinguo/pgo2/util"
)
type ServerConfig struct {
httpAddr string // address for http
httpsAddr string // address for https
debugAddr string // address for pprof
crtFile string // https certificate file
keyFile string // https private key file
maxHeaderBytes int // max http header bytes
readTimeout time.Duration // timeout for reading request
writeTimeout time.Duration // timeout for writing response
statsInterval time.Duration // interval for output server stats
enableAccessLog bool
pluginNames []string
maxPostBodySize int64 // max post body size
}
// Server the server component, configuration:
// server:
// httpAddr: "0.0.0.0:8000"
// debugAddr: "0.0.0.0:8100"
// httpsAddr: "0.0.0.0:8443"
// crtFile: "@app/conf/site.crt"
// keyFile: "@app/conf/site.key"
// maxHeaderBytes: 1048576
// readTimeout: "30s"
// writeTimeout: "30s"
// statsInterval: "60s"
// enableAccessLog: true
// maxPostBodySize: 1048576
// debug:true
// disableCheckListen: true
func NewServer(config map[string]interface{}) *Server {
server := &Server{
maxHeaderBytes: DefaultHeaderBytes,
readTimeout: DefaultTimeout,
writeTimeout: DefaultTimeout,
statsInterval: 60 * time.Second,
enableAccessLog: true,
}
server.pool.New = func() interface{} {
return new(Context)
}
core.Configure(server, config)
return server
}
type Server struct {
httpAddr string // address for http
httpsAddr string // address for https
debugAddr string // address for pprof
crtFile string // https certificate file
keyFile string // https private key file
maxHeaderBytes int // max http header bytes
readTimeout time.Duration // timeout for reading request
writeTimeout time.Duration // timeout for writing response
statsInterval time.Duration // interval for output server stats
enableAccessLog bool
pluginNames []string
numReq uint64 // request num handled
plugins []iface.IPlugin // server plugin list
servers []*http.Server // http server list
pool sync.Pool // Context pool
maxPostBodySize int64 // max post body size
debug bool // debug=true not recover panic ,Output more stack information
accessLogFormat iface.IAccessLogFormat
disableCheckListen bool // Close the check listener port
}
// SetHttpAddr set http addr, if both httpAddr and httpsAddr
// are empty, "0.0.0.0:8000" will be used as httpAddr.
func (s *Server) SetHttpAddr(addr string) {
s.httpAddr = addr
}
// SetAccessLogFormat set accessLogFormat
func (s *Server) SetAccessLogFormat(v iface.IAccessLogFormat) {
s.accessLogFormat = v
}
// SetHttpsAddr set https addr.
func (s *Server) SetHttpsAddr(addr string) {
s.httpsAddr = addr
}
// SetDebugAddr set debug and pprof addr.
func (s *Server) SetDebugAddr(addr string) {
s.debugAddr = addr
}
// SetCrtFile set certificate file for https
func (s *Server) SetCrtFile(certFile string) {
s.crtFile, _ = filepath.Abs(GetAlias(certFile))
}
// SetKeyFile set private key file for https
func (s *Server) SetKeyFile(keyFile string) {
s.keyFile, _ = filepath.Abs(GetAlias(keyFile))
}
// SetMaxHeaderBytes set max header bytes
func (s *Server) SetMaxHeaderBytes(maxBytes int) {
s.maxHeaderBytes = maxBytes
}
// SetMaxPostBodySize set max header bytes
func (s *Server) SetMaxPostBodySize(maxBytes int64) {
s.maxPostBodySize = maxBytes
}
// SetReadTimeout set timeout to read request
func (s *Server) SetReadTimeout(v string) {
if timeout, err := time.ParseDuration(v); err != nil {
panic(fmt.Sprintf("Server: SetReadTimeout failed, val:%s, err:%s", v, err.Error()))
} else {
s.readTimeout = timeout
}
}
// SetWriteTimeout set timeout to write response
func (s *Server) SetWriteTimeout(v string) {
if timeout, err := time.ParseDuration(v); err != nil {
panic(fmt.Sprintf("Server: SetWriteTimeout failed, val:%s, err:%s", v, err.Error()))
} else {
s.writeTimeout = timeout
}
}
// SetStatsInterval set interval to output stats
func (s *Server) SetStatsInterval(v string) {
if interval, err := time.ParseDuration(v); err != nil {
panic(fmt.Sprintf("Server: SetStatsInterval failed, val:%s, err:%s", v, err.Error()))
} else {
s.statsInterval = interval
}
}
// SetEnableAccessLog set access log enable or not
func (s *Server) SetEnableAccessLog(v bool) {
s.enableAccessLog = v
}
// SetDebug set debug
func (s *Server) SetDebug(v bool) {
s.debug = v
}
// SetPlugins set plugin by names
func (s *Server) SetPlugins(v []interface{}) {
for _, vv := range v {
name := vv.(string)
switch name {
case "gzip":
s.AddPlugin(NewGzip())
case "file":
s.AddPlugin(NewFile(nil))
default:
panic("For the defined plug-in:" + name)
}
}
}
// AddPlugins add plugin
func (s *Server) AddPlugin(v iface.IPlugin) {
s.plugins = append(s.plugins, v)
}
// SetDisableCheckListen Disable check listen port
func (s *Server) SetDisableCheckListen(v bool) {
s.disableCheckListen = v
}
// ServerStats server stats
type ServerStats struct {
MemMB uint // memory obtained from os
NumReq uint64 // number of handled requests
NumGO uint // number of goroutines
NumGC uint // number of gc runs
TimeGC string // total time of gc pause
TimeRun string // total time of app runs
}
// TimeRun time duration since app run
func (s *Server) timeRun() time.Duration {
d := time.Since(appTime)
d -= d % time.Second
return d
}
// GetStats get server stats
func (s *Server) GetStats() *ServerStats {
memStats := runtime.MemStats{}
runtime.ReadMemStats(&memStats)
timeGC := time.Duration(memStats.PauseTotalNs)
if timeGC > time.Minute {
timeGC -= timeGC % time.Second
} else {
timeGC -= timeGC % time.Millisecond
}
return &ServerStats{
MemMB: uint(memStats.Sys / (1 << 20)),
NumReq: atomic.LoadUint64(&s.numReq),
NumGO: uint(runtime.NumGoroutine()),
NumGC: uint(memStats.NumGC),
TimeGC: timeGC.String(),
TimeRun: s.timeRun().String(),
}
}
// Serve request processing entry
func (s *Server) Serve() {
// flush log when app end
defer App().Log().Flush()
// exec stopBefore when app end
defer App().StopBefore().Exec()
// add server plugins
s.addServerPlugin()
// process command request
if App().Mode() == ModeCmd {
s.ServeCMD()
return
}
//
if App().help() {
cmdList("")
return
}
// process http request
if s.httpAddr == "" && s.httpsAddr == "" {
s.httpAddr = DefaultHttpAddr
}
wg := sync.WaitGroup{}
s.handleHttp(&wg)
s.handleHttps(&wg)
s.handleDebug(&wg)
s.handleSignal(&wg)
s.handleStats(&wg)
wg.Wait()
}
// ServeCMD serve command request
func (s *Server) ServeCMD() {
ctx := Context{debug: s.debug}
ctx.SetEnableAccessLog(s.enableAccessLog)
ctx.SetAccessLogFormat(s.accessLogFormat)
// only apply the last plugin for command
ctx.Process(s.plugins[len(s.plugins)-1:])
}
// ServeHTTP serve http request
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Change the maxPostBodySize
if s.maxPostBodySize > 0 {
r.Body = http.MaxBytesReader(w, r.Body, s.maxPostBodySize)
}
// increase request num
atomic.AddUint64(&s.numReq, 1)
ctx := s.pool.Get().(iface.IContext)
ctx.HttpRW(s.debug, s.enableAccessLog, r, w)
ctx.SetAccessLogFormat(s.accessLogFormat)
ctx.Process(s.plugins)
s.pool.Put(ctx)
}
// HandleRequest handle request of cmd or http,
// this method called in the last of plugin chain.
func (s *Server) HandleRequest(ctx iface.IContext) {
// get request path and resolve route
path := ctx.Path()
// get new controller bind to this route
rv, action, params := App().Router().CreateController(path, ctx)
if !rv.IsValid() {
if s.help(rv, action, "") {
return
}
func() {
defer func() {
if err := recover(); err != nil {
ctx.End(http.StatusNotFound, []byte("route not found"))
ctx.Error("%s, trace[%s]", util.ToString(err), util.PanicTrace(TraceMaxDepth, false, s.debug))
}
}()
App().Router().ErrorController(ctx, http.StatusNotFound).(iface.IErrorController).Error(http.StatusNotFound, "route not found")
}()
return
}
if s.help(rv, action, ctx.Path()) {
return
}
actionId := ctx.ActionId()
controller := rv.Interface().(iface.IController)
// fill empty string for missing param
numIn := action.Type().NumIn()
if len(params) < numIn {
fill := make([]string, numIn-len(params))
params = append(params, fill...)
}
// prepare params for action call
callParams := make([]reflect.Value, 0)
for _, param := range params {
callParams = append(callParams, reflect.ValueOf(param))
}
defer func() {
if v := recover(); v != nil {
controller.HandlePanic(v, s.debug)
}
// after action hook
controller.AfterAction(actionId)
}()
// before action hook
controller.BeforeAction(actionId)
// call action method
res := action.Call(callParams)
if len(res) > 0 {
controller.Response(s.parseActionResult(res))
}
}
func (s *Server) parseActionResult(result []reflect.Value) (interface{}, error) {
switch len(result) {
case 1:
v := result[0].Interface()
err, isErr := v.(error)
if isErr {
return nil, err
}
return v, nil
case 2:
err, _ := result[1].Interface().(error)
return result[0].Interface(), err
default:
panic("Server: too many values returned by action")
}
}
func (s *Server) help(rv, action reflect.Value, path string) bool {
if !App().help() {
return false
}
cmdList(path)
return true
}
func (s *Server) handleHttp(wg *sync.WaitGroup) {
if s.httpAddr == "" {
return
}
s.checkListen(s.httpAddr)
svr := s.newHttpServer(s.httpAddr)
s.servers = append(s.servers, svr)
wg.Add(1)
GLogger().Info("start running http at " + svr.Addr)
go func() {
if err := svr.ListenAndServe(); err != http.ErrServerClosed {
panic("ListenAndServe failed, " + err.Error())
}
}()
}
func (s *Server) handleHttps(wg *sync.WaitGroup) {
if s.httpsAddr == "" {
return
} else if s.crtFile == "" || s.keyFile == "" {
panic("https no crtFile or keyFile configured")
}
s.checkListen(s.httpsAddr)
svr := s.newHttpServer(s.httpsAddr)
s.servers = append(s.servers, svr)
wg.Add(1)
GLogger().Info("start running https at " + svr.Addr)
go func() {
if err := svr.ListenAndServeTLS(s.crtFile, s.keyFile); err != http.ErrServerClosed {
panic("ListenAndServeTLS failed, " + err.Error())
}
}()
}
func (s *Server) handleDebug(wg *sync.WaitGroup) {
if s.debugAddr == "" {
return
}
s.checkListen(s.debugAddr)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
})
http.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
data, _ := json.Marshal(s.GetStats())
w.Write(data)
})
svr := s.newHttpServer(s.debugAddr)
svr.Handler = nil // use default handler
s.servers = append(s.servers, svr)
wg.Add(1)
GLogger().Info("start running debug at " + svr.Addr)
go func() {
if err := svr.ListenAndServe(); err != http.ErrServerClosed {
panic("ListenAndServe failed, " + err.Error())
}
}()
}
// checkListen check listen port
func (s *Server) checkListen(addr string) {
if s.disableCheckListen {
return
}
network := "tcp"
tcpAddr, err := net.ResolveTCPAddr(network, addr)
if err != nil {
panic("ResolveTCPAddr err, " + err.Error())
}
oriIp := strings.Replace(addr, fmt.Sprintf(":%d", tcpAddr.Port), "", 1)
oriIp = strings.ToLower(oriIp)
mapIp := map[string][]string{
"127.0.0.1": {"0.0.0.0", "[::1]"},
"localhost": {"0.0.0.0", "[::1]"},
"[::1]": {"[::]", "127.0.0.1"},
"0.0.0.0": {"127.0.0.1", "[::1]"},
"": {"127.0.0.1", "[::1]"},
"[::]": {"[::1]", "127.0.0.1"},
"[::0]": {"[::1]", "127.0.0.1"},
}
newIps := mapIp[oriIp]
if len(newIps) == 0 {
newIps = []string{"[::1]", "127.0.0.1", "0.0.0.0", "[::]"}
}
for _, newIp := range newIps {
checkAddr := fmt.Sprintf("%s:%d", newIp, tcpAddr.Port)
if listener, err := net.Listen(network, checkAddr); err != nil {
errMsg := err.Error()
if strings.Index(errMsg, "address already in use") > 0 {
errMsg = strings.Replace(errMsg, newIp, oriIp, 1)
panic("checkListen,ip " + oriIp + ", map ip " + newIp + ",err:" + errMsg)
}
} else {
listener.Close()
}
}
}
func (s *Server) handleSignal(wg *sync.WaitGroup) {
sig := make(chan os.Signal)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sig // wait signal
for _, svr := range s.servers {
GLogger().Info("stop running " + svr.Addr)
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
svr.Shutdown(ctx)
wg.Done()
}
}()
}
func (s *Server) handleStats(wg *sync.WaitGroup) {
timer := time.Tick(s.statsInterval)
go func() {
for {
<-timer // wait timer
data, _ := json.Marshal(s.GetStats())
GLogger().Info("app stats: " + string(data))
}
}()
}
func (s *Server) newHttpServer(addr string) *http.Server {
return &http.Server{
Addr: addr,
ReadTimeout: s.readTimeout,
WriteTimeout: s.writeTimeout,
MaxHeaderBytes: s.maxHeaderBytes,
Handler: s,
}
}
func (s *Server) addServerPlugin() {
// server is the last plugin
s.AddPlugin(s)
if len(s.plugins) > MaxPlugins {
panic("Server: too many plugins")
}
}