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.

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