github.com/wangyougui/gf/v2@v2.6.5/net/ghttp/ghttp_server.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package ghttp 8 9 import ( 10 "bytes" 11 "context" 12 "fmt" 13 "net/http" 14 "os" 15 "runtime" 16 "strings" 17 "sync" 18 "time" 19 20 "github.com/olekukonko/tablewriter" 21 22 "github.com/wangyougui/gf/v2/container/garray" 23 "github.com/wangyougui/gf/v2/container/gset" 24 "github.com/wangyougui/gf/v2/container/gtype" 25 "github.com/wangyougui/gf/v2/debug/gdebug" 26 "github.com/wangyougui/gf/v2/errors/gcode" 27 "github.com/wangyougui/gf/v2/errors/gerror" 28 "github.com/wangyougui/gf/v2/internal/intlog" 29 "github.com/wangyougui/gf/v2/net/ghttp/internal/swaggerui" 30 "github.com/wangyougui/gf/v2/net/goai" 31 "github.com/wangyougui/gf/v2/net/gsvc" 32 "github.com/wangyougui/gf/v2/os/gcache" 33 "github.com/wangyougui/gf/v2/os/gctx" 34 "github.com/wangyougui/gf/v2/os/genv" 35 "github.com/wangyougui/gf/v2/os/gfile" 36 "github.com/wangyougui/gf/v2/os/glog" 37 "github.com/wangyougui/gf/v2/os/gproc" 38 "github.com/wangyougui/gf/v2/os/gsession" 39 "github.com/wangyougui/gf/v2/os/gtimer" 40 "github.com/wangyougui/gf/v2/text/gregex" 41 "github.com/wangyougui/gf/v2/text/gstr" 42 "github.com/wangyougui/gf/v2/util/gconv" 43 ) 44 45 func init() { 46 // Initialize the method map. 47 for _, v := range strings.Split(supportedHttpMethods, ",") { 48 methodsMap[v] = struct{}{} 49 } 50 } 51 52 // serverProcessInit initializes some process configurations, which can only be done once. 53 func serverProcessInit() { 54 var ctx = context.TODO() 55 if !serverProcessInitialized.Cas(false, true) { 56 return 57 } 58 // This means it is a restart server. It should kill its parent before starting its listening, 59 // to avoid duplicated port listening in two processes. 60 if !genv.Get(adminActionRestartEnvKey).IsEmpty() { 61 if p, err := os.FindProcess(gproc.PPid()); err == nil { 62 if err = p.Kill(); err != nil { 63 intlog.Errorf(ctx, `%+v`, err) 64 } 65 if _, err = p.Wait(); err != nil { 66 intlog.Errorf(ctx, `%+v`, err) 67 } 68 } else { 69 glog.Error(ctx, err) 70 } 71 } 72 73 // Process message handler. 74 // It enabled only a graceful feature is enabled. 75 if gracefulEnabled { 76 intlog.Printf(ctx, "pid[%d]: graceful reload feature is enabled", gproc.Pid()) 77 go handleProcessMessage() 78 } else { 79 intlog.Printf(ctx, "pid[%d]: graceful reload feature is disabled", gproc.Pid()) 80 } 81 82 // It's an ugly calling for better initializing the main package path 83 // in source development environment. It is useful only be used in main goroutine. 84 // It fails to retrieve the main package path in asynchronous goroutines. 85 gfile.MainPkgPath() 86 } 87 88 // GetServer creates and returns a server instance using given name and default configurations. 89 // Note that the parameter `name` should be unique for different servers. It returns an existing 90 // server instance if given `name` is already existing in the server mapping. 91 func GetServer(name ...interface{}) *Server { 92 serverName := DefaultServerName 93 if len(name) > 0 && name[0] != "" { 94 serverName = gconv.String(name[0]) 95 } 96 v := serverMapping.GetOrSetFuncLock(serverName, func() interface{} { 97 s := &Server{ 98 instance: serverName, 99 plugins: make([]Plugin, 0), 100 servers: make([]*gracefulServer, 0), 101 closeChan: make(chan struct{}, 10000), 102 serverCount: gtype.NewInt(), 103 statusHandlerMap: make(map[string][]HandlerFunc), 104 serveTree: make(map[string]interface{}), 105 serveCache: gcache.New(), 106 routesMap: make(map[string][]*HandlerItem), 107 openapi: goai.New(), 108 registrar: gsvc.GetRegistry(), 109 } 110 // Initialize the server using default configurations. 111 if err := s.SetConfig(NewConfig()); err != nil { 112 panic(gerror.WrapCode(gcode.CodeInvalidConfiguration, err, "")) 113 } 114 // It enables OpenTelemetry for server in default. 115 s.Use(internalMiddlewareServerTracing) 116 return s 117 }) 118 return v.(*Server) 119 } 120 121 // Start starts listening on configured port. 122 // This function does not block the process, you can use function Wait blocking the process. 123 func (s *Server) Start() error { 124 var ctx = gctx.GetInitCtx() 125 126 // Swagger UI. 127 if s.config.SwaggerPath != "" { 128 swaggerui.Init() 129 s.AddStaticPath(s.config.SwaggerPath, swaggerUIPackedPath) 130 s.BindHookHandler(s.config.SwaggerPath+"/*", HookBeforeServe, s.swaggerUI) 131 } 132 133 // OpenApi specification json producing handler. 134 if s.config.OpenApiPath != "" { 135 s.BindHandler(s.config.OpenApiPath, s.openapiSpec) 136 } 137 138 // Register group routes. 139 s.handlePreBindItems(ctx) 140 141 // Server process initialization, which can only be initialized once. 142 serverProcessInit() 143 144 // Server can only be run once. 145 if s.Status() == ServerStatusRunning { 146 return gerror.NewCode(gcode.CodeInvalidOperation, "server is already running") 147 } 148 149 // Logging path setting check. 150 if s.config.LogPath != "" && s.config.LogPath != s.config.Logger.GetPath() { 151 if err := s.config.Logger.SetPath(s.config.LogPath); err != nil { 152 return err 153 } 154 } 155 // Default session storage. 156 if s.config.SessionStorage == nil { 157 sessionStoragePath := "" 158 if s.config.SessionPath != "" { 159 sessionStoragePath = gfile.Join(s.config.SessionPath, s.config.Name) 160 if !gfile.Exists(sessionStoragePath) { 161 if err := gfile.Mkdir(sessionStoragePath); err != nil { 162 return gerror.Wrapf(err, `mkdir failed for "%s"`, sessionStoragePath) 163 } 164 } 165 } 166 s.config.SessionStorage = gsession.NewStorageFile(sessionStoragePath, s.config.SessionMaxAge) 167 } 168 // Initialize session manager when start running. 169 s.sessionManager = gsession.New( 170 s.config.SessionMaxAge, 171 s.config.SessionStorage, 172 ) 173 174 // PProf feature. 175 if s.config.PProfEnabled { 176 s.EnablePProf(s.config.PProfPattern) 177 } 178 179 // Default HTTP handler. 180 if s.config.Handler == nil { 181 s.config.Handler = s.ServeHTTP 182 } 183 184 // Install external plugins. 185 for _, p := range s.plugins { 186 if err := p.Install(s); err != nil { 187 s.Logger().Fatalf(ctx, `%+v`, err) 188 } 189 } 190 // Check the group routes again for internally registered routes. 191 s.handlePreBindItems(ctx) 192 193 // If there's no route registered and no static service enabled, 194 // it then returns an error of invalid usage of server. 195 if len(s.routesMap) == 0 && !s.config.FileServerEnabled { 196 return gerror.NewCode( 197 gcode.CodeInvalidOperation, 198 `there's no route set or static feature enabled, did you forget import the router?`, 199 ) 200 } 201 // ================================================================================================ 202 // Start the HTTP server. 203 // ================================================================================================ 204 reloaded := false 205 fdMapStr := genv.Get(adminActionReloadEnvKey).String() 206 if len(fdMapStr) > 0 { 207 sfm := bufferToServerFdMap([]byte(fdMapStr)) 208 if v, ok := sfm[s.config.Name]; ok { 209 s.startServer(v) 210 reloaded = true 211 } 212 } 213 if !reloaded { 214 s.startServer(nil) 215 } 216 217 // Swagger UI info. 218 if s.config.SwaggerPath != "" { 219 s.Logger().Infof( 220 ctx, 221 `swagger ui is serving at address: %s%s/`, 222 s.getLocalListenedAddress(), 223 s.config.SwaggerPath, 224 ) 225 } 226 // OpenApi specification info. 227 if s.config.OpenApiPath != "" { 228 s.Logger().Infof( 229 ctx, 230 `openapi specification is serving at address: %s%s`, 231 s.getLocalListenedAddress(), 232 s.config.OpenApiPath, 233 ) 234 } else { 235 if s.config.SwaggerPath != "" { 236 s.Logger().Warning( 237 ctx, 238 `openapi specification is disabled but swagger ui is serving, which might make no sense`, 239 ) 240 } else { 241 s.Logger().Info( 242 ctx, 243 `openapi specification is disabled`, 244 ) 245 } 246 } 247 248 // If this is a child process, it then notifies its parent exit. 249 if gproc.IsChild() { 250 gtimer.SetTimeout(ctx, time.Duration(s.config.GracefulTimeout)*time.Second, func(ctx context.Context) { 251 if err := gproc.Send(gproc.PPid(), []byte("exit"), adminGProcCommGroup); err != nil { 252 intlog.Errorf(ctx, `server error in process communication: %+v`, err) 253 } 254 }) 255 } 256 s.initOpenApi() 257 s.doServiceRegister() 258 s.doRouterMapDump() 259 260 return nil 261 } 262 263 func (s *Server) getLocalListenedAddress() string { 264 return fmt.Sprintf(`http://127.0.0.1:%d`, s.GetListenedPort()) 265 } 266 267 // doRouterMapDump checks and dumps the router map to the log. 268 func (s *Server) doRouterMapDump() { 269 if !s.config.DumpRouterMap { 270 return 271 } 272 273 var ( 274 ctx = context.TODO() 275 routes = s.GetRoutes() 276 isJustDefaultServerAndDomain = true 277 headers = []string{ 278 "SERVER", "DOMAIN", "ADDRESS", "METHOD", "ROUTE", "HANDLER", "MIDDLEWARE", 279 } 280 ) 281 for _, item := range routes { 282 if item.Server != DefaultServerName || item.Domain != DefaultDomainName { 283 isJustDefaultServerAndDomain = false 284 break 285 } 286 } 287 if isJustDefaultServerAndDomain { 288 headers = []string{"ADDRESS", "METHOD", "ROUTE", "HANDLER", "MIDDLEWARE"} 289 } 290 if len(routes) > 0 { 291 buffer := bytes.NewBuffer(nil) 292 table := tablewriter.NewWriter(buffer) 293 table.SetHeader(headers) 294 table.SetRowLine(true) 295 table.SetBorder(false) 296 table.SetCenterSeparator("|") 297 298 for _, item := range routes { 299 var ( 300 data = make([]string, 0) 301 handlerName = gstr.TrimRightStr(item.Handler.Name, "-fm") 302 middlewares = gstr.SplitAndTrim(item.Middleware, ",") 303 ) 304 305 // No printing special internal middleware that may lead confused. 306 if gstr.SubStrFromREx(handlerName, ".") == noPrintInternalRoute { 307 continue 308 } 309 for k, v := range middlewares { 310 middlewares[k] = gstr.TrimRightStr(v, "-fm") 311 } 312 item.Middleware = gstr.Join(middlewares, "\n") 313 if isJustDefaultServerAndDomain { 314 data = append( 315 data, 316 item.Address, 317 item.Method, 318 item.Route, 319 handlerName, 320 item.Middleware, 321 ) 322 } else { 323 data = append( 324 data, 325 item.Server, 326 item.Domain, 327 item.Address, 328 item.Method, 329 item.Route, 330 handlerName, 331 item.Middleware, 332 ) 333 } 334 table.Append(data) 335 } 336 table.Render() 337 s.config.Logger.Header(false).Printf(ctx, "\n%s", buffer.String()) 338 } 339 } 340 341 // GetOpenApi returns the OpenApi specification management object of current server. 342 func (s *Server) GetOpenApi() *goai.OpenApiV3 { 343 return s.openapi 344 } 345 346 // GetRoutes retrieves and returns the router array. 347 func (s *Server) GetRoutes() []RouterItem { 348 var ( 349 m = make(map[string]*garray.SortedArray) 350 routeFilterSet = gset.NewStrSet() 351 address = s.GetListenedAddress() 352 ) 353 if s.config.HTTPSAddr != "" { 354 if len(address) > 0 { 355 address += "," 356 } 357 address += "tls" + s.config.HTTPSAddr 358 } 359 for k, handlerItems := range s.routesMap { 360 array, _ := gregex.MatchString(`(.*?)%([A-Z]+):(.+)@(.+)`, k) 361 for index := len(handlerItems) - 1; index >= 0; index-- { 362 var ( 363 handlerItem = handlerItems[index] 364 item = RouterItem{ 365 Server: s.config.Name, 366 Address: address, 367 Domain: array[4], 368 Type: handlerItem.Type, 369 Middleware: array[1], 370 Method: array[2], 371 Route: array[3], 372 Priority: index, 373 Handler: handlerItem, 374 } 375 ) 376 switch item.Handler.Type { 377 case HandlerTypeObject, HandlerTypeHandler: 378 item.IsServiceHandler = true 379 380 case HandlerTypeMiddleware: 381 item.Middleware = "GLOBAL MIDDLEWARE" 382 } 383 // Repeated route filtering for dump. 384 var setKey = fmt.Sprintf( 385 `%s|%s|%s|%s`, 386 item.Method, item.Route, item.Domain, item.Type, 387 ) 388 if !routeFilterSet.AddIfNotExist(setKey) { 389 continue 390 } 391 if len(item.Handler.Middleware) > 0 { 392 for _, v := range item.Handler.Middleware { 393 if item.Middleware != "" { 394 item.Middleware += "," 395 } 396 item.Middleware += gdebug.FuncName(v) 397 } 398 } 399 // If the domain does not exist in the dump map, it creates the map. 400 // The value of the map is a custom sorted array. 401 if _, ok := m[item.Domain]; !ok { 402 // Sort in ASC order. 403 m[item.Domain] = garray.NewSortedArray(func(v1, v2 interface{}) int { 404 item1 := v1.(RouterItem) 405 item2 := v2.(RouterItem) 406 r := 0 407 if r = strings.Compare(item1.Domain, item2.Domain); r == 0 { 408 if r = strings.Compare(item1.Route, item2.Route); r == 0 { 409 if r = strings.Compare(item1.Method, item2.Method); r == 0 { 410 if item1.Handler.Type == HandlerTypeMiddleware && item2.Handler.Type != HandlerTypeMiddleware { 411 return -1 412 } else if item1.Handler.Type == HandlerTypeMiddleware && item2.Handler.Type == HandlerTypeMiddleware { 413 return 1 414 } else if r = strings.Compare(item1.Middleware, item2.Middleware); r == 0 { 415 r = item2.Priority - item1.Priority 416 } 417 } 418 } 419 } 420 return r 421 }) 422 } 423 m[item.Domain].Add(item) 424 } 425 } 426 427 routerArray := make([]RouterItem, 0, 128) 428 for _, array := range m { 429 for _, v := range array.Slice() { 430 routerArray = append(routerArray, v.(RouterItem)) 431 } 432 } 433 return routerArray 434 } 435 436 // Run starts server listening in blocking way. 437 // It's commonly used for single server situation. 438 func (s *Server) Run() { 439 var ctx = context.TODO() 440 441 if err := s.Start(); err != nil { 442 s.Logger().Fatalf(ctx, `%+v`, err) 443 } 444 445 // Signal handler in asynchronous way. 446 go handleProcessSignal() 447 448 // Blocking using channel for graceful restart. 449 <-s.closeChan 450 // Remove plugins. 451 if len(s.plugins) > 0 { 452 for _, p := range s.plugins { 453 intlog.Printf(ctx, `remove plugin: %s`, p.Name()) 454 if err := p.Remove(); err != nil { 455 intlog.Errorf(ctx, "%+v", err) 456 } 457 } 458 } 459 s.doServiceDeregister() 460 s.Logger().Infof(ctx, "pid[%d]: all servers shutdown", gproc.Pid()) 461 } 462 463 // Wait blocks to wait for all servers done. 464 // It's commonly used in multiple server situation. 465 func Wait() { 466 var ctx = context.TODO() 467 468 // Signal handler in asynchronous way. 469 go handleProcessSignal() 470 471 <-allShutdownChan 472 473 // Remove plugins. 474 serverMapping.Iterator(func(k string, v interface{}) bool { 475 s := v.(*Server) 476 if len(s.plugins) > 0 { 477 for _, p := range s.plugins { 478 intlog.Printf(ctx, `remove plugin: %s`, p.Name()) 479 if err := p.Remove(); err != nil { 480 intlog.Errorf(ctx, `%+v`, err) 481 } 482 } 483 } 484 return true 485 }) 486 glog.Infof(ctx, "pid[%d]: all servers shutdown", gproc.Pid()) 487 } 488 489 // startServer starts the underlying server listening. 490 func (s *Server) startServer(fdMap listenerFdMap) { 491 var ( 492 ctx = context.TODO() 493 httpsEnabled bool 494 ) 495 // HTTPS 496 if s.config.TLSConfig != nil || (s.config.HTTPSCertPath != "" && s.config.HTTPSKeyPath != "") { 497 if len(s.config.HTTPSAddr) == 0 { 498 if len(s.config.Address) > 0 { 499 s.config.HTTPSAddr = s.config.Address 500 s.config.Address = "" 501 } else { 502 s.config.HTTPSAddr = defaultHttpsAddr 503 } 504 } 505 httpsEnabled = len(s.config.HTTPSAddr) > 0 506 var array []string 507 if v, ok := fdMap["https"]; ok && len(v) > 0 { 508 array = strings.Split(v, ",") 509 } else { 510 array = strings.Split(s.config.HTTPSAddr, ",") 511 } 512 for _, v := range array { 513 if len(v) == 0 { 514 continue 515 } 516 var ( 517 fd = 0 518 itemFunc = v 519 addrAndFd = strings.Split(v, "#") 520 ) 521 if len(addrAndFd) > 1 { 522 itemFunc = addrAndFd[0] 523 // The Windows OS does not support socket file descriptor passing 524 // from parent process. 525 if runtime.GOOS != "windows" { 526 fd = gconv.Int(addrAndFd[1]) 527 } 528 } 529 if fd > 0 { 530 s.servers = append(s.servers, s.newGracefulServer(itemFunc, fd)) 531 } else { 532 s.servers = append(s.servers, s.newGracefulServer(itemFunc)) 533 } 534 s.servers[len(s.servers)-1].isHttps = true 535 } 536 } 537 // HTTP 538 if !httpsEnabled && len(s.config.Address) == 0 { 539 s.config.Address = defaultHttpAddr 540 } 541 var array []string 542 if v, ok := fdMap["http"]; ok && len(v) > 0 { 543 array = gstr.SplitAndTrim(v, ",") 544 } else { 545 array = gstr.SplitAndTrim(s.config.Address, ",") 546 } 547 for _, v := range array { 548 if len(v) == 0 { 549 continue 550 } 551 var ( 552 fd = 0 553 itemFunc = v 554 addrAndFd = strings.Split(v, "#") 555 ) 556 if len(addrAndFd) > 1 { 557 itemFunc = addrAndFd[0] 558 // The Window OS does not support socket file descriptor passing 559 // from the parent process. 560 if runtime.GOOS != "windows" { 561 fd = gconv.Int(addrAndFd[1]) 562 } 563 } 564 if fd > 0 { 565 s.servers = append(s.servers, s.newGracefulServer(itemFunc, fd)) 566 } else { 567 s.servers = append(s.servers, s.newGracefulServer(itemFunc)) 568 } 569 } 570 // Start listening asynchronously. 571 serverRunning.Add(1) 572 var wg = sync.WaitGroup{} 573 for _, v := range s.servers { 574 wg.Add(1) 575 go func(server *gracefulServer) { 576 s.serverCount.Add(1) 577 var err error 578 // Create listener. 579 if server.isHttps { 580 err = server.CreateListenerTLS( 581 s.config.HTTPSCertPath, s.config.HTTPSKeyPath, s.config.TLSConfig, 582 ) 583 } else { 584 err = server.CreateListener() 585 } 586 if err != nil { 587 s.Logger().Fatalf(ctx, `%+v`, err) 588 } 589 wg.Done() 590 // Start listening and serving in blocking way. 591 err = server.Serve(ctx) 592 // The process exits if the server is closed with none closing error. 593 if err != nil && !strings.EqualFold(http.ErrServerClosed.Error(), err.Error()) { 594 s.Logger().Fatalf(ctx, `%+v`, err) 595 } 596 // If all the underlying servers' shutdown, the process exits. 597 if s.serverCount.Add(-1) < 1 { 598 s.closeChan <- struct{}{} 599 if serverRunning.Add(-1) < 1 { 600 serverMapping.Remove(s.instance) 601 allShutdownChan <- struct{}{} 602 } 603 } 604 }(v) 605 } 606 wg.Wait() 607 } 608 609 // Status retrieves and returns the server status. 610 func (s *Server) Status() ServerStatus { 611 if serverRunning.Val() == 0 { 612 return ServerStatusStopped 613 } 614 // If any underlying server is running, the server status is running. 615 for _, v := range s.servers { 616 if v.status.Val() == ServerStatusRunning { 617 return ServerStatusRunning 618 } 619 } 620 return ServerStatusStopped 621 } 622 623 // getListenerFdMap retrieves and returns the socket file descriptors. 624 // The key of the returned map is "http" and "https". 625 func (s *Server) getListenerFdMap() map[string]string { 626 m := map[string]string{ 627 "https": "", 628 "http": "", 629 } 630 for _, v := range s.servers { 631 str := v.address + "#" + gconv.String(v.Fd()) + "," 632 if v.isHttps { 633 if len(m["https"]) > 0 { 634 m["https"] += "," 635 } 636 m["https"] += str 637 } else { 638 if len(m["http"]) > 0 { 639 m["http"] += "," 640 } 641 m["http"] += str 642 } 643 } 644 return m 645 } 646 647 // GetListenedPort retrieves and returns one port which is listened by current server. 648 func (s *Server) GetListenedPort() int { 649 ports := s.GetListenedPorts() 650 if len(ports) > 0 { 651 return ports[0] 652 } 653 return 0 654 } 655 656 // GetListenedPorts retrieves and returns the ports which are listened by current server. 657 func (s *Server) GetListenedPorts() []int { 658 ports := make([]int, 0) 659 for _, server := range s.servers { 660 ports = append(ports, server.GetListenedPort()) 661 } 662 return ports 663 } 664 665 // GetListenedAddress retrieves and returns the address string which are listened by current server. 666 func (s *Server) GetListenedAddress() string { 667 if !gstr.Contains(s.config.Address, FreePortAddress) { 668 return s.config.Address 669 } 670 var ( 671 address = s.config.Address 672 listenedPorts = s.GetListenedPorts() 673 ) 674 for _, listenedPort := range listenedPorts { 675 address = gstr.Replace(address, FreePortAddress, fmt.Sprintf(`:%d`, listenedPort), 1) 676 } 677 return address 678 }