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.

248 lines
6.5 KiB

9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
6 years ago
9 years ago
6 years ago
6 years ago
6 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "io"
  5. "io/ioutil"
  6. "mime"
  7. "mime/multipart"
  8. "net/http"
  9. "net/url"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "github.com/chrislusf/seaweedfs/weed/filer2"
  14. "github.com/chrislusf/seaweedfs/weed/glog"
  15. "github.com/chrislusf/seaweedfs/weed/stats"
  16. "github.com/chrislusf/seaweedfs/weed/util"
  17. )
  18. func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request, isGetMethod bool) {
  19. path := r.URL.Path
  20. isForDirectory := strings.HasSuffix(path, "/")
  21. if isForDirectory && len(path) > 1 {
  22. path = path[:len(path)-1]
  23. }
  24. entry, err := fs.filer.FindEntry(context.Background(), filer2.FullPath(path))
  25. if err != nil {
  26. if path == "/" {
  27. fs.listDirectoryHandler(w, r)
  28. return
  29. }
  30. glog.V(1).Infof("Not found %s: %v", path, err)
  31. stats.FilerRequestCounter.WithLabelValues("read.notfound").Inc()
  32. w.WriteHeader(http.StatusNotFound)
  33. return
  34. }
  35. if entry.IsDirectory() {
  36. if fs.option.DisableDirListing {
  37. w.WriteHeader(http.StatusMethodNotAllowed)
  38. return
  39. }
  40. fs.listDirectoryHandler(w, r)
  41. return
  42. }
  43. if isForDirectory {
  44. w.WriteHeader(http.StatusNotFound)
  45. return
  46. }
  47. if len(entry.Chunks) == 0 {
  48. glog.V(1).Infof("no file chunks for %s, attr=%+v", path, entry.Attr)
  49. stats.FilerRequestCounter.WithLabelValues("read.nocontent").Inc()
  50. w.WriteHeader(http.StatusNoContent)
  51. return
  52. }
  53. w.Header().Set("Accept-Ranges", "bytes")
  54. if r.Method == "HEAD" {
  55. w.Header().Set("Content-Length", strconv.FormatInt(int64(filer2.TotalSize(entry.Chunks)), 10))
  56. w.Header().Set("Last-Modified", entry.Attr.Mtime.Format(http.TimeFormat))
  57. setEtag(w, filer2.ETag(entry.Chunks))
  58. return
  59. }
  60. if len(entry.Chunks) == 1 {
  61. fs.handleSingleChunk(w, r, entry)
  62. return
  63. }
  64. fs.handleMultipleChunks(w, r, entry)
  65. }
  66. func (fs *FilerServer) handleSingleChunk(w http.ResponseWriter, r *http.Request, entry *filer2.Entry) {
  67. fileId := entry.Chunks[0].GetFileIdString()
  68. urlString, err := fs.filer.MasterClient.LookupFileId(fileId)
  69. if err != nil {
  70. glog.V(1).Infof("operation LookupFileId %s failed, err: %v", fileId, err)
  71. w.WriteHeader(http.StatusNotFound)
  72. return
  73. }
  74. if fs.option.RedirectOnRead {
  75. stats.FilerRequestCounter.WithLabelValues("redirect").Inc()
  76. http.Redirect(w, r, urlString, http.StatusFound)
  77. return
  78. }
  79. u, _ := url.Parse(urlString)
  80. q := u.Query()
  81. for key, values := range r.URL.Query() {
  82. for _, value := range values {
  83. q.Add(key, value)
  84. }
  85. }
  86. u.RawQuery = q.Encode()
  87. request := &http.Request{
  88. Method: r.Method,
  89. URL: u,
  90. Proto: r.Proto,
  91. ProtoMajor: r.ProtoMajor,
  92. ProtoMinor: r.ProtoMinor,
  93. Header: r.Header,
  94. Body: r.Body,
  95. Host: r.Host,
  96. ContentLength: r.ContentLength,
  97. }
  98. glog.V(3).Infoln("retrieving from", u)
  99. resp, do_err := util.Do(request)
  100. if do_err != nil {
  101. glog.V(0).Infoln("failing to connect to volume server", do_err.Error())
  102. writeJsonError(w, r, http.StatusInternalServerError, do_err)
  103. return
  104. }
  105. defer func() {
  106. io.Copy(ioutil.Discard, resp.Body)
  107. resp.Body.Close()
  108. }()
  109. for k, v := range resp.Header {
  110. w.Header()[k] = v
  111. }
  112. if entry.Attr.Mime != "" {
  113. w.Header().Set("Content-Type", entry.Attr.Mime)
  114. }
  115. w.WriteHeader(resp.StatusCode)
  116. io.Copy(w, resp.Body)
  117. }
  118. func (fs *FilerServer) handleMultipleChunks(w http.ResponseWriter, r *http.Request, entry *filer2.Entry) {
  119. mimeType := entry.Attr.Mime
  120. if mimeType == "" {
  121. if ext := path.Ext(entry.Name()); ext != "" {
  122. mimeType = mime.TypeByExtension(ext)
  123. }
  124. }
  125. if mimeType != "" {
  126. w.Header().Set("Content-Type", mimeType)
  127. }
  128. setEtag(w, filer2.ETag(entry.Chunks))
  129. totalSize := int64(filer2.TotalSize(entry.Chunks))
  130. rangeReq := r.Header.Get("Range")
  131. if rangeReq == "" {
  132. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  133. if err := fs.writeContent(w, entry, 0, int(totalSize)); err != nil {
  134. http.Error(w, err.Error(), http.StatusInternalServerError)
  135. return
  136. }
  137. return
  138. }
  139. //the rest is dealing with partial content request
  140. //mostly copy from src/pkg/net/http/fs.go
  141. ranges, err := parseRange(rangeReq, totalSize)
  142. if err != nil {
  143. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  144. return
  145. }
  146. if sumRangesSize(ranges) > totalSize {
  147. // The total number of bytes in all the ranges
  148. // is larger than the size of the file by
  149. // itself, so this is probably an attack, or a
  150. // dumb client. Ignore the range request.
  151. return
  152. }
  153. if len(ranges) == 0 {
  154. return
  155. }
  156. if len(ranges) == 1 {
  157. // RFC 2616, Section 14.16:
  158. // "When an HTTP message includes the content of a single
  159. // range (for example, a response to a request for a
  160. // single range, or to a request for a set of ranges
  161. // that overlap without any holes), this content is
  162. // transmitted with a Content-Range header, and a
  163. // Content-Length header showing the number of bytes
  164. // actually transferred.
  165. // ...
  166. // A response to a request for a single range MUST NOT
  167. // be sent using the multipart/byteranges media type."
  168. ra := ranges[0]
  169. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  170. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  171. w.WriteHeader(http.StatusPartialContent)
  172. err = fs.writeContent(w, entry, ra.start, int(ra.length))
  173. if err != nil {
  174. http.Error(w, err.Error(), http.StatusInternalServerError)
  175. return
  176. }
  177. return
  178. }
  179. // process multiple ranges
  180. for _, ra := range ranges {
  181. if ra.start > totalSize {
  182. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  183. return
  184. }
  185. }
  186. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  187. pr, pw := io.Pipe()
  188. mw := multipart.NewWriter(pw)
  189. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  190. sendContent := pr
  191. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  192. go func() {
  193. for _, ra := range ranges {
  194. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  195. if e != nil {
  196. pw.CloseWithError(e)
  197. return
  198. }
  199. if e = fs.writeContent(part, entry, ra.start, int(ra.length)); e != nil {
  200. pw.CloseWithError(e)
  201. return
  202. }
  203. }
  204. mw.Close()
  205. pw.Close()
  206. }()
  207. if w.Header().Get("Content-Encoding") == "" {
  208. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  209. }
  210. w.WriteHeader(http.StatusPartialContent)
  211. if _, err := io.CopyN(w, sendContent, sendSize); err != nil {
  212. http.Error(w, "Internal Error", http.StatusInternalServerError)
  213. return
  214. }
  215. }
  216. func (fs *FilerServer) writeContent(w io.Writer, entry *filer2.Entry, offset int64, size int) error {
  217. return filer2.StreamContent(fs.filer.MasterClient, w, entry.Chunks, offset, size)
  218. }