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.

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