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.

417 lines
12 KiB

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