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.

416 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. NotFound(w)
  156. return
  157. }
  158. if n.LastModified != 0 {
  159. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  160. if r.Header.Get("If-Modified-Since") != "" {
  161. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  162. if t.Unix() >= int64(n.LastModified) {
  163. w.WriteHeader(http.StatusNotModified)
  164. return
  165. }
  166. }
  167. }
  168. }
  169. if inm := r.Header.Get("If-None-Match"); inm == "\""+n.Etag()+"\"" {
  170. w.WriteHeader(http.StatusNotModified)
  171. return
  172. }
  173. setEtag(w, n.Etag())
  174. if n.HasPairs() {
  175. pairMap := make(map[string]string)
  176. err = json.Unmarshal(n.Pairs, &pairMap)
  177. if err != nil {
  178. glog.V(0).Infoln("Unmarshal pairs error:", err)
  179. }
  180. for k, v := range pairMap {
  181. w.Header().Set(k, v)
  182. }
  183. }
  184. if vs.tryHandleChunkedFile(n, filename, ext, w, r) {
  185. return
  186. }
  187. if n.NameSize > 0 && filename == "" {
  188. filename = string(n.Name)
  189. if ext == "" {
  190. ext = filepath.Ext(filename)
  191. }
  192. }
  193. mtype := ""
  194. if n.MimeSize > 0 {
  195. mt := string(n.Mime)
  196. if !strings.HasPrefix(mt, "application/octet-stream") {
  197. mtype = mt
  198. }
  199. }
  200. if n.IsCompressed() {
  201. _, _, _, shouldResize := shouldResizeImages(ext, r)
  202. _, _, _, _, shouldCrop := shouldCropImages(ext, r)
  203. if shouldResize || shouldCrop {
  204. if n.Data, err = util.DecompressData(n.Data); err != nil {
  205. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  206. }
  207. // } else if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") && util.IsZstdContent(n.Data) {
  208. // w.Header().Set("Content-Encoding", "zstd")
  209. } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && util.IsGzippedContent(n.Data) {
  210. w.Header().Set("Content-Encoding", "gzip")
  211. } else {
  212. if n.Data, err = util.DecompressData(n.Data); err != nil {
  213. glog.V(0).Infoln("uncompress error:", err, r.URL.Path)
  214. }
  215. }
  216. }
  217. if !readOption.IsMetaOnly {
  218. rs := conditionallyCropImages(bytes.NewReader(n.Data), ext, r)
  219. rs = conditionallyResizeImages(rs, ext, r)
  220. if e := writeResponseContent(filename, mtype, rs, w, r); e != nil {
  221. glog.V(2).Infoln("response write error:", e)
  222. }
  223. } else {
  224. vs.streamWriteResponseContent(filename, mtype, volumeId, n, w, r, readOption)
  225. }
  226. }
  227. func shouldAttemptStreamWrite(hasLocalVolume bool, ext string, r *http.Request) (shouldAttempt bool, mustMetaOnly bool) {
  228. if !hasLocalVolume {
  229. return false, false
  230. }
  231. if len(ext) > 0 {
  232. ext = strings.ToLower(ext)
  233. }
  234. if r.Method == "HEAD" {
  235. return true, true
  236. }
  237. _, _, _, shouldResize := shouldResizeImages(ext, r)
  238. _, _, _, _, shouldCrop := shouldCropImages(ext, r)
  239. if shouldResize || shouldCrop {
  240. return false, false
  241. }
  242. return true, false
  243. }
  244. func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, ext string, w http.ResponseWriter, r *http.Request) (processed bool) {
  245. if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
  246. return false
  247. }
  248. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsCompressed())
  249. if e != nil {
  250. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  251. return false
  252. }
  253. if fileName == "" && chunkManifest.Name != "" {
  254. fileName = chunkManifest.Name
  255. }
  256. if ext == "" {
  257. ext = filepath.Ext(fileName)
  258. }
  259. mType := ""
  260. if chunkManifest.Mime != "" {
  261. mt := chunkManifest.Mime
  262. if !strings.HasPrefix(mt, "application/octet-stream") {
  263. mType = mt
  264. }
  265. }
  266. w.Header().Set("X-File-Store", "chunked")
  267. chunkedFileReader := operation.NewChunkedFileReader(chunkManifest.Chunks, vs.GetMaster(), vs.grpcDialOption)
  268. defer chunkedFileReader.Close()
  269. rs := conditionallyCropImages(chunkedFileReader, ext, r)
  270. rs = conditionallyResizeImages(rs, ext, r)
  271. if e := writeResponseContent(fileName, mType, rs, w, r); e != nil {
  272. glog.V(2).Infoln("response write error:", e)
  273. }
  274. return true
  275. }
  276. func conditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  277. rs := originalDataReaderSeeker
  278. if len(ext) > 0 {
  279. ext = strings.ToLower(ext)
  280. }
  281. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  282. if shouldResize {
  283. rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, mode)
  284. }
  285. return rs
  286. }
  287. func shouldResizeImages(ext string, r *http.Request) (width, height int, mode string, shouldResize bool) {
  288. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".webp" {
  289. if r.FormValue("width") != "" {
  290. width, _ = strconv.Atoi(r.FormValue("width"))
  291. }
  292. if r.FormValue("height") != "" {
  293. height, _ = strconv.Atoi(r.FormValue("height"))
  294. }
  295. }
  296. mode = r.FormValue("mode")
  297. shouldResize = width > 0 || height > 0
  298. return
  299. }
  300. func conditionallyCropImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  301. rs := originalDataReaderSeeker
  302. if len(ext) > 0 {
  303. ext = strings.ToLower(ext)
  304. }
  305. x1, y1, x2, y2, shouldCrop := shouldCropImages(ext, r)
  306. if shouldCrop {
  307. var err error
  308. rs, err = images.Cropped(ext, rs, x1, y1, x2, y2)
  309. if err != nil {
  310. glog.Errorf("Cropping images error: %s", err)
  311. }
  312. }
  313. return rs
  314. }
  315. func shouldCropImages(ext string, r *http.Request) (x1, y1, x2, y2 int, shouldCrop bool) {
  316. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
  317. if r.FormValue("crop_x1") != "" {
  318. x1, _ = strconv.Atoi(r.FormValue("crop_x1"))
  319. }
  320. if r.FormValue("crop_y1") != "" {
  321. y1, _ = strconv.Atoi(r.FormValue("crop_y1"))
  322. }
  323. if r.FormValue("crop_x2") != "" {
  324. x2, _ = strconv.Atoi(r.FormValue("crop_x2"))
  325. }
  326. if r.FormValue("crop_y2") != "" {
  327. y2, _ = strconv.Atoi(r.FormValue("crop_y2"))
  328. }
  329. }
  330. shouldCrop = x1 >= 0 && y1 >= 0 && x2 > x1 && y2 > y1
  331. return
  332. }
  333. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  334. totalSize, e := rs.Seek(0, 2)
  335. if mimeType == "" {
  336. if ext := filepath.Ext(filename); ext != "" {
  337. mimeType = mime.TypeByExtension(ext)
  338. }
  339. }
  340. if mimeType != "" {
  341. w.Header().Set("Content-Type", mimeType)
  342. }
  343. w.Header().Set("Accept-Ranges", "bytes")
  344. adjustPassthroughHeaders(w, r, filename)
  345. if r.Method == "HEAD" {
  346. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  347. return nil
  348. }
  349. return processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  350. if _, e = rs.Seek(offset, 0); e != nil {
  351. return e
  352. }
  353. _, e = io.CopyN(writer, rs, size)
  354. return e
  355. })
  356. }
  357. func (vs *VolumeServer) streamWriteResponseContent(filename string, mimeType string, volumeId needle.VolumeId, n *needle.Needle, w http.ResponseWriter, r *http.Request, readOption *storage.ReadOption) {
  358. totalSize := int64(n.DataSize)
  359. if mimeType == "" {
  360. if ext := filepath.Ext(filename); ext != "" {
  361. mimeType = mime.TypeByExtension(ext)
  362. }
  363. }
  364. if mimeType != "" {
  365. w.Header().Set("Content-Type", mimeType)
  366. }
  367. w.Header().Set("Accept-Ranges", "bytes")
  368. adjustPassthroughHeaders(w, r, filename)
  369. if r.Method == "HEAD" {
  370. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  371. return
  372. }
  373. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  374. return vs.store.ReadVolumeNeedleDataInto(volumeId, n, readOption, writer, offset, size)
  375. })
  376. }