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.

608 lines
16 KiB

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