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.

304 lines
7.3 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. // +build rocksdb
  2. package rocksdb
  3. import (
  4. "bytes"
  5. "context"
  6. "crypto/md5"
  7. "fmt"
  8. "io"
  9. "os"
  10. "github.com/tecbot/gorocksdb"
  11. "github.com/chrislusf/seaweedfs/weed/filer"
  12. "github.com/chrislusf/seaweedfs/weed/glog"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. weed_util "github.com/chrislusf/seaweedfs/weed/util"
  15. )
  16. func init() {
  17. filer.Stores = append(filer.Stores, &RocksDBStore{})
  18. }
  19. type options struct {
  20. opt *gorocksdb.Options
  21. ro *gorocksdb.ReadOptions
  22. wo *gorocksdb.WriteOptions
  23. }
  24. func (opt *options) init() {
  25. opt.opt = gorocksdb.NewDefaultOptions()
  26. opt.ro = gorocksdb.NewDefaultReadOptions()
  27. opt.wo = gorocksdb.NewDefaultWriteOptions()
  28. }
  29. func (opt *options) close() {
  30. opt.opt.Destroy()
  31. opt.ro.Destroy()
  32. opt.wo.Destroy()
  33. }
  34. type RocksDBStore struct {
  35. path string
  36. db *gorocksdb.DB
  37. options
  38. }
  39. func (store *RocksDBStore) GetName() string {
  40. return "rocksdb"
  41. }
  42. func (store *RocksDBStore) Initialize(configuration weed_util.Configuration, prefix string) (err error) {
  43. dir := configuration.GetString(prefix + "dir")
  44. return store.initialize(dir)
  45. }
  46. func (store *RocksDBStore) initialize(dir string) (err error) {
  47. glog.Infof("filer store rocksdb dir: %s", dir)
  48. os.MkdirAll(dir, 0755)
  49. if err := weed_util.TestFolderWritable(dir); err != nil {
  50. return fmt.Errorf("Check Level Folder %s Writable: %s", dir, err)
  51. }
  52. store.options.init()
  53. store.opt.SetCreateIfMissing(true)
  54. // reduce write amplification
  55. // also avoid expired data stored in highest level never get compacted
  56. store.opt.SetLevelCompactionDynamicLevelBytes(true)
  57. store.opt.SetCompactionFilter(NewTTLFilter())
  58. // store.opt.SetMaxBackgroundCompactions(2)
  59. store.db, err = gorocksdb.OpenDb(store.opt, dir)
  60. return
  61. }
  62. func (store *RocksDBStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  63. return ctx, nil
  64. }
  65. func (store *RocksDBStore) CommitTransaction(ctx context.Context) error {
  66. return nil
  67. }
  68. func (store *RocksDBStore) RollbackTransaction(ctx context.Context) error {
  69. return nil
  70. }
  71. func (store *RocksDBStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  72. dir, name := entry.DirAndName()
  73. key := genKey(dir, name)
  74. value, err := entry.EncodeAttributesAndChunks()
  75. if err != nil {
  76. return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
  77. }
  78. err = store.db.Put(store.wo, key, value)
  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 *RocksDBStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  86. return store.InsertEntry(ctx, entry)
  87. }
  88. func (store *RocksDBStore) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer.Entry, err error) {
  89. dir, name := fullpath.DirAndName()
  90. key := genKey(dir, name)
  91. data, err := store.db.Get(store.ro, key)
  92. if data == nil {
  93. return nil, filer_pb.ErrNotFound
  94. }
  95. defer data.Free()
  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(data.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.Chunks), "data", len(data), string(data))
  107. return entry, nil
  108. }
  109. func (store *RocksDBStore) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  110. dir, name := fullpath.DirAndName()
  111. key := genKey(dir, name)
  112. err = store.db.Delete(store.wo, key)
  113. if err != nil {
  114. return fmt.Errorf("delete %s : %v", fullpath, err)
  115. }
  116. return nil
  117. }
  118. func (store *RocksDBStore) DeleteFolderChildren(ctx context.Context, fullpath weed_util.FullPath, limit int64) (err error) {
  119. directoryPrefix := genDirectoryKeyPrefix(fullpath, "")
  120. batch := gorocksdb.NewWriteBatch()
  121. defer batch.Destroy()
  122. ro := gorocksdb.NewDefaultReadOptions()
  123. defer ro.Destroy()
  124. ro.SetFillCache(false)
  125. iter := store.db.NewIterator(ro)
  126. defer iter.Close()
  127. err = enumerate(iter, directoryPrefix, nil, false, -1, func(key, value []byte) bool {
  128. batch.Delete(key)
  129. return true
  130. })
  131. if err != nil {
  132. return fmt.Errorf("delete list %s : %v", fullpath, err)
  133. }
  134. err = store.db.Write(store.wo, batch)
  135. if err != nil {
  136. return fmt.Errorf("delete %s : %v", fullpath, err)
  137. }
  138. return nil
  139. }
  140. func enumerate(iter *gorocksdb.Iterator, prefix, lastKey []byte, includeLastKey bool, limit int64, fn func(key, value []byte) bool) (err error) {
  141. if len(lastKey) == 0 {
  142. iter.Seek(prefix)
  143. } else {
  144. iter.Seek(lastKey)
  145. if !includeLastKey {
  146. if iter.Valid() {
  147. if bytes.Equal(iter.Key().Data(), lastKey) {
  148. iter.Next()
  149. }
  150. }
  151. }
  152. }
  153. i := int64(0)
  154. for ; iter.Valid(); iter.Next() {
  155. if limit > 0 {
  156. i++
  157. if i > limit {
  158. break
  159. }
  160. }
  161. key := iter.Key().Data()
  162. if !bytes.HasPrefix(key, prefix) {
  163. break
  164. }
  165. ret := fn(key, iter.Value().Data())
  166. if !ret {
  167. break
  168. }
  169. }
  170. if err := iter.Err(); err != nil {
  171. return fmt.Errorf("prefix scan iterator: %v", err)
  172. }
  173. return nil
  174. }
  175. func (store *RocksDBStore) ListDirectoryEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  176. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", eachEntryFunc)
  177. }
  178. func (store *RocksDBStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  179. directoryPrefix := genDirectoryKeyPrefix(dirPath, prefix)
  180. lastFileStart := directoryPrefix
  181. if startFileName != "" {
  182. lastFileStart = genDirectoryKeyPrefix(dirPath, startFileName)
  183. }
  184. ro := gorocksdb.NewDefaultReadOptions()
  185. defer ro.Destroy()
  186. ro.SetFillCache(false)
  187. iter := store.db.NewIterator(ro)
  188. defer iter.Close()
  189. err = enumerate(iter, directoryPrefix, lastFileStart, includeStartFile, limit, func(key, value []byte) bool {
  190. fileName := getNameFromKey(key)
  191. if fileName == "" {
  192. return true
  193. }
  194. entry := &filer.Entry{
  195. FullPath: weed_util.NewFullPath(string(dirPath), fileName),
  196. }
  197. lastFileName = fileName
  198. // println("list", entry.FullPath, "chunks", len(entry.Chunks))
  199. if decodeErr := entry.DecodeAttributesAndChunks(value); decodeErr != nil {
  200. err = decodeErr
  201. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  202. return false
  203. }
  204. if !eachEntryFunc(entry) {
  205. return false
  206. }
  207. return true
  208. })
  209. if err != nil {
  210. return lastFileName, fmt.Errorf("prefix list %s : %v", dirPath, err)
  211. }
  212. return lastFileName, err
  213. }
  214. func genKey(dirPath, fileName string) (key []byte) {
  215. key = hashToBytes(dirPath)
  216. key = append(key, []byte(fileName)...)
  217. return key
  218. }
  219. func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string) (keyPrefix []byte) {
  220. keyPrefix = hashToBytes(string(fullpath))
  221. if len(startFileName) > 0 {
  222. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  223. }
  224. return keyPrefix
  225. }
  226. func getNameFromKey(key []byte) string {
  227. return string(key[md5.Size:])
  228. }
  229. // hash directory, and use last byte for partitioning
  230. func hashToBytes(dir string) []byte {
  231. h := md5.New()
  232. io.WriteString(h, dir)
  233. b := h.Sum(nil)
  234. return b
  235. }
  236. func (store *RocksDBStore) Shutdown() {
  237. store.db.Close()
  238. store.options.close()
  239. }