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.

272 lines
7.8 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
4 years ago
5 years ago
4 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. if err != nil && err != storage.ErrorDeleted && r.FormValue("type") != "replicate" && hasVolume {
  84. glog.V(4).Infof("read needle: %v", err)
  85. // start to fix it from other replicas, if not deleted and hasVolume and is not a replicated request
  86. }
  87. // glog.V(4).Infoln("read bytes", count, "error", err)
  88. if err != nil || count < 0 {
  89. glog.V(3).Infof("read %s isNormalVolume %v error: %v", r.URL.Path, hasVolume, err)
  90. w.WriteHeader(http.StatusNotFound)
  91. return
  92. }
  93. if n.Cookie != cookie {
  94. 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())
  95. w.WriteHeader(http.StatusNotFound)
  96. return
  97. }
  98. if n.LastModified != 0 {
  99. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  100. if r.Header.Get("If-Modified-Since") != "" {
  101. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  102. if t.Unix() >= int64(n.LastModified) {
  103. w.WriteHeader(http.StatusNotModified)
  104. return
  105. }
  106. }
  107. }
  108. }
  109. if inm := r.Header.Get("If-None-Match"); inm == "\""+n.Etag()+"\"" {
  110. w.WriteHeader(http.StatusNotModified)
  111. return
  112. }
  113. setEtag(w, n.Etag())
  114. if n.HasPairs() {
  115. pairMap := make(map[string]string)
  116. err = json.Unmarshal(n.Pairs, &pairMap)
  117. if err != nil {
  118. glog.V(0).Infoln("Unmarshal pairs error:", err)
  119. }
  120. for k, v := range pairMap {
  121. w.Header().Set(k, v)
  122. }
  123. }
  124. if vs.tryHandleChunkedFile(n, filename, ext, w, r) {
  125. return
  126. }
  127. if n.NameSize > 0 && filename == "" {
  128. filename = string(n.Name)
  129. if ext == "" {
  130. ext = filepath.Ext(filename)
  131. }
  132. }
  133. mtype := ""
  134. if n.MimeSize > 0 {
  135. mt := string(n.Mime)
  136. if !strings.HasPrefix(mt, "application/octet-stream") {
  137. mtype = mt
  138. }
  139. }
  140. if n.IsCompressed() {
  141. if _, _, _, shouldResize := shouldResizeImages(ext, r); shouldResize {
  142. if n.Data, err = util.DecompressData(n.Data); err != nil {
  143. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  144. }
  145. // } else if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") && util.IsZstdContent(n.Data) {
  146. // w.Header().Set("Content-Encoding", "zstd")
  147. } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && util.IsGzippedContent(n.Data) {
  148. w.Header().Set("Content-Encoding", "gzip")
  149. } else {
  150. if n.Data, err = util.DecompressData(n.Data); err != nil {
  151. glog.V(0).Infoln("uncompress error:", err, r.URL.Path)
  152. }
  153. }
  154. }
  155. rs := conditionallyResizeImages(bytes.NewReader(n.Data), ext, r)
  156. if e := writeResponseContent(filename, mtype, rs, w, r); e != nil {
  157. glog.V(2).Infoln("response write error:", e)
  158. }
  159. }
  160. func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, ext string, w http.ResponseWriter, r *http.Request) (processed bool) {
  161. if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
  162. return false
  163. }
  164. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsCompressed())
  165. if e != nil {
  166. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  167. return false
  168. }
  169. if fileName == "" && chunkManifest.Name != "" {
  170. fileName = chunkManifest.Name
  171. }
  172. if ext == "" {
  173. ext = filepath.Ext(fileName)
  174. }
  175. mType := ""
  176. if chunkManifest.Mime != "" {
  177. mt := chunkManifest.Mime
  178. if !strings.HasPrefix(mt, "application/octet-stream") {
  179. mType = mt
  180. }
  181. }
  182. w.Header().Set("X-File-Store", "chunked")
  183. chunkedFileReader := operation.NewChunkedFileReader(chunkManifest.Chunks, vs.GetMaster())
  184. defer chunkedFileReader.Close()
  185. rs := conditionallyResizeImages(chunkedFileReader, ext, r)
  186. if e := writeResponseContent(fileName, mType, rs, w, r); e != nil {
  187. glog.V(2).Infoln("response write error:", e)
  188. }
  189. return true
  190. }
  191. func conditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  192. rs := originalDataReaderSeeker
  193. if len(ext) > 0 {
  194. ext = strings.ToLower(ext)
  195. }
  196. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  197. if shouldResize {
  198. rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, mode)
  199. }
  200. return rs
  201. }
  202. func shouldResizeImages(ext string, r *http.Request) (width, height int, mode string, shouldResize bool) {
  203. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
  204. if r.FormValue("width") != "" {
  205. width, _ = strconv.Atoi(r.FormValue("width"))
  206. }
  207. if r.FormValue("height") != "" {
  208. height, _ = strconv.Atoi(r.FormValue("height"))
  209. }
  210. }
  211. mode = r.FormValue("mode")
  212. shouldResize = width > 0 || height > 0
  213. return
  214. }
  215. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  216. totalSize, e := rs.Seek(0, 2)
  217. if mimeType == "" {
  218. if ext := filepath.Ext(filename); ext != "" {
  219. mimeType = mime.TypeByExtension(ext)
  220. }
  221. }
  222. if mimeType != "" {
  223. w.Header().Set("Content-Type", mimeType)
  224. }
  225. w.Header().Set("Accept-Ranges", "bytes")
  226. adjustHeaderContentDisposition(w, r, filename)
  227. if r.Method == "HEAD" {
  228. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  229. return nil
  230. }
  231. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  232. if _, e = rs.Seek(offset, 0); e != nil {
  233. return e
  234. }
  235. _, e = io.CopyN(writer, rs, size)
  236. return e
  237. })
  238. return nil
  239. }