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.

620 lines
16 KiB

7 years ago
5 years ago
7 years ago
7 years ago
7 years ago
5 years ago
3 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)
  136. return file, fh, nil
  137. }
  138. func (dir *Dir) Mknod(ctx context.Context, req *fuse.MknodRequest) (fs.Node, error) {
  139. glog.V(3).Infof("dir %s Mknod %+v", dir.FullPath(), req)
  140. _, err := dir.doCreateEntry(req.Name, req.Mode, req.Uid, req.Gid, false)
  141. if err != nil {
  142. return nil, err
  143. }
  144. var node fs.Node
  145. node = dir.newFile(req.Name)
  146. return node, nil
  147. }
  148. func (dir *Dir) doCreateEntry(name string, mode os.FileMode, uid, gid uint32, exclusive bool) (*filer_pb.CreateEntryRequest, error) {
  149. dirFullPath := dir.FullPath()
  150. request := &filer_pb.CreateEntryRequest{
  151. Directory: dirFullPath,
  152. Entry: &filer_pb.Entry{
  153. Name: name,
  154. IsDirectory: mode&os.ModeDir > 0,
  155. Attributes: &filer_pb.FuseAttributes{
  156. Mtime: time.Now().Unix(),
  157. Crtime: time.Now().Unix(),
  158. FileMode: uint32(mode &^ dir.wfs.option.Umask),
  159. Uid: uid,
  160. Gid: gid,
  161. Collection: dir.wfs.option.Collection,
  162. Replication: dir.wfs.option.Replication,
  163. TtlSec: dir.wfs.option.TtlSec,
  164. },
  165. },
  166. OExcl: exclusive,
  167. Signatures: []int32{dir.wfs.signature},
  168. }
  169. glog.V(1).Infof("create %s/%s", dirFullPath, name)
  170. err := dir.wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  171. dir.wfs.mapPbIdFromLocalToFiler(request.Entry)
  172. defer dir.wfs.mapPbIdFromFilerToLocal(request.Entry)
  173. if err := filer_pb.CreateEntry(client, request); err != nil {
  174. if strings.Contains(err.Error(), "EEXIST") {
  175. return fuse.EEXIST
  176. }
  177. glog.V(0).Infof("create %s/%s: %v", dirFullPath, name, err)
  178. return fuse.EIO
  179. }
  180. if err := dir.wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
  181. glog.Errorf("local InsertEntry dir %s/%s: %v", dirFullPath, name, err)
  182. return fuse.EIO
  183. }
  184. return nil
  185. })
  186. return request, err
  187. }
  188. func (dir *Dir) Mkdir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) {
  189. glog.V(4).Infof("mkdir %s: %s", dir.FullPath(), req.Name)
  190. newEntry := &filer_pb.Entry{
  191. Name: req.Name,
  192. IsDirectory: true,
  193. Attributes: &filer_pb.FuseAttributes{
  194. Mtime: time.Now().Unix(),
  195. Crtime: time.Now().Unix(),
  196. FileMode: uint32(req.Mode &^ dir.wfs.option.Umask),
  197. Uid: req.Uid,
  198. Gid: req.Gid,
  199. },
  200. }
  201. dirFullPath := dir.FullPath()
  202. err := dir.wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  203. dir.wfs.mapPbIdFromLocalToFiler(newEntry)
  204. defer dir.wfs.mapPbIdFromFilerToLocal(newEntry)
  205. request := &filer_pb.CreateEntryRequest{
  206. Directory: dirFullPath,
  207. Entry: newEntry,
  208. Signatures: []int32{dir.wfs.signature},
  209. }
  210. glog.V(1).Infof("mkdir: %v", request)
  211. if err := filer_pb.CreateEntry(client, request); err != nil {
  212. glog.V(0).Infof("mkdir %s/%s: %v", dirFullPath, req.Name, err)
  213. return err
  214. }
  215. if err := dir.wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
  216. glog.Errorf("local mkdir dir %s/%s: %v", dirFullPath, req.Name, err)
  217. return fuse.EIO
  218. }
  219. return nil
  220. })
  221. if err == nil {
  222. node := dir.newDirectory(util.NewFullPath(dirFullPath, req.Name))
  223. return node, nil
  224. }
  225. glog.V(0).Infof("mkdir %s/%s: %v", dirFullPath, req.Name, err)
  226. return nil, fuse.EIO
  227. }
  228. func (dir *Dir) Lookup(ctx context.Context, req *fuse.LookupRequest, resp *fuse.LookupResponse) (node fs.Node, err error) {
  229. dirPath := util.FullPath(dir.FullPath())
  230. // glog.V(4).Infof("dir Lookup %s: %s by %s", dirPath, req.Name, req.Header.String())
  231. fullFilePath := dirPath.Child(req.Name)
  232. visitErr := meta_cache.EnsureVisited(dir.wfs.metaCache, dir.wfs, dirPath)
  233. if visitErr != nil {
  234. glog.Errorf("dir Lookup %s: %v", dirPath, visitErr)
  235. return nil, fuse.EIO
  236. }
  237. localEntry, cacheErr := dir.wfs.metaCache.FindEntry(context.Background(), fullFilePath)
  238. if cacheErr == filer_pb.ErrNotFound {
  239. return nil, fuse.ENOENT
  240. }
  241. if localEntry == nil {
  242. // glog.V(3).Infof("dir Lookup cache miss %s", fullFilePath)
  243. entry, err := filer_pb.GetEntry(dir.wfs, fullFilePath)
  244. if err != nil {
  245. glog.V(1).Infof("dir GetEntry %s: %v", fullFilePath, err)
  246. return nil, fuse.ENOENT
  247. }
  248. localEntry = filer.FromPbEntry(string(dirPath), entry)
  249. } else {
  250. glog.V(4).Infof("dir Lookup cache hit %s", fullFilePath)
  251. }
  252. if localEntry != nil {
  253. if localEntry.IsDirectory() {
  254. node = dir.newDirectory(fullFilePath)
  255. } else {
  256. node = dir.newFile(req.Name)
  257. }
  258. // resp.EntryValid = time.Second
  259. resp.Attr.Inode = fullFilePath.AsInode()
  260. resp.Attr.Valid = time.Second
  261. resp.Attr.Size = localEntry.FileSize
  262. resp.Attr.Mtime = localEntry.Attr.Mtime
  263. resp.Attr.Crtime = localEntry.Attr.Crtime
  264. resp.Attr.Mode = localEntry.Attr.Mode
  265. resp.Attr.Gid = localEntry.Attr.Gid
  266. resp.Attr.Uid = localEntry.Attr.Uid
  267. if localEntry.HardLinkCounter > 0 {
  268. resp.Attr.Nlink = uint32(localEntry.HardLinkCounter)
  269. }
  270. return node, nil
  271. }
  272. glog.V(4).Infof("not found dir GetEntry %s: %v", fullFilePath, err)
  273. return nil, fuse.ENOENT
  274. }
  275. func (dir *Dir) ReadDirAll(ctx context.Context) (ret []fuse.Dirent, err error) {
  276. dirPath := util.FullPath(dir.FullPath())
  277. glog.V(4).Infof("dir ReadDirAll %s", dirPath)
  278. processEachEntryFn := func(entry *filer.Entry, isLast bool) {
  279. if entry.IsDirectory() {
  280. dirent := fuse.Dirent{Name: entry.Name(), Type: fuse.DT_Dir, Inode: dirPath.Child(entry.Name()).AsInode()}
  281. ret = append(ret, dirent)
  282. } else {
  283. dirent := fuse.Dirent{Name: entry.Name(), Type: findFileType(uint16(entry.Attr.Mode)), Inode: dirPath.Child(entry.Name()).AsInode()}
  284. ret = append(ret, dirent)
  285. }
  286. }
  287. if err = meta_cache.EnsureVisited(dir.wfs.metaCache, dir.wfs, dirPath); err != nil {
  288. glog.Errorf("dir ReadDirAll %s: %v", dirPath, err)
  289. return nil, fuse.EIO
  290. }
  291. listErr := dir.wfs.metaCache.ListDirectoryEntries(context.Background(), dirPath, "", false, int64(math.MaxInt32), func(entry *filer.Entry) bool {
  292. processEachEntryFn(entry, false)
  293. return true
  294. })
  295. if listErr != nil {
  296. glog.Errorf("list meta cache: %v", listErr)
  297. return nil, fuse.EIO
  298. }
  299. // create proper . and .. directories
  300. ret = append(ret, fuse.Dirent{
  301. Inode: dirPath.AsInode(),
  302. Name: ".",
  303. Type: fuse.DT_Dir,
  304. })
  305. // return the correct parent inode for the mount root
  306. var inode uint64
  307. if string(dirPath) == dir.wfs.option.FilerMountRootPath {
  308. inode = dir.wfs.option.MountParentInode
  309. } else {
  310. inode = util.FullPath(dir.parent.FullPath()).AsInode()
  311. }
  312. ret = append(ret, fuse.Dirent{
  313. Inode: inode,
  314. Name: "..",
  315. Type: fuse.DT_Dir,
  316. })
  317. return
  318. }
  319. func findFileType(mode uint16) fuse.DirentType {
  320. switch mode & (syscall.S_IFMT & 0xffff) {
  321. case syscall.S_IFSOCK:
  322. return fuse.DT_Socket
  323. case syscall.S_IFLNK:
  324. return fuse.DT_Link
  325. case syscall.S_IFREG:
  326. return fuse.DT_File
  327. case syscall.S_IFBLK:
  328. return fuse.DT_Block
  329. case syscall.S_IFDIR:
  330. return fuse.DT_Dir
  331. case syscall.S_IFCHR:
  332. return fuse.DT_Char
  333. case syscall.S_IFIFO:
  334. return fuse.DT_FIFO
  335. }
  336. return fuse.DT_File
  337. }
  338. func (dir *Dir) Remove(ctx context.Context, req *fuse.RemoveRequest) error {
  339. if !req.Dir {
  340. return dir.removeOneFile(req)
  341. }
  342. return dir.removeFolder(req)
  343. }
  344. func (dir *Dir) removeOneFile(req *fuse.RemoveRequest) error {
  345. dirFullPath := dir.FullPath()
  346. filePath := util.NewFullPath(dirFullPath, req.Name)
  347. entry, err := filer_pb.GetEntry(dir.wfs, filePath)
  348. if err != nil {
  349. return err
  350. }
  351. // first, ensure the filer store can correctly delete
  352. glog.V(3).Infof("remove file: %v", req)
  353. isDeleteData := entry != nil && entry.HardLinkCounter <= 1
  354. err = filer_pb.Remove(dir.wfs, dirFullPath, req.Name, isDeleteData, false, false, false, []int32{dir.wfs.signature})
  355. if err != nil {
  356. glog.V(3).Infof("not found remove file %s: %v", filePath, err)
  357. return fuse.ENOENT
  358. }
  359. // then, delete meta cache and fsNode cache
  360. if err = dir.wfs.metaCache.DeleteEntry(context.Background(), filePath); err != nil {
  361. glog.V(3).Infof("local DeleteEntry %s: %v", filePath, err)
  362. return fuse.ESTALE
  363. }
  364. // remove current file handle if any
  365. dir.wfs.handlesLock.Lock()
  366. defer dir.wfs.handlesLock.Unlock()
  367. inodeId := filePath.AsInode()
  368. if fh, ok := dir.wfs.handles[inodeId]; ok {
  369. delete(dir.wfs.handles, inodeId)
  370. fh.isDeleted = true
  371. }
  372. return nil
  373. }
  374. func (dir *Dir) removeFolder(req *fuse.RemoveRequest) error {
  375. dirFullPath := dir.FullPath()
  376. glog.V(3).Infof("remove directory entry: %v", req)
  377. ignoreRecursiveErr := true // ignore recursion error since the OS should manage it
  378. err := filer_pb.Remove(dir.wfs, dirFullPath, req.Name, true, true, ignoreRecursiveErr, false, []int32{dir.wfs.signature})
  379. if err != nil {
  380. glog.V(0).Infof("remove %s/%s: %v", dirFullPath, req.Name, err)
  381. if strings.Contains(err.Error(), "non-empty") {
  382. return fuse.EEXIST
  383. }
  384. return fuse.ENOENT
  385. }
  386. t := util.NewFullPath(dirFullPath, req.Name)
  387. dir.wfs.metaCache.DeleteEntry(context.Background(), t)
  388. return nil
  389. }
  390. func (dir *Dir) Setattr(ctx context.Context, req *fuse.SetattrRequest, resp *fuse.SetattrResponse) error {
  391. glog.V(4).Infof("%v dir setattr %+v", dir.FullPath(), req)
  392. entry, err := dir.maybeLoadEntry()
  393. if err != nil {
  394. return err
  395. }
  396. if req.Valid.Mode() {
  397. entry.Attributes.FileMode = uint32(req.Mode)
  398. }
  399. if req.Valid.Uid() {
  400. entry.Attributes.Uid = req.Uid
  401. }
  402. if req.Valid.Gid() {
  403. entry.Attributes.Gid = req.Gid
  404. }
  405. if req.Valid.Mtime() {
  406. entry.Attributes.Mtime = req.Mtime.Unix()
  407. }
  408. return dir.saveEntry(entry)
  409. }
  410. func (dir *Dir) Setxattr(ctx context.Context, req *fuse.SetxattrRequest) error {
  411. glog.V(4).Infof("dir Setxattr %s: %s", dir.FullPath(), req.Name)
  412. entry, err := dir.maybeLoadEntry()
  413. if err != nil {
  414. return err
  415. }
  416. if err := setxattr(entry, req); err != nil {
  417. return err
  418. }
  419. return dir.saveEntry(entry)
  420. }
  421. func (dir *Dir) Removexattr(ctx context.Context, req *fuse.RemovexattrRequest) error {
  422. glog.V(4).Infof("dir Removexattr %s: %s", dir.FullPath(), req.Name)
  423. entry, err := dir.maybeLoadEntry()
  424. if err != nil {
  425. return err
  426. }
  427. if err := removexattr(entry, req); err != nil {
  428. return err
  429. }
  430. return dir.saveEntry(entry)
  431. }
  432. func (dir *Dir) Listxattr(ctx context.Context, req *fuse.ListxattrRequest, resp *fuse.ListxattrResponse) error {
  433. glog.V(4).Infof("dir Listxattr %s", dir.FullPath())
  434. entry, err := dir.maybeLoadEntry()
  435. if err != nil {
  436. return err
  437. }
  438. if err := listxattr(entry, req, resp); err != nil {
  439. return err
  440. }
  441. return nil
  442. }
  443. func (dir *Dir) Forget() {
  444. glog.V(4).Infof("Forget dir %s", dir.FullPath())
  445. }
  446. func (dir *Dir) maybeLoadEntry() (*filer_pb.Entry, error) {
  447. parentDirPath, name := util.FullPath(dir.FullPath()).DirAndName()
  448. return dir.wfs.maybeLoadEntry(parentDirPath, name)
  449. }
  450. func (dir *Dir) saveEntry(entry *filer_pb.Entry) error {
  451. parentDir, name := util.FullPath(dir.FullPath()).DirAndName()
  452. return dir.wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  453. dir.wfs.mapPbIdFromLocalToFiler(entry)
  454. defer dir.wfs.mapPbIdFromFilerToLocal(entry)
  455. request := &filer_pb.UpdateEntryRequest{
  456. Directory: parentDir,
  457. Entry: entry,
  458. Signatures: []int32{dir.wfs.signature},
  459. }
  460. glog.V(1).Infof("save dir entry: %v", request)
  461. _, err := client.UpdateEntry(context.Background(), request)
  462. if err != nil {
  463. glog.Errorf("UpdateEntry dir %s/%s: %v", parentDir, name, err)
  464. return fuse.EIO
  465. }
  466. if err := dir.wfs.metaCache.UpdateEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
  467. glog.Errorf("UpdateEntry dir %s/%s: %v", parentDir, name, err)
  468. return fuse.ESTALE
  469. }
  470. return nil
  471. })
  472. }
  473. func (dir *Dir) FullPath() string {
  474. var parts []string
  475. for p := dir; p != nil; p = p.parent {
  476. if strings.HasPrefix(p.name, "/") {
  477. if len(p.name) > 1 {
  478. parts = append(parts, p.name[1:])
  479. }
  480. } else {
  481. parts = append(parts, p.name)
  482. }
  483. }
  484. if len(parts) == 0 {
  485. return "/"
  486. }
  487. var buf bytes.Buffer
  488. for i := len(parts) - 1; i >= 0; i-- {
  489. buf.WriteString("/")
  490. buf.WriteString(parts[i])
  491. }
  492. return buf.String()
  493. }