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.

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