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.

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