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.

266 lines
7.8 KiB

9 years ago
6 years ago
9 years ago
9 years ago
4 years ago
4 years ago
4 years ago
4 years ago
9 years ago
4 years ago
4 years ago
4 years ago
4 years ago
9 years ago
9 years ago
9 years ago
9 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "strings"
  9. "time"
  10. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  11. "github.com/seaweedfs/seaweedfs/weed/glog"
  12. "github.com/seaweedfs/seaweedfs/weed/operation"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/security"
  15. "github.com/seaweedfs/seaweedfs/weed/stats"
  16. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  17. "github.com/seaweedfs/seaweedfs/weed/util"
  18. )
  19. var (
  20. OS_UID = uint32(os.Getuid())
  21. OS_GID = uint32(os.Getgid())
  22. ErrReadOnly = errors.New("read only")
  23. )
  24. type FilerPostResult struct {
  25. Name string `json:"name,omitempty"`
  26. Size int64 `json:"size,omitempty"`
  27. Error string `json:"error,omitempty"`
  28. }
  29. func (fs *FilerServer) assignNewFileInfo(so *operation.StorageOption) (fileId, urlLocation string, auth security.EncodedJwt, err error) {
  30. stats.FilerRequestCounter.WithLabelValues(stats.ChunkAssign).Inc()
  31. start := time.Now()
  32. defer func() {
  33. stats.FilerRequestHistogram.WithLabelValues(stats.ChunkAssign).Observe(time.Since(start).Seconds())
  34. }()
  35. ar, altRequest := so.ToAssignRequests(1)
  36. assignResult, ae := operation.Assign(fs.filer.GetMaster, fs.grpcDialOption, ar, altRequest)
  37. if ae != nil {
  38. glog.Errorf("failing to assign a file id: %v", ae)
  39. err = ae
  40. return
  41. }
  42. fileId = assignResult.Fid
  43. assignUrl := assignResult.Url
  44. // Prefer same data center
  45. if fs.option.DataCenter != "" {
  46. for _, repl := range assignResult.Replicas {
  47. if repl.DataCenter == fs.option.DataCenter {
  48. assignUrl = repl.Url
  49. break
  50. }
  51. }
  52. }
  53. urlLocation = "http://" + assignUrl + "/" + assignResult.Fid
  54. if so.Fsync {
  55. urlLocation += "?fsync=true"
  56. }
  57. auth = assignResult.Auth
  58. return
  59. }
  60. func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request, contentLength int64) {
  61. ctx := context.Background()
  62. destination := r.RequestURI
  63. if finalDestination := r.Header.Get(s3_constants.SeaweedStorageDestinationHeader); finalDestination != "" {
  64. destination = finalDestination
  65. }
  66. query := r.URL.Query()
  67. so, err := fs.detectStorageOption0(destination,
  68. query.Get("collection"),
  69. query.Get("replication"),
  70. query.Get("ttl"),
  71. query.Get("disk"),
  72. query.Get("fsync"),
  73. query.Get("dataCenter"),
  74. query.Get("rack"),
  75. query.Get("dataNode"),
  76. )
  77. if err != nil {
  78. if err == ErrReadOnly {
  79. w.WriteHeader(http.StatusInsufficientStorage)
  80. } else {
  81. glog.V(1).Infoln("post", r.RequestURI, ":", err.Error())
  82. w.WriteHeader(http.StatusInternalServerError)
  83. }
  84. return
  85. }
  86. // When DiskType is empty,use filer's -disk
  87. if so.DiskType == "" {
  88. so.DiskType = fs.option.DiskType
  89. }
  90. if query.Has("mv.from") {
  91. fs.move(ctx, w, r, so)
  92. } else {
  93. fs.autoChunk(ctx, w, r, contentLength, so)
  94. }
  95. util.CloseRequest(r)
  96. }
  97. func (fs *FilerServer) move(ctx context.Context, w http.ResponseWriter, r *http.Request, so *operation.StorageOption) {
  98. src := r.URL.Query().Get("mv.from")
  99. dst := r.URL.Path
  100. glog.V(2).Infof("FilerServer.move %v to %v", src, dst)
  101. var err error
  102. if src, err = clearName(src); err != nil {
  103. writeJsonError(w, r, http.StatusBadRequest, err)
  104. return
  105. }
  106. if dst, err = clearName(dst); err != nil {
  107. writeJsonError(w, r, http.StatusBadRequest, err)
  108. return
  109. }
  110. src = strings.TrimRight(src, "/")
  111. if src == "" {
  112. err = fmt.Errorf("invalid source '/'")
  113. writeJsonError(w, r, http.StatusBadRequest, err)
  114. return
  115. }
  116. srcPath := util.FullPath(src)
  117. dstPath := util.FullPath(dst)
  118. srcEntry, err := fs.filer.FindEntry(ctx, srcPath)
  119. if err != nil {
  120. err = fmt.Errorf("failed to get src entry '%s', err: %s", src, err)
  121. writeJsonError(w, r, http.StatusBadRequest, err)
  122. return
  123. }
  124. oldDir, oldName := srcPath.DirAndName()
  125. newDir, newName := dstPath.DirAndName()
  126. newName = util.Nvl(newName, oldName)
  127. dstEntry, err := fs.filer.FindEntry(ctx, util.FullPath(strings.TrimRight(dst, "/")))
  128. if err != nil && err != filer_pb.ErrNotFound {
  129. err = fmt.Errorf("failed to get dst entry '%s', err: %s", dst, err)
  130. writeJsonError(w, r, http.StatusInternalServerError, err)
  131. return
  132. }
  133. if err == nil && !dstEntry.IsDirectory() && srcEntry.IsDirectory() {
  134. err = fmt.Errorf("move: cannot overwrite non-directory '%s' with directory '%s'", dst, src)
  135. writeJsonError(w, r, http.StatusBadRequest, err)
  136. return
  137. }
  138. _, err = fs.AtomicRenameEntry(ctx, &filer_pb.AtomicRenameEntryRequest{
  139. OldDirectory: oldDir,
  140. OldName: oldName,
  141. NewDirectory: newDir,
  142. NewName: newName,
  143. })
  144. if err != nil {
  145. err = fmt.Errorf("failed to move entry from '%s' to '%s', err: %s", src, dst, err)
  146. writeJsonError(w, r, http.StatusBadRequest, err)
  147. return
  148. }
  149. w.WriteHeader(http.StatusNoContent)
  150. }
  151. // curl -X DELETE http://localhost:8888/path/to
  152. // curl -X DELETE http://localhost:8888/path/to?recursive=true
  153. // curl -X DELETE http://localhost:8888/path/to?recursive=true&ignoreRecursiveError=true
  154. // curl -X DELETE http://localhost:8888/path/to?recursive=true&skipChunkDeletion=true
  155. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  156. isRecursive := r.FormValue("recursive") == "true"
  157. if !isRecursive && fs.option.recursiveDelete {
  158. if r.FormValue("recursive") != "false" {
  159. isRecursive = true
  160. }
  161. }
  162. ignoreRecursiveError := r.FormValue("ignoreRecursiveError") == "true"
  163. skipChunkDeletion := r.FormValue("skipChunkDeletion") == "true"
  164. objectPath := r.URL.Path
  165. if len(r.URL.Path) > 1 && strings.HasSuffix(objectPath, "/") {
  166. objectPath = objectPath[0 : len(objectPath)-1]
  167. }
  168. err := fs.filer.DeleteEntryMetaAndData(context.Background(), util.FullPath(objectPath), isRecursive, ignoreRecursiveError, !skipChunkDeletion, false, nil)
  169. if err != nil {
  170. glog.V(1).Infoln("deleting", objectPath, ":", err.Error())
  171. httpStatus := http.StatusInternalServerError
  172. if err == filer_pb.ErrNotFound {
  173. httpStatus = http.StatusNoContent
  174. writeJsonQuiet(w, r, httpStatus, nil)
  175. return
  176. }
  177. writeJsonError(w, r, httpStatus, err)
  178. return
  179. }
  180. w.WriteHeader(http.StatusNoContent)
  181. }
  182. func (fs *FilerServer) detectStorageOption(requestURI, qCollection, qReplication string, ttlSeconds int32, diskType, dataCenter, rack, dataNode string) (*operation.StorageOption, error) {
  183. rule := fs.filer.FilerConf.MatchStorageRule(requestURI)
  184. if rule.ReadOnly {
  185. return nil, ErrReadOnly
  186. }
  187. // required by buckets folder
  188. bucketDefaultCollection := ""
  189. if strings.HasPrefix(requestURI, fs.filer.DirBucketsPath+"/") {
  190. bucketDefaultCollection = fs.filer.DetectBucket(util.FullPath(requestURI))
  191. }
  192. if ttlSeconds == 0 {
  193. ttl, err := needle.ReadTTL(rule.GetTtl())
  194. if err != nil {
  195. glog.Errorf("fail to parse %s ttl setting %s: %v", rule.LocationPrefix, rule.Ttl, err)
  196. }
  197. ttlSeconds = int32(ttl.Minutes()) * 60
  198. }
  199. return &operation.StorageOption{
  200. Replication: util.Nvl(qReplication, rule.Replication, fs.option.DefaultReplication),
  201. Collection: util.Nvl(qCollection, rule.Collection, bucketDefaultCollection, fs.option.Collection),
  202. DataCenter: util.Nvl(dataCenter, rule.DataCenter, fs.option.DataCenter),
  203. Rack: util.Nvl(rack, rule.Rack, fs.option.Rack),
  204. DataNode: util.Nvl(dataNode, rule.DataNode, fs.option.DataNode),
  205. TtlSeconds: ttlSeconds,
  206. DiskType: util.Nvl(diskType, rule.DiskType),
  207. Fsync: rule.Fsync,
  208. VolumeGrowthCount: rule.VolumeGrowthCount,
  209. }, nil
  210. }
  211. func (fs *FilerServer) detectStorageOption0(requestURI, qCollection, qReplication string, qTtl string, diskType string, fsync string, dataCenter, rack, dataNode string) (*operation.StorageOption, error) {
  212. ttl, err := needle.ReadTTL(qTtl)
  213. if err != nil {
  214. glog.Errorf("fail to parse ttl %s: %v", qTtl, err)
  215. }
  216. so, err := fs.detectStorageOption(requestURI, qCollection, qReplication, int32(ttl.Minutes())*60, diskType, dataCenter, rack, dataNode)
  217. if so != nil {
  218. if fsync == "false" {
  219. so.Fsync = false
  220. } else if fsync == "true" {
  221. so.Fsync = true
  222. }
  223. }
  224. return so, err
  225. }