memdb_store.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package memdb
  2. import (
  3. "github.com/chrislusf/seaweedfs/weed/filer2"
  4. "github.com/google/btree"
  5. "strings"
  6. "fmt"
  7. "time"
  8. )
  9. type MemDbStore struct {
  10. tree *btree.BTree
  11. }
  12. type Entry struct {
  13. *filer2.Entry
  14. }
  15. func (a Entry) Less(b btree.Item) bool {
  16. return strings.Compare(string(a.FullPath), string(b.(Entry).FullPath)) < 0
  17. }
  18. func NewMemDbStore() (filer *MemDbStore) {
  19. filer = &MemDbStore{}
  20. filer.tree = btree.New(8)
  21. return
  22. }
  23. func (filer *MemDbStore) InsertEntry(entry *filer2.Entry) (err error) {
  24. // println("inserting", entry.FullPath)
  25. filer.tree.ReplaceOrInsert(Entry{entry})
  26. return nil
  27. }
  28. func (filer *MemDbStore) AppendFileChunk(fullpath filer2.FullPath, fileChunk filer2.FileChunk) (err error) {
  29. found, entry, err := filer.FindEntry(fullpath)
  30. if !found {
  31. return fmt.Errorf("No such file: %s", fullpath)
  32. }
  33. entry.Chunks = append(entry.Chunks, fileChunk)
  34. entry.Mtime = time.Now()
  35. return nil
  36. }
  37. func (filer *MemDbStore) FindEntry(fullpath filer2.FullPath) (found bool, entry *filer2.Entry, err error) {
  38. item := filer.tree.Get(Entry{&filer2.Entry{FullPath: fullpath}})
  39. if item == nil {
  40. return false, nil, nil
  41. }
  42. entry = item.(Entry).Entry
  43. return true, entry, nil
  44. }
  45. func (filer *MemDbStore) DeleteEntry(fullpath filer2.FullPath) (entry *filer2.Entry, err error) {
  46. item := filer.tree.Delete(Entry{&filer2.Entry{FullPath: fullpath}})
  47. if item == nil {
  48. return nil, nil
  49. }
  50. entry = item.(Entry).Entry
  51. return entry, nil
  52. }
  53. func (filer *MemDbStore) ListDirectoryEntries(fullpath filer2.FullPath) (entries []*filer2.Entry, err error) {
  54. filer.tree.AscendGreaterOrEqual(Entry{&filer2.Entry{FullPath: fullpath}},
  55. func(item btree.Item) bool {
  56. entry := item.(Entry).Entry
  57. // println("checking", entry.FullPath)
  58. if entry.FullPath == fullpath {
  59. // skipping the current directory
  60. // println("skipping the folder", entry.FullPath)
  61. return true
  62. }
  63. dir, _ := entry.FullPath.DirAndName()
  64. if !strings.HasPrefix(dir, string(fullpath)) {
  65. // println("directory is:", dir, "fullpath:", fullpath)
  66. // println("breaking from", entry.FullPath)
  67. return false
  68. }
  69. if dir != string(fullpath) {
  70. // this could be items in deeper directories
  71. // println("skipping deeper folder", entry.FullPath)
  72. return true
  73. }
  74. // now process the directory items
  75. // println("adding entry", entry.FullPath)
  76. entries = append(entries, entry)
  77. return true
  78. },
  79. )
  80. return entries, nil
  81. }