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.

245 lines
6.8 KiB

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. "mime"
  10. "net/http"
  11. "strconv"
  12. "strings"
  13. "time"
  14. )
  15. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  16. func (vs *VolumeServer) storeHandler(w http.ResponseWriter, r *http.Request) {
  17. switch r.Method {
  18. case "GET":
  19. stats.ReadRequest()
  20. vs.GetOrHeadHandler(w, r, true)
  21. case "HEAD":
  22. stats.ReadRequest()
  23. vs.GetOrHeadHandler(w, r, false)
  24. case "DELETE":
  25. stats.DeleteRequest()
  26. secure(vs.whiteList, vs.DeleteHandler)(w, r)
  27. case "PUT":
  28. stats.WriteRequest()
  29. secure(vs.whiteList, vs.PostHandler)(w, r)
  30. case "POST":
  31. stats.WriteRequest()
  32. secure(vs.whiteList, vs.PostHandler)(w, r)
  33. }
  34. }
  35. func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request, isGetMethod bool) {
  36. n := new(storage.Needle)
  37. vid, fid, filename, ext, _ := parseURLPath(r.URL.Path)
  38. volumeId, err := storage.NewVolumeId(vid)
  39. if err != nil {
  40. glog.V(2).Infoln("parsing error:", err, r.URL.Path)
  41. w.WriteHeader(http.StatusBadRequest)
  42. return
  43. }
  44. err = n.ParsePath(fid)
  45. if err != nil {
  46. glog.V(2).Infoln("parsing fid error:", err, r.URL.Path)
  47. w.WriteHeader(http.StatusBadRequest)
  48. return
  49. }
  50. glog.V(4).Infoln("volume", volumeId, "reading", n)
  51. if !vs.store.HasVolume(volumeId) {
  52. lookupResult, err := operation.Lookup(vs.masterNode, volumeId.String())
  53. glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err)
  54. if err == nil && len(lookupResult.Locations) > 0 {
  55. http.Redirect(w, r, "http://"+lookupResult.Locations[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
  56. } else {
  57. glog.V(2).Infoln("lookup error:", err, r.URL.Path)
  58. w.WriteHeader(http.StatusNotFound)
  59. }
  60. return
  61. }
  62. cookie := n.Cookie
  63. count, e := vs.store.Read(volumeId, n)
  64. glog.V(4).Infoln("read bytes", count, "error", e)
  65. if e != nil || count <= 0 {
  66. glog.V(0).Infoln("read error:", e, r.URL.Path)
  67. w.WriteHeader(http.StatusNotFound)
  68. return
  69. }
  70. if n.Cookie != cookie {
  71. glog.V(0).Infoln("request", r.URL.Path, "with unmaching cookie seen:", cookie, "expected:", n.Cookie, "from", r.RemoteAddr, "agent", r.UserAgent())
  72. w.WriteHeader(http.StatusNotFound)
  73. return
  74. }
  75. if n.LastModified != 0 {
  76. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  77. if r.Header.Get("If-Modified-Since") != "" {
  78. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  79. if t.Unix() >= int64(n.LastModified) {
  80. w.WriteHeader(http.StatusNotModified)
  81. return
  82. }
  83. }
  84. }
  85. }
  86. if n.NameSize > 0 && filename == "" {
  87. filename = string(n.Name)
  88. dotIndex := strings.LastIndex(filename, ".")
  89. if dotIndex > 0 {
  90. ext = filename[dotIndex:]
  91. }
  92. }
  93. mtype := ""
  94. if ext != "" {
  95. mtype = mime.TypeByExtension(ext)
  96. }
  97. if n.MimeSize > 0 {
  98. mtype = string(n.Mime)
  99. }
  100. if mtype != "" {
  101. w.Header().Set("Content-Type", mtype)
  102. }
  103. if filename != "" {
  104. w.Header().Set("Content-Disposition", "filename=\""+fileNameEscaper.Replace(filename)+"\"")
  105. }
  106. if ext != ".gz" {
  107. if n.IsGzipped() {
  108. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  109. w.Header().Set("Content-Encoding", "gzip")
  110. } else {
  111. if n.Data, err = storage.UnGzipData(n.Data); err != nil {
  112. glog.V(0).Infoln("lookup error:", err, r.URL.Path)
  113. }
  114. }
  115. }
  116. }
  117. if ext == ".png" || ext == ".jpg" || ext == ".gif" {
  118. width, height := 0, 0
  119. if r.FormValue("width") != "" {
  120. width, _ = strconv.Atoi(r.FormValue("width"))
  121. }
  122. if r.FormValue("height") != "" {
  123. height, _ = strconv.Atoi(r.FormValue("height"))
  124. }
  125. n.Data = images.Resized(ext, n.Data, width, height)
  126. }
  127. w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
  128. if isGetMethod {
  129. if _, e = w.Write(n.Data); e != nil {
  130. glog.V(0).Infoln("response write error:", e)
  131. }
  132. }
  133. }
  134. func (vs *VolumeServer) PostHandler(w http.ResponseWriter, r *http.Request) {
  135. if e := r.ParseForm(); e != nil {
  136. glog.V(0).Infoln("form parse error:", e)
  137. writeJsonError(w, r, e)
  138. return
  139. }
  140. vid, _, _, _, _ := parseURLPath(r.URL.Path)
  141. volumeId, ve := storage.NewVolumeId(vid)
  142. if ve != nil {
  143. glog.V(0).Infoln("NewVolumeId error:", ve)
  144. writeJsonError(w, r, ve)
  145. return
  146. }
  147. needle, ne := storage.NewNeedle(r)
  148. if ne != nil {
  149. writeJsonError(w, r, ne)
  150. return
  151. }
  152. ret := operation.UploadResult{}
  153. size, errorStatus := topology.ReplicatedWrite(vs.masterNode, vs.store, volumeId, needle, r)
  154. if errorStatus == "" {
  155. w.WriteHeader(http.StatusCreated)
  156. } else {
  157. w.WriteHeader(http.StatusInternalServerError)
  158. ret.Error = errorStatus
  159. }
  160. if needle.HasName() {
  161. ret.Name = string(needle.Name)
  162. }
  163. ret.Size = size
  164. writeJsonQuiet(w, r, ret)
  165. }
  166. func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  167. n := new(storage.Needle)
  168. vid, fid, _, _, _ := parseURLPath(r.URL.Path)
  169. volumeId, _ := storage.NewVolumeId(vid)
  170. n.ParsePath(fid)
  171. glog.V(2).Infoln("deleting", n)
  172. cookie := n.Cookie
  173. count, ok := vs.store.Read(volumeId, n)
  174. if ok != nil {
  175. m := make(map[string]uint32)
  176. m["size"] = 0
  177. writeJsonQuiet(w, r, m)
  178. return
  179. }
  180. if n.Cookie != cookie {
  181. glog.V(0).Infoln("delete", r.URL.Path, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  182. return
  183. }
  184. n.Size = 0
  185. ret := topology.ReplicatedDelete(vs.masterNode, vs.store, volumeId, n, r)
  186. if ret != 0 {
  187. w.WriteHeader(http.StatusAccepted)
  188. } else {
  189. w.WriteHeader(http.StatusInternalServerError)
  190. }
  191. m := make(map[string]uint32)
  192. m["size"] = uint32(count)
  193. writeJsonQuiet(w, r, m)
  194. }
  195. //Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
  196. func (vs *VolumeServer) batchDeleteHandler(w http.ResponseWriter, r *http.Request) {
  197. r.ParseForm()
  198. var ret []operation.DeleteResult
  199. for _, fid := range r.Form["fid"] {
  200. vid, id_cookie, err := operation.ParseFileId(fid)
  201. if err != nil {
  202. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  203. continue
  204. }
  205. n := new(storage.Needle)
  206. volumeId, _ := storage.NewVolumeId(vid)
  207. n.ParsePath(id_cookie)
  208. glog.V(4).Infoln("batch deleting", n)
  209. cookie := n.Cookie
  210. if _, err := vs.store.Read(volumeId, n); err != nil {
  211. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  212. continue
  213. }
  214. if n.Cookie != cookie {
  215. ret = append(ret, operation.DeleteResult{Fid: fid, Error: "File Random Cookie does not match."})
  216. glog.V(0).Infoln("deleting", fid, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  217. return
  218. }
  219. if size, err := vs.store.Delete(volumeId, n); err != nil {
  220. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  221. } else {
  222. ret = append(ret, operation.DeleteResult{Fid: fid, Size: int(size)})
  223. }
  224. }
  225. w.WriteHeader(http.StatusAccepted)
  226. writeJsonQuiet(w, r, ret)
  227. }