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.

320 lines
9.3 KiB

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