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.

270 lines
7.5 KiB

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