engine.go 5.6 KB

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