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.

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