filer_server_handlers_write.go 8.0 KB

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