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.

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