volume_server_handlers_read.go 12 KB

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