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.

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