filer_server_handlers_write.go 7.2 KB

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