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.

319 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
4 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. "io"
  9. "mime"
  10. "net/http"
  11. "net/url"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "sync/atomic"
  16. "time"
  17. "github.com/chrislusf/seaweedfs/weed/glog"
  18. "github.com/chrislusf/seaweedfs/weed/images"
  19. "github.com/chrislusf/seaweedfs/weed/operation"
  20. "github.com/chrislusf/seaweedfs/weed/stats"
  21. "github.com/chrislusf/seaweedfs/weed/storage"
  22. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  23. "github.com/chrislusf/seaweedfs/weed/util"
  24. )
  25. var fileNameEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`)
  26. func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  27. glog.V(9).Info(r.Method + " " + r.URL.Path + " " + r.Header.Get("Range"))
  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. io.Copy(w, response.Body)
  96. return
  97. } else {
  98. // redirect
  99. u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations[0].PublicUrl))
  100. u.Path = fmt.Sprintf("%s/%s,%s", u.Path, vid, fid)
  101. arg := url.Values{}
  102. if c := r.FormValue("collection"); c != "" {
  103. arg.Set("collection", c)
  104. }
  105. u.RawQuery = arg.Encode()
  106. http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
  107. return
  108. }
  109. }
  110. cookie := n.Cookie
  111. readOption := &storage.ReadOption{
  112. ReadDeleted: r.FormValue("readDeleted") == "true",
  113. }
  114. var count int
  115. var needleSize types.Size
  116. onReadSizeFn := func(size types.Size) {
  117. needleSize = size
  118. atomic.AddInt64(&vs.inFlightDownloadDataSize, int64(needleSize))
  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(needleSize))
  127. vs.inFlightDownloadDataLimitCond.Signal()
  128. }()
  129. if err != nil && err != storage.ErrorDeleted && r.FormValue("type") != "replicate" && 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. w.WriteHeader(http.StatusNotFound)
  137. return
  138. }
  139. if n.Cookie != cookie {
  140. 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())
  141. w.WriteHeader(http.StatusNotFound)
  142. return
  143. }
  144. if n.LastModified != 0 {
  145. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  146. if r.Header.Get("If-Modified-Since") != "" {
  147. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  148. if t.Unix() >= int64(n.LastModified) {
  149. w.WriteHeader(http.StatusNotModified)
  150. return
  151. }
  152. }
  153. }
  154. }
  155. if inm := r.Header.Get("If-None-Match"); inm == "\""+n.Etag()+"\"" {
  156. w.WriteHeader(http.StatusNotModified)
  157. return
  158. }
  159. setEtag(w, n.Etag())
  160. if n.HasPairs() {
  161. pairMap := make(map[string]string)
  162. err = json.Unmarshal(n.Pairs, &pairMap)
  163. if err != nil {
  164. glog.V(0).Infoln("Unmarshal pairs error:", err)
  165. }
  166. for k, v := range pairMap {
  167. w.Header().Set(k, v)
  168. }
  169. }
  170. if vs.tryHandleChunkedFile(n, filename, ext, w, r) {
  171. return
  172. }
  173. if n.NameSize > 0 && filename == "" {
  174. filename = string(n.Name)
  175. if ext == "" {
  176. ext = filepath.Ext(filename)
  177. }
  178. }
  179. mtype := ""
  180. if n.MimeSize > 0 {
  181. mt := string(n.Mime)
  182. if !strings.HasPrefix(mt, "application/octet-stream") {
  183. mtype = mt
  184. }
  185. }
  186. if n.IsCompressed() {
  187. if _, _, _, shouldResize := shouldResizeImages(ext, r); shouldResize {
  188. if n.Data, err = util.DecompressData(n.Data); err != nil {
  189. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  190. }
  191. // } else if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") && util.IsZstdContent(n.Data) {
  192. // w.Header().Set("Content-Encoding", "zstd")
  193. } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && util.IsGzippedContent(n.Data) {
  194. w.Header().Set("Content-Encoding", "gzip")
  195. } else {
  196. if n.Data, err = util.DecompressData(n.Data); err != nil {
  197. glog.V(0).Infoln("uncompress error:", err, r.URL.Path)
  198. }
  199. }
  200. }
  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. }
  206. func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, ext string, w http.ResponseWriter, r *http.Request) (processed bool) {
  207. if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
  208. return false
  209. }
  210. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsCompressed())
  211. if e != nil {
  212. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  213. return false
  214. }
  215. if fileName == "" && chunkManifest.Name != "" {
  216. fileName = chunkManifest.Name
  217. }
  218. if ext == "" {
  219. ext = filepath.Ext(fileName)
  220. }
  221. mType := ""
  222. if chunkManifest.Mime != "" {
  223. mt := chunkManifest.Mime
  224. if !strings.HasPrefix(mt, "application/octet-stream") {
  225. mType = mt
  226. }
  227. }
  228. w.Header().Set("X-File-Store", "chunked")
  229. chunkedFileReader := operation.NewChunkedFileReader(chunkManifest.Chunks, vs.GetMaster(), vs.grpcDialOption)
  230. defer chunkedFileReader.Close()
  231. rs := conditionallyResizeImages(chunkedFileReader, ext, r)
  232. if e := writeResponseContent(fileName, mType, rs, w, r); e != nil {
  233. glog.V(2).Infoln("response write error:", e)
  234. }
  235. return true
  236. }
  237. func conditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  238. rs := originalDataReaderSeeker
  239. if len(ext) > 0 {
  240. ext = strings.ToLower(ext)
  241. }
  242. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  243. if shouldResize {
  244. rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, mode)
  245. }
  246. return rs
  247. }
  248. func shouldResizeImages(ext string, r *http.Request) (width, height int, mode string, shouldResize bool) {
  249. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".webp" {
  250. if r.FormValue("width") != "" {
  251. width, _ = strconv.Atoi(r.FormValue("width"))
  252. }
  253. if r.FormValue("height") != "" {
  254. height, _ = strconv.Atoi(r.FormValue("height"))
  255. }
  256. }
  257. mode = r.FormValue("mode")
  258. shouldResize = width > 0 || height > 0
  259. return
  260. }
  261. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  262. totalSize, e := rs.Seek(0, 2)
  263. if mimeType == "" {
  264. if ext := filepath.Ext(filename); ext != "" {
  265. mimeType = mime.TypeByExtension(ext)
  266. }
  267. }
  268. if mimeType != "" {
  269. w.Header().Set("Content-Type", mimeType)
  270. }
  271. w.Header().Set("Accept-Ranges", "bytes")
  272. adjustHeaderContentDisposition(w, r, filename)
  273. if r.Method == "HEAD" {
  274. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  275. return nil
  276. }
  277. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  278. if _, e = rs.Seek(offset, 0); e != nil {
  279. return e
  280. }
  281. _, e = io.CopyN(writer, rs, size)
  282. return e
  283. })
  284. return nil
  285. }