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.

359 lines
10 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
6 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. }
  112. var count int
  113. var needleSize types.Size
  114. readOption.AttemptMetaOnly, readOption.MustMetaOnly = shouldAttemptStreamWrite(hasVolume, ext, r)
  115. onReadSizeFn := func(size types.Size) {
  116. needleSize = size
  117. atomic.AddInt64(&vs.inFlightDownloadDataSize, int64(needleSize))
  118. }
  119. if hasVolume {
  120. count, err = vs.store.ReadVolumeNeedle(volumeId, n, readOption, onReadSizeFn)
  121. } else if hasEcVolume {
  122. count, err = vs.store.ReadEcShardNeedle(volumeId, n, onReadSizeFn)
  123. }
  124. defer func() {
  125. atomic.AddInt64(&vs.inFlightDownloadDataSize, -int64(needleSize))
  126. vs.inFlightDownloadDataLimitCond.Signal()
  127. }()
  128. if err != nil && err != storage.ErrorDeleted && hasVolume {
  129. glog.V(4).Infof("read needle: %v", err)
  130. // start to fix it from other replicas, if not deleted and hasVolume and is not a replicated request
  131. }
  132. // glog.V(4).Infoln("read bytes", count, "error", err)
  133. if err != nil || count < 0 {
  134. glog.V(3).Infof("read %s isNormalVolume %v error: %v", r.URL.Path, hasVolume, err)
  135. w.WriteHeader(http.StatusNotFound)
  136. return
  137. }
  138. if n.Cookie != cookie {
  139. 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())
  140. w.WriteHeader(http.StatusNotFound)
  141. return
  142. }
  143. if n.LastModified != 0 {
  144. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  145. if r.Header.Get("If-Modified-Since") != "" {
  146. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  147. if t.Unix() >= int64(n.LastModified) {
  148. w.WriteHeader(http.StatusNotModified)
  149. return
  150. }
  151. }
  152. }
  153. }
  154. if inm := r.Header.Get("If-None-Match"); inm == "\""+n.Etag()+"\"" {
  155. w.WriteHeader(http.StatusNotModified)
  156. return
  157. }
  158. setEtag(w, n.Etag())
  159. if n.HasPairs() {
  160. pairMap := make(map[string]string)
  161. err = json.Unmarshal(n.Pairs, &pairMap)
  162. if err != nil {
  163. glog.V(0).Infoln("Unmarshal pairs error:", err)
  164. }
  165. for k, v := range pairMap {
  166. w.Header().Set(k, v)
  167. }
  168. }
  169. if vs.tryHandleChunkedFile(n, filename, ext, w, r) {
  170. return
  171. }
  172. if n.NameSize > 0 && filename == "" {
  173. filename = string(n.Name)
  174. if ext == "" {
  175. ext = filepath.Ext(filename)
  176. }
  177. }
  178. mtype := ""
  179. if n.MimeSize > 0 {
  180. mt := string(n.Mime)
  181. if !strings.HasPrefix(mt, "application/octet-stream") {
  182. mtype = mt
  183. }
  184. }
  185. if n.IsCompressed() {
  186. if _, _, _, shouldResize := shouldResizeImages(ext, r); shouldResize {
  187. if n.Data, err = util.DecompressData(n.Data); err != nil {
  188. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  189. }
  190. // } else if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") && util.IsZstdContent(n.Data) {
  191. // w.Header().Set("Content-Encoding", "zstd")
  192. } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && util.IsGzippedContent(n.Data) {
  193. w.Header().Set("Content-Encoding", "gzip")
  194. } else {
  195. if n.Data, err = util.DecompressData(n.Data); err != nil {
  196. glog.V(0).Infoln("uncompress error:", err, r.URL.Path)
  197. }
  198. }
  199. }
  200. if !readOption.IsMetaOnly {
  201. rs := conditionallyResizeImages(bytes.NewReader(n.Data), ext, r)
  202. if e := writeResponseContent(filename, mtype, rs, w, r); e != nil {
  203. glog.V(2).Infoln("response write error:", e)
  204. }
  205. } else {
  206. vs.streamWriteResponseContent(filename, mtype, volumeId, n, w, r, readOption)
  207. }
  208. }
  209. func shouldAttemptStreamWrite(hasLocalVolume bool, ext string, r *http.Request) (shouldAttempt bool, mustMetaOnly bool) {
  210. if !hasLocalVolume {
  211. return false, false
  212. }
  213. if len(ext) > 0 {
  214. ext = strings.ToLower(ext)
  215. }
  216. if r.Method == "HEAD" {
  217. return true, true
  218. }
  219. _, _, _, shouldResize := shouldResizeImages(ext, r)
  220. if shouldResize {
  221. return false, false
  222. }
  223. return true, false
  224. }
  225. func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, ext string, w http.ResponseWriter, r *http.Request) (processed bool) {
  226. if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
  227. return false
  228. }
  229. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsCompressed())
  230. if e != nil {
  231. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  232. return false
  233. }
  234. if fileName == "" && chunkManifest.Name != "" {
  235. fileName = chunkManifest.Name
  236. }
  237. if ext == "" {
  238. ext = filepath.Ext(fileName)
  239. }
  240. mType := ""
  241. if chunkManifest.Mime != "" {
  242. mt := chunkManifest.Mime
  243. if !strings.HasPrefix(mt, "application/octet-stream") {
  244. mType = mt
  245. }
  246. }
  247. w.Header().Set("X-File-Store", "chunked")
  248. chunkedFileReader := operation.NewChunkedFileReader(chunkManifest.Chunks, vs.GetMaster(), vs.grpcDialOption)
  249. defer chunkedFileReader.Close()
  250. rs := conditionallyResizeImages(chunkedFileReader, ext, r)
  251. if e := writeResponseContent(fileName, mType, rs, w, r); e != nil {
  252. glog.V(2).Infoln("response write error:", e)
  253. }
  254. return true
  255. }
  256. func conditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  257. rs := originalDataReaderSeeker
  258. if len(ext) > 0 {
  259. ext = strings.ToLower(ext)
  260. }
  261. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  262. if shouldResize {
  263. rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, mode)
  264. }
  265. return rs
  266. }
  267. func shouldResizeImages(ext string, r *http.Request) (width, height int, mode string, shouldResize bool) {
  268. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".webp" {
  269. if r.FormValue("width") != "" {
  270. width, _ = strconv.Atoi(r.FormValue("width"))
  271. }
  272. if r.FormValue("height") != "" {
  273. height, _ = strconv.Atoi(r.FormValue("height"))
  274. }
  275. }
  276. mode = r.FormValue("mode")
  277. shouldResize = width > 0 || height > 0
  278. return
  279. }
  280. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  281. totalSize, e := rs.Seek(0, 2)
  282. if mimeType == "" {
  283. if ext := filepath.Ext(filename); ext != "" {
  284. mimeType = mime.TypeByExtension(ext)
  285. }
  286. }
  287. if mimeType != "" {
  288. w.Header().Set("Content-Type", mimeType)
  289. }
  290. w.Header().Set("Accept-Ranges", "bytes")
  291. adjustPassthroughHeaders(w, r, filename)
  292. if r.Method == "HEAD" {
  293. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  294. return nil
  295. }
  296. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  297. if _, e = rs.Seek(offset, 0); e != nil {
  298. return e
  299. }
  300. _, e = io.CopyN(writer, rs, size)
  301. return e
  302. })
  303. return nil
  304. }
  305. func (vs *VolumeServer) streamWriteResponseContent(filename string, mimeType string, volumeId needle.VolumeId, n *needle.Needle, w http.ResponseWriter, r *http.Request, readOption *storage.ReadOption) {
  306. totalSize := int64(n.DataSize)
  307. if mimeType == "" {
  308. if ext := filepath.Ext(filename); ext != "" {
  309. mimeType = mime.TypeByExtension(ext)
  310. }
  311. }
  312. if mimeType != "" {
  313. w.Header().Set("Content-Type", mimeType)
  314. }
  315. w.Header().Set("Accept-Ranges", "bytes")
  316. adjustPassthroughHeaders(w, r, filename)
  317. if r.Method == "HEAD" {
  318. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  319. return
  320. }
  321. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  322. return vs.store.ReadVolumeNeedleDataInto(volumeId, n, readOption, writer, offset, size)
  323. })
  324. }