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.

368 lines
10 KiB

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