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.

375 lines
11 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. "github.com/chrislusf/seaweedfs/weed/s3api/s3_constants"
  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 := s3_constants.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. glog.Errorf("processRangeRequest headers: %+v err: %v", w.Header(), err)
  259. http.Error(w, err.Error(), http.StatusInternalServerError)
  260. return
  261. }
  262. return
  263. }
  264. //the rest is dealing with partial content request
  265. //mostly copy from src/pkg/net/http/fs.go
  266. ranges, err := parseRange(rangeReq, totalSize)
  267. if err != nil {
  268. glog.Errorf("processRangeRequest headers: %+v err: %v", w.Header(), err)
  269. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  270. return
  271. }
  272. if sumRangesSize(ranges) > totalSize {
  273. // The total number of bytes in all the ranges
  274. // is larger than the size of the file by
  275. // itself, so this is probably an attack, or a
  276. // dumb client. Ignore the range request.
  277. return
  278. }
  279. if len(ranges) == 0 {
  280. return
  281. }
  282. if len(ranges) == 1 {
  283. // RFC 2616, Section 14.16:
  284. // "When an HTTP message includes the content of a single
  285. // range (for example, a response to a request for a
  286. // single range, or to a request for a set of ranges
  287. // that overlap without any holes), this content is
  288. // transmitted with a Content-Range header, and a
  289. // Content-Length header showing the number of bytes
  290. // actually transferred.
  291. // ...
  292. // A response to a request for a single range MUST NOT
  293. // be sent using the multipart/byteranges media type."
  294. ra := ranges[0]
  295. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  296. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  297. w.WriteHeader(http.StatusPartialContent)
  298. err = writeFn(bufferedWriter, ra.start, ra.length)
  299. if err != nil {
  300. glog.Errorf("processRangeRequest headers: %+v err: %v", w.Header(), err)
  301. http.Error(w, err.Error(), http.StatusInternalServerError)
  302. return
  303. }
  304. return
  305. }
  306. // process multiple ranges
  307. for _, ra := range ranges {
  308. if ra.start > totalSize {
  309. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  310. return
  311. }
  312. }
  313. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  314. pr, pw := io.Pipe()
  315. mw := multipart.NewWriter(pw)
  316. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  317. sendContent := pr
  318. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  319. go func() {
  320. for _, ra := range ranges {
  321. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  322. if e != nil {
  323. pw.CloseWithError(e)
  324. return
  325. }
  326. if e = writeFn(part, ra.start, ra.length); e != nil {
  327. pw.CloseWithError(e)
  328. return
  329. }
  330. }
  331. mw.Close()
  332. pw.Close()
  333. }()
  334. if w.Header().Get("Content-Encoding") == "" {
  335. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  336. }
  337. w.WriteHeader(http.StatusPartialContent)
  338. if _, err := io.CopyN(bufferedWriter, sendContent, sendSize); err != nil {
  339. glog.Errorf("processRangeRequest err: %v", err)
  340. http.Error(w, "Internal Error", http.StatusInternalServerError)
  341. return
  342. }
  343. }