filer_server_handlers_read.go 6.7 KB

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