filer_server_handlers_write.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. 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. glog.V(1).Infoln("deleting", objectPath, ":", err.Error())
  185. httpStatus := http.StatusInternalServerError
  186. if err == filer_pb.ErrNotFound {
  187. httpStatus = http.StatusNoContent
  188. writeJsonQuiet(w, r, httpStatus, nil)
  189. return
  190. }
  191. writeJsonError(w, r, httpStatus, err)
  192. return
  193. }
  194. w.WriteHeader(http.StatusNoContent)
  195. }
  196. func (fs *FilerServer) detectStorageOption(requestURI, qCollection, qReplication string, ttlSeconds int32, diskType, dataCenter, rack, dataNode string) (*operation.StorageOption, error) {
  197. rule := fs.filer.FilerConf.MatchStorageRule(requestURI)
  198. if rule.ReadOnly {
  199. return nil, ErrReadOnly
  200. }
  201. if rule.MaxFileNameLength == 0 {
  202. rule.MaxFileNameLength = fs.filer.MaxFilenameLength
  203. }
  204. // required by buckets folder
  205. bucketDefaultCollection := ""
  206. if strings.HasPrefix(requestURI, fs.filer.DirBucketsPath+"/") {
  207. bucketDefaultCollection = fs.filer.DetectBucket(util.FullPath(requestURI))
  208. }
  209. if ttlSeconds == 0 {
  210. ttl, err := needle.ReadTTL(rule.GetTtl())
  211. if err != nil {
  212. glog.Errorf("fail to parse %s ttl setting %s: %v", rule.LocationPrefix, rule.Ttl, err)
  213. }
  214. ttlSeconds = int32(ttl.Minutes()) * 60
  215. }
  216. return &operation.StorageOption{
  217. Replication: util.Nvl(qReplication, rule.Replication, fs.option.DefaultReplication),
  218. Collection: util.Nvl(qCollection, rule.Collection, bucketDefaultCollection, fs.option.Collection),
  219. DataCenter: util.Nvl(dataCenter, rule.DataCenter, fs.option.DataCenter),
  220. Rack: util.Nvl(rack, rule.Rack, fs.option.Rack),
  221. DataNode: util.Nvl(dataNode, rule.DataNode, fs.option.DataNode),
  222. TtlSeconds: ttlSeconds,
  223. DiskType: util.Nvl(diskType, rule.DiskType),
  224. Fsync: rule.Fsync,
  225. VolumeGrowthCount: rule.VolumeGrowthCount,
  226. MaxFileNameLength: rule.MaxFileNameLength,
  227. }, nil
  228. }
  229. func (fs *FilerServer) detectStorageOption0(requestURI, qCollection, qReplication string, qTtl string, diskType string, fsync string, dataCenter, rack, dataNode, saveInside string) (*operation.StorageOption, error) {
  230. ttl, err := needle.ReadTTL(qTtl)
  231. if err != nil {
  232. glog.Errorf("fail to parse ttl %s: %v", qTtl, err)
  233. }
  234. so, err := fs.detectStorageOption(requestURI, qCollection, qReplication, int32(ttl.Minutes())*60, diskType, dataCenter, rack, dataNode)
  235. if so != nil {
  236. if fsync == "false" {
  237. so.Fsync = false
  238. } else if fsync == "true" {
  239. so.Fsync = true
  240. }
  241. if saveInside == "true" {
  242. so.SaveInside = true
  243. } else {
  244. so.SaveInside = false
  245. }
  246. }
  247. return so, err
  248. }