You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

364 lines
10 KiB

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