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.

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