common.go 11 KB

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