filer_server_handlers_write.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package weed_server
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  7. "net/http"
  8. "os"
  9. "strings"
  10. "time"
  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. if query.Has("mv.from") {
  87. fs.move(ctx, w, r, so)
  88. } else {
  89. fs.autoChunk(ctx, w, r, contentLength, so)
  90. }
  91. util.CloseRequest(r)
  92. }
  93. func (fs *FilerServer) move(ctx context.Context, w http.ResponseWriter, r *http.Request, so *operation.StorageOption) {
  94. src := r.URL.Query().Get("mv.from")
  95. dst := r.URL.Path
  96. glog.V(2).Infof("FilerServer.move %v to %v", src, dst)
  97. var err error
  98. if src, err = clearName(src); err != nil {
  99. writeJsonError(w, r, http.StatusBadRequest, err)
  100. return
  101. }
  102. if dst, err = clearName(dst); err != nil {
  103. writeJsonError(w, r, http.StatusBadRequest, err)
  104. return
  105. }
  106. src = strings.TrimRight(src, "/")
  107. if src == "" {
  108. err = fmt.Errorf("invalid source '/'")
  109. writeJsonError(w, r, http.StatusBadRequest, err)
  110. return
  111. }
  112. srcPath := util.FullPath(src)
  113. dstPath := util.FullPath(dst)
  114. srcEntry, err := fs.filer.FindEntry(ctx, srcPath)
  115. if err != nil {
  116. err = fmt.Errorf("failed to get src entry '%s', err: %s", src, err)
  117. writeJsonError(w, r, http.StatusBadRequest, err)
  118. return
  119. }
  120. oldDir, oldName := srcPath.DirAndName()
  121. newDir, newName := dstPath.DirAndName()
  122. newName = util.Nvl(newName, oldName)
  123. dstEntry, err := fs.filer.FindEntry(ctx, util.FullPath(strings.TrimRight(dst, "/")))
  124. if err != nil && err != filer_pb.ErrNotFound {
  125. err = fmt.Errorf("failed to get dst entry '%s', err: %s", dst, err)
  126. writeJsonError(w, r, http.StatusInternalServerError, err)
  127. return
  128. }
  129. if err == nil && !dstEntry.IsDirectory() && srcEntry.IsDirectory() {
  130. err = fmt.Errorf("move: cannot overwrite non-directory '%s' with directory '%s'", dst, src)
  131. writeJsonError(w, r, http.StatusBadRequest, err)
  132. return
  133. }
  134. _, err = fs.AtomicRenameEntry(ctx, &filer_pb.AtomicRenameEntryRequest{
  135. OldDirectory: oldDir,
  136. OldName: oldName,
  137. NewDirectory: newDir,
  138. NewName: newName,
  139. })
  140. if err != nil {
  141. err = fmt.Errorf("failed to move entry from '%s' to '%s', err: %s", src, dst, err)
  142. writeJsonError(w, r, http.StatusBadRequest, err)
  143. return
  144. }
  145. w.WriteHeader(http.StatusNoContent)
  146. }
  147. // curl -X DELETE http://localhost:8888/path/to
  148. // curl -X DELETE http://localhost:8888/path/to?recursive=true
  149. // curl -X DELETE http://localhost:8888/path/to?recursive=true&ignoreRecursiveError=true
  150. // curl -X DELETE http://localhost:8888/path/to?recursive=true&skipChunkDeletion=true
  151. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  152. isRecursive := r.FormValue("recursive") == "true"
  153. if !isRecursive && fs.option.recursiveDelete {
  154. if r.FormValue("recursive") != "false" {
  155. isRecursive = true
  156. }
  157. }
  158. ignoreRecursiveError := r.FormValue("ignoreRecursiveError") == "true"
  159. skipChunkDeletion := r.FormValue("skipChunkDeletion") == "true"
  160. objectPath := r.URL.Path
  161. if len(r.URL.Path) > 1 && strings.HasSuffix(objectPath, "/") {
  162. objectPath = objectPath[0 : len(objectPath)-1]
  163. }
  164. err := fs.filer.DeleteEntryMetaAndData(context.Background(), util.FullPath(objectPath), isRecursive, ignoreRecursiveError, !skipChunkDeletion, false, nil)
  165. if err != nil {
  166. glog.V(1).Infoln("deleting", objectPath, ":", err.Error())
  167. httpStatus := http.StatusInternalServerError
  168. if err == filer_pb.ErrNotFound {
  169. httpStatus = http.StatusNoContent
  170. writeJsonQuiet(w, r, httpStatus, nil)
  171. return
  172. }
  173. writeJsonError(w, r, httpStatus, err)
  174. return
  175. }
  176. w.WriteHeader(http.StatusNoContent)
  177. }
  178. func (fs *FilerServer) detectStorageOption(requestURI, qCollection, qReplication string, ttlSeconds int32, diskType, dataCenter, rack, dataNode string) (*operation.StorageOption, error) {
  179. rule := fs.filer.FilerConf.MatchStorageRule(requestURI)
  180. if rule.ReadOnly {
  181. return nil, ErrReadOnly
  182. }
  183. // required by buckets folder
  184. bucketDefaultCollection := ""
  185. if strings.HasPrefix(requestURI, fs.filer.DirBucketsPath+"/") {
  186. bucketDefaultCollection = fs.filer.DetectBucket(util.FullPath(requestURI))
  187. }
  188. if ttlSeconds == 0 {
  189. ttl, err := needle.ReadTTL(rule.GetTtl())
  190. if err != nil {
  191. glog.Errorf("fail to parse %s ttl setting %s: %v", rule.LocationPrefix, rule.Ttl, err)
  192. }
  193. ttlSeconds = int32(ttl.Minutes()) * 60
  194. }
  195. return &operation.StorageOption{
  196. Replication: util.Nvl(qReplication, rule.Replication, fs.option.DefaultReplication),
  197. Collection: util.Nvl(qCollection, rule.Collection, bucketDefaultCollection, fs.option.Collection),
  198. DataCenter: util.Nvl(dataCenter, rule.DataCenter, fs.option.DataCenter),
  199. Rack: util.Nvl(rack, rule.Rack, fs.option.Rack),
  200. DataNode: util.Nvl(dataNode, rule.DataNode, fs.option.DataNode),
  201. TtlSeconds: ttlSeconds,
  202. DiskType: util.Nvl(diskType, rule.DiskType),
  203. Fsync: rule.Fsync,
  204. VolumeGrowthCount: rule.VolumeGrowthCount,
  205. }, nil
  206. }
  207. func (fs *FilerServer) detectStorageOption0(requestURI, qCollection, qReplication string, qTtl string, diskType string, fsync string, dataCenter, rack, dataNode string) (*operation.StorageOption, error) {
  208. ttl, err := needle.ReadTTL(qTtl)
  209. if err != nil {
  210. glog.Errorf("fail to parse ttl %s: %v", qTtl, err)
  211. }
  212. so, err := fs.detectStorageOption(requestURI, qCollection, qReplication, int32(ttl.Minutes())*60, diskType, dataCenter, rack, dataNode)
  213. if so != nil {
  214. if fsync == "false" {
  215. so.Fsync = false
  216. } else if fsync == "true" {
  217. so.Fsync = true
  218. }
  219. }
  220. return so, err
  221. }