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.

354 lines
9.8 KiB

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