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.

618 lines
16 KiB

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