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.4 KiB

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