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.

268 lines
7.6 KiB

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