leveldb3_store.go 9.5 KB

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