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.

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