engine.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package rest
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/justinas/alice"
  8. "github.com/tal-tech/go-zero/core/codec"
  9. "github.com/tal-tech/go-zero/core/load"
  10. "github.com/tal-tech/go-zero/core/stat"
  11. "github.com/tal-tech/go-zero/rest/handler"
  12. "github.com/tal-tech/go-zero/rest/httpx"
  13. "github.com/tal-tech/go-zero/rest/internal"
  14. "github.com/tal-tech/go-zero/rest/router"
  15. )
  16. // use 1000m to represent 100%
  17. const topCpuUsage = 1000
  18. var ErrSignatureConfig = errors.New("bad config for Signature")
  19. type engine struct {
  20. conf RestConf
  21. routes []featuredRoutes
  22. unauthorizedCallback handler.UnauthorizedCallback
  23. unsignedCallback handler.UnsignedCallback
  24. middlewares []Middleware
  25. shedder load.Shedder
  26. priorityShedder load.Shedder
  27. }
  28. func newEngine(c RestConf) *engine {
  29. srv := &engine{
  30. conf: c,
  31. }
  32. if c.CpuThreshold > 0 {
  33. srv.shedder = load.NewAdaptiveShedder(load.WithCpuThreshold(c.CpuThreshold))
  34. srv.priorityShedder = load.NewAdaptiveShedder(load.WithCpuThreshold(
  35. (c.CpuThreshold + topCpuUsage) >> 1))
  36. }
  37. return srv
  38. }
  39. func (s *engine) AddRoutes(r featuredRoutes) {
  40. s.routes = append(s.routes, r)
  41. }
  42. func (s *engine) SetUnauthorizedCallback(callback handler.UnauthorizedCallback) {
  43. s.unauthorizedCallback = callback
  44. }
  45. func (s *engine) SetUnsignedCallback(callback handler.UnsignedCallback) {
  46. s.unsignedCallback = callback
  47. }
  48. func (s *engine) Start() error {
  49. return s.StartWithRouter(router.NewPatRouter())
  50. }
  51. func (s *engine) StartWithRouter(router httpx.Router) error {
  52. if err := s.bindRoutes(router); err != nil {
  53. return err
  54. }
  55. return internal.StartHttp(s.conf.Host, s.conf.Port, router)
  56. }
  57. func (s *engine) appendAuthHandler(fr featuredRoutes, chain alice.Chain,
  58. verifier func(alice.Chain) alice.Chain) alice.Chain {
  59. if fr.jwt.enabled {
  60. if len(fr.jwt.prevSecret) == 0 {
  61. chain = chain.Append(handler.Authorize(fr.jwt.secret,
  62. handler.WithUnauthorizedCallback(s.unauthorizedCallback)))
  63. } else {
  64. chain = chain.Append(handler.Authorize(fr.jwt.secret,
  65. handler.WithPrevSecret(fr.jwt.prevSecret),
  66. handler.WithUnauthorizedCallback(s.unauthorizedCallback)))
  67. }
  68. }
  69. return verifier(chain)
  70. }
  71. func (s *engine) bindFeaturedRoutes(router httpx.Router, fr featuredRoutes, metrics *stat.Metrics) error {
  72. verifier, err := s.signatureVerifier(fr.signature)
  73. if err != nil {
  74. return err
  75. }
  76. for _, route := range fr.routes {
  77. if err := s.bindRoute(fr, router, metrics, route, verifier); err != nil {
  78. return err
  79. }
  80. }
  81. return nil
  82. }
  83. func (s *engine) bindRoute(fr featuredRoutes, router httpx.Router, metrics *stat.Metrics,
  84. route Route, verifier func(chain alice.Chain) alice.Chain) error {
  85. chain := alice.New(
  86. handler.TracingHandler,
  87. s.getLogHandler(),
  88. handler.MaxConns(s.conf.MaxConns),
  89. handler.BreakerHandler(route.Method, route.Path, metrics),
  90. handler.SheddingHandler(s.getShedder(fr.priority), metrics),
  91. handler.TimeoutHandler(time.Duration(s.conf.Timeout)*time.Millisecond),
  92. handler.RecoverHandler,
  93. handler.MetricHandler(metrics),
  94. handler.PromethousHandler(route.Path),
  95. handler.MaxBytesHandler(s.conf.MaxBytes),
  96. handler.GunzipHandler,
  97. )
  98. chain = s.appendAuthHandler(fr, chain, verifier)
  99. for _, middleware := range s.middlewares {
  100. chain = chain.Append(convertMiddleware(middleware))
  101. }
  102. handle := chain.ThenFunc(route.Handler)
  103. return router.Handle(route.Method, route.Path, handle)
  104. }
  105. func (s *engine) bindRoutes(router httpx.Router) error {
  106. metrics := s.createMetrics()
  107. for _, fr := range s.routes {
  108. if err := s.bindFeaturedRoutes(router, fr, metrics); err != nil {
  109. return err
  110. }
  111. }
  112. return nil
  113. }
  114. func (s *engine) createMetrics() *stat.Metrics {
  115. var metrics *stat.Metrics
  116. if len(s.conf.Name) > 0 {
  117. metrics = stat.NewMetrics(s.conf.Name)
  118. } else {
  119. metrics = stat.NewMetrics(fmt.Sprintf("%s:%d", s.conf.Host, s.conf.Port))
  120. }
  121. return metrics
  122. }
  123. func (s *engine) getLogHandler() func(http.Handler) http.Handler {
  124. if s.conf.Verbose {
  125. return handler.DetailedLogHandler
  126. } else {
  127. return handler.LogHandler
  128. }
  129. }
  130. func (s *engine) getShedder(priority bool) load.Shedder {
  131. if priority && s.priorityShedder != nil {
  132. return s.priorityShedder
  133. }
  134. return s.shedder
  135. }
  136. func (s *engine) signatureVerifier(signature signatureSetting) (func(chain alice.Chain) alice.Chain, error) {
  137. if !signature.enabled {
  138. return func(chain alice.Chain) alice.Chain {
  139. return chain
  140. }, nil
  141. }
  142. if len(signature.PrivateKeys) == 0 {
  143. if signature.Strict {
  144. return nil, ErrSignatureConfig
  145. } else {
  146. return func(chain alice.Chain) alice.Chain {
  147. return chain
  148. }, nil
  149. }
  150. }
  151. decrypters := make(map[string]codec.RsaDecrypter)
  152. for _, key := range signature.PrivateKeys {
  153. fingerprint := key.Fingerprint
  154. file := key.KeyFile
  155. decrypter, err := codec.NewRsaDecrypter(file)
  156. if err != nil {
  157. return nil, err
  158. }
  159. decrypters[fingerprint] = decrypter
  160. }
  161. return func(chain alice.Chain) alice.Chain {
  162. if s.unsignedCallback != nil {
  163. return chain.Append(handler.ContentSecurityHandler(
  164. decrypters, signature.Expiry, signature.Strict, s.unsignedCallback))
  165. } else {
  166. return chain.Append(handler.ContentSecurityHandler(
  167. decrypters, signature.Expiry, signature.Strict))
  168. }
  169. }, nil
  170. }
  171. func (s *engine) use(middleware Middleware) {
  172. s.middlewares = append(s.middlewares, middleware)
  173. }
  174. func convertMiddleware(ware Middleware) func(http.Handler) http.Handler {
  175. return func(next http.Handler) http.Handler {
  176. return ware(next.ServeHTTP)
  177. }
  178. }