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.

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