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.

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