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.

325 lines
9.1 KiB

10 years ago
5 years ago
6 years ago
5 years ago
10 years ago
5 years ago
5 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. Replication: r.FormValue("replication"),
  115. Collection: r.FormValue("collection"),
  116. Ttl: r.FormValue("ttl"),
  117. }
  118. assignResult, ae := operation.Assign(masterUrl, grpcDialOption, ar)
  119. if ae != nil {
  120. writeJsonError(w, r, http.StatusInternalServerError, ae)
  121. return
  122. }
  123. url := "http://" + assignResult.Url + "/" + assignResult.Fid
  124. if pu.ModifiedTime != 0 {
  125. url = url + "?ts=" + strconv.FormatUint(pu.ModifiedTime, 10)
  126. }
  127. debug("upload file to store", url)
  128. uploadResult, err := operation.UploadData(url, pu.FileName, false, pu.Data, pu.IsGzipped, pu.MimeType, pu.PairMap, assignResult.Auth)
  129. if err != nil {
  130. writeJsonError(w, r, http.StatusInternalServerError, err)
  131. return
  132. }
  133. m["fileName"] = pu.FileName
  134. m["fid"] = assignResult.Fid
  135. m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid
  136. m["size"] = pu.OriginalDataSize
  137. m["eTag"] = uploadResult.ETag
  138. writeJsonQuiet(w, r, http.StatusCreated, m)
  139. return
  140. }
  141. func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {
  142. switch strings.Count(path, "/") {
  143. case 3:
  144. parts := strings.Split(path, "/")
  145. vid, fid, filename = parts[1], parts[2], parts[3]
  146. ext = filepath.Ext(filename)
  147. case 2:
  148. parts := strings.Split(path, "/")
  149. vid, fid = parts[1], parts[2]
  150. dotIndex := strings.LastIndex(fid, ".")
  151. if dotIndex > 0 {
  152. ext = fid[dotIndex:]
  153. fid = fid[0:dotIndex]
  154. }
  155. default:
  156. sepIndex := strings.LastIndex(path, "/")
  157. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  158. if commaIndex <= 0 {
  159. vid, isVolumeIdOnly = path[sepIndex+1:], true
  160. return
  161. }
  162. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  163. vid = path[sepIndex+1 : commaIndex]
  164. fid = path[commaIndex+1:]
  165. ext = ""
  166. if dotIndex > 0 {
  167. fid = path[commaIndex+1 : dotIndex]
  168. ext = path[dotIndex:]
  169. }
  170. }
  171. return
  172. }
  173. func statsHealthHandler(w http.ResponseWriter, r *http.Request) {
  174. m := make(map[string]interface{})
  175. m["Version"] = util.Version()
  176. writeJsonQuiet(w, r, http.StatusOK, m)
  177. }
  178. func statsCounterHandler(w http.ResponseWriter, r *http.Request) {
  179. m := make(map[string]interface{})
  180. m["Version"] = util.Version()
  181. m["Counters"] = serverStats
  182. writeJsonQuiet(w, r, http.StatusOK, m)
  183. }
  184. func statsMemoryHandler(w http.ResponseWriter, r *http.Request) {
  185. m := make(map[string]interface{})
  186. m["Version"] = util.Version()
  187. m["Memory"] = stats.MemStat()
  188. writeJsonQuiet(w, r, http.StatusOK, m)
  189. }
  190. func handleStaticResources(defaultMux *http.ServeMux) {
  191. defaultMux.Handle("/favicon.ico", http.FileServer(statikFS))
  192. defaultMux.Handle("/seaweedfsstatic/", http.StripPrefix("/seaweedfsstatic", http.FileServer(statikFS)))
  193. }
  194. func handleStaticResources2(r *mux.Router) {
  195. r.Handle("/favicon.ico", http.FileServer(statikFS))
  196. r.PathPrefix("/seaweedfsstatic/").Handler(http.StripPrefix("/seaweedfsstatic", http.FileServer(statikFS)))
  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. w.WriteHeader(http.StatusPartialContent)
  252. err = writeFn(w, ra.start, ra.length)
  253. if err != nil {
  254. http.Error(w, err.Error(), http.StatusInternalServerError)
  255. return
  256. }
  257. return
  258. }
  259. // process multiple ranges
  260. for _, ra := range ranges {
  261. if ra.start > totalSize {
  262. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  263. return
  264. }
  265. }
  266. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  267. pr, pw := io.Pipe()
  268. mw := multipart.NewWriter(pw)
  269. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  270. sendContent := pr
  271. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  272. go func() {
  273. for _, ra := range ranges {
  274. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  275. if e != nil {
  276. pw.CloseWithError(e)
  277. return
  278. }
  279. if e = writeFn(part, ra.start, ra.length); e != nil {
  280. pw.CloseWithError(e)
  281. return
  282. }
  283. }
  284. mw.Close()
  285. pw.Close()
  286. }()
  287. if w.Header().Get("Content-Encoding") == "" {
  288. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  289. }
  290. w.WriteHeader(http.StatusPartialContent)
  291. if _, err := io.CopyN(w, sendContent, sendSize); err != nil {
  292. http.Error(w, "Internal Error", http.StatusInternalServerError)
  293. return
  294. }
  295. }