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.

246 lines
6.3 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. totalSize := int64(filer2.TotalSize(entry.Chunks))
  106. rangeReq := r.Header.Get("Range")
  107. if rangeReq == "" {
  108. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  109. if err := fs.writeContent(w, entry, 0, int(totalSize)); err != nil {
  110. http.Error(w, err.Error(), http.StatusInternalServerError)
  111. return
  112. }
  113. return
  114. }
  115. //the rest is dealing with partial content request
  116. //mostly copy from src/pkg/net/http/fs.go
  117. ranges, err := parseRange(rangeReq, totalSize)
  118. if err != nil {
  119. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  120. return
  121. }
  122. if sumRangesSize(ranges) > totalSize {
  123. // The total number of bytes in all the ranges
  124. // is larger than the size of the file by
  125. // itself, so this is probably an attack, or a
  126. // dumb client. Ignore the range request.
  127. return
  128. }
  129. if len(ranges) == 0 {
  130. return
  131. }
  132. if len(ranges) == 1 {
  133. // RFC 2616, Section 14.16:
  134. // "When an HTTP message includes the content of a single
  135. // range (for example, a response to a request for a
  136. // single range, or to a request for a set of ranges
  137. // that overlap without any holes), this content is
  138. // transmitted with a Content-Range header, and a
  139. // Content-Length header showing the number of bytes
  140. // actually transferred.
  141. // ...
  142. // A response to a request for a single range MUST NOT
  143. // be sent using the multipart/byteranges media type."
  144. ra := ranges[0]
  145. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  146. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  147. w.WriteHeader(http.StatusPartialContent)
  148. err = fs.writeContent(w, entry, ra.start, int(ra.length))
  149. if err != nil {
  150. http.Error(w, err.Error(), http.StatusInternalServerError)
  151. return
  152. }
  153. return
  154. }
  155. // process multiple ranges
  156. for _, ra := range ranges {
  157. if ra.start > totalSize {
  158. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  159. return
  160. }
  161. }
  162. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  163. pr, pw := io.Pipe()
  164. mw := multipart.NewWriter(pw)
  165. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  166. sendContent := pr
  167. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  168. go func() {
  169. for _, ra := range ranges {
  170. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  171. if e != nil {
  172. pw.CloseWithError(e)
  173. return
  174. }
  175. if e = fs.writeContent(part, entry, ra.start, int(ra.length)); e != nil {
  176. pw.CloseWithError(e)
  177. return
  178. }
  179. }
  180. mw.Close()
  181. pw.Close()
  182. }()
  183. if w.Header().Get("Content-Encoding") == "" {
  184. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  185. }
  186. w.WriteHeader(http.StatusPartialContent)
  187. if _, err := io.CopyN(w, sendContent, sendSize); err != nil {
  188. http.Error(w, "Internal Error", http.StatusInternalServerError)
  189. return
  190. }
  191. }
  192. func (fs *FilerServer) writeContent(w io.Writer, entry *filer2.Entry, offset int64, size int) error {
  193. chunkViews := filer2.ViewFromChunks(entry.Chunks, offset, size)
  194. fileId2Url := make(map[string]string)
  195. for _, chunkView := range chunkViews {
  196. urlString, err := fs.filer.MasterClient.LookupFileId(chunkView.FileId)
  197. if err != nil {
  198. glog.V(1).Infof("operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
  199. return err
  200. }
  201. fileId2Url[chunkView.FileId] = urlString
  202. }
  203. for _, chunkView := range chunkViews {
  204. urlString := fileId2Url[chunkView.FileId]
  205. _, err := util.ReadUrlAsStream(urlString, chunkView.Offset, int(chunkView.Size), func(data []byte) {
  206. w.Write(data)
  207. })
  208. if err != nil {
  209. glog.V(1).Infof("read %s failed, err: %v", chunkView.FileId, err)
  210. return err
  211. }
  212. }
  213. return nil
  214. }