leveldb2_store.go 7.3 KB

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