-
Notifications
You must be signed in to change notification settings - Fork 490
/
appsrv.go
639 lines (579 loc) · 18.2 KB
/
appsrv.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package appsrv
import (
"bufio"
"context"
"crypto/sha1"
"encoding/base64"
"fmt"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"syscall"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/trace"
"yunion.io/x/pkg/util/signalutils"
"yunion.io/x/pkg/utils"
"yunion.io/x/onecloud/pkg/appctx"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/i18n"
"yunion.io/x/onecloud/pkg/proxy"
"yunion.io/x/onecloud/pkg/util/ctx"
"yunion.io/x/onecloud/pkg/util/httputils"
)
type Application struct {
name string
context context.Context
session *SWorkerManager
readSession *SWorkerManager
systemSession *SWorkerManager
roots map[string]*RadixNode
rootLock *sync.RWMutex
connMax int
idleTimeout time.Duration
readTimeout time.Duration
readHeaderTimeout time.Duration
writeTimeout time.Duration
processTimeout time.Duration
defHandlerInfo SHandlerInfo
cors *Cors
middlewares []MiddlewareFunc
hostId string
isExiting bool
idleConnsClosed chan struct{}
httpServer *http.Server
slaveHttpServer *http.Server
isTLS bool
}
const (
DEFAULT_BACKLOG = 1024
DEFAULT_IDLE_TIMEOUT = 10 * time.Second
DEFAULT_READ_TIMEOUT = 0
DEFAULT_READ_HEADER_TIMEOUT = 10 * time.Second
DEFAULT_WRITE_TIMEOUT = 0
// set default process timeout to 60 seconds
DEFAULT_PROCESS_TIMEOUT = 60 * time.Second
)
var quitHandlerRegisted bool
func NewApplication(name string, connMax int, db bool) *Application {
app := Application{name: name,
context: ctx.CtxWithTime(),
connMax: connMax,
session: NewWorkerManager("HttpRequestWorkerManager", connMax, DEFAULT_BACKLOG, db),
readSession: NewWorkerManager("HttpGetRequestWorkerManager", connMax, DEFAULT_BACKLOG, db),
systemSession: NewWorkerManager("InternalHttpRequestWorkerManager", 1, DEFAULT_BACKLOG, false),
roots: make(map[string]*RadixNode),
rootLock: &sync.RWMutex{},
idleTimeout: DEFAULT_IDLE_TIMEOUT,
readTimeout: DEFAULT_READ_TIMEOUT,
readHeaderTimeout: DEFAULT_READ_HEADER_TIMEOUT,
writeTimeout: DEFAULT_WRITE_TIMEOUT,
processTimeout: DEFAULT_PROCESS_TIMEOUT,
}
app.SetContext(appctx.APP_CONTEXT_KEY_APP, &app)
app.SetContext(appctx.APP_CONTEXT_KEY_APPNAME, app.name)
hm := sha1.New()
hm.Write([]byte(name))
hostname, _ := os.Hostname()
hm.Write([]byte(hostname))
outIp := utils.GetOutboundIP()
hm.Write([]byte(outIp.String()))
hostId := base64.URLEncoding.EncodeToString(hm.Sum(nil))
log.Infof("App hostId: %s (%s,%s,%s)", hostId, name, hostname, outIp.String())
app.hostId = hostId
app.SetContext(appctx.APP_CONTEXT_KEY_HOST_ID, hostId)
// initialize random seed
rand.Seed(time.Now().UnixNano())
return &app
}
func SplitPath(path string) []string {
ret := make([]string, 0)
for _, seg := range strings.Split(path, "/") {
seg = strings.Trim(seg, " \t\r\n")
if len(seg) > 0 {
ret = append(ret, seg)
}
}
return ret
}
func (app *Application) GetName() string {
return app.name
}
func (app *Application) getRoot(method string) *RadixNode {
app.rootLock.RLock()
if v, ok := app.roots[method]; ok {
app.rootLock.RUnlock()
return v
}
app.rootLock.RUnlock()
v := NewRadix()
app.rootLock.Lock()
app.roots[method] = v
app.rootLock.Unlock()
return v
}
func (app *Application) AddReverseProxyHandler(prefix string, ef *proxy.SEndpointFactory, m proxy.RequestManipulator) {
app.AddReverseProxyHandlerWithCallbackConfig(prefix, ef, m,
func(method string, hi *SHandlerInfo) *SHandlerInfo {
return hi
},
)
}
func (app *Application) AddReverseProxyHandlerWithCallbackConfig(prefix string, ef *proxy.SEndpointFactory, m proxy.RequestManipulator, confCb func(string, *SHandlerInfo) *SHandlerInfo) {
handler := proxy.NewHTTPReverseProxy(ef, m).ServeHTTP
for _, method := range []string{"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"} {
hi := &SHandlerInfo{}
hi = confCb(method, hi)
if hi != nil {
hi.SetMethod(method)
hi.SetPath(prefix)
hi.SetHandler(handler)
app.AddHandler3(hi)
}
}
}
func (app *Application) AddHandler(method string, prefix string,
handler func(context.Context, http.ResponseWriter, *http.Request)) *SHandlerInfo {
return app.AddHandler2(method, prefix, handler, nil, "", nil)
}
func (app *Application) AddHandler2(method string, prefix string,
handler func(context.Context, http.ResponseWriter, *http.Request),
metadata map[string]interface{}, name string, tags map[string]string) *SHandlerInfo {
segs := SplitPath(prefix)
hi := newHandlerInfo(method, segs, handler, metadata, name, tags)
return app.AddHandler3(hi)
}
func (app *Application) AddHandler3(hi *SHandlerInfo) *SHandlerInfo {
e := app.getRoot(hi.method).Add(hi.path, hi)
if e != nil {
log.Fatalf("Fail to register %s %s: %s", hi.method, hi.path, e)
}
return hi
}
type loggingResponseWriter struct {
http.ResponseWriter
status int
}
func (lrw *loggingResponseWriter) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
if f, ok := lrw.ResponseWriter.(http.Hijacker); ok {
return f.Hijack()
}
return nil, nil, fmt.Errorf("not a hijacker")
}
func (lrw *loggingResponseWriter) WriteHeader(code int) {
if code < 100 || code >= 600 {
log.Errorf("Invalud status code %d, set code to 598", code)
code = 598
}
lrw.status = code
lrw.ResponseWriter.WriteHeader(code)
}
func genRequestId(w http.ResponseWriter, r *http.Request) string {
rid := r.Header.Get("X-Request-Id")
if len(rid) == 0 {
rid = utils.GenRequestId(3)
} else {
rid = fmt.Sprintf("%s-%s", rid, utils.GenRequestId(3))
}
w.Header().Set("X-Request-Id", rid)
return rid
}
func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// log.Printf("defaultHandler %s %s", r.Method, r.URL.Path)
rid := genRequestId(w, r)
w.Header().Set("X-Request-Host-Id", app.hostId)
lrw := &loggingResponseWriter{w, http.StatusOK}
start := time.Now()
hi, params := app.defaultHandle(lrw, r, rid)
if hi == nil {
hi = &app.defHandlerInfo
}
var counter *handlerRequestCounter
if lrw.status < 400 {
counter = &hi.counter2XX
} else if lrw.status < 500 {
counter = &hi.counter4XX
} else {
counter = &hi.counter5XX
}
duration := float64(time.Since(start).Nanoseconds()) / 1000000
counter.hit += 1
counter.duration += duration
skipLog := false
if params != nil {
if params.SkipLog {
skipLog = true
}
} else if hi.skipLog {
skipLog = true
}
if !skipLog {
peerServiceName := r.Header.Get("X-Yunion-Peer-Service-Name")
var remote string
if len(peerServiceName) > 0 {
remote = fmt.Sprintf("%s:%s", r.RemoteAddr, peerServiceName)
} else {
remote = r.RemoteAddr
}
log.Infof("%s %d %s %s %s (%s) %.2fms", app.hostId, lrw.status, rid, r.Method, r.URL, remote, duration)
}
}
func (app *Application) handleCORS(w http.ResponseWriter, r *http.Request) bool {
if app.cors == nil {
return false
}
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
app.cors.handlePreflight(w, r)
return true
} else {
app.cors.handleActualRequest(w, r)
return false
}
}
type appTask struct {
ctx context.Context
hand *SHandlerInfo
rid string
params map[string]string
appParams *SAppParams
app *Application
fw responseWriterChannel
r *http.Request
segs []string
to time.Duration
cancel context.CancelFunc
}
func (t *appTask) Run() {
if t.ctx.Err() == nil {
t.ctx = context.WithValue(t.ctx, appctx.APP_CONTEXT_KEY_REQUEST_ID, t.rid)
t.ctx = context.WithValue(t.ctx, appctx.APP_CONTEXT_KEY_CUR_ROOT, t.hand.path)
t.ctx = context.WithValue(t.ctx, appctx.APP_CONTEXT_KEY_CUR_PATH, t.segs[len(t.hand.path):])
t.ctx = context.WithValue(t.ctx, appctx.APP_CONTEXT_KEY_PARAMS, t.params)
t.ctx = context.WithValue(t.ctx, appctx.APP_CONTEXT_KEY_START_TIME, time.Now().UTC())
if t.hand.metadata != nil {
t.ctx = context.WithValue(t.ctx, appctx.APP_CONTEXT_KEY_METADATA, t.hand.metadata)
}
t.ctx = context.WithValue(t.ctx, APP_CONTEXT_KEY_APP_PARAMS, t.appParams)
func() {
span := trace.StartServerTrace(&t.fw, t.r, t.appParams.Name, t.app.GetName(), t.hand.GetTags())
defer func() {
if !t.appParams.SkipTrace {
span.EndTrace()
}
}()
t.ctx = context.WithValue(t.ctx, appctx.APP_CONTEXT_KEY_TRACE, span)
t.hand.handler(t.ctx, &t.fw, t.r)
}()
} // otherwise, the task has been timeout
t.fw.closeChannels()
}
func (t *appTask) Dump() string {
return fmt.Sprintf("%s %s", t.r.Method, t.r.URL.String())
}
func (app *Application) defaultHandle(w http.ResponseWriter, r *http.Request, rid string) (*SHandlerInfo, *SAppParams) {
segs := SplitPath(r.URL.EscapedPath())
for i := range segs {
if p, err := url.PathUnescape(segs[i]); err == nil {
segs[i] = p
}
}
params := make(map[string]string)
w.Header().Set("Server", "Yunion AppServer/Go/2018.4")
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("X-XSS-Protection", "1; mode=block")
if app.isTLS {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
isCors := app.handleCORS(w, r)
handler := app.getRoot(r.Method).Match(segs, params)
if handler != nil {
// log.Print("Found handler", params)
hand, ok := handler.(*SHandlerInfo)
if ok {
task := &appTask{
ctx: app.context,
hand: hand,
rid: rid,
params: params,
app: app,
fw: newResponseWriterChannel(w),
r: r,
segs: segs,
to: hand.FetchProcessTimeout(r),
cancel: nil,
}
currentWorker := make(chan *SWorker, 1) // make it a buffered channel
if task.to == 0 {
task.to = app.processTimeout
}
if task.to > 0 {
task.ctx, task.cancel = context.WithTimeout(task.ctx, task.to)
}
if task.cancel != nil {
defer task.cancel()
}
task.ctx = i18n.WithRequestLang(task.ctx, r)
session := hand.workerMan
if session == nil {
if r.Method == "GET" || r.Method == "HEAD" {
session = app.readSession
} else {
session = app.session
}
}
task.appParams = hand.GetAppParams(params, segs)
task.appParams.Request = r
task.appParams.Response = w
session.Run(
task,
currentWorker,
func(err error) {
httperrors.InternalServerError(task.ctx, &task.fw, "Internal server error: %s", err)
task.fw.closeChannels()
},
)
runErr := task.fw.wait(task.ctx, currentWorker)
if runErr != nil {
switch runErr.(type) {
case *httputils.JSONClientError:
je := runErr.(*httputils.JSONClientError)
httperrors.GeneralServerError(task.ctx, w, je)
default:
httperrors.InternalServerError(task.ctx, w, "Internal server error")
}
}
task.fw.closeChannels()
return hand, task.appParams
} else {
ctx := i18n.WithRequestLang(context.TODO(), r)
httperrors.InternalServerError(ctx, w, "Invalid handler %s", r.URL)
}
} else if !isCors {
ctx := i18n.WithRequestLang(context.TODO(), r)
httperrors.NotFoundError(ctx, w, "Handler not found")
}
return nil, nil
}
func (app *Application) AddDefaultHandler(method string, prefix string, handler func(context.Context, http.ResponseWriter, *http.Request), name string) {
segs := SplitPath(prefix)
hi := newHandlerInfo(method, segs, handler, nil, name, nil)
hi.SetSkipLog(true).SetWorkerManager(app.systemSession)
app.AddHandler3(hi)
}
func (app *Application) addDefaultHandlers() {
app.AddDefaultHandler("GET", "/version", VersionHandler, "version")
app.AddDefaultHandler("GET", "/stats", StatisticHandler, "stats")
app.AddDefaultHandler("POST", "/ping", PingHandler, "ping")
app.AddDefaultHandler("GET", "/ping", PingHandler, "ping")
app.AddDefaultHandler("GET", "/worker_stats", WorkerStatsHandler, "worker_stats")
app.AddDefaultHandler("GET", "/process_stats", ProcessStatsHandler, "process_stats")
}
func timeoutHandle(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && strings.HasSuffix(r.URL.Path, "upload") {
// 上传文件接口默认不超时
h.ServeHTTP(w, r)
} else {
// 服务器超时时间默认设置为10秒.
http.TimeoutHandler(h, DEFAULT_IDLE_TIMEOUT, "").ServeHTTP(w, r)
}
}
}
func (app *Application) initServer(addr string) *http.Server {
/* db := AppContextDB(app.context)
if db != nil {
db.SetMaxIdleConns(app.connMax + 1)
db.SetMaxOpenConns(app.connMax + 1)
}
*/
s := &http.Server{
Addr: addr,
Handler: app,
IdleTimeout: app.idleTimeout,
ReadTimeout: app.readTimeout,
ReadHeaderTimeout: app.readHeaderTimeout,
WriteTimeout: app.writeTimeout,
MaxHeaderBytes: 1 << 20,
}
return s
}
func (app *Application) registerCleanShutdown(s *http.Server, onStop func()) {
if quitHandlerRegisted {
log.Warningf("Application quit handler registed, duplicated!!!")
return
} else {
quitHandlerRegisted = true
}
app.idleConnsClosed = make(chan struct{})
signalutils.SetDumpStackSignal()
quitSignals := []os.Signal{syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM}
signalutils.RegisterSignal(func() {
if app.isExiting {
log.Infof("Quit signal received!!! clean up in progress, be patient...")
return
}
app.isExiting = true
log.Infof("Quit signal received!!! do cleanup...")
if err := s.Shutdown(context.Background()); err != nil {
// Error from closing listeners, or context timeout:
log.Errorf("HTTP server Shutdown: %v", err)
}
if onStop != nil {
func() {
defer func() {
if r := recover(); r != nil {
log.Errorf("app exiting error: %s", r)
}
}()
onStop()
}()
}
close(app.idleConnsClosed)
}, quitSignals...)
signalutils.StartTrap()
}
func (app *Application) waitCleanShutdown() {
<-app.idleConnsClosed
log.Infof("Service stopped.")
}
func (app *Application) ListenAndServe(addr string) {
app.ListenAndServeWithCleanup(addr, nil)
}
func (app *Application) ListenAndServeTLS(addr string, certFile, keyFile string) {
app.ListenAndServeTLSWithCleanup(addr, certFile, keyFile, nil)
}
func (app *Application) ListenAndServeWithCleanup(addr string, onStop func()) {
app.ListenAndServeTLSWithCleanup(addr, "", "", onStop)
}
func (app *Application) ListenAndServeTLSWithCleanup(addr string, certFile, keyFile string, onStop func()) {
app.ListenAndServeTLSWithCleanup2(addr, certFile, keyFile, onStop, true)
}
func (app *Application) ListenAndServeWithoutCleanup(addr, certFile, keyFile string) {
app.ListenAndServeTLSWithCleanup2(addr, certFile, keyFile, nil, false)
}
func (app *Application) ListenAndServeTLSWithCleanup2(addr string, certFile, keyFile string, onStop func(), isMaster bool) {
app.isTLS = true
httpSrv := app.initServer(addr)
if isMaster {
app.addDefaultHandlers()
AddPProfHandler("", app)
app.httpServer = httpSrv
app.registerCleanShutdown(app.httpServer, onStop)
} else {
app.slaveHttpServer = httpSrv
}
app.listenAndServeInternal(httpSrv, certFile, keyFile)
if isMaster {
app.waitCleanShutdown()
}
}
func (app *Application) Stop(ctx context.Context) error {
if app.httpServer != nil {
return app.httpServer.Shutdown(ctx)
}
return nil
}
func (app *Application) listenAndServeInternal(s *http.Server, certFile, keyFile string) {
var err error
if len(certFile) == 0 && len(keyFile) == 0 {
err = s.ListenAndServe()
} else {
err = s.ListenAndServeTLS(certFile, keyFile)
}
if err != nil && err != http.ErrServerClosed {
log.Fatalf("ListAndServer fail: %s (cert=%s key=%s)", err, certFile, keyFile)
}
}
func isJsonContentType(r *http.Request) bool {
contType := strings.ToLower(r.Header.Get("Content-Type"))
if strings.HasPrefix(contType, "application/json") {
return true
}
return false
}
func isFormContentType(r *http.Request) bool {
contType := strings.ToLower(r.Header.Get("Content-Type"))
if strings.HasPrefix(contType, "application/json") {
return true
}
return false
}
type TContentType string
const (
ContentTypeJson = TContentType("Json")
ContentTypeForm = TContentType("Form")
ContentTypeUnknown = TContentType("Unknown")
)
func getContentType(r *http.Request) TContentType {
contType := func() string {
for _, k := range []string{"Content-Type", "content-type"} {
contentType := r.Header.Get(k)
if len(contentType) > 0 {
return strings.ToLower(contentType)
}
}
return ""
}()
for k, v := range map[string]TContentType{
"application/json": ContentTypeJson,
"application/x-www-form-urlencoded": ContentTypeForm,
} {
if strings.HasPrefix(contType, k) {
return v
}
}
return ContentTypeUnknown
}
func FetchEnv(ctx context.Context, w http.ResponseWriter, r *http.Request) (params map[string]string, query jsonutils.JSONObject, body jsonutils.JSONObject) {
var err error
params = appctx.AppContextParams(ctx)
query, err = jsonutils.ParseQueryString(r.URL.RawQuery)
if err != nil {
log.Errorf("Parse query string %s failed: %v", r.URL.RawQuery, err)
}
//var body jsonutils.JSONObject = nil
if r.Method == "PUT" || r.Method == "POST" || r.Method == "DELETE" || r.Method == "PATCH" {
switch getContentType(r) {
case ContentTypeJson:
if r.ContentLength > 0 {
body, err = FetchJSON(r)
if err != nil {
log.Warningf("Fail to decode JSON request body: %v", err)
}
}
case ContentTypeForm:
err := r.ParseForm()
if err != nil {
log.Warningf("ParseForm %s error: %v", r.URL.String(), err)
}
query, err = jsonutils.ParseQueryString(r.PostForm.Encode())
if err != nil {
log.Warningf("Parse query string %s failed: %v", r.PostForm.Encode(), err)
}
default:
log.Warningf("%s invalid contentType with header %v", r.URL.String(), r.Header)
}
}
return params, query, body
}
func (app *Application) GetContext() context.Context {
return app.context
}