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.

285 lines
7.3 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. var lastFileName string
  146. for count < limit {
  147. for _, entry := range notPrefixed {
  148. lastFileName = entry.Name()
  149. if strings.HasPrefix(entry.Name(), prefix) {
  150. count++
  151. entries = append(entries, entry)
  152. }
  153. }
  154. if count >= limit {
  155. break
  156. }
  157. notPrefixed, err = store.ListDirectoryEntries(ctx, fullpath, lastFileName, inclusive, limit)
  158. if err != nil {
  159. return nil, err
  160. }
  161. if len(notPrefixed) == 0 {
  162. break
  163. }
  164. }
  165. return entries, nil
  166. }
  167. func (store *LevelDB2Store) ListDirectoryEntries(ctx context.Context, fullpath weed_util.FullPath, startFileName string, inclusive bool,
  168. limit int) (entries []*filer2.Entry, err error) {
  169. directoryPrefix, partitionId := genDirectoryKeyPrefix(fullpath, "", store.dbCount)
  170. lastFileStart, _ := genDirectoryKeyPrefix(fullpath, startFileName, store.dbCount)
  171. iter := store.dbs[partitionId].NewIterator(&leveldb_util.Range{Start: lastFileStart}, nil)
  172. for iter.Next() {
  173. key := iter.Key()
  174. if !bytes.HasPrefix(key, directoryPrefix) {
  175. break
  176. }
  177. fileName := getNameFromKey(key)
  178. if fileName == "" {
  179. continue
  180. }
  181. if fileName == startFileName && !inclusive {
  182. continue
  183. }
  184. limit--
  185. if limit < 0 {
  186. break
  187. }
  188. entry := &filer2.Entry{
  189. FullPath: weed_util.NewFullPath(string(fullpath), fileName),
  190. }
  191. // println("list", entry.FullPath, "chunks", len(entry.Chunks))
  192. if decodeErr := entry.DecodeAttributesAndChunks(iter.Value()); decodeErr != nil {
  193. err = decodeErr
  194. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  195. break
  196. }
  197. entries = append(entries, entry)
  198. }
  199. iter.Release()
  200. return entries, err
  201. }
  202. func genKey(dirPath, fileName string, dbCount int) (key []byte, partitionId int) {
  203. key, partitionId = hashToBytes(dirPath, dbCount)
  204. key = append(key, []byte(fileName)...)
  205. return key, partitionId
  206. }
  207. func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string, dbCount int) (keyPrefix []byte, partitionId int) {
  208. keyPrefix, partitionId = hashToBytes(string(fullpath), dbCount)
  209. if len(startFileName) > 0 {
  210. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  211. }
  212. return keyPrefix, partitionId
  213. }
  214. func getNameFromKey(key []byte) string {
  215. return string(key[md5.Size:])
  216. }
  217. // hash directory, and use last byte for partitioning
  218. func hashToBytes(dir string, dbCount int) ([]byte, int) {
  219. h := md5.New()
  220. io.WriteString(h, dir)
  221. b := h.Sum(nil)
  222. x := b[len(b)-1]
  223. return b, int(x) % dbCount
  224. }
  225. func (store *LevelDB2Store) Shutdown() {
  226. for d := 0; d < store.dbCount; d++ {
  227. store.dbs[d].Close()
  228. }
  229. }