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.

326 lines
9.1 KiB

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