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.

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