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.

254 lines
6.9 KiB

4 years ago
6 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
  1. package leveldb
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/md5"
  6. "fmt"
  7. "github.com/syndtr/goleveldb/leveldb"
  8. leveldb_errors "github.com/syndtr/goleveldb/leveldb/errors"
  9. "github.com/syndtr/goleveldb/leveldb/opt"
  10. leveldb_util "github.com/syndtr/goleveldb/leveldb/util"
  11. "io"
  12. "os"
  13. "github.com/chrislusf/seaweedfs/weed/filer"
  14. "github.com/chrislusf/seaweedfs/weed/glog"
  15. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  16. weed_util "github.com/chrislusf/seaweedfs/weed/util"
  17. )
  18. func init() {
  19. filer.Stores = append(filer.Stores, &LevelDB2Store{})
  20. }
  21. type LevelDB2Store struct {
  22. dbs []*leveldb.DB
  23. dbCount int
  24. }
  25. func (store *LevelDB2Store) GetName() string {
  26. return "leveldb2"
  27. }
  28. func (store *LevelDB2Store) Initialize(configuration weed_util.Configuration, prefix string) (err error) {
  29. dir := configuration.GetString(prefix + "dir")
  30. return store.initialize(dir, 8)
  31. }
  32. func (store *LevelDB2Store) initialize(dir string, dbCount int) (err error) {
  33. glog.Infof("filer store leveldb2 dir: %s", dir)
  34. if err := weed_util.TestFolderWritable(dir); err != nil {
  35. return fmt.Errorf("Check Level Folder %s Writable: %s", dir, err)
  36. }
  37. opts := &opt.Options{
  38. BlockCacheCapacity: 32 * 1024 * 1024, // default value is 8MiB
  39. WriteBuffer: 16 * 1024 * 1024, // default value is 4MiB
  40. CompactionTableSizeMultiplier: 4,
  41. }
  42. for d := 0; d < dbCount; d++ {
  43. dbFolder := fmt.Sprintf("%s/%02d", dir, d)
  44. os.MkdirAll(dbFolder, 0755)
  45. db, dbErr := leveldb.OpenFile(dbFolder, opts)
  46. if leveldb_errors.IsCorrupted(dbErr) {
  47. db, dbErr = leveldb.RecoverFile(dbFolder, opts)
  48. }
  49. if dbErr != nil {
  50. glog.Errorf("filer store open dir %s: %v", dbFolder, dbErr)
  51. return dbErr
  52. }
  53. store.dbs = append(store.dbs, db)
  54. }
  55. store.dbCount = dbCount
  56. return
  57. }
  58. func (store *LevelDB2Store) BeginTransaction(ctx context.Context) (context.Context, error) {
  59. return ctx, nil
  60. }
  61. func (store *LevelDB2Store) CommitTransaction(ctx context.Context) error {
  62. return nil
  63. }
  64. func (store *LevelDB2Store) RollbackTransaction(ctx context.Context) error {
  65. return nil
  66. }
  67. func (store *LevelDB2Store) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  68. dir, name := entry.DirAndName()
  69. key, partitionId := genKey(dir, name, store.dbCount)
  70. value, err := entry.EncodeAttributesAndChunks()
  71. if err != nil {
  72. return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
  73. }
  74. if len(entry.Chunks) > 50 {
  75. value = weed_util.MaybeGzipData(value)
  76. }
  77. err = store.dbs[partitionId].Put(key, value, nil)
  78. if err != nil {
  79. return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
  80. }
  81. // println("saved", entry.FullPath, "chunks", len(entry.Chunks))
  82. return nil
  83. }
  84. func (store *LevelDB2Store) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  85. return store.InsertEntry(ctx, entry)
  86. }
  87. func (store *LevelDB2Store) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer.Entry, err error) {
  88. dir, name := fullpath.DirAndName()
  89. key, partitionId := genKey(dir, name, store.dbCount)
  90. data, err := store.dbs[partitionId].Get(key, nil)
  91. if err == leveldb.ErrNotFound {
  92. return nil, filer_pb.ErrNotFound
  93. }
  94. if err != nil {
  95. return nil, fmt.Errorf("get %s : %v", entry.FullPath, err)
  96. }
  97. entry = &filer.Entry{
  98. FullPath: fullpath,
  99. }
  100. err = entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(data))
  101. if err != nil {
  102. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  103. }
  104. // println("read", entry.FullPath, "chunks", len(entry.Chunks), "data", len(data), string(data))
  105. return entry, nil
  106. }
  107. func (store *LevelDB2Store) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  108. dir, name := fullpath.DirAndName()
  109. key, partitionId := genKey(dir, name, store.dbCount)
  110. err = store.dbs[partitionId].Delete(key, nil)
  111. if err != nil {
  112. return fmt.Errorf("delete %s : %v", fullpath, err)
  113. }
  114. return nil
  115. }
  116. func (store *LevelDB2Store) DeleteFolderChildren(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  117. directoryPrefix, partitionId := genDirectoryKeyPrefix(fullpath, "", store.dbCount)
  118. batch := new(leveldb.Batch)
  119. iter := store.dbs[partitionId].NewIterator(&leveldb_util.Range{Start: directoryPrefix}, nil)
  120. for iter.Next() {
  121. key := iter.Key()
  122. if !bytes.HasPrefix(key, directoryPrefix) {
  123. break
  124. }
  125. fileName := getNameFromKey(key)
  126. if fileName == "" {
  127. continue
  128. }
  129. batch.Delete(append(directoryPrefix, []byte(fileName)...))
  130. }
  131. iter.Release()
  132. err = store.dbs[partitionId].Write(batch, nil)
  133. if err != nil {
  134. return fmt.Errorf("delete %s : %v", fullpath, err)
  135. }
  136. return nil
  137. }
  138. func (store *LevelDB2Store) ListDirectoryEntries(ctx context.Context, fullpath weed_util.FullPath, startFileName string, inclusive bool,
  139. limit int) (entries []*filer.Entry, err error) {
  140. return store.ListDirectoryPrefixedEntries(ctx, fullpath, startFileName, inclusive, limit, "")
  141. }
  142. func (store *LevelDB2Store) ListDirectoryPrefixedEntries(ctx context.Context, fullpath weed_util.FullPath, startFileName string, inclusive bool, limit int, prefix string) (entries []*filer.Entry, err error) {
  143. directoryPrefix, partitionId := genDirectoryKeyPrefix(fullpath, prefix, store.dbCount)
  144. lastFileStart, _ := genDirectoryKeyPrefix(fullpath, startFileName, store.dbCount)
  145. iter := store.dbs[partitionId].NewIterator(&leveldb_util.Range{Start: lastFileStart}, nil)
  146. for iter.Next() {
  147. key := iter.Key()
  148. if !bytes.HasPrefix(key, directoryPrefix) {
  149. break
  150. }
  151. fileName := getNameFromKey(key)
  152. if fileName == "" {
  153. continue
  154. }
  155. if fileName == startFileName && !inclusive {
  156. continue
  157. }
  158. limit--
  159. if limit < 0 {
  160. break
  161. }
  162. entry := &filer.Entry{
  163. FullPath: weed_util.NewFullPath(string(fullpath), fileName),
  164. }
  165. // println("list", entry.FullPath, "chunks", len(entry.Chunks))
  166. if decodeErr := entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(iter.Value())); decodeErr != nil {
  167. err = decodeErr
  168. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  169. break
  170. }
  171. entries = append(entries, entry)
  172. }
  173. iter.Release()
  174. return entries, err
  175. }
  176. func genKey(dirPath, fileName string, dbCount int) (key []byte, partitionId int) {
  177. key, partitionId = hashToBytes(dirPath, dbCount)
  178. key = append(key, []byte(fileName)...)
  179. return key, partitionId
  180. }
  181. func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string, dbCount int) (keyPrefix []byte, partitionId int) {
  182. keyPrefix, partitionId = hashToBytes(string(fullpath), dbCount)
  183. if len(startFileName) > 0 {
  184. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  185. }
  186. return keyPrefix, partitionId
  187. }
  188. func getNameFromKey(key []byte) string {
  189. return string(key[md5.Size:])
  190. }
  191. // hash directory, and use last byte for partitioning
  192. func hashToBytes(dir string, dbCount int) ([]byte, int) {
  193. h := md5.New()
  194. io.WriteString(h, dir)
  195. b := h.Sum(nil)
  196. x := b[len(b)-1]
  197. return b, int(x) % dbCount
  198. }
  199. func (store *LevelDB2Store) Shutdown() {
  200. for d := 0; d < store.dbCount; d++ {
  201. store.dbs[d].Close()
  202. }
  203. }