leveldb3_store.go 9.4 KB

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