common.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package weed_server
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/fs"
  11. "mime/multipart"
  12. "net/http"
  13. "net/url"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/google/uuid"
  20. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  21. "github.com/seaweedfs/seaweedfs/weed/util/request_id"
  22. "github.com/seaweedfs/seaweedfs/weed/util/version"
  23. "google.golang.org/grpc/metadata"
  24. "github.com/seaweedfs/seaweedfs/weed/filer"
  25. "google.golang.org/grpc"
  26. "github.com/gorilla/mux"
  27. "github.com/seaweedfs/seaweedfs/weed/glog"
  28. "github.com/seaweedfs/seaweedfs/weed/operation"
  29. "github.com/seaweedfs/seaweedfs/weed/stats"
  30. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  31. )
  32. var serverStats *stats.ServerStats
  33. var startTime = time.Now()
  34. var writePool = sync.Pool{New: func() interface{} {
  35. return bufio.NewWriterSize(nil, 128*1024)
  36. },
  37. }
  38. func init() {
  39. serverStats = stats.NewServerStats()
  40. go serverStats.Start()
  41. }
  42. // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
  43. func bodyAllowedForStatus(status int) bool {
  44. switch {
  45. case status >= 100 && status <= 199:
  46. return false
  47. case status == http.StatusNoContent:
  48. return false
  49. case status == http.StatusNotModified:
  50. return false
  51. }
  52. return true
  53. }
  54. func writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {
  55. if !bodyAllowedForStatus(httpStatus) {
  56. return
  57. }
  58. var bytes []byte
  59. if obj != nil {
  60. if r.FormValue("pretty") != "" {
  61. bytes, err = json.MarshalIndent(obj, "", " ")
  62. } else {
  63. bytes, err = json.Marshal(obj)
  64. }
  65. }
  66. if err != nil {
  67. return
  68. }
  69. if httpStatus >= 400 {
  70. glog.V(0).Infof("response method:%s URL:%s with httpStatus:%d and JSON:%s",
  71. r.Method, r.URL.String(), httpStatus, string(bytes))
  72. }
  73. callback := r.FormValue("callback")
  74. if callback == "" {
  75. w.Header().Set("Content-Type", "application/json")
  76. w.WriteHeader(httpStatus)
  77. if httpStatus == http.StatusNotModified {
  78. return
  79. }
  80. _, err = w.Write(bytes)
  81. } else {
  82. w.Header().Set("Content-Type", "application/javascript")
  83. w.WriteHeader(httpStatus)
  84. if httpStatus == http.StatusNotModified {
  85. return
  86. }
  87. if _, err = w.Write([]uint8(callback)); err != nil {
  88. return
  89. }
  90. if _, err = w.Write([]uint8("(")); err != nil {
  91. return
  92. }
  93. fmt.Fprint(w, string(bytes))
  94. if _, err = w.Write([]uint8(")")); err != nil {
  95. return
  96. }
  97. }
  98. return
  99. }
  100. // wrapper for writeJson - just logs errors
  101. func writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {
  102. if err := writeJson(w, r, httpStatus, obj); err != nil {
  103. glog.V(0).Infof("error writing JSON status %s %d: %v", r.URL, httpStatus, err)
  104. glog.V(1).Infof("JSON content: %+v", obj)
  105. }
  106. }
  107. func writeJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) {
  108. m := make(map[string]interface{})
  109. m["error"] = err.Error()
  110. glog.V(1).Infof("error JSON response status %d: %s", httpStatus, m["error"])
  111. writeJsonQuiet(w, r, httpStatus, m)
  112. }
  113. func debug(params ...interface{}) {
  114. glog.V(4).Infoln(params...)
  115. }
  116. func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterFn operation.GetMasterFn, grpcDialOption grpc.DialOption) {
  117. ctx := r.Context()
  118. m := make(map[string]interface{})
  119. if r.Method != http.MethodPost {
  120. writeJsonError(w, r, http.StatusMethodNotAllowed, errors.New("Only submit via POST!"))
  121. return
  122. }
  123. debug("parsing upload file...")
  124. bytesBuffer := bufPool.Get().(*bytes.Buffer)
  125. defer bufPool.Put(bytesBuffer)
  126. pu, pe := needle.ParseUpload(r, 256*1024*1024, bytesBuffer)
  127. if pe != nil {
  128. writeJsonError(w, r, http.StatusBadRequest, pe)
  129. return
  130. }
  131. debug("assigning file id for", pu.FileName)
  132. r.ParseForm()
  133. count := uint64(1)
  134. if r.FormValue("count") != "" {
  135. count, pe = strconv.ParseUint(r.FormValue("count"), 10, 32)
  136. if pe != nil {
  137. writeJsonError(w, r, http.StatusBadRequest, pe)
  138. return
  139. }
  140. }
  141. ar := &operation.VolumeAssignRequest{
  142. Count: count,
  143. DataCenter: r.FormValue("dataCenter"),
  144. Rack: r.FormValue("rack"),
  145. Replication: r.FormValue("replication"),
  146. Collection: r.FormValue("collection"),
  147. Ttl: r.FormValue("ttl"),
  148. DiskType: r.FormValue("disk"),
  149. }
  150. assignResult, ae := operation.Assign(ctx, masterFn, grpcDialOption, ar)
  151. if ae != nil {
  152. writeJsonError(w, r, http.StatusInternalServerError, ae)
  153. return
  154. }
  155. url := "http://" + assignResult.Url + "/" + assignResult.Fid
  156. if pu.ModifiedTime != 0 {
  157. url = url + "?ts=" + strconv.FormatUint(pu.ModifiedTime, 10)
  158. }
  159. debug("upload file to store", url)
  160. uploadOption := &operation.UploadOption{
  161. UploadUrl: url,
  162. Filename: pu.FileName,
  163. Cipher: false,
  164. IsInputCompressed: pu.IsGzipped,
  165. MimeType: pu.MimeType,
  166. PairMap: pu.PairMap,
  167. Jwt: assignResult.Auth,
  168. }
  169. uploader, err := operation.NewUploader()
  170. if err != nil {
  171. writeJsonError(w, r, http.StatusInternalServerError, err)
  172. return
  173. }
  174. uploadResult, err := uploader.UploadData(ctx, pu.Data, uploadOption)
  175. if err != nil {
  176. writeJsonError(w, r, http.StatusInternalServerError, err)
  177. return
  178. }
  179. m["fileName"] = pu.FileName
  180. m["fid"] = assignResult.Fid
  181. m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid
  182. m["size"] = pu.OriginalDataSize
  183. m["eTag"] = uploadResult.ETag
  184. writeJsonQuiet(w, r, http.StatusCreated, m)
  185. return
  186. }
  187. func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {
  188. switch strings.Count(path, "/") {
  189. case 3:
  190. parts := strings.Split(path, "/")
  191. vid, fid, filename = parts[1], parts[2], parts[3]
  192. ext = filepath.Ext(filename)
  193. case 2:
  194. parts := strings.Split(path, "/")
  195. vid, fid = parts[1], parts[2]
  196. dotIndex := strings.LastIndex(fid, ".")
  197. if dotIndex > 0 {
  198. ext = fid[dotIndex:]
  199. fid = fid[0:dotIndex]
  200. }
  201. default:
  202. sepIndex := strings.LastIndex(path, "/")
  203. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  204. if commaIndex <= 0 {
  205. vid, isVolumeIdOnly = path[sepIndex+1:], true
  206. return
  207. }
  208. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  209. vid = path[sepIndex+1 : commaIndex]
  210. fid = path[commaIndex+1:]
  211. ext = ""
  212. if dotIndex > 0 {
  213. fid = path[commaIndex+1 : dotIndex]
  214. ext = path[dotIndex:]
  215. }
  216. }
  217. return
  218. }
  219. func statsHealthHandler(w http.ResponseWriter, r *http.Request) {
  220. m := make(map[string]interface{})
  221. m["Version"] = version.Version()
  222. writeJsonQuiet(w, r, http.StatusOK, m)
  223. }
  224. func statsCounterHandler(w http.ResponseWriter, r *http.Request) {
  225. m := make(map[string]interface{})
  226. m["Version"] = version.Version()
  227. m["Counters"] = serverStats
  228. writeJsonQuiet(w, r, http.StatusOK, m)
  229. }
  230. func statsMemoryHandler(w http.ResponseWriter, r *http.Request) {
  231. m := make(map[string]interface{})
  232. m["Version"] = version.Version()
  233. m["Memory"] = stats.MemStat()
  234. writeJsonQuiet(w, r, http.StatusOK, m)
  235. }
  236. var StaticFS fs.FS
  237. func handleStaticResources(defaultMux *http.ServeMux) {
  238. defaultMux.Handle("/favicon.ico", http.FileServer(http.FS(StaticFS)))
  239. defaultMux.Handle("/seaweedfsstatic/", http.StripPrefix("/seaweedfsstatic", http.FileServer(http.FS(StaticFS))))
  240. }
  241. func handleStaticResources2(r *mux.Router) {
  242. r.Handle("/favicon.ico", http.FileServer(http.FS(StaticFS)))
  243. r.PathPrefix("/seaweedfsstatic/").Handler(http.StripPrefix("/seaweedfsstatic", http.FileServer(http.FS(StaticFS))))
  244. }
  245. func AdjustPassthroughHeaders(w http.ResponseWriter, r *http.Request, filename string) {
  246. // Apply S3 passthrough headers from query parameters
  247. // AWS S3 supports overriding response headers via query parameters like:
  248. // ?response-cache-control=no-cache&response-content-type=application/json
  249. for queryParam, headerValue := range r.URL.Query() {
  250. if normalizedHeader, ok := s3_constants.PassThroughHeaders[strings.ToLower(queryParam)]; ok && len(headerValue) > 0 {
  251. w.Header().Set(normalizedHeader, headerValue[0])
  252. }
  253. }
  254. adjustHeaderContentDisposition(w, r, filename)
  255. }
  256. func adjustHeaderContentDisposition(w http.ResponseWriter, r *http.Request, filename string) {
  257. if contentDisposition := w.Header().Get("Content-Disposition"); contentDisposition != "" {
  258. return
  259. }
  260. if filename != "" {
  261. filename = url.QueryEscape(filename)
  262. contentDisposition := "inline"
  263. if r.FormValue("dl") != "" {
  264. if dl, _ := strconv.ParseBool(r.FormValue("dl")); dl {
  265. contentDisposition = "attachment"
  266. }
  267. }
  268. w.Header().Set("Content-Disposition", contentDisposition+`; filename="`+fileNameEscaper.Replace(filename)+`"`)
  269. }
  270. }
  271. func ProcessRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64, mimeType string, prepareWriteFn func(offset int64, size int64) (filer.DoStreamContent, error)) error {
  272. rangeReq := r.Header.Get("Range")
  273. bufferedWriter := writePool.Get().(*bufio.Writer)
  274. bufferedWriter.Reset(w)
  275. defer func() {
  276. bufferedWriter.Flush()
  277. writePool.Put(bufferedWriter)
  278. }()
  279. if rangeReq == "" {
  280. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  281. writeFn, err := prepareWriteFn(0, totalSize)
  282. if err != nil {
  283. glog.Errorf("ProcessRangeRequest: %v", err)
  284. w.Header().Del("Content-Length")
  285. http.Error(w, err.Error(), http.StatusInternalServerError)
  286. return fmt.Errorf("ProcessRangeRequest: %w", err)
  287. }
  288. if err = writeFn(bufferedWriter); err != nil {
  289. glog.Errorf("ProcessRangeRequest: %v", err)
  290. w.Header().Del("Content-Length")
  291. http.Error(w, err.Error(), http.StatusInternalServerError)
  292. return fmt.Errorf("ProcessRangeRequest: %w", err)
  293. }
  294. return nil
  295. }
  296. //the rest is dealing with partial content request
  297. //mostly copy from src/pkg/net/http/fs.go
  298. ranges, err := parseRange(rangeReq, totalSize)
  299. if err != nil {
  300. glog.Errorf("ProcessRangeRequest headers: %+v err: %v", w.Header(), err)
  301. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  302. return fmt.Errorf("ProcessRangeRequest header: %w", err)
  303. }
  304. if sumRangesSize(ranges) > totalSize {
  305. // The total number of bytes in all the ranges
  306. // is larger than the size of the file by
  307. // itself, so this is probably an attack, or a
  308. // dumb client. Ignore the range request.
  309. return nil
  310. }
  311. if len(ranges) == 0 {
  312. return nil
  313. }
  314. if len(ranges) == 1 {
  315. // RFC 2616, Section 14.16:
  316. // "When an HTTP message includes the content of a single
  317. // range (for example, a response to a request for a
  318. // single range, or to a request for a set of ranges
  319. // that overlap without any holes), this content is
  320. // transmitted with a Content-Range header, and a
  321. // Content-Length header showing the number of bytes
  322. // actually transferred.
  323. // ...
  324. // A response to a request for a single range MUST NOT
  325. // be sent using the multipart/byteranges media type."
  326. ra := ranges[0]
  327. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  328. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  329. writeFn, err := prepareWriteFn(ra.start, ra.length)
  330. if err != nil {
  331. glog.Errorf("ProcessRangeRequest range[0]: %+v err: %v", w.Header(), err)
  332. w.Header().Del("Content-Length")
  333. http.Error(w, err.Error(), http.StatusInternalServerError)
  334. return fmt.Errorf("ProcessRangeRequest: %w", err)
  335. }
  336. w.WriteHeader(http.StatusPartialContent)
  337. err = writeFn(bufferedWriter)
  338. if err != nil {
  339. glog.Errorf("ProcessRangeRequest range[0]: %+v err: %v", w.Header(), err)
  340. w.Header().Del("Content-Length")
  341. http.Error(w, err.Error(), http.StatusInternalServerError)
  342. return fmt.Errorf("ProcessRangeRequest range[0]: %w", err)
  343. }
  344. return nil
  345. }
  346. // process multiple ranges
  347. writeFnByRange := make(map[int](func(writer io.Writer) error))
  348. for i, ra := range ranges {
  349. if ra.start > totalSize {
  350. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  351. return fmt.Errorf("out of range: %w", err)
  352. }
  353. writeFn, err := prepareWriteFn(ra.start, ra.length)
  354. if err != nil {
  355. glog.Errorf("ProcessRangeRequest range[%d] err: %v", i, err)
  356. http.Error(w, "Internal Error", http.StatusInternalServerError)
  357. return fmt.Errorf("ProcessRangeRequest range[%d] err: %v", i, err)
  358. }
  359. writeFnByRange[i] = writeFn
  360. }
  361. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  362. pr, pw := io.Pipe()
  363. mw := multipart.NewWriter(pw)
  364. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  365. sendContent := pr
  366. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  367. go func() {
  368. for i, ra := range ranges {
  369. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  370. if e != nil {
  371. pw.CloseWithError(e)
  372. return
  373. }
  374. writeFn := writeFnByRange[i]
  375. if writeFn == nil {
  376. pw.CloseWithError(e)
  377. return
  378. }
  379. if e = writeFn(part); e != nil {
  380. pw.CloseWithError(e)
  381. return
  382. }
  383. }
  384. mw.Close()
  385. pw.Close()
  386. }()
  387. if w.Header().Get("Content-Encoding") == "" {
  388. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  389. }
  390. w.WriteHeader(http.StatusPartialContent)
  391. if _, err := io.CopyN(bufferedWriter, sendContent, sendSize); err != nil {
  392. glog.Errorf("ProcessRangeRequest err: %v", err)
  393. http.Error(w, "Internal Error", http.StatusInternalServerError)
  394. return fmt.Errorf("ProcessRangeRequest err: %w", err)
  395. }
  396. return nil
  397. }
  398. func requestIDMiddleware(h http.HandlerFunc) http.HandlerFunc {
  399. return func(w http.ResponseWriter, r *http.Request) {
  400. reqID := r.Header.Get(request_id.AmzRequestIDHeader)
  401. if reqID == "" {
  402. reqID = uuid.New().String()
  403. }
  404. ctx := context.WithValue(r.Context(), request_id.AmzRequestIDHeader, reqID)
  405. ctx = metadata.NewOutgoingContext(ctx,
  406. metadata.New(map[string]string{
  407. request_id.AmzRequestIDHeader: reqID,
  408. }))
  409. w.Header().Set(request_id.AmzRequestIDHeader, reqID)
  410. h(w, r.WithContext(ctx))
  411. }
  412. }