volume_server_handlers_read.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "mime"
  10. "net/http"
  11. "net/url"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "sync/atomic"
  16. "time"
  17. "github.com/seaweedfs/seaweedfs/weed/filer"
  18. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  19. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  20. "github.com/seaweedfs/seaweedfs/weed/glog"
  21. "github.com/seaweedfs/seaweedfs/weed/images"
  22. "github.com/seaweedfs/seaweedfs/weed/operation"
  23. "github.com/seaweedfs/seaweedfs/weed/stats"
  24. "github.com/seaweedfs/seaweedfs/weed/storage"
  25. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  26. "github.com/seaweedfs/seaweedfs/weed/util"
  27. )
  28. var fileNameEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`)
  29. func NotFound(w http.ResponseWriter) {
  30. stats.VolumeServerHandlerCounter.WithLabelValues(stats.ErrorGetNotFound).Inc()
  31. w.WriteHeader(http.StatusNotFound)
  32. }
  33. func InternalError(w http.ResponseWriter) {
  34. stats.VolumeServerHandlerCounter.WithLabelValues(stats.ErrorGetInternal).Inc()
  35. w.WriteHeader(http.StatusInternalServerError)
  36. }
  37. func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  38. n := new(needle.Needle)
  39. vid, fid, filename, ext, _ := parseURLPath(r.URL.Path)
  40. if !vs.maybeCheckJwtAuthorization(r, vid, fid, false) {
  41. writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
  42. return
  43. }
  44. volumeId, err := needle.NewVolumeId(vid)
  45. if err != nil {
  46. glog.V(2).Infof("parsing vid %s: %v", r.URL.Path, err)
  47. w.WriteHeader(http.StatusBadRequest)
  48. return
  49. }
  50. err = n.ParsePath(fid)
  51. if err != nil {
  52. glog.V(2).Infof("parsing fid %s: %v", r.URL.Path, err)
  53. w.WriteHeader(http.StatusBadRequest)
  54. return
  55. }
  56. // glog.V(4).Infoln("volume", volumeId, "reading", n)
  57. hasVolume := vs.store.HasVolume(volumeId)
  58. _, hasEcVolume := vs.store.FindEcVolume(volumeId)
  59. if !hasVolume && !hasEcVolume {
  60. if vs.ReadMode == "local" {
  61. glog.V(0).Infoln("volume is not local:", err, r.URL.Path)
  62. NotFound(w)
  63. return
  64. }
  65. lookupResult, err := operation.LookupVolumeId(vs.GetMaster, vs.grpcDialOption, volumeId.String())
  66. glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err)
  67. if err != nil || len(lookupResult.Locations) <= 0 {
  68. glog.V(0).Infoln("lookup error:", err, r.URL.Path)
  69. NotFound(w)
  70. return
  71. }
  72. if vs.ReadMode == "proxy" {
  73. // proxy client request to target server
  74. u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations[0].Url))
  75. r.URL.Host = u.Host
  76. r.URL.Scheme = u.Scheme
  77. request, err := http.NewRequest("GET", r.URL.String(), nil)
  78. if err != nil {
  79. glog.V(0).Infof("failed to instance http request of url %s: %v", r.URL.String(), err)
  80. InternalError(w)
  81. return
  82. }
  83. for k, vv := range r.Header {
  84. for _, v := range vv {
  85. request.Header.Add(k, v)
  86. }
  87. }
  88. response, err := client.Do(request)
  89. if err != nil {
  90. glog.V(0).Infof("request remote url %s: %v", r.URL.String(), err)
  91. InternalError(w)
  92. return
  93. }
  94. defer util.CloseResponse(response)
  95. // proxy target response to client
  96. for k, vv := range response.Header {
  97. for _, v := range vv {
  98. w.Header().Add(k, v)
  99. }
  100. }
  101. w.WriteHeader(response.StatusCode)
  102. buf := mem.Allocate(128 * 1024)
  103. defer mem.Free(buf)
  104. io.CopyBuffer(w, response.Body, buf)
  105. return
  106. } else {
  107. // redirect
  108. u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations[0].PublicUrl))
  109. u.Path = fmt.Sprintf("%s/%s,%s", u.Path, vid, fid)
  110. arg := url.Values{}
  111. if c := r.FormValue("collection"); c != "" {
  112. arg.Set("collection", c)
  113. }
  114. u.RawQuery = arg.Encode()
  115. http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
  116. return
  117. }
  118. }
  119. cookie := n.Cookie
  120. readOption := &storage.ReadOption{
  121. ReadDeleted: r.FormValue("readDeleted") == "true",
  122. HasSlowRead: vs.hasSlowRead,
  123. ReadBufferSize: vs.readBufferSizeMB * 1024 * 1024,
  124. }
  125. var count int
  126. var memoryCost types.Size
  127. readOption.AttemptMetaOnly, readOption.MustMetaOnly = shouldAttemptStreamWrite(hasVolume, ext, r)
  128. onReadSizeFn := func(size types.Size) {
  129. memoryCost = size
  130. atomic.AddInt64(&vs.inFlightDownloadDataSize, int64(memoryCost))
  131. }
  132. if hasVolume {
  133. count, err = vs.store.ReadVolumeNeedle(volumeId, n, readOption, onReadSizeFn)
  134. } else if hasEcVolume {
  135. count, err = vs.store.ReadEcShardNeedle(volumeId, n, onReadSizeFn)
  136. }
  137. defer func() {
  138. atomic.AddInt64(&vs.inFlightDownloadDataSize, -int64(memoryCost))
  139. vs.inFlightDownloadDataLimitCond.Signal()
  140. }()
  141. if err != nil && err != storage.ErrorDeleted && hasVolume {
  142. glog.V(4).Infof("read needle: %v", err)
  143. // start to fix it from other replicas, if not deleted and hasVolume and is not a replicated request
  144. }
  145. // glog.V(4).Infoln("read bytes", count, "error", err)
  146. if err != nil || count < 0 {
  147. glog.V(3).Infof("read %s isNormalVolume %v error: %v", r.URL.Path, hasVolume, err)
  148. if err == storage.ErrorNotFound || err == storage.ErrorDeleted {
  149. NotFound(w)
  150. } else {
  151. InternalError(w)
  152. }
  153. return
  154. }
  155. if n.Cookie != cookie {
  156. 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())
  157. NotFound(w)
  158. return
  159. }
  160. if n.LastModified != 0 {
  161. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  162. if r.Header.Get("If-Modified-Since") != "" {
  163. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  164. if t.Unix() >= int64(n.LastModified) {
  165. w.WriteHeader(http.StatusNotModified)
  166. return
  167. }
  168. }
  169. }
  170. }
  171. if inm := r.Header.Get("If-None-Match"); inm == "\""+n.Etag()+"\"" {
  172. w.WriteHeader(http.StatusNotModified)
  173. return
  174. }
  175. setEtag(w, n.Etag())
  176. if n.HasPairs() {
  177. pairMap := make(map[string]string)
  178. err = json.Unmarshal(n.Pairs, &pairMap)
  179. if err != nil {
  180. glog.V(0).Infoln("Unmarshal pairs error:", err)
  181. }
  182. for k, v := range pairMap {
  183. w.Header().Set(k, v)
  184. }
  185. }
  186. if vs.tryHandleChunkedFile(n, filename, ext, w, r) {
  187. return
  188. }
  189. if n.NameSize > 0 && filename == "" {
  190. filename = string(n.Name)
  191. if ext == "" {
  192. ext = filepath.Ext(filename)
  193. }
  194. }
  195. mtype := ""
  196. if n.MimeSize > 0 {
  197. mt := string(n.Mime)
  198. if !strings.HasPrefix(mt, "application/octet-stream") {
  199. mtype = mt
  200. }
  201. }
  202. if n.IsCompressed() {
  203. _, _, _, shouldResize := shouldResizeImages(ext, r)
  204. _, _, _, _, shouldCrop := shouldCropImages(ext, r)
  205. if shouldResize || shouldCrop {
  206. if n.Data, err = util.DecompressData(n.Data); err != nil {
  207. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  208. }
  209. // } else if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") && util.IsZstdContent(n.Data) {
  210. // w.Header().Set("Content-Encoding", "zstd")
  211. } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && util.IsGzippedContent(n.Data) {
  212. w.Header().Set("Content-Encoding", "gzip")
  213. } else {
  214. if n.Data, err = util.DecompressData(n.Data); err != nil {
  215. glog.V(0).Infoln("uncompress error:", err, r.URL.Path)
  216. }
  217. }
  218. }
  219. if !readOption.IsMetaOnly {
  220. rs := conditionallyCropImages(bytes.NewReader(n.Data), ext, r)
  221. rs = conditionallyResizeImages(rs, ext, r)
  222. if e := writeResponseContent(filename, mtype, rs, w, r); e != nil {
  223. glog.V(2).Infoln("response write error:", e)
  224. }
  225. } else {
  226. vs.streamWriteResponseContent(filename, mtype, volumeId, n, w, r, readOption)
  227. }
  228. }
  229. func shouldAttemptStreamWrite(hasLocalVolume bool, ext string, r *http.Request) (shouldAttempt bool, mustMetaOnly bool) {
  230. if !hasLocalVolume {
  231. return false, false
  232. }
  233. if len(ext) > 0 {
  234. ext = strings.ToLower(ext)
  235. }
  236. if r.Method == "HEAD" {
  237. return true, true
  238. }
  239. _, _, _, shouldResize := shouldResizeImages(ext, r)
  240. _, _, _, _, shouldCrop := shouldCropImages(ext, r)
  241. if shouldResize || shouldCrop {
  242. return false, false
  243. }
  244. return true, false
  245. }
  246. func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, ext string, w http.ResponseWriter, r *http.Request) (processed bool) {
  247. if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
  248. return false
  249. }
  250. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsCompressed())
  251. if e != nil {
  252. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  253. return false
  254. }
  255. if fileName == "" && chunkManifest.Name != "" {
  256. fileName = chunkManifest.Name
  257. }
  258. if ext == "" {
  259. ext = filepath.Ext(fileName)
  260. }
  261. mType := ""
  262. if chunkManifest.Mime != "" {
  263. mt := chunkManifest.Mime
  264. if !strings.HasPrefix(mt, "application/octet-stream") {
  265. mType = mt
  266. }
  267. }
  268. w.Header().Set("X-File-Store", "chunked")
  269. chunkedFileReader := operation.NewChunkedFileReader(chunkManifest.Chunks, vs.GetMaster(context.Background()), vs.grpcDialOption)
  270. defer chunkedFileReader.Close()
  271. rs := conditionallyCropImages(chunkedFileReader, ext, r)
  272. rs = conditionallyResizeImages(rs, ext, r)
  273. if e := writeResponseContent(fileName, mType, rs, w, r); e != nil {
  274. glog.V(2).Infoln("response write error:", e)
  275. }
  276. return true
  277. }
  278. func conditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  279. rs := originalDataReaderSeeker
  280. if len(ext) > 0 {
  281. ext = strings.ToLower(ext)
  282. }
  283. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  284. if shouldResize {
  285. rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, mode)
  286. }
  287. return rs
  288. }
  289. func shouldResizeImages(ext string, r *http.Request) (width, height int, mode string, shouldResize bool) {
  290. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".webp" {
  291. if r.FormValue("width") != "" {
  292. width, _ = strconv.Atoi(r.FormValue("width"))
  293. }
  294. if r.FormValue("height") != "" {
  295. height, _ = strconv.Atoi(r.FormValue("height"))
  296. }
  297. }
  298. mode = r.FormValue("mode")
  299. shouldResize = width > 0 || height > 0
  300. return
  301. }
  302. func conditionallyCropImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  303. rs := originalDataReaderSeeker
  304. if len(ext) > 0 {
  305. ext = strings.ToLower(ext)
  306. }
  307. x1, y1, x2, y2, shouldCrop := shouldCropImages(ext, r)
  308. if shouldCrop {
  309. var err error
  310. rs, err = images.Cropped(ext, rs, x1, y1, x2, y2)
  311. if err != nil {
  312. glog.Errorf("Cropping images error: %s", err)
  313. }
  314. }
  315. return rs
  316. }
  317. func shouldCropImages(ext string, r *http.Request) (x1, y1, x2, y2 int, shouldCrop bool) {
  318. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
  319. if r.FormValue("crop_x1") != "" {
  320. x1, _ = strconv.Atoi(r.FormValue("crop_x1"))
  321. }
  322. if r.FormValue("crop_y1") != "" {
  323. y1, _ = strconv.Atoi(r.FormValue("crop_y1"))
  324. }
  325. if r.FormValue("crop_x2") != "" {
  326. x2, _ = strconv.Atoi(r.FormValue("crop_x2"))
  327. }
  328. if r.FormValue("crop_y2") != "" {
  329. y2, _ = strconv.Atoi(r.FormValue("crop_y2"))
  330. }
  331. }
  332. shouldCrop = x1 >= 0 && y1 >= 0 && x2 > x1 && y2 > y1
  333. return
  334. }
  335. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  336. totalSize, e := rs.Seek(0, 2)
  337. if mimeType == "" {
  338. if ext := filepath.Ext(filename); ext != "" {
  339. mimeType = mime.TypeByExtension(ext)
  340. }
  341. }
  342. if mimeType != "" {
  343. w.Header().Set("Content-Type", mimeType)
  344. }
  345. w.Header().Set("Accept-Ranges", "bytes")
  346. adjustPassthroughHeaders(w, r, filename)
  347. if r.Method == "HEAD" {
  348. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  349. return nil
  350. }
  351. return processRangeRequest(r, w, totalSize, mimeType, func(offset int64, size int64) (filer.DoStreamContent, error) {
  352. return func(writer io.Writer) error {
  353. if _, e = rs.Seek(offset, 0); e != nil {
  354. return e
  355. }
  356. _, e = io.CopyN(writer, rs, size)
  357. return e
  358. }, nil
  359. })
  360. }
  361. func (vs *VolumeServer) streamWriteResponseContent(filename string, mimeType string, volumeId needle.VolumeId, n *needle.Needle, w http.ResponseWriter, r *http.Request, readOption *storage.ReadOption) {
  362. totalSize := int64(n.DataSize)
  363. if mimeType == "" {
  364. if ext := filepath.Ext(filename); ext != "" {
  365. mimeType = mime.TypeByExtension(ext)
  366. }
  367. }
  368. if mimeType != "" {
  369. w.Header().Set("Content-Type", mimeType)
  370. }
  371. w.Header().Set("Accept-Ranges", "bytes")
  372. adjustPassthroughHeaders(w, r, filename)
  373. if r.Method == "HEAD" {
  374. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  375. return
  376. }
  377. processRangeRequest(r, w, totalSize, mimeType, func(offset int64, size int64) (filer.DoStreamContent, error) {
  378. return func(writer io.Writer) error {
  379. return vs.store.ReadVolumeNeedleDataInto(volumeId, n, readOption, writer, offset, size)
  380. }, nil
  381. })
  382. }