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.

252 lines
7.4 KiB

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