leveldb2_store.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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", 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, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  139. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", eachEntryFunc)
  140. }
  141. 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) {
  142. directoryPrefix, partitionId := genDirectoryKeyPrefix(dirPath, prefix, store.dbCount)
  143. lastFileStart := directoryPrefix
  144. if startFileName != "" {
  145. lastFileStart, _ = genDirectoryKeyPrefix(dirPath, startFileName, store.dbCount)
  146. }
  147. iter := store.dbs[partitionId].NewIterator(&leveldb_util.Range{Start: lastFileStart}, nil)
  148. for iter.Next() {
  149. key := iter.Key()
  150. if !bytes.HasPrefix(key, directoryPrefix) {
  151. break
  152. }
  153. fileName := getNameFromKey(key)
  154. if fileName == "" {
  155. continue
  156. }
  157. if fileName == startFileName && !includeStartFile {
  158. continue
  159. }
  160. lastFileName = fileName
  161. limit--
  162. if limit < 0 {
  163. break
  164. }
  165. entry := &filer.Entry{
  166. FullPath: weed_util.NewFullPath(string(dirPath), fileName),
  167. }
  168. // println("list", entry.FullPath, "chunks", len(entry.Chunks))
  169. if decodeErr := entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(iter.Value())); decodeErr != nil {
  170. err = decodeErr
  171. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  172. break
  173. }
  174. if !eachEntryFunc(entry) {
  175. break
  176. }
  177. }
  178. iter.Release()
  179. return lastFileName, err
  180. }
  181. func genKey(dirPath, fileName string, dbCount int) (key []byte, partitionId int) {
  182. key, partitionId = hashToBytes(dirPath, dbCount)
  183. key = append(key, []byte(fileName)...)
  184. return key, partitionId
  185. }
  186. func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string, dbCount int) (keyPrefix []byte, partitionId int) {
  187. keyPrefix, partitionId = hashToBytes(string(fullpath), dbCount)
  188. if len(startFileName) > 0 {
  189. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  190. }
  191. return keyPrefix, partitionId
  192. }
  193. func getNameFromKey(key []byte) string {
  194. return string(key[md5.Size:])
  195. }
  196. // hash directory, and use last byte for partitioning
  197. func hashToBytes(dir string, dbCount int) ([]byte, int) {
  198. h := md5.New()
  199. io.WriteString(h, dir)
  200. b := h.Sum(nil)
  201. x := b[len(b)-1]
  202. return b, int(x) % dbCount
  203. }
  204. func (store *LevelDB2Store) Shutdown() {
  205. for d := 0; d < store.dbCount; d++ {
  206. store.dbs[d].Close()
  207. }
  208. }