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.

266 lines
7.5 KiB

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