dir.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. package filesys
  2. import (
  3. "bytes"
  4. "context"
  5. "math"
  6. "os"
  7. "strings"
  8. "time"
  9. "github.com/seaweedfs/fuse"
  10. "github.com/seaweedfs/fuse/fs"
  11. "github.com/chrislusf/seaweedfs/weed/filer"
  12. "github.com/chrislusf/seaweedfs/weed/filesys/meta_cache"
  13. "github.com/chrislusf/seaweedfs/weed/util/log"
  14. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. )
  17. type Dir struct {
  18. name string
  19. wfs *WFS
  20. entry *filer_pb.Entry
  21. parent *Dir
  22. }
  23. var _ = fs.Node(&Dir{})
  24. var _ = fs.NodeCreater(&Dir{})
  25. var _ = fs.NodeMknoder(&Dir{})
  26. var _ = fs.NodeMkdirer(&Dir{})
  27. var _ = fs.NodeFsyncer(&Dir{})
  28. var _ = fs.NodeRequestLookuper(&Dir{})
  29. var _ = fs.HandleReadDirAller(&Dir{})
  30. var _ = fs.NodeRemover(&Dir{})
  31. var _ = fs.NodeRenamer(&Dir{})
  32. var _ = fs.NodeSetattrer(&Dir{})
  33. var _ = fs.NodeGetxattrer(&Dir{})
  34. var _ = fs.NodeSetxattrer(&Dir{})
  35. var _ = fs.NodeRemovexattrer(&Dir{})
  36. var _ = fs.NodeListxattrer(&Dir{})
  37. var _ = fs.NodeForgetter(&Dir{})
  38. func (dir *Dir) Attr(ctx context.Context, attr *fuse.Attr) error {
  39. // https://github.com/bazil/fuse/issues/196
  40. attr.Valid = time.Second
  41. if dir.FullPath() == dir.wfs.option.FilerMountRootPath {
  42. dir.setRootDirAttributes(attr)
  43. log.Tracef("root dir Attr %s, attr: %+v", dir.FullPath(), attr)
  44. return nil
  45. }
  46. if err := dir.maybeLoadEntry(); err != nil {
  47. log.Tracef("dir Attr %s,err: %+v", dir.FullPath(), err)
  48. return err
  49. }
  50. attr.Inode = util.FullPath(dir.FullPath()).AsInode()
  51. attr.Mode = os.FileMode(dir.entry.Attributes.FileMode) | os.ModeDir
  52. attr.Mtime = time.Unix(dir.entry.Attributes.Mtime, 0)
  53. attr.Crtime = time.Unix(dir.entry.Attributes.Crtime, 0)
  54. attr.Gid = dir.entry.Attributes.Gid
  55. attr.Uid = dir.entry.Attributes.Uid
  56. log.Tracef("dir Attr %s, attr: %+v", dir.FullPath(), attr)
  57. return nil
  58. }
  59. func (dir *Dir) Getxattr(ctx context.Context, req *fuse.GetxattrRequest, resp *fuse.GetxattrResponse) error {
  60. log.Tracef("dir Getxattr %s", dir.FullPath())
  61. if err := dir.maybeLoadEntry(); err != nil {
  62. return err
  63. }
  64. return getxattr(dir.entry, req, resp)
  65. }
  66. func (dir *Dir) setRootDirAttributes(attr *fuse.Attr) {
  67. attr.Inode = 1 // filer2.FullPath(dir.Path).AsInode()
  68. attr.Valid = time.Hour
  69. attr.Uid = dir.wfs.option.MountUid
  70. attr.Gid = dir.wfs.option.MountGid
  71. attr.Mode = dir.wfs.option.MountMode
  72. attr.Crtime = dir.wfs.option.MountCtime
  73. attr.Ctime = dir.wfs.option.MountCtime
  74. attr.Mtime = dir.wfs.option.MountMtime
  75. attr.Atime = dir.wfs.option.MountMtime
  76. attr.BlockSize = 1024 * 1024
  77. }
  78. func (dir *Dir) Fsync(ctx context.Context, req *fuse.FsyncRequest) error {
  79. // fsync works at OS level
  80. // write the file chunks to the filerGrpcAddress
  81. log.Tracef("dir %s fsync %+v", dir.FullPath(), req)
  82. return nil
  83. }
  84. func (dir *Dir) newFile(name string, entry *filer_pb.Entry) fs.Node {
  85. f := dir.wfs.fsNodeCache.EnsureFsNode(util.NewFullPath(dir.FullPath(), name), func() fs.Node {
  86. return &File{
  87. Name: name,
  88. dir: dir,
  89. wfs: dir.wfs,
  90. entry: entry,
  91. entryViewCache: nil,
  92. }
  93. })
  94. f.(*File).dir = dir // in case dir node was created later
  95. return f
  96. }
  97. func (dir *Dir) newDirectory(fullpath util.FullPath, entry *filer_pb.Entry) fs.Node {
  98. d := dir.wfs.fsNodeCache.EnsureFsNode(fullpath, func() fs.Node {
  99. return &Dir{name: entry.Name, wfs: dir.wfs, entry: entry, parent: dir}
  100. })
  101. d.(*Dir).parent = dir // in case dir node was created later
  102. return d
  103. }
  104. func (dir *Dir) Create(ctx context.Context, req *fuse.CreateRequest,
  105. resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {
  106. request := &filer_pb.CreateEntryRequest{
  107. Directory: dir.FullPath(),
  108. Entry: &filer_pb.Entry{
  109. Name: req.Name,
  110. IsDirectory: req.Mode&os.ModeDir > 0,
  111. Attributes: &filer_pb.FuseAttributes{
  112. Mtime: time.Now().Unix(),
  113. Crtime: time.Now().Unix(),
  114. FileMode: uint32(req.Mode &^ dir.wfs.option.Umask),
  115. Uid: req.Uid,
  116. Gid: req.Gid,
  117. Collection: dir.wfs.option.Collection,
  118. Replication: dir.wfs.option.Replication,
  119. TtlSec: dir.wfs.option.TtlSec,
  120. },
  121. },
  122. OExcl: req.Flags&fuse.OpenExclusive != 0,
  123. Signatures: []int32{dir.wfs.signature},
  124. }
  125. log.Debugf("create %s/%s: %v", dir.FullPath(), req.Name, req.Flags)
  126. if err := dir.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  127. dir.wfs.mapPbIdFromLocalToFiler(request.Entry)
  128. defer dir.wfs.mapPbIdFromFilerToLocal(request.Entry)
  129. if err := filer_pb.CreateEntry(client, request); err != nil {
  130. if strings.Contains(err.Error(), "EEXIST") {
  131. return fuse.EEXIST
  132. }
  133. log.Infof("create %s/%s: %v", dir.FullPath(), req.Name, err)
  134. return fuse.EIO
  135. }
  136. dir.wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
  137. return nil
  138. }); err != nil {
  139. return nil, nil, err
  140. }
  141. var node fs.Node
  142. if request.Entry.IsDirectory {
  143. node = dir.newDirectory(util.NewFullPath(dir.FullPath(), req.Name), request.Entry)
  144. return node, nil, nil
  145. }
  146. node = dir.newFile(req.Name, request.Entry)
  147. file := node.(*File)
  148. fh := dir.wfs.AcquireHandle(file, req.Uid, req.Gid)
  149. return file, fh, nil
  150. }
  151. func (dir *Dir) Mknod(ctx context.Context, req *fuse.MknodRequest) (fs.Node, error) {
  152. if req.Mode&os.ModeNamedPipe != 0 {
  153. log.Debugf("mknod named pipe %s", req.String())
  154. return nil, fuse.ENOSYS
  155. }
  156. if req.Mode&req.Mode&os.ModeSocket != 0 {
  157. log.Debugf("mknod socket %s", req.String())
  158. return nil, fuse.ENOSYS
  159. }
  160. // not going to support mknod for normal files either
  161. log.Debugf("mknod %s", req.String())
  162. return nil, fuse.ENOSYS
  163. }
  164. func (dir *Dir) Mkdir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) {
  165. log.Tracef("mkdir %s: %s", dir.FullPath(), req.Name)
  166. newEntry := &filer_pb.Entry{
  167. Name: req.Name,
  168. IsDirectory: true,
  169. Attributes: &filer_pb.FuseAttributes{
  170. Mtime: time.Now().Unix(),
  171. Crtime: time.Now().Unix(),
  172. FileMode: uint32(req.Mode &^ dir.wfs.option.Umask),
  173. Uid: req.Uid,
  174. Gid: req.Gid,
  175. },
  176. }
  177. err := dir.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  178. dir.wfs.mapPbIdFromLocalToFiler(newEntry)
  179. defer dir.wfs.mapPbIdFromFilerToLocal(newEntry)
  180. request := &filer_pb.CreateEntryRequest{
  181. Directory: dir.FullPath(),
  182. Entry: newEntry,
  183. Signatures: []int32{dir.wfs.signature},
  184. }
  185. log.Debugf("mkdir: %v", request)
  186. if err := filer_pb.CreateEntry(client, request); err != nil {
  187. log.Infof("mkdir %s/%s: %v", dir.FullPath(), req.Name, err)
  188. return err
  189. }
  190. dir.wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
  191. return nil
  192. })
  193. if err == nil {
  194. node := dir.newDirectory(util.NewFullPath(dir.FullPath(), req.Name), newEntry)
  195. return node, nil
  196. }
  197. log.Infof("mkdir %s/%s: %v", dir.FullPath(), req.Name, err)
  198. return nil, fuse.EIO
  199. }
  200. func (dir *Dir) Lookup(ctx context.Context, req *fuse.LookupRequest, resp *fuse.LookupResponse) (node fs.Node, err error) {
  201. log.Tracef("dir Lookup %s: %s by %s", dir.FullPath(), req.Name, req.Header.String())
  202. fullFilePath := util.NewFullPath(dir.FullPath(), req.Name)
  203. dirPath := util.FullPath(dir.FullPath())
  204. visitErr := meta_cache.EnsureVisited(dir.wfs.metaCache, dir.wfs, dirPath)
  205. if visitErr != nil {
  206. log.Errorf("dir Lookup %s: %v", dirPath, visitErr)
  207. return nil, fuse.EIO
  208. }
  209. cachedEntry, cacheErr := dir.wfs.metaCache.FindEntry(context.Background(), fullFilePath)
  210. if cacheErr == filer_pb.ErrNotFound {
  211. return nil, fuse.ENOENT
  212. }
  213. entry := cachedEntry.ToProtoEntry()
  214. if entry == nil {
  215. // log.Tracef("dir Lookup cache miss %s", fullFilePath)
  216. entry, err = filer_pb.GetEntry(dir.wfs, fullFilePath)
  217. if err != nil {
  218. log.Debugf("dir GetEntry %s: %v", fullFilePath, err)
  219. return nil, fuse.ENOENT
  220. }
  221. } else {
  222. log.Tracef("dir Lookup cache hit %s", fullFilePath)
  223. }
  224. if entry != nil {
  225. if entry.IsDirectory {
  226. node = dir.newDirectory(fullFilePath, entry)
  227. } else {
  228. node = dir.newFile(req.Name, entry)
  229. }
  230. // resp.EntryValid = time.Second
  231. resp.Attr.Inode = fullFilePath.AsInode()
  232. resp.Attr.Valid = time.Second
  233. resp.Attr.Mtime = time.Unix(entry.Attributes.Mtime, 0)
  234. resp.Attr.Crtime = time.Unix(entry.Attributes.Crtime, 0)
  235. resp.Attr.Mode = os.FileMode(entry.Attributes.FileMode)
  236. resp.Attr.Gid = entry.Attributes.Gid
  237. resp.Attr.Uid = entry.Attributes.Uid
  238. if entry.HardLinkCounter > 0 {
  239. resp.Attr.Nlink = uint32(entry.HardLinkCounter)
  240. }
  241. return node, nil
  242. }
  243. log.Tracef("not found dir GetEntry %s: %v", fullFilePath, err)
  244. return nil, fuse.ENOENT
  245. }
  246. func (dir *Dir) ReadDirAll(ctx context.Context) (ret []fuse.Dirent, err error) {
  247. log.Tracef("dir ReadDirAll %s", dir.FullPath())
  248. processEachEntryFn := func(entry *filer_pb.Entry, isLast bool) error {
  249. fullpath := util.NewFullPath(dir.FullPath(), entry.Name)
  250. inode := fullpath.AsInode()
  251. if entry.IsDirectory {
  252. dirent := fuse.Dirent{Inode: inode, Name: entry.Name, Type: fuse.DT_Dir}
  253. ret = append(ret, dirent)
  254. } else {
  255. dirent := fuse.Dirent{Inode: inode, Name: entry.Name, Type: fuse.DT_File}
  256. ret = append(ret, dirent)
  257. }
  258. return nil
  259. }
  260. dirPath := util.FullPath(dir.FullPath())
  261. if err = meta_cache.EnsureVisited(dir.wfs.metaCache, dir.wfs, dirPath); err != nil {
  262. log.Errorf("dir ReadDirAll %s: %v", dirPath, err)
  263. return nil, fuse.EIO
  264. }
  265. listedEntries, listErr := dir.wfs.metaCache.ListDirectoryEntries(context.Background(), util.FullPath(dir.FullPath()), "", false, int(math.MaxInt32))
  266. if listErr != nil {
  267. log.Errorf("list meta cache: %v", listErr)
  268. return nil, fuse.EIO
  269. }
  270. for _, cachedEntry := range listedEntries {
  271. processEachEntryFn(cachedEntry.ToProtoEntry(), false)
  272. }
  273. return
  274. }
  275. func (dir *Dir) Remove(ctx context.Context, req *fuse.RemoveRequest) error {
  276. if !req.Dir {
  277. return dir.removeOneFile(req)
  278. }
  279. return dir.removeFolder(req)
  280. }
  281. func (dir *Dir) removeOneFile(req *fuse.RemoveRequest) error {
  282. filePath := util.NewFullPath(dir.FullPath(), req.Name)
  283. entry, err := filer_pb.GetEntry(dir.wfs, filePath)
  284. if err != nil {
  285. return err
  286. }
  287. if entry == nil {
  288. return nil
  289. }
  290. // first, ensure the filer store can correctly delete
  291. log.Tracef("remove file: %v", req)
  292. isDeleteData := entry.HardLinkCounter <= 1
  293. err = filer_pb.Remove(dir.wfs, dir.FullPath(), req.Name, isDeleteData, false, false, false, []int32{dir.wfs.signature})
  294. if err != nil {
  295. log.Tracef("not found remove file %s/%s: %v", dir.FullPath(), req.Name, err)
  296. return fuse.ENOENT
  297. }
  298. // then, delete meta cache and fsNode cache
  299. dir.wfs.metaCache.DeleteEntry(context.Background(), filePath)
  300. // clear entry inside the file
  301. fsNode := dir.wfs.fsNodeCache.GetFsNode(filePath)
  302. if fsNode != nil {
  303. if file, ok := fsNode.(*File); ok {
  304. file.clearEntry()
  305. }
  306. }
  307. dir.wfs.fsNodeCache.DeleteFsNode(filePath)
  308. // remove current file handle if any
  309. dir.wfs.handlesLock.Lock()
  310. defer dir.wfs.handlesLock.Unlock()
  311. inodeId := util.NewFullPath(dir.FullPath(), req.Name).AsInode()
  312. delete(dir.wfs.handles, inodeId)
  313. // delete the chunks last
  314. if isDeleteData {
  315. dir.wfs.deleteFileChunks(entry.Chunks)
  316. }
  317. return nil
  318. }
  319. func (dir *Dir) removeFolder(req *fuse.RemoveRequest) error {
  320. log.Tracef("remove directory entry: %v", req)
  321. ignoreRecursiveErr := true // ignore recursion error since the OS should manage it
  322. err := filer_pb.Remove(dir.wfs, dir.FullPath(), req.Name, true, false, ignoreRecursiveErr, false, []int32{dir.wfs.signature})
  323. if err != nil {
  324. log.Infof("remove %s/%s: %v", dir.FullPath(), req.Name, err)
  325. if strings.Contains(err.Error(), "non-empty") {
  326. return fuse.EEXIST
  327. }
  328. return fuse.ENOENT
  329. }
  330. t := util.NewFullPath(dir.FullPath(), req.Name)
  331. dir.wfs.metaCache.DeleteEntry(context.Background(), t)
  332. dir.wfs.fsNodeCache.DeleteFsNode(t)
  333. return nil
  334. }
  335. func (dir *Dir) Setattr(ctx context.Context, req *fuse.SetattrRequest, resp *fuse.SetattrResponse) error {
  336. log.Tracef("%v dir setattr %+v", dir.FullPath(), req)
  337. if err := dir.maybeLoadEntry(); err != nil {
  338. return err
  339. }
  340. if req.Valid.Mode() {
  341. dir.entry.Attributes.FileMode = uint32(req.Mode)
  342. }
  343. if req.Valid.Uid() {
  344. dir.entry.Attributes.Uid = req.Uid
  345. }
  346. if req.Valid.Gid() {
  347. dir.entry.Attributes.Gid = req.Gid
  348. }
  349. if req.Valid.Mtime() {
  350. dir.entry.Attributes.Mtime = req.Mtime.Unix()
  351. }
  352. return dir.saveEntry()
  353. }
  354. func (dir *Dir) Setxattr(ctx context.Context, req *fuse.SetxattrRequest) error {
  355. log.Tracef("dir Setxattr %s: %s", dir.FullPath(), req.Name)
  356. if err := dir.maybeLoadEntry(); err != nil {
  357. return err
  358. }
  359. if err := setxattr(dir.entry, req); err != nil {
  360. return err
  361. }
  362. return dir.saveEntry()
  363. }
  364. func (dir *Dir) Removexattr(ctx context.Context, req *fuse.RemovexattrRequest) error {
  365. log.Tracef("dir Removexattr %s: %s", dir.FullPath(), req.Name)
  366. if err := dir.maybeLoadEntry(); err != nil {
  367. return err
  368. }
  369. if err := removexattr(dir.entry, req); err != nil {
  370. return err
  371. }
  372. return dir.saveEntry()
  373. }
  374. func (dir *Dir) Listxattr(ctx context.Context, req *fuse.ListxattrRequest, resp *fuse.ListxattrResponse) error {
  375. log.Tracef("dir Listxattr %s", dir.FullPath())
  376. if err := dir.maybeLoadEntry(); err != nil {
  377. return err
  378. }
  379. if err := listxattr(dir.entry, req, resp); err != nil {
  380. return err
  381. }
  382. return nil
  383. }
  384. func (dir *Dir) Forget() {
  385. log.Tracef("Forget dir %s", dir.FullPath())
  386. dir.wfs.fsNodeCache.DeleteFsNode(util.FullPath(dir.FullPath()))
  387. }
  388. func (dir *Dir) maybeLoadEntry() error {
  389. if dir.entry == nil {
  390. parentDirPath, name := util.FullPath(dir.FullPath()).DirAndName()
  391. entry, err := dir.wfs.maybeLoadEntry(parentDirPath, name)
  392. if err != nil {
  393. return err
  394. }
  395. dir.entry = entry
  396. }
  397. return nil
  398. }
  399. func (dir *Dir) saveEntry() error {
  400. parentDir, name := util.FullPath(dir.FullPath()).DirAndName()
  401. return dir.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  402. dir.wfs.mapPbIdFromLocalToFiler(dir.entry)
  403. defer dir.wfs.mapPbIdFromFilerToLocal(dir.entry)
  404. request := &filer_pb.UpdateEntryRequest{
  405. Directory: parentDir,
  406. Entry: dir.entry,
  407. Signatures: []int32{dir.wfs.signature},
  408. }
  409. log.Debugf("save dir entry: %v", request)
  410. _, err := client.UpdateEntry(context.Background(), request)
  411. if err != nil {
  412. log.Errorf("UpdateEntry dir %s/%s: %v", parentDir, name, err)
  413. return fuse.EIO
  414. }
  415. dir.wfs.metaCache.UpdateEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
  416. return nil
  417. })
  418. }
  419. func (dir *Dir) FullPath() string {
  420. var parts []string
  421. for p := dir; p != nil; p = p.parent {
  422. if strings.HasPrefix(p.name, "/") {
  423. if len(p.name) > 1 {
  424. parts = append(parts, p.name[1:])
  425. }
  426. } else {
  427. parts = append(parts, p.name)
  428. }
  429. }
  430. if len(parts) == 0 {
  431. return "/"
  432. }
  433. var buf bytes.Buffer
  434. for i := len(parts) - 1; i >= 0; i-- {
  435. buf.WriteString("/")
  436. buf.WriteString(parts[i])
  437. }
  438. return buf.String()
  439. }