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.

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