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.

249 lines
7.0 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. if vs.FixJpgOrientation && strings.HasSuffix(string(needle.Name), ".jpg") {
  153. needle.Data = images.FixJpgOrientation(needle.Data)
  154. }
  155. ret := operation.UploadResult{}
  156. size, errorStatus := topology.ReplicatedWrite(vs.masterNode, vs.store, volumeId, needle, r)
  157. if errorStatus == "" {
  158. w.WriteHeader(http.StatusCreated)
  159. } else {
  160. w.WriteHeader(http.StatusInternalServerError)
  161. ret.Error = errorStatus
  162. }
  163. if needle.HasName() {
  164. ret.Name = string(needle.Name)
  165. }
  166. ret.Size = size
  167. writeJsonQuiet(w, r, ret)
  168. }
  169. func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  170. n := new(storage.Needle)
  171. vid, fid, _, _, _ := parseURLPath(r.URL.Path)
  172. volumeId, _ := storage.NewVolumeId(vid)
  173. n.ParsePath(fid)
  174. glog.V(2).Infoln("deleting", n)
  175. cookie := n.Cookie
  176. count, ok := vs.store.Read(volumeId, n)
  177. if ok != nil {
  178. m := make(map[string]uint32)
  179. m["size"] = 0
  180. writeJsonQuiet(w, r, m)
  181. return
  182. }
  183. if n.Cookie != cookie {
  184. glog.V(0).Infoln("delete", r.URL.Path, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  185. return
  186. }
  187. n.Size = 0
  188. ret := topology.ReplicatedDelete(vs.masterNode, vs.store, volumeId, n, r)
  189. if ret != 0 {
  190. w.WriteHeader(http.StatusAccepted)
  191. } else {
  192. w.WriteHeader(http.StatusInternalServerError)
  193. }
  194. m := make(map[string]uint32)
  195. m["size"] = uint32(count)
  196. writeJsonQuiet(w, r, m)
  197. }
  198. //Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
  199. func (vs *VolumeServer) batchDeleteHandler(w http.ResponseWriter, r *http.Request) {
  200. r.ParseForm()
  201. var ret []operation.DeleteResult
  202. for _, fid := range r.Form["fid"] {
  203. vid, id_cookie, err := operation.ParseFileId(fid)
  204. if err != nil {
  205. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  206. continue
  207. }
  208. n := new(storage.Needle)
  209. volumeId, _ := storage.NewVolumeId(vid)
  210. n.ParsePath(id_cookie)
  211. glog.V(4).Infoln("batch deleting", n)
  212. cookie := n.Cookie
  213. if _, err := vs.store.Read(volumeId, n); err != nil {
  214. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  215. continue
  216. }
  217. if n.Cookie != cookie {
  218. ret = append(ret, operation.DeleteResult{Fid: fid, Error: "File Random Cookie does not match."})
  219. glog.V(0).Infoln("deleting", fid, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  220. return
  221. }
  222. if size, err := vs.store.Delete(volumeId, n); err != nil {
  223. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  224. } else {
  225. ret = append(ret, operation.DeleteResult{Fid: fid, Size: int(size)})
  226. }
  227. }
  228. w.WriteHeader(http.StatusAccepted)
  229. writeJsonQuiet(w, r, ret)
  230. }