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.

317 lines
8.9 KiB

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