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.

279 lines
7.2 KiB

6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 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. "io"
  8. "os"
  9. "strings"
  10. "github.com/syndtr/goleveldb/leveldb"
  11. "github.com/syndtr/goleveldb/leveldb/errors"
  12. "github.com/syndtr/goleveldb/leveldb/opt"
  13. leveldb_util "github.com/syndtr/goleveldb/leveldb/util"
  14. "github.com/chrislusf/seaweedfs/weed/filer2"
  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. filer2.Stores = append(filer2.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. 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 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 *filer2.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. err = store.dbs[partitionId].Put(key, value, nil)
  76. if err != nil {
  77. return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
  78. }
  79. // println("saved", entry.FullPath, "chunks", len(entry.Chunks))
  80. return nil
  81. }
  82. func (store *LevelDB2Store) UpdateEntry(ctx context.Context, entry *filer2.Entry) (err error) {
  83. return store.InsertEntry(ctx, entry)
  84. }
  85. func (store *LevelDB2Store) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer2.Entry, err error) {
  86. dir, name := fullpath.DirAndName()
  87. key, partitionId := genKey(dir, name, store.dbCount)
  88. data, err := store.dbs[partitionId].Get(key, nil)
  89. if err == leveldb.ErrNotFound {
  90. return nil, filer_pb.ErrNotFound
  91. }
  92. if err != nil {
  93. return nil, fmt.Errorf("get %s : %v", entry.FullPath, err)
  94. }
  95. entry = &filer2.Entry{
  96. FullPath: fullpath,
  97. }
  98. err = entry.DecodeAttributesAndChunks(data)
  99. if err != nil {
  100. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  101. }
  102. // println("read", entry.FullPath, "chunks", len(entry.Chunks), "data", len(data), string(data))
  103. return entry, nil
  104. }
  105. func (store *LevelDB2Store) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  106. dir, name := fullpath.DirAndName()
  107. key, partitionId := genKey(dir, name, store.dbCount)
  108. err = store.dbs[partitionId].Delete(key, nil)
  109. if err != nil {
  110. return fmt.Errorf("delete %s : %v", fullpath, err)
  111. }
  112. return nil
  113. }
  114. func (store *LevelDB2Store) DeleteFolderChildren(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  115. directoryPrefix, partitionId := genDirectoryKeyPrefix(fullpath, "", store.dbCount)
  116. batch := new(leveldb.Batch)
  117. iter := store.dbs[partitionId].NewIterator(&leveldb_util.Range{Start: directoryPrefix}, nil)
  118. for iter.Next() {
  119. key := iter.Key()
  120. if !bytes.HasPrefix(key, directoryPrefix) {
  121. break
  122. }
  123. fileName := getNameFromKey(key)
  124. if fileName == "" {
  125. continue
  126. }
  127. batch.Delete(append(directoryPrefix, []byte(fileName)...))
  128. }
  129. iter.Release()
  130. err = store.dbs[partitionId].Write(batch, nil)
  131. if err != nil {
  132. return fmt.Errorf("delete %s : %v", fullpath, err)
  133. }
  134. return nil
  135. }
  136. func (store *LevelDB2Store) ListDirectoryPrefixedEntries(ctx context.Context, fullpath weed_util.FullPath, startFileName string, inclusive bool, limit int, prefix string) (entries []*filer2.Entry, err error) {
  137. count := 0
  138. notPrefixed, err := store.ListDirectoryEntries(ctx, fullpath, startFileName, inclusive, limit)
  139. if err != nil {
  140. return nil, err
  141. }
  142. if prefix == "" {
  143. return notPrefixed, nil
  144. }
  145. for count < limit {
  146. for _, entry := range notPrefixed {
  147. if strings.HasPrefix(entry.Name(), prefix) {
  148. count++
  149. entries = append(entries, entry)
  150. }
  151. }
  152. if count >= limit {
  153. break
  154. }
  155. notPrefixed, err = store.ListDirectoryEntries(ctx, fullpath, startFileName, inclusive, limit)
  156. if err != nil {
  157. return nil, err
  158. }
  159. }
  160. return entries, nil
  161. }
  162. func (store *LevelDB2Store) ListDirectoryEntries(ctx context.Context, fullpath weed_util.FullPath, startFileName string, inclusive bool,
  163. limit int) (entries []*filer2.Entry, err error) {
  164. directoryPrefix, partitionId := genDirectoryKeyPrefix(fullpath, "", store.dbCount)
  165. lastFileStart, _ := genDirectoryKeyPrefix(fullpath, startFileName, store.dbCount)
  166. iter := store.dbs[partitionId].NewIterator(&leveldb_util.Range{Start: lastFileStart}, nil)
  167. for iter.Next() {
  168. key := iter.Key()
  169. if !bytes.HasPrefix(key, directoryPrefix) {
  170. break
  171. }
  172. fileName := getNameFromKey(key)
  173. if fileName == "" {
  174. continue
  175. }
  176. if fileName == startFileName && !inclusive {
  177. continue
  178. }
  179. limit--
  180. if limit < 0 {
  181. break
  182. }
  183. entry := &filer2.Entry{
  184. FullPath: weed_util.NewFullPath(string(fullpath), fileName),
  185. }
  186. // println("list", entry.FullPath, "chunks", len(entry.Chunks))
  187. if decodeErr := entry.DecodeAttributesAndChunks(iter.Value()); decodeErr != nil {
  188. err = decodeErr
  189. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  190. break
  191. }
  192. entries = append(entries, entry)
  193. }
  194. iter.Release()
  195. return entries, err
  196. }
  197. func genKey(dirPath, fileName string, dbCount int) (key []byte, partitionId int) {
  198. key, partitionId = hashToBytes(dirPath, dbCount)
  199. key = append(key, []byte(fileName)...)
  200. return key, partitionId
  201. }
  202. func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string, dbCount int) (keyPrefix []byte, partitionId int) {
  203. keyPrefix, partitionId = hashToBytes(string(fullpath), dbCount)
  204. if len(startFileName) > 0 {
  205. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  206. }
  207. return keyPrefix, partitionId
  208. }
  209. func getNameFromKey(key []byte) string {
  210. return string(key[md5.Size:])
  211. }
  212. // hash directory, and use last byte for partitioning
  213. func hashToBytes(dir string, dbCount int) ([]byte, int) {
  214. h := md5.New()
  215. io.WriteString(h, dir)
  216. b := h.Sum(nil)
  217. x := b[len(b)-1]
  218. return b, int(x) % dbCount
  219. }
  220. func (store *LevelDB2Store) Shutdown() {
  221. for d := 0; d < store.dbCount; d++ {
  222. store.dbs[d].Close()
  223. }
  224. }