filer_server_handlers.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package weed_server
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "os"
  7. "strconv"
  8. "strings"
  9. "sync/atomic"
  10. "time"
  11. "github.com/seaweedfs/seaweedfs/weed/filer"
  12. "github.com/seaweedfs/seaweedfs/weed/glog"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/security"
  15. "github.com/seaweedfs/seaweedfs/weed/util"
  16. "github.com/seaweedfs/seaweedfs/weed/stats"
  17. )
  18. func (fs *FilerServer) filerHandler(w http.ResponseWriter, r *http.Request) {
  19. start := time.Now()
  20. inFlightGauge := stats.FilerInFlightRequestsGauge.WithLabelValues(r.Method)
  21. inFlightGauge.Inc()
  22. defer inFlightGauge.Dec()
  23. statusRecorder := stats.NewStatusResponseWriter(w)
  24. w = statusRecorder
  25. origin := r.Header.Get("Origin")
  26. if origin != "" {
  27. if fs.option.AllowedOrigins == nil || len(fs.option.AllowedOrigins) == 0 || fs.option.AllowedOrigins[0] == "*" {
  28. origin = "*"
  29. } else {
  30. originFound := false
  31. for _, allowedOrigin := range fs.option.AllowedOrigins {
  32. if origin == allowedOrigin {
  33. originFound = true
  34. }
  35. }
  36. if !originFound {
  37. writeJsonError(w, r, http.StatusForbidden, errors.New("origin not allowed"))
  38. return
  39. }
  40. }
  41. w.Header().Set("Access-Control-Allow-Origin", origin)
  42. w.Header().Set("Access-Control-Expose-Headers", "*")
  43. w.Header().Set("Access-Control-Allow-Headers", "*")
  44. w.Header().Set("Access-Control-Allow-Credentials", "true")
  45. w.Header().Set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS")
  46. }
  47. if r.Method == http.MethodOptions {
  48. OptionsHandler(w, r, false)
  49. return
  50. }
  51. // proxy to volume servers
  52. var fileId string
  53. if strings.HasPrefix(r.RequestURI, "/?proxyChunkId=") {
  54. fileId = r.RequestURI[len("/?proxyChunkId="):]
  55. }
  56. if fileId != "" {
  57. fs.proxyToVolumeServer(w, r, fileId)
  58. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkProxy).Inc()
  59. stats.FilerRequestHistogram.WithLabelValues(stats.ChunkProxy).Observe(time.Since(start).Seconds())
  60. return
  61. }
  62. requestMethod := r.Method
  63. defer func(method *string) {
  64. stats.FilerRequestCounter.WithLabelValues(*method, strconv.Itoa(statusRecorder.Status)).Inc()
  65. stats.FilerRequestHistogram.WithLabelValues(*method).Observe(time.Since(start).Seconds())
  66. }(&requestMethod)
  67. isReadHttpCall := r.Method == http.MethodGet || r.Method == http.MethodHead
  68. if !fs.maybeCheckJwtAuthorization(r, !isReadHttpCall) {
  69. writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
  70. return
  71. }
  72. w.Header().Set("Server", "SeaweedFS "+util.VERSION)
  73. switch r.Method {
  74. case http.MethodGet, http.MethodHead:
  75. fs.GetOrHeadHandler(w, r)
  76. case http.MethodDelete:
  77. if _, ok := r.URL.Query()["tagging"]; ok {
  78. fs.DeleteTaggingHandler(w, r)
  79. } else {
  80. fs.DeleteHandler(w, r)
  81. }
  82. case http.MethodPost, http.MethodPut:
  83. // wait until in flight data is less than the limit
  84. contentLength := getContentLength(r)
  85. fs.inFlightDataLimitCond.L.Lock()
  86. inFlightDataSize := atomic.LoadInt64(&fs.inFlightDataSize)
  87. for fs.option.ConcurrentUploadLimit != 0 && inFlightDataSize > fs.option.ConcurrentUploadLimit {
  88. glog.V(4).Infof("wait because inflight data %d > %d", inFlightDataSize, fs.option.ConcurrentUploadLimit)
  89. fs.inFlightDataLimitCond.Wait()
  90. inFlightDataSize = atomic.LoadInt64(&fs.inFlightDataSize)
  91. }
  92. fs.inFlightDataLimitCond.L.Unlock()
  93. atomic.AddInt64(&fs.inFlightDataSize, contentLength)
  94. defer func() {
  95. atomic.AddInt64(&fs.inFlightDataSize, -contentLength)
  96. fs.inFlightDataLimitCond.Signal()
  97. }()
  98. if r.Method == http.MethodPut {
  99. if _, ok := r.URL.Query()["tagging"]; ok {
  100. fs.PutTaggingHandler(w, r)
  101. } else {
  102. fs.PostHandler(w, r, contentLength)
  103. }
  104. } else { // method == "POST"
  105. fs.PostHandler(w, r, contentLength)
  106. }
  107. default:
  108. requestMethod = "INVALID"
  109. w.WriteHeader(http.StatusMethodNotAllowed)
  110. }
  111. }
  112. func (fs *FilerServer) readonlyFilerHandler(w http.ResponseWriter, r *http.Request) {
  113. start := time.Now()
  114. statusRecorder := stats.NewStatusResponseWriter(w)
  115. w = statusRecorder
  116. os.Stdout.WriteString("Request: " + r.Method + " " + r.URL.String() + "\n")
  117. origin := r.Header.Get("Origin")
  118. if origin != "" {
  119. if fs.option.AllowedOrigins == nil || len(fs.option.AllowedOrigins) == 0 || fs.option.AllowedOrigins[0] == "*" {
  120. origin = "*"
  121. } else {
  122. originFound := false
  123. for _, allowedOrigin := range fs.option.AllowedOrigins {
  124. if origin == allowedOrigin {
  125. originFound = true
  126. }
  127. }
  128. if !originFound {
  129. writeJsonError(w, r, http.StatusForbidden, errors.New("origin not allowed"))
  130. return
  131. }
  132. }
  133. w.Header().Set("Access-Control-Allow-Origin", origin)
  134. w.Header().Set("Access-Control-Allow-Headers", "OPTIONS, GET, HEAD")
  135. w.Header().Set("Access-Control-Allow-Credentials", "true")
  136. }
  137. requestMethod := r.Method
  138. defer func(method *string) {
  139. stats.FilerRequestCounter.WithLabelValues(*method, strconv.Itoa(statusRecorder.Status)).Inc()
  140. stats.FilerRequestHistogram.WithLabelValues(*method).Observe(time.Since(start).Seconds())
  141. }(&requestMethod)
  142. // We handle OPTIONS first because it never should be authenticated
  143. if r.Method == http.MethodOptions {
  144. OptionsHandler(w, r, true)
  145. return
  146. }
  147. if !fs.maybeCheckJwtAuthorization(r, false) {
  148. writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
  149. return
  150. }
  151. w.Header().Set("Server", "SeaweedFS "+util.VERSION)
  152. switch r.Method {
  153. case http.MethodGet, http.MethodHead:
  154. fs.GetOrHeadHandler(w, r)
  155. default:
  156. requestMethod = "INVALID"
  157. w.WriteHeader(http.StatusMethodNotAllowed)
  158. }
  159. }
  160. func OptionsHandler(w http.ResponseWriter, r *http.Request, isReadOnly bool) {
  161. if isReadOnly {
  162. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  163. } else {
  164. w.Header().Set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS")
  165. w.Header().Set("Access-Control-Expose-Headers", "*")
  166. }
  167. w.Header().Set("Access-Control-Allow-Headers", "*")
  168. w.Header().Set("Access-Control-Allow-Credentials", "true")
  169. }
  170. // maybeCheckJwtAuthorization returns true if access should be granted, false if it should be denied
  171. func (fs *FilerServer) maybeCheckJwtAuthorization(r *http.Request, isWrite bool) bool {
  172. var signingKey security.SigningKey
  173. if isWrite {
  174. if len(fs.filerGuard.SigningKey) == 0 {
  175. return true
  176. } else {
  177. signingKey = fs.filerGuard.SigningKey
  178. }
  179. } else {
  180. if len(fs.filerGuard.ReadSigningKey) == 0 {
  181. return true
  182. } else {
  183. signingKey = fs.filerGuard.ReadSigningKey
  184. }
  185. }
  186. tokenStr := security.GetJwt(r)
  187. if tokenStr == "" {
  188. glog.V(1).Infof("missing jwt from %s", r.RemoteAddr)
  189. return false
  190. }
  191. token, err := security.DecodeJwt(signingKey, tokenStr, &security.SeaweedFilerClaims{})
  192. if err != nil {
  193. glog.V(1).Infof("jwt verification error from %s: %v", r.RemoteAddr, err)
  194. return false
  195. }
  196. if !token.Valid {
  197. glog.V(1).Infof("jwt invalid from %s: %v", r.RemoteAddr, tokenStr)
  198. return false
  199. } else {
  200. return true
  201. }
  202. }
  203. func (fs *FilerServer) filerHealthzHandler(w http.ResponseWriter, r *http.Request) {
  204. w.Header().Set("Server", "SeaweedFS "+util.VERSION)
  205. if _, err := fs.filer.Store.FindEntry(context.Background(), filer.TopicsDir); err != nil && err != filer_pb.ErrNotFound {
  206. glog.Warningf("filerHealthzHandler FindEntry: %+v", err)
  207. w.WriteHeader(http.StatusServiceUnavailable)
  208. } else {
  209. w.WriteHeader(http.StatusOK)
  210. }
  211. }