filer_server_handlers_read.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  7. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  8. "io"
  9. "math"
  10. "mime"
  11. "net/http"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/seaweedfs/seaweedfs/weed/filer"
  17. "github.com/seaweedfs/seaweedfs/weed/glog"
  18. "github.com/seaweedfs/seaweedfs/weed/images"
  19. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  20. "github.com/seaweedfs/seaweedfs/weed/stats"
  21. "github.com/seaweedfs/seaweedfs/weed/util"
  22. )
  23. // Validates the preconditions. Returns true if GET/HEAD operation should not proceed.
  24. // Preconditions supported are:
  25. //
  26. // If-Modified-Since
  27. // If-Unmodified-Since
  28. // If-Match
  29. // If-None-Match
  30. func checkPreconditions(w http.ResponseWriter, r *http.Request, entry *filer.Entry) bool {
  31. etag := filer.ETagEntry(entry)
  32. /// When more than one conditional request header field is present in a
  33. /// request, the order in which the fields are evaluated becomes
  34. /// important. In practice, the fields defined in this document are
  35. /// consistently implemented in a single, logical order, since "lost
  36. /// update" preconditions have more strict requirements than cache
  37. /// validation, a validated cache is more efficient than a partial
  38. /// response, and entity tags are presumed to be more accurate than date
  39. /// validators. https://tools.ietf.org/html/rfc7232#section-5
  40. if entry.Attr.Mtime.IsZero() {
  41. return false
  42. }
  43. w.Header().Set("Last-Modified", entry.Attr.Mtime.UTC().Format(http.TimeFormat))
  44. ifMatchETagHeader := r.Header.Get("If-Match")
  45. ifUnmodifiedSinceHeader := r.Header.Get("If-Unmodified-Since")
  46. if ifMatchETagHeader != "" {
  47. if util.CanonicalizeETag(etag) != util.CanonicalizeETag(ifMatchETagHeader) {
  48. w.WriteHeader(http.StatusPreconditionFailed)
  49. return true
  50. }
  51. } else if ifUnmodifiedSinceHeader != "" {
  52. if t, parseError := time.Parse(http.TimeFormat, ifUnmodifiedSinceHeader); parseError == nil {
  53. if t.Before(entry.Attr.Mtime) {
  54. w.WriteHeader(http.StatusPreconditionFailed)
  55. return true
  56. }
  57. }
  58. }
  59. ifNoneMatchETagHeader := r.Header.Get("If-None-Match")
  60. ifModifiedSinceHeader := r.Header.Get("If-Modified-Since")
  61. if ifNoneMatchETagHeader != "" {
  62. if util.CanonicalizeETag(etag) == util.CanonicalizeETag(ifNoneMatchETagHeader) {
  63. w.WriteHeader(http.StatusNotModified)
  64. return true
  65. }
  66. } else if ifModifiedSinceHeader != "" {
  67. if t, parseError := time.Parse(http.TimeFormat, ifModifiedSinceHeader); parseError == nil {
  68. if !t.Before(entry.Attr.Mtime) {
  69. w.WriteHeader(http.StatusNotModified)
  70. return true
  71. }
  72. }
  73. }
  74. return false
  75. }
  76. func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  77. path := r.URL.Path
  78. isForDirectory := strings.HasSuffix(path, "/")
  79. if isForDirectory && len(path) > 1 {
  80. path = path[:len(path)-1]
  81. }
  82. entry, err := fs.filer.FindEntry(context.Background(), util.FullPath(path))
  83. if err != nil {
  84. if path == "/" {
  85. fs.listDirectoryHandler(w, r)
  86. return
  87. }
  88. if err == filer_pb.ErrNotFound {
  89. glog.V(2).Infof("Not found %s: %v", path, err)
  90. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadNotFound).Inc()
  91. w.WriteHeader(http.StatusNotFound)
  92. } else {
  93. glog.Errorf("Internal %s: %v", path, err)
  94. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadInternal).Inc()
  95. w.WriteHeader(http.StatusInternalServerError)
  96. }
  97. return
  98. }
  99. if entry.IsDirectory() {
  100. if fs.option.DisableDirListing {
  101. w.WriteHeader(http.StatusMethodNotAllowed)
  102. return
  103. }
  104. if entry.Attr.Mime == "" {
  105. fs.listDirectoryHandler(w, r)
  106. return
  107. }
  108. // inform S3 API this is a user created directory key object
  109. w.Header().Set(s3_constants.X_SeaweedFS_Header_Directory_Key, "true")
  110. }
  111. if isForDirectory {
  112. w.WriteHeader(http.StatusNotFound)
  113. return
  114. }
  115. query := r.URL.Query()
  116. if query.Get("metadata") == "true" {
  117. if query.Get("resolveManifest") == "true" {
  118. if entry.Chunks, _, err = filer.ResolveChunkManifest(
  119. fs.filer.MasterClient.GetLookupFileIdFunction(),
  120. entry.Chunks, 0, math.MaxInt64); err != nil {
  121. err = fmt.Errorf("failed to resolve chunk manifest, err: %s", err.Error())
  122. writeJsonError(w, r, http.StatusInternalServerError, err)
  123. }
  124. }
  125. writeJsonQuiet(w, r, http.StatusOK, entry)
  126. return
  127. }
  128. etag := filer.ETagEntry(entry)
  129. if checkPreconditions(w, r, entry) {
  130. return
  131. }
  132. w.Header().Set("Accept-Ranges", "bytes")
  133. // mime type
  134. mimeType := entry.Attr.Mime
  135. if mimeType == "" {
  136. if ext := filepath.Ext(entry.Name()); ext != "" {
  137. mimeType = mime.TypeByExtension(ext)
  138. }
  139. }
  140. if mimeType != "" {
  141. w.Header().Set("Content-Type", mimeType)
  142. }
  143. // print out the header from extended properties
  144. for k, v := range entry.Extended {
  145. if !strings.HasPrefix(k, "xattr-") {
  146. // "xattr-" prefix is set in filesys.XATTR_PREFIX
  147. w.Header().Set(k, string(v))
  148. }
  149. }
  150. //Seaweed custom header are not visible to Vue or javascript
  151. seaweedHeaders := []string{}
  152. for header := range w.Header() {
  153. if strings.HasPrefix(header, "Seaweed-") {
  154. seaweedHeaders = append(seaweedHeaders, header)
  155. }
  156. }
  157. seaweedHeaders = append(seaweedHeaders, "Content-Disposition")
  158. w.Header().Set("Access-Control-Expose-Headers", strings.Join(seaweedHeaders, ","))
  159. //set tag count
  160. tagCount := 0
  161. for k := range entry.Extended {
  162. if strings.HasPrefix(k, s3_constants.AmzObjectTagging+"-") {
  163. tagCount++
  164. }
  165. }
  166. if tagCount > 0 {
  167. w.Header().Set(s3_constants.AmzTagCount, strconv.Itoa(tagCount))
  168. }
  169. setEtag(w, etag)
  170. filename := entry.Name()
  171. adjustPassthroughHeaders(w, r, filename)
  172. totalSize := int64(entry.Size())
  173. if r.Method == "HEAD" {
  174. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  175. return
  176. }
  177. if rangeReq := r.Header.Get("Range"); rangeReq == "" {
  178. ext := filepath.Ext(filename)
  179. if len(ext) > 0 {
  180. ext = strings.ToLower(ext)
  181. }
  182. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  183. if shouldResize {
  184. data := mem.Allocate(int(totalSize))
  185. defer mem.Free(data)
  186. err := filer.ReadAll(data, fs.filer.MasterClient, entry.Chunks)
  187. if err != nil {
  188. glog.Errorf("failed to read %s: %v", path, err)
  189. w.WriteHeader(http.StatusInternalServerError)
  190. return
  191. }
  192. rs, _, _ := images.Resized(ext, bytes.NewReader(data), width, height, mode)
  193. io.Copy(w, rs)
  194. return
  195. }
  196. }
  197. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  198. if offset+size <= int64(len(entry.Content)) {
  199. _, err := writer.Write(entry.Content[offset : offset+size])
  200. if err != nil {
  201. stats.FilerRequestCounter.WithLabelValues(stats.ErrorWriteEntry).Inc()
  202. glog.Errorf("failed to write entry content: %v", err)
  203. }
  204. return err
  205. }
  206. chunks := entry.Chunks
  207. if entry.IsInRemoteOnly() {
  208. dir, name := entry.FullPath.DirAndName()
  209. if resp, err := fs.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
  210. Directory: dir,
  211. Name: name,
  212. }); err != nil {
  213. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadCache).Inc()
  214. glog.Errorf("CacheRemoteObjectToLocalCluster %s: %v", entry.FullPath, err)
  215. return fmt.Errorf("cache %s: %v", entry.FullPath, err)
  216. } else {
  217. chunks = resp.Entry.Chunks
  218. }
  219. }
  220. err = filer.StreamContentWithThrottler(fs.filer.MasterClient, writer, chunks, offset, size, fs.option.DownloadMaxBytesPs)
  221. if err != nil {
  222. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  223. glog.Errorf("failed to stream content %s: %v", r.URL, err)
  224. }
  225. return err
  226. })
  227. }