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.

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