You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

305 lines
9.0 KiB

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