leveldb3_store.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package leveldb
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/md5"
  6. "fmt"
  7. "io"
  8. "os"
  9. "strings"
  10. "sync"
  11. "github.com/syndtr/goleveldb/leveldb"
  12. leveldb_errors "github.com/syndtr/goleveldb/leveldb/errors"
  13. "github.com/syndtr/goleveldb/leveldb/filter"
  14. "github.com/syndtr/goleveldb/leveldb/opt"
  15. leveldb_util "github.com/syndtr/goleveldb/leveldb/util"
  16. "github.com/chrislusf/seaweedfs/weed/filer"
  17. "github.com/chrislusf/seaweedfs/weed/glog"
  18. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  19. weed_util "github.com/chrislusf/seaweedfs/weed/util"
  20. )
  21. const (
  22. DEFAULT = "_main"
  23. )
  24. func init() {
  25. filer.Stores = append(filer.Stores, &LevelDB3Store{})
  26. }
  27. type LevelDB3Store struct {
  28. dir string
  29. dbs map[string]*leveldb.DB
  30. dbsLock sync.RWMutex
  31. }
  32. func (store *LevelDB3Store) GetName() string {
  33. return "leveldb3"
  34. }
  35. func (store *LevelDB3Store) Initialize(configuration weed_util.Configuration, prefix string) (err error) {
  36. dir := configuration.GetString(prefix + "dir")
  37. return store.initialize(dir)
  38. }
  39. func (store *LevelDB3Store) initialize(dir string) (err error) {
  40. glog.Infof("filer store leveldb3 dir: %s", dir)
  41. os.MkdirAll(dir, 0755)
  42. if err := weed_util.TestFolderWritable(dir); err != nil {
  43. return fmt.Errorf("Check Level Folder %s Writable: %s", dir, err)
  44. }
  45. store.dir = dir
  46. db, loadDbErr := store.loadDB(DEFAULT)
  47. if loadDbErr != nil {
  48. return loadDbErr
  49. }
  50. store.dbs = make(map[string]*leveldb.DB)
  51. store.dbs[DEFAULT] = db
  52. return
  53. }
  54. func (store *LevelDB3Store) loadDB(name string) (*leveldb.DB, error) {
  55. bloom := filter.NewBloomFilter(8) // false positive rate 0.02
  56. opts := &opt.Options{
  57. BlockCacheCapacity: 32 * 1024 * 1024, // default value is 8MiB
  58. WriteBuffer: 16 * 1024 * 1024, // default value is 4MiB
  59. CompactionTableSizeMultiplier: 4,
  60. Filter: bloom,
  61. }
  62. if name != DEFAULT {
  63. opts = &opt.Options{
  64. BlockCacheCapacity: 4 * 1024 * 1024, // default value is 8MiB
  65. WriteBuffer: 2 * 1024 * 1024, // default value is 4MiB
  66. CompactionTableSizeMultiplier: 4,
  67. Filter: bloom,
  68. }
  69. }
  70. dbFolder := fmt.Sprintf("%s/%s", store.dir, name)
  71. os.MkdirAll(dbFolder, 0755)
  72. db, dbErr := leveldb.OpenFile(dbFolder, opts)
  73. if leveldb_errors.IsCorrupted(dbErr) {
  74. db, dbErr = leveldb.RecoverFile(dbFolder, opts)
  75. }
  76. if dbErr != nil {
  77. glog.Errorf("filer store open dir %s: %v", dbFolder, dbErr)
  78. return nil, dbErr
  79. }
  80. return db, nil
  81. }
  82. func (store *LevelDB3Store) findDB(fullpath weed_util.FullPath, isForChildren bool) (*leveldb.DB, string, weed_util.FullPath, error) {
  83. store.dbsLock.RLock()
  84. defaultDB := store.dbs[DEFAULT]
  85. if !strings.HasPrefix(string(fullpath), "/buckets/") {
  86. store.dbsLock.RUnlock()
  87. return defaultDB, DEFAULT, fullpath, nil
  88. }
  89. // detect bucket
  90. bucketAndObjectKey := string(fullpath)[len("/buckets/"):]
  91. t := strings.Index(bucketAndObjectKey, "/")
  92. if t < 0 && !isForChildren {
  93. store.dbsLock.RUnlock()
  94. return defaultDB, DEFAULT, fullpath, nil
  95. }
  96. bucket := bucketAndObjectKey
  97. shortPath := weed_util.FullPath("/")
  98. if t > 0 {
  99. bucket = bucketAndObjectKey[:t]
  100. shortPath = weed_util.FullPath(bucketAndObjectKey[t:])
  101. }
  102. if db, found := store.dbs[bucket]; found {
  103. store.dbsLock.RUnlock()
  104. return db, bucket, shortPath, nil
  105. }
  106. store.dbsLock.RUnlock()
  107. // upgrade to write lock
  108. store.dbsLock.Lock()
  109. defer store.dbsLock.Unlock()
  110. // double check after getting the write lock
  111. if db, found := store.dbs[bucket]; found {
  112. return db, bucket, shortPath, nil
  113. }
  114. // create db
  115. db, err := store.loadDB(bucket)
  116. if err != nil {
  117. return nil, bucket, shortPath, err
  118. }
  119. store.dbs[bucket] = db
  120. return db, bucket, shortPath, nil
  121. }
  122. func (store *LevelDB3Store) closeDB(bucket string) {
  123. store.dbsLock.Lock()
  124. defer store.dbsLock.Unlock()
  125. if db, found := store.dbs[bucket]; found {
  126. db.Close()
  127. delete(store.dbs, bucket)
  128. }
  129. }
  130. func (store *LevelDB3Store) BeginTransaction(ctx context.Context) (context.Context, error) {
  131. return ctx, nil
  132. }
  133. func (store *LevelDB3Store) CommitTransaction(ctx context.Context) error {
  134. return nil
  135. }
  136. func (store *LevelDB3Store) RollbackTransaction(ctx context.Context) error {
  137. return nil
  138. }
  139. func (store *LevelDB3Store) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  140. db, _, shortPath, err := store.findDB(entry.FullPath, false)
  141. if err != nil {
  142. return fmt.Errorf("findDB %s : %v", entry.FullPath, err)
  143. }
  144. dir, name := shortPath.DirAndName()
  145. key := genKey(dir, name)
  146. value, err := entry.EncodeAttributesAndChunks()
  147. if err != nil {
  148. return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
  149. }
  150. if len(entry.Chunks) > 50 {
  151. value = weed_util.MaybeGzipData(value)
  152. }
  153. err = db.Put(key, value, nil)
  154. if err != nil {
  155. return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
  156. }
  157. // println("saved", entry.FullPath, "chunks", len(entry.Chunks))
  158. return nil
  159. }
  160. func (store *LevelDB3Store) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  161. return store.InsertEntry(ctx, entry)
  162. }
  163. func (store *LevelDB3Store) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer.Entry, err error) {
  164. db, _, shortPath, err := store.findDB(fullpath, false)
  165. if err != nil {
  166. return nil, fmt.Errorf("findDB %s : %v", fullpath, err)
  167. }
  168. dir, name := shortPath.DirAndName()
  169. key := genKey(dir, name)
  170. data, err := db.Get(key, nil)
  171. if err == leveldb.ErrNotFound {
  172. return nil, filer_pb.ErrNotFound
  173. }
  174. if err != nil {
  175. return nil, fmt.Errorf("get %s : %v", fullpath, err)
  176. }
  177. entry = &filer.Entry{
  178. FullPath: fullpath,
  179. }
  180. err = entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(data))
  181. if err != nil {
  182. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  183. }
  184. // println("read", entry.FullPath, "chunks", len(entry.Chunks), "data", len(data), string(data))
  185. return entry, nil
  186. }
  187. func (store *LevelDB3Store) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  188. db, _, shortPath, err := store.findDB(fullpath, false)
  189. if err != nil {
  190. return fmt.Errorf("findDB %s : %v", fullpath, err)
  191. }
  192. dir, name := shortPath.DirAndName()
  193. key := genKey(dir, name)
  194. err = db.Delete(key, nil)
  195. if err != nil {
  196. return fmt.Errorf("delete %s : %v", fullpath, err)
  197. }
  198. return nil
  199. }
  200. func (store *LevelDB3Store) DeleteFolderChildren(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  201. db, bucket, shortPath, err := store.findDB(fullpath, true)
  202. if err != nil {
  203. return fmt.Errorf("findDB %s : %v", fullpath, err)
  204. }
  205. if bucket != DEFAULT && shortPath == "/" {
  206. store.closeDB(bucket)
  207. if bucket != "" { // just to make sure
  208. os.RemoveAll(store.dir + "/" + bucket)
  209. }
  210. return nil
  211. }
  212. directoryPrefix := genDirectoryKeyPrefix(shortPath, "")
  213. batch := new(leveldb.Batch)
  214. iter := db.NewIterator(&leveldb_util.Range{Start: directoryPrefix}, nil)
  215. for iter.Next() {
  216. key := iter.Key()
  217. if !bytes.HasPrefix(key, directoryPrefix) {
  218. break
  219. }
  220. fileName := getNameFromKey(key)
  221. if fileName == "" {
  222. continue
  223. }
  224. batch.Delete(append(directoryPrefix, []byte(fileName)...))
  225. }
  226. iter.Release()
  227. err = db.Write(batch, nil)
  228. if err != nil {
  229. return fmt.Errorf("delete %s : %v", fullpath, err)
  230. }
  231. return nil
  232. }
  233. func (store *LevelDB3Store) ListDirectoryEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  234. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", eachEntryFunc)
  235. }
  236. func (store *LevelDB3Store) ListDirectoryPrefixedEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  237. db, _, shortPath, err := store.findDB(dirPath, true)
  238. if err != nil {
  239. return lastFileName, fmt.Errorf("findDB %s : %v", dirPath, err)
  240. }
  241. directoryPrefix := genDirectoryKeyPrefix(shortPath, prefix)
  242. lastFileStart := directoryPrefix
  243. if startFileName != "" {
  244. lastFileStart = genDirectoryKeyPrefix(shortPath, startFileName)
  245. }
  246. iter := db.NewIterator(&leveldb_util.Range{Start: lastFileStart}, nil)
  247. for iter.Next() {
  248. key := iter.Key()
  249. if !bytes.HasPrefix(key, directoryPrefix) {
  250. break
  251. }
  252. fileName := getNameFromKey(key)
  253. if fileName == "" {
  254. continue
  255. }
  256. if fileName == startFileName && !includeStartFile {
  257. continue
  258. }
  259. limit--
  260. if limit < 0 {
  261. break
  262. }
  263. lastFileName = fileName
  264. entry := &filer.Entry{
  265. FullPath: weed_util.NewFullPath(string(dirPath), fileName),
  266. }
  267. // println("list", entry.FullPath, "chunks", len(entry.Chunks))
  268. if decodeErr := entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(iter.Value())); decodeErr != nil {
  269. err = decodeErr
  270. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  271. break
  272. }
  273. if !eachEntryFunc(entry) {
  274. break
  275. }
  276. }
  277. iter.Release()
  278. return lastFileName, err
  279. }
  280. func genKey(dirPath, fileName string) (key []byte) {
  281. key = hashToBytes(dirPath)
  282. key = append(key, []byte(fileName)...)
  283. return key
  284. }
  285. func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string) (keyPrefix []byte) {
  286. keyPrefix = hashToBytes(string(fullpath))
  287. if len(startFileName) > 0 {
  288. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  289. }
  290. return keyPrefix
  291. }
  292. func getNameFromKey(key []byte) string {
  293. return string(key[md5.Size:])
  294. }
  295. // hash directory
  296. func hashToBytes(dir string) []byte {
  297. h := md5.New()
  298. io.WriteString(h, dir)
  299. b := h.Sum(nil)
  300. return b
  301. }
  302. func (store *LevelDB3Store) Shutdown() {
  303. for _, db := range store.dbs {
  304. db.Close()
  305. }
  306. }