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.

247 lines
6.4 KiB

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