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.

333 lines
9.4 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. "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. if n.NameSize > 0 && filename == "" {
  89. filename = string(n.Name)
  90. dotIndex := strings.LastIndex(filename, ".")
  91. if dotIndex > 0 {
  92. ext = filename[dotIndex:]
  93. }
  94. }
  95. mtype := ""
  96. if ext != "" {
  97. mtype = mime.TypeByExtension(ext)
  98. }
  99. if n.MimeSize > 0 {
  100. mt := string(n.Mime)
  101. if mt != "application/octet-stream" {
  102. mtype = mt
  103. }
  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. n.Data = images.Resized(ext, n.Data, width, height)
  131. }
  132. w.Header().Set("Accept-Ranges", "bytes")
  133. if r.Method == "HEAD" {
  134. w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
  135. return
  136. }
  137. rangeReq := r.Header.Get("Range")
  138. if rangeReq == "" {
  139. w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
  140. if _, e = w.Write(n.Data); e != nil {
  141. glog.V(0).Infoln("response write error:", e)
  142. }
  143. return
  144. }
  145. //the rest is dealing with partial content request
  146. //mostly copy from src/pkg/net/http/fs.go
  147. size := int64(len(n.Data))
  148. ranges, err := parseRange(rangeReq, size)
  149. if err != nil {
  150. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  151. return
  152. }
  153. if sumRangesSize(ranges) > size {
  154. // The total number of bytes in all the ranges
  155. // is larger than the size of the file by
  156. // itself, so this is probably an attack, or a
  157. // dumb client. Ignore the range request.
  158. ranges = nil
  159. return
  160. }
  161. if len(ranges) == 0 {
  162. return
  163. }
  164. if len(ranges) == 1 {
  165. // RFC 2616, Section 14.16:
  166. // "When an HTTP message includes the content of a single
  167. // range (for example, a response to a request for a
  168. // single range, or to a request for a set of ranges
  169. // that overlap without any holes), this content is
  170. // transmitted with a Content-Range header, and a
  171. // Content-Length header showing the number of bytes
  172. // actually transferred.
  173. // ...
  174. // A response to a request for a single range MUST NOT
  175. // be sent using the multipart/byteranges media type."
  176. ra := ranges[0]
  177. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  178. w.Header().Set("Content-Range", ra.contentRange(size))
  179. w.WriteHeader(http.StatusPartialContent)
  180. if _, e = w.Write(n.Data[ra.start : ra.start+ra.length]); e != nil {
  181. glog.V(0).Infoln("response write error:", e)
  182. }
  183. return
  184. }
  185. // process mulitple ranges
  186. for _, ra := range ranges {
  187. if ra.start > size {
  188. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  189. return
  190. }
  191. }
  192. sendSize := rangesMIMESize(ranges, mtype, size)
  193. pr, pw := io.Pipe()
  194. mw := multipart.NewWriter(pw)
  195. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  196. sendContent := pr
  197. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  198. go func() {
  199. for _, ra := range ranges {
  200. part, err := mw.CreatePart(ra.mimeHeader(mtype, size))
  201. if err != nil {
  202. pw.CloseWithError(err)
  203. return
  204. }
  205. if _, err = part.Write(n.Data[ra.start : ra.start+ra.length]); err != nil {
  206. pw.CloseWithError(err)
  207. return
  208. }
  209. }
  210. mw.Close()
  211. pw.Close()
  212. }()
  213. if w.Header().Get("Content-Encoding") == "" {
  214. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  215. }
  216. w.WriteHeader(http.StatusPartialContent)
  217. io.CopyN(w, sendContent, sendSize)
  218. }
  219. func (vs *VolumeServer) PostHandler(w http.ResponseWriter, r *http.Request) {
  220. if e := r.ParseForm(); e != nil {
  221. glog.V(0).Infoln("form parse error:", e)
  222. writeJsonError(w, r, e)
  223. return
  224. }
  225. vid, _, _, _, _ := parseURLPath(r.URL.Path)
  226. volumeId, ve := storage.NewVolumeId(vid)
  227. if ve != nil {
  228. glog.V(0).Infoln("NewVolumeId error:", ve)
  229. writeJsonError(w, r, ve)
  230. return
  231. }
  232. needle, ne := storage.NewNeedle(r, vs.FixJpgOrientation)
  233. if ne != nil {
  234. writeJsonError(w, r, ne)
  235. return
  236. }
  237. ret := operation.UploadResult{}
  238. size, errorStatus := topology.ReplicatedWrite(vs.masterNode, vs.store, volumeId, needle, r)
  239. if errorStatus == "" {
  240. w.WriteHeader(http.StatusCreated)
  241. } else {
  242. w.WriteHeader(http.StatusInternalServerError)
  243. ret.Error = errorStatus
  244. }
  245. if needle.HasName() {
  246. ret.Name = string(needle.Name)
  247. }
  248. ret.Size = size
  249. writeJsonQuiet(w, r, ret)
  250. }
  251. func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  252. n := new(storage.Needle)
  253. vid, fid, _, _, _ := parseURLPath(r.URL.Path)
  254. volumeId, _ := storage.NewVolumeId(vid)
  255. n.ParsePath(fid)
  256. glog.V(2).Infoln("deleting", n)
  257. cookie := n.Cookie
  258. count, ok := vs.store.Read(volumeId, n)
  259. if ok != nil {
  260. m := make(map[string]uint32)
  261. m["size"] = 0
  262. writeJsonQuiet(w, r, m)
  263. return
  264. }
  265. if n.Cookie != cookie {
  266. glog.V(0).Infoln("delete", r.URL.Path, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  267. return
  268. }
  269. n.Size = 0
  270. ret := topology.ReplicatedDelete(vs.masterNode, vs.store, volumeId, n, r)
  271. if ret != 0 {
  272. w.WriteHeader(http.StatusAccepted)
  273. } else {
  274. w.WriteHeader(http.StatusInternalServerError)
  275. }
  276. m := make(map[string]uint32)
  277. m["size"] = uint32(count)
  278. writeJsonQuiet(w, r, m)
  279. }
  280. //Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
  281. func (vs *VolumeServer) batchDeleteHandler(w http.ResponseWriter, r *http.Request) {
  282. r.ParseForm()
  283. var ret []operation.DeleteResult
  284. for _, fid := range r.Form["fid"] {
  285. vid, id_cookie, err := operation.ParseFileId(fid)
  286. if err != nil {
  287. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  288. continue
  289. }
  290. n := new(storage.Needle)
  291. volumeId, _ := storage.NewVolumeId(vid)
  292. n.ParsePath(id_cookie)
  293. glog.V(4).Infoln("batch deleting", n)
  294. cookie := n.Cookie
  295. if _, err := vs.store.Read(volumeId, n); err != nil {
  296. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  297. continue
  298. }
  299. if n.Cookie != cookie {
  300. ret = append(ret, operation.DeleteResult{Fid: fid, Error: "File Random Cookie does not match."})
  301. glog.V(0).Infoln("deleting", fid, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  302. return
  303. }
  304. if size, err := vs.store.Delete(volumeId, n); err != nil {
  305. ret = append(ret, operation.DeleteResult{Fid: fid, Error: err.Error()})
  306. } else {
  307. ret = append(ret, operation.DeleteResult{Fid: fid, Size: int(size)})
  308. }
  309. }
  310. w.WriteHeader(http.StatusAccepted)
  311. writeJsonQuiet(w, r, ret)
  312. }