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.

339 lines
9.6 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. package weed_server
  2. import (
  3. "code.google.com/p/weed-fs/go/glog"
  4. "code.google.com/p/weed-fs/go/images"
  5. "code.google.com/p/weed-fs/go/operation"
  6. "code.google.com/p/weed-fs/go/stats"
  7. "code.google.com/p/weed-fs/go/storage"
  8. "code.google.com/p/weed-fs/go/topology"
  9. "io"
  10. "mime"
  11. "mime/multipart"
  12. "net/http"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  18. func (vs *VolumeServer) storeHandler(w http.ResponseWriter, r *http.Request) {
  19. switch r.Method {
  20. case "GET":
  21. stats.ReadRequest()
  22. vs.GetOrHeadHandler(w, r)
  23. case "HEAD":
  24. stats.ReadRequest()
  25. vs.GetOrHeadHandler(w, r)
  26. case "DELETE":
  27. stats.DeleteRequest()
  28. secure(vs.whiteList, vs.DeleteHandler)(w, r)
  29. case "PUT":
  30. stats.WriteRequest()
  31. secure(vs.whiteList, vs.PostHandler)(w, r)
  32. case "POST":
  33. stats.WriteRequest()
  34. secure(vs.whiteList, vs.PostHandler)(w, r)
  35. }
  36. }
  37. func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  38. n := new(storage.Needle)
  39. vid, fid, filename, ext, _ := parseURLPath(r.URL.Path)
  40. volumeId, err := storage.NewVolumeId(vid)
  41. if err != nil {
  42. glog.V(2).Infoln("parsing error:", err, r.URL.Path)
  43. w.WriteHeader(http.StatusBadRequest)
  44. return
  45. }
  46. err = n.ParsePath(fid)
  47. if err != nil {
  48. glog.V(2).Infoln("parsing fid error:", err, r.URL.Path)
  49. w.WriteHeader(http.StatusBadRequest)
  50. return
  51. }
  52. glog.V(4).Infoln("volume", volumeId, "reading", n)
  53. if !vs.store.HasVolume(volumeId) {
  54. lookupResult, err := operation.Lookup(vs.masterNode, volumeId.String())
  55. glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err)
  56. if err == nil && len(lookupResult.Locations) > 0 {
  57. http.Redirect(w, r, "http://"+lookupResult.Locations[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
  58. } else {
  59. glog.V(2).Infoln("lookup error:", err, r.URL.Path)
  60. w.WriteHeader(http.StatusNotFound)
  61. }
  62. return
  63. }
  64. cookie := n.Cookie
  65. count, e := vs.store.Read(volumeId, n)
  66. glog.V(4).Infoln("read bytes", count, "error", e)
  67. if e != nil || count <= 0 {
  68. glog.V(0).Infoln("read error:", e, r.URL.Path)
  69. w.WriteHeader(http.StatusNotFound)
  70. return
  71. }
  72. if n.Cookie != cookie {
  73. glog.V(0).Infoln("request", r.URL.Path, "with unmaching cookie seen:", cookie, "expected:", n.Cookie, "from", r.RemoteAddr, "agent", r.UserAgent())
  74. w.WriteHeader(http.StatusNotFound)
  75. return
  76. }
  77. if n.LastModified != 0 {
  78. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  79. if r.Header.Get("If-Modified-Since") != "" {
  80. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  81. if t.Unix() >= int64(n.LastModified) {
  82. w.WriteHeader(http.StatusNotModified)
  83. return
  84. }
  85. }
  86. }
  87. }
  88. etag := n.Etag()
  89. if inm := r.Header.Get("If-None-Match"); inm == etag {
  90. w.WriteHeader(http.StatusNotModified)
  91. return
  92. }
  93. w.Header().Set("Etag", etag)
  94. if n.NameSize > 0 && filename == "" {
  95. filename = string(n.Name)
  96. dotIndex := strings.LastIndex(filename, ".")
  97. if dotIndex > 0 {
  98. ext = filename[dotIndex:]
  99. }
  100. }
  101. mtype := ""
  102. if ext != "" {
  103. mtype = mime.TypeByExtension(ext)
  104. }
  105. if n.MimeSize > 0 {
  106. mt := string(n.Mime)
  107. if mt != "application/octet-stream" {
  108. mtype = mt
  109. }
  110. }
  111. if mtype != "" {
  112. w.Header().Set("Content-Type", mtype)
  113. }
  114. if filename != "" {
  115. w.Header().Set("Content-Disposition", "filename=\""+fileNameEscaper.Replace(filename)+"\"")
  116. }
  117. if ext != ".gz" {
  118. if n.IsGzipped() {
  119. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  120. w.Header().Set("Content-Encoding", "gzip")
  121. } else {
  122. if n.Data, err = storage.UnGzipData(n.Data); err != nil {
  123. glog.V(0).Infoln("lookup error:", err, r.URL.Path)
  124. }
  125. }
  126. }
  127. }
  128. if ext == ".png" || ext == ".jpg" || ext == ".gif" {
  129. width, height := 0, 0
  130. if r.FormValue("width") != "" {
  131. width, _ = strconv.Atoi(r.FormValue("width"))
  132. }
  133. if r.FormValue("height") != "" {
  134. height, _ = strconv.Atoi(r.FormValue("height"))
  135. }
  136. n.Data, _, _ = images.Resized(ext, n.Data, width, height)
  137. }
  138. w.Header().Set("Accept-Ranges", "bytes")
  139. if r.Method == "HEAD" {
  140. w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
  141. return
  142. }
  143. rangeReq := r.Header.Get("Range")
  144. if rangeReq == "" {
  145. w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
  146. if _, e = w.Write(n.Data); e != nil {
  147. glog.V(0).Infoln("response write error:", e)
  148. }
  149. return
  150. }
  151. //the rest is dealing with partial content request
  152. //mostly copy from src/pkg/net/http/fs.go
  153. size := int64(len(n.Data))
  154. ranges, err := parseRange(rangeReq, size)
  155. if err != nil {
  156. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  157. return
  158. }
  159. if sumRangesSize(ranges) > size {
  160. // The total number of bytes in all the ranges
  161. // is larger than the size of the file by
  162. // itself, so this is probably an attack, or a
  163. // dumb client. Ignore the range request.
  164. ranges = nil
  165. return
  166. }
  167. if len(ranges) == 0 {
  168. return
  169. }
  170. if len(ranges) == 1 {
  171. // RFC 2616, Section 14.16:
  172. // "When an HTTP message includes the content of a single
  173. // range (for example, a response to a request for a
  174. // single range, or to a request for a set of ranges
  175. // that overlap without any holes), this content is
  176. // transmitted with a Content-Range header, and a
  177. // Content-Length header showing the number of bytes
  178. // actually transferred.
  179. // ...
  180. // A response to a request for a single range MUST NOT
  181. // be sent using the multipart/byteranges media type."
  182. ra := ranges[0]
  183. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  184. w.Header().Set("Content-Range", ra.contentRange(size))
  185. w.WriteHeader(http.StatusPartialContent)
  186. if _, e = w.Write(n.Data[ra.start : ra.start+ra.length]); e != nil {
  187. glog.V(0).Infoln("response write error:", e)
  188. }
  189. return
  190. }
  191. // process mulitple ranges
  192. for _, ra := range ranges {
  193. if ra.start > size {
  194. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  195. return
  196. }
  197. }
  198. sendSize := rangesMIMESize(ranges, mtype, size)
  199. pr, pw := io.Pipe()
  200. mw := multipart.NewWriter(pw)
  201. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  202. sendContent := pr
  203. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  204. go func() {
  205. for _, ra := range ranges {
  206. part, err := mw.CreatePart(ra.mimeHeader(mtype, size))
  207. if err != nil {
  208. pw.CloseWithError(err)
  209. return
  210. }
  211. if _, err = part.Write(n.Data[ra.start : ra.start+ra.length]); err != nil {
  212. pw.CloseWithError(err)
  213. return
  214. }
  215. }
  216. mw.Close()
  217. pw.Close()
  218. }()
  219. if w.Header().Get("Content-Encoding") == "" {
  220. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  221. }
  222. w.WriteHeader(http.StatusPartialContent)
  223. io.CopyN(w, sendContent, sendSize)
  224. }
  225. func (vs *VolumeServer) PostHandler(w http.ResponseWriter, r *http.Request) {
  226. if e := r.ParseForm(); e != nil {
  227. glog.V(0).Infoln("form parse error:", e)
  228. writeJsonError(w, r, e)
  229. return
  230. }
  231. vid, _, _, _, _ := parseURLPath(r.URL.Path)
  232. volumeId, ve := storage.NewVolumeId(vid)
  233. if ve != nil {
  234. glog.V(0).Infoln("NewVolumeId error:", ve)
  235. writeJsonError(w, r, ve)
  236. return
  237. }
  238. needle, ne := storage.NewNeedle(r, vs.FixJpgOrientation)
  239. if ne != nil {
  240. writeJsonError(w, r, ne)
  241. return
  242. }
  243. ret := operation.UploadResult{}
  244. size, errorStatus := topology.ReplicatedWrite(vs.masterNode, vs.store, volumeId, needle, r)
  245. if errorStatus == "" {
  246. w.WriteHeader(http.StatusCreated)
  247. } else {
  248. w.WriteHeader(http.StatusInternalServerError)
  249. ret.Error = errorStatus
  250. }
  251. if needle.HasName() {
  252. ret.Name = string(needle.Name)
  253. }
  254. ret.Size = size
  255. writeJsonQuiet(w, r, ret)
  256. }
  257. func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  258. n := new(storage.Needle)
  259. vid, fid, _, _, _ := parseURLPath(r.URL.Path)
  260. volumeId, _ := storage.NewVolumeId(vid)
  261. n.ParsePath(fid)
  262. glog.V(2).Infoln("deleting", n)
  263. cookie := n.Cookie
  264. count, ok := vs.store.Read(volumeId, n)
  265. if ok != nil {
  266. m := make(map[string]uint32)
  267. m["size"] = 0
  268. writeJsonQuiet(w, r, m)
  269. return
  270. }
  271. if n.Cookie != cookie {
  272. glog.V(0).Infoln("delete", r.URL.Path, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  273. return
  274. }
  275. n.Size = 0
  276. ret := topology.ReplicatedDelete(vs.masterNode, vs.store, volumeId, n, r)
  277. if ret != 0 {
  278. w.WriteHeader(http.StatusAccepted)
  279. } else {
  280. w.WriteHeader(http.StatusInternalServerError)
  281. }
  282. m := make(map[string]uint32)
  283. m["size"] = uint32(count)
  284. writeJsonQuiet(w, r, m)
  285. }
  286. //Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
  287. func (vs *VolumeServer) batchDeleteHandler(w http.ResponseWriter, r *http.Request) {
  288. r.ParseForm()
  289. var ret []operation.DeleteResult
  290. for _, fid := range r.Form["fid"] {
  291. vid, id_cookie, err := operation.ParseFileId(fid)
  292. if err != nil {
  293. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  294. continue
  295. }
  296. n := new(storage.Needle)
  297. volumeId, _ := storage.NewVolumeId(vid)
  298. n.ParsePath(id_cookie)
  299. glog.V(4).Infoln("batch deleting", n)
  300. cookie := n.Cookie
  301. if _, err := vs.store.Read(volumeId, n); err != nil {
  302. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  303. continue
  304. }
  305. if n.Cookie != cookie {
  306. ret = append(ret, operation.DeleteResult{Fid: fid, Error: "File Random Cookie does not match."})
  307. glog.V(0).Infoln("deleting", fid, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  308. return
  309. }
  310. if size, err := vs.store.Delete(volumeId, n); err != nil {
  311. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  312. } else {
  313. ret = append(ret, operation.DeleteResult{Fid: fid, Size: int(size)})
  314. }
  315. }
  316. w.WriteHeader(http.StatusAccepted)
  317. writeJsonQuiet(w, r, ret)
  318. }