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.

264 lines
6.9 KiB

7 years ago
5 years ago
7 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
7 years ago
  1. package leveldb
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "github.com/syndtr/goleveldb/leveldb"
  7. leveldb_errors "github.com/syndtr/goleveldb/leveldb/errors"
  8. "github.com/syndtr/goleveldb/leveldb/filter"
  9. "github.com/syndtr/goleveldb/leveldb/opt"
  10. leveldb_util "github.com/syndtr/goleveldb/leveldb/util"
  11. "io"
  12. "os"
  13. "github.com/seaweedfs/seaweedfs/weed/filer"
  14. "github.com/seaweedfs/seaweedfs/weed/glog"
  15. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  16. weed_util "github.com/seaweedfs/seaweedfs/weed/util"
  17. )
  18. const (
  19. DIR_FILE_SEPARATOR = byte(0x00)
  20. )
  21. var (
  22. _ = filer.Debuggable(&LevelDBStore{})
  23. )
  24. func init() {
  25. filer.Stores = append(filer.Stores, &LevelDBStore{})
  26. }
  27. type LevelDBStore struct {
  28. db *leveldb.DB
  29. }
  30. func (store *LevelDBStore) GetName() string {
  31. return "leveldb"
  32. }
  33. func (store *LevelDBStore) Initialize(configuration weed_util.Configuration, prefix string) (err error) {
  34. dir := configuration.GetString(prefix + "dir")
  35. return store.initialize(dir)
  36. }
  37. // For adhoc usage
  38. func (store *LevelDBStore) CustomInitialize(dir string) (err error) {
  39. return store.initialize(dir)
  40. }
  41. func (store *LevelDBStore) initialize(dir string) (err error) {
  42. glog.Infof("filer store dir: %s", dir)
  43. os.MkdirAll(dir, 0755)
  44. if err := weed_util.TestFolderWritable(dir); err != nil {
  45. return fmt.Errorf("Check Level Folder %s Writable: %s", dir, err)
  46. }
  47. opts := &opt.Options{
  48. BlockCacheCapacity: 32 * 1024 * 1024, // default value is 8MiB
  49. WriteBuffer: 16 * 1024 * 1024, // default value is 4MiB
  50. Filter: filter.NewBloomFilter(8), // false positive rate 0.02
  51. }
  52. if store.db, err = leveldb.OpenFile(dir, opts); err != nil {
  53. if leveldb_errors.IsCorrupted(err) {
  54. store.db, err = leveldb.RecoverFile(dir, opts)
  55. }
  56. if err != nil {
  57. glog.Infof("filer store open dir %s: %v", dir, err)
  58. return
  59. }
  60. }
  61. return
  62. }
  63. func (store *LevelDBStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  64. return ctx, nil
  65. }
  66. func (store *LevelDBStore) CommitTransaction(ctx context.Context) error {
  67. return nil
  68. }
  69. func (store *LevelDBStore) RollbackTransaction(ctx context.Context) error {
  70. return nil
  71. }
  72. func (store *LevelDBStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  73. key := genKey(entry.DirAndName())
  74. value, err := entry.EncodeAttributesAndChunks()
  75. if err != nil {
  76. return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
  77. }
  78. if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
  79. value = weed_util.MaybeGzipData(value)
  80. }
  81. err = store.db.Put(key, value, nil)
  82. if err != nil {
  83. return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
  84. }
  85. // println("saved", entry.FullPath, "chunks", len(entry.GetChunks()))
  86. return nil
  87. }
  88. func (store *LevelDBStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  89. return store.InsertEntry(ctx, entry)
  90. }
  91. func (store *LevelDBStore) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer.Entry, err error) {
  92. key := genKey(fullpath.DirAndName())
  93. data, err := store.db.Get(key, nil)
  94. if err == leveldb.ErrNotFound {
  95. return nil, filer_pb.ErrNotFound
  96. }
  97. if err != nil {
  98. return nil, fmt.Errorf("get %s : %v", fullpath, err)
  99. }
  100. entry = &filer.Entry{
  101. FullPath: fullpath,
  102. }
  103. err = entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData((data)))
  104. if err != nil {
  105. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  106. }
  107. // println("read", entry.FullPath, "chunks", len(entry.GetChunks()), "data", len(data), string(data))
  108. return entry, nil
  109. }
  110. func (store *LevelDBStore) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  111. key := genKey(fullpath.DirAndName())
  112. err = store.db.Delete(key, nil)
  113. if err != nil {
  114. return fmt.Errorf("delete %s : %v", fullpath, err)
  115. }
  116. return nil
  117. }
  118. func (store *LevelDBStore) DeleteFolderChildren(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  119. batch := new(leveldb.Batch)
  120. directoryPrefix := genDirectoryKeyPrefix(fullpath, "")
  121. iter := store.db.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([]byte(genKey(string(fullpath), fileName)))
  132. }
  133. iter.Release()
  134. err = store.db.Write(batch, nil)
  135. if err != nil {
  136. return fmt.Errorf("delete %s : %v", fullpath, err)
  137. }
  138. return nil
  139. }
  140. func (store *LevelDBStore) 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 *LevelDBStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  144. directoryPrefix := genDirectoryKeyPrefix(dirPath, prefix)
  145. lastFileStart := directoryPrefix
  146. if startFileName != "" {
  147. lastFileStart = genDirectoryKeyPrefix(dirPath, startFileName)
  148. }
  149. iter := store.db.NewIterator(&leveldb_util.Range{Start: lastFileStart}, nil)
  150. for iter.Next() {
  151. key := iter.Key()
  152. if !bytes.HasPrefix(key, directoryPrefix) {
  153. break
  154. }
  155. fileName := getNameFromKey(key)
  156. if fileName == "" {
  157. continue
  158. }
  159. if fileName == startFileName && !includeStartFile {
  160. continue
  161. }
  162. limit--
  163. if limit < 0 {
  164. break
  165. }
  166. lastFileName = fileName
  167. entry := &filer.Entry{
  168. FullPath: weed_util.NewFullPath(string(dirPath), fileName),
  169. }
  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) (key []byte) {
  183. key = []byte(dirPath)
  184. key = append(key, DIR_FILE_SEPARATOR)
  185. key = append(key, []byte(fileName)...)
  186. return key
  187. }
  188. func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string) (keyPrefix []byte) {
  189. keyPrefix = []byte(string(fullpath))
  190. keyPrefix = append(keyPrefix, DIR_FILE_SEPARATOR)
  191. if len(startFileName) > 0 {
  192. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  193. }
  194. return keyPrefix
  195. }
  196. func getNameFromKey(key []byte) string {
  197. sepIndex := len(key) - 1
  198. for sepIndex >= 0 && key[sepIndex] != DIR_FILE_SEPARATOR {
  199. sepIndex--
  200. }
  201. return string(key[sepIndex+1:])
  202. }
  203. func (store *LevelDBStore) Shutdown() {
  204. store.db.Close()
  205. }
  206. func (store *LevelDBStore) Debug(writer io.Writer) {
  207. iter := store.db.NewIterator(&leveldb_util.Range{}, nil)
  208. for iter.Next() {
  209. key := iter.Key()
  210. fullName := bytes.Replace(key, []byte{DIR_FILE_SEPARATOR}, []byte{' '}, 1)
  211. fmt.Fprintf(writer, "%v\n", string(fullName))
  212. }
  213. iter.Release()
  214. }