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.

258 lines
7.5 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
5 years ago
3 years ago
3 years ago
5 years ago
  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. query := r.URL.Query()
  100. if entry.IsDirectory() {
  101. if fs.option.DisableDirListing {
  102. w.WriteHeader(http.StatusForbidden)
  103. return
  104. }
  105. if query.Get("metadata") == "true" {
  106. writeJsonQuiet(w, r, http.StatusOK, entry)
  107. return
  108. }
  109. if entry.Attr.Mime == "" {
  110. fs.listDirectoryHandler(w, r)
  111. return
  112. }
  113. // inform S3 API this is a user created directory key object
  114. w.Header().Set(s3_constants.X_SeaweedFS_Header_Directory_Key, "true")
  115. }
  116. if isForDirectory {
  117. w.WriteHeader(http.StatusNotFound)
  118. return
  119. }
  120. if query.Get("metadata") == "true" {
  121. if query.Get("resolveManifest") == "true" {
  122. if entry.Chunks, _, err = filer.ResolveChunkManifest(
  123. fs.filer.MasterClient.GetLookupFileIdFunction(),
  124. entry.GetChunks(), 0, math.MaxInt64); err != nil {
  125. err = fmt.Errorf("failed to resolve chunk manifest, err: %s", err.Error())
  126. writeJsonError(w, r, http.StatusInternalServerError, err)
  127. }
  128. }
  129. writeJsonQuiet(w, r, http.StatusOK, entry)
  130. return
  131. }
  132. etag := filer.ETagEntry(entry)
  133. if checkPreconditions(w, r, entry) {
  134. return
  135. }
  136. w.Header().Set("Accept-Ranges", "bytes")
  137. // mime type
  138. mimeType := entry.Attr.Mime
  139. if mimeType == "" {
  140. if ext := filepath.Ext(entry.Name()); ext != "" {
  141. mimeType = mime.TypeByExtension(ext)
  142. }
  143. }
  144. if mimeType != "" {
  145. w.Header().Set("Content-Type", mimeType)
  146. }
  147. // print out the header from extended properties
  148. for k, v := range entry.Extended {
  149. if !strings.HasPrefix(k, "xattr-") {
  150. // "xattr-" prefix is set in filesys.XATTR_PREFIX
  151. w.Header().Set(k, string(v))
  152. }
  153. }
  154. //Seaweed custom header are not visible to Vue or javascript
  155. seaweedHeaders := []string{}
  156. for header := range w.Header() {
  157. if strings.HasPrefix(header, "Seaweed-") {
  158. seaweedHeaders = append(seaweedHeaders, header)
  159. }
  160. }
  161. seaweedHeaders = append(seaweedHeaders, "Content-Disposition")
  162. w.Header().Set("Access-Control-Expose-Headers", strings.Join(seaweedHeaders, ","))
  163. //set tag count
  164. tagCount := 0
  165. for k := range entry.Extended {
  166. if strings.HasPrefix(k, s3_constants.AmzObjectTagging+"-") {
  167. tagCount++
  168. }
  169. }
  170. if tagCount > 0 {
  171. w.Header().Set(s3_constants.AmzTagCount, strconv.Itoa(tagCount))
  172. }
  173. setEtag(w, etag)
  174. filename := entry.Name()
  175. adjustPassthroughHeaders(w, r, filename)
  176. totalSize := int64(entry.Size())
  177. if r.Method == "HEAD" {
  178. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  179. return
  180. }
  181. if rangeReq := r.Header.Get("Range"); rangeReq == "" {
  182. ext := filepath.Ext(filename)
  183. if len(ext) > 0 {
  184. ext = strings.ToLower(ext)
  185. }
  186. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  187. if shouldResize {
  188. data := mem.Allocate(int(totalSize))
  189. defer mem.Free(data)
  190. err := filer.ReadAll(data, fs.filer.MasterClient, entry.GetChunks())
  191. if err != nil {
  192. glog.Errorf("failed to read %s: %v", path, err)
  193. w.WriteHeader(http.StatusInternalServerError)
  194. return
  195. }
  196. rs, _, _ := images.Resized(ext, bytes.NewReader(data), width, height, mode)
  197. io.Copy(w, rs)
  198. return
  199. }
  200. }
  201. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  202. if offset+size <= int64(len(entry.Content)) {
  203. _, err := writer.Write(entry.Content[offset : offset+size])
  204. if err != nil {
  205. stats.FilerRequestCounter.WithLabelValues(stats.ErrorWriteEntry).Inc()
  206. glog.Errorf("failed to write entry content: %v", err)
  207. }
  208. return err
  209. }
  210. chunks := entry.GetChunks()
  211. if entry.IsInRemoteOnly() {
  212. dir, name := entry.FullPath.DirAndName()
  213. if resp, err := fs.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
  214. Directory: dir,
  215. Name: name,
  216. }); err != nil {
  217. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadCache).Inc()
  218. glog.Errorf("CacheRemoteObjectToLocalCluster %s: %v", entry.FullPath, err)
  219. return fmt.Errorf("cache %s: %v", entry.FullPath, err)
  220. } else {
  221. chunks = resp.Entry.GetChunks()
  222. }
  223. }
  224. err = filer.StreamContentWithThrottler(fs.filer.MasterClient, writer, chunks, offset, size, fs.option.DownloadMaxBytesPs)
  225. if err != nil {
  226. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  227. glog.Errorf("failed to stream content %s: %v", r.URL, err)
  228. }
  229. return err
  230. })
  231. }