filer_server_handlers_write.go 9.3 KB

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