filer_server_handlers_write.go 8.4 KB

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