volume_server_handlers_read.go 7.4 KB

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