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.

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