volume_server_handlers_read.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package weed_server
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "mime"
  9. "net/http"
  10. "net/url"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/chrislusf/seaweedfs/weed/glog"
  16. "github.com/chrislusf/seaweedfs/weed/images"
  17. "github.com/chrislusf/seaweedfs/weed/operation"
  18. "github.com/chrislusf/seaweedfs/weed/stats"
  19. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  20. "github.com/chrislusf/seaweedfs/weed/util"
  21. )
  22. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  23. func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  24. stats.VolumeServerRequestCounter.WithLabelValues("get").Inc()
  25. start := time.Now()
  26. defer func() { stats.VolumeServerRequestHistogram.WithLabelValues("get").Observe(time.Since(start).Seconds()) }()
  27. n := new(needle.Needle)
  28. vid, fid, filename, ext, _ := parseURLPath(r.URL.Path)
  29. if !vs.maybeCheckJwtAuthorization(r, vid, fid, false) {
  30. writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
  31. return
  32. }
  33. volumeId, err := needle.NewVolumeId(vid)
  34. if err != nil {
  35. glog.V(2).Infoln("parsing error:", err, r.URL.Path)
  36. w.WriteHeader(http.StatusBadRequest)
  37. return
  38. }
  39. err = n.ParsePath(fid)
  40. if err != nil {
  41. glog.V(2).Infoln("parsing fid error:", err, r.URL.Path)
  42. w.WriteHeader(http.StatusBadRequest)
  43. return
  44. }
  45. // glog.V(4).Infoln("volume", volumeId, "reading", n)
  46. hasVolume := vs.store.HasVolume(volumeId)
  47. _, hasEcVolume := vs.store.FindEcVolume(volumeId)
  48. if !hasVolume && !hasEcVolume {
  49. if !vs.ReadRedirect {
  50. glog.V(2).Infoln("volume is not local:", err, r.URL.Path)
  51. w.WriteHeader(http.StatusNotFound)
  52. return
  53. }
  54. lookupResult, err := operation.Lookup(vs.GetMaster(), volumeId.String())
  55. glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err)
  56. if err == nil && len(lookupResult.Locations) > 0 {
  57. u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations[0].PublicUrl))
  58. u.Path = fmt.Sprintf("%s/%s,%s", u.Path, vid, fid)
  59. arg := url.Values{}
  60. if c := r.FormValue("collection"); c != "" {
  61. arg.Set("collection", c)
  62. }
  63. u.RawQuery = arg.Encode()
  64. http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
  65. } else {
  66. glog.V(2).Infoln("lookup error:", err, r.URL.Path)
  67. w.WriteHeader(http.StatusNotFound)
  68. }
  69. return
  70. }
  71. cookie := n.Cookie
  72. var count int
  73. if hasVolume {
  74. count, err = vs.store.ReadVolumeNeedle(volumeId, n)
  75. } else if hasEcVolume {
  76. count, err = vs.store.ReadEcShardNeedle(volumeId, n)
  77. }
  78. // glog.V(4).Infoln("read bytes", count, "error", err)
  79. if err != nil || count < 0 {
  80. glog.V(0).Infof("read %s isNormalVolume %v error: %v", r.URL.Path, hasVolume, err)
  81. w.WriteHeader(http.StatusNotFound)
  82. return
  83. }
  84. if n.Cookie != cookie {
  85. glog.V(0).Infof("request %s with cookie:%x expected:%x from %s agent %s", r.URL.Path, cookie, n.Cookie, r.RemoteAddr, r.UserAgent())
  86. w.WriteHeader(http.StatusNotFound)
  87. return
  88. }
  89. if n.LastModified != 0 {
  90. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  91. if r.Header.Get("If-Modified-Since") != "" {
  92. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  93. if t.Unix() >= int64(n.LastModified) {
  94. w.WriteHeader(http.StatusNotModified)
  95. return
  96. }
  97. }
  98. }
  99. }
  100. if inm := r.Header.Get("If-None-Match"); inm == "\""+n.Etag()+"\"" {
  101. w.WriteHeader(http.StatusNotModified)
  102. return
  103. }
  104. setEtag(w, n.Etag())
  105. if n.HasPairs() {
  106. pairMap := make(map[string]string)
  107. err = json.Unmarshal(n.Pairs, &pairMap)
  108. if err != nil {
  109. glog.V(0).Infoln("Unmarshal pairs error:", err)
  110. }
  111. for k, v := range pairMap {
  112. w.Header().Set(k, v)
  113. }
  114. }
  115. if vs.tryHandleChunkedFile(n, filename, w, r) {
  116. return
  117. }
  118. if n.NameSize > 0 && filename == "" {
  119. filename = string(n.Name)
  120. if ext == "" {
  121. ext = filepath.Ext(filename)
  122. }
  123. }
  124. mtype := ""
  125. if n.MimeSize > 0 {
  126. mt := string(n.Mime)
  127. if !strings.HasPrefix(mt, "application/octet-stream") {
  128. mtype = mt
  129. }
  130. }
  131. if ext != ".gz" {
  132. if n.IsGzipped() {
  133. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  134. w.Header().Set("Content-Encoding", "gzip")
  135. } else {
  136. if n.Data, err = util.UnGzipData(n.Data); err != nil {
  137. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  138. }
  139. }
  140. }
  141. }
  142. rs := conditionallyResizeImages(bytes.NewReader(n.Data), ext, r)
  143. if e := writeResponseContent(filename, mtype, rs, w, r); e != nil {
  144. glog.V(2).Infoln("response write error:", e)
  145. }
  146. }
  147. func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, w http.ResponseWriter, r *http.Request) (processed bool) {
  148. if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
  149. return false
  150. }
  151. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
  152. if e != nil {
  153. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  154. return false
  155. }
  156. if fileName == "" && chunkManifest.Name != "" {
  157. fileName = chunkManifest.Name
  158. }
  159. ext := filepath.Ext(fileName)
  160. mType := ""
  161. if chunkManifest.Mime != "" {
  162. mt := chunkManifest.Mime
  163. if !strings.HasPrefix(mt, "application/octet-stream") {
  164. mType = mt
  165. }
  166. }
  167. w.Header().Set("X-File-Store", "chunked")
  168. chunkedFileReader := &operation.ChunkedFileReader{
  169. Manifest: chunkManifest,
  170. Master: vs.GetMaster(),
  171. }
  172. defer chunkedFileReader.Close()
  173. rs := conditionallyResizeImages(chunkedFileReader, ext, r)
  174. if e := writeResponseContent(fileName, mType, rs, w, r); e != nil {
  175. glog.V(2).Infoln("response write error:", e)
  176. }
  177. return true
  178. }
  179. func conditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  180. rs := originalDataReaderSeeker
  181. if len(ext) > 0 {
  182. ext = strings.ToLower(ext)
  183. }
  184. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
  185. width, height := 0, 0
  186. if r.FormValue("width") != "" {
  187. width, _ = strconv.Atoi(r.FormValue("width"))
  188. }
  189. if r.FormValue("height") != "" {
  190. height, _ = strconv.Atoi(r.FormValue("height"))
  191. }
  192. rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, r.FormValue("mode"))
  193. }
  194. return rs
  195. }
  196. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  197. totalSize, e := rs.Seek(0, 2)
  198. if mimeType == "" {
  199. if ext := filepath.Ext(filename); ext != "" {
  200. mimeType = mime.TypeByExtension(ext)
  201. }
  202. }
  203. if mimeType != "" {
  204. w.Header().Set("Content-Type", mimeType)
  205. }
  206. w.Header().Set("Accept-Ranges", "bytes")
  207. if r.Method == "HEAD" {
  208. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  209. return nil
  210. }
  211. adjustHeadersAfterHEAD(w, r, filename)
  212. processRangeRequst(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  213. if _, e = rs.Seek(offset, 0); e != nil {
  214. return e
  215. }
  216. _, e = io.CopyN(writer, rs, size)
  217. return e
  218. })
  219. return nil
  220. }