common.go 12 KB

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