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.

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