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.

253 lines
6.6 KiB

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