common.go 11 KB

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