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.

332 lines
9.3 KiB

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