Files
talent-plan-tinykv/kv/util/engine_util/engines.go
Connor 5e089a2cd1 init course framework
Signed-off-by: Connor <zbk602423539@gmail.com>
Co-authored-by: Nick Cameron <nrc@ncameron.org>
Co-authored-by: linning <linningde25@gmail.com>
Co-authored-by: YangKeao <keao.yang@yahoo.com>
Co-authored-by: andylokandy <andylokandy@hotmail.com>
Co-authored-by: Iosmanthus Teng <myosmanthustree@gmail.com>
2020-04-30 15:25:07 +08:00

83 lines
1.9 KiB
Go

package engine_util
import (
"os"
"path/filepath"
"github.com/Connor1996/badger"
"github.com/pingcap-incubator/tinykv/kv/config"
"github.com/pingcap-incubator/tinykv/log"
)
// Engines keeps references to and data for the engines used by unistore.
// All engines are badger key/value databases.
// the Path fields are the filesystem path to where the data is stored.
type Engines struct {
// Data, including data which is committed (i.e., committed across other nodes) and un-committed (i.e., only present
// locally).
Kv *badger.DB
KvPath string
// Metadata used by Raft.
Raft *badger.DB
RaftPath string
}
func NewEngines(kvEngine, raftEngine *badger.DB, kvPath, raftPath string) *Engines {
return &Engines{
Kv: kvEngine,
KvPath: kvPath,
Raft: raftEngine,
RaftPath: raftPath,
}
}
func (en *Engines) WriteKV(wb *WriteBatch) error {
return wb.WriteToDB(en.Kv)
}
func (en *Engines) WriteRaft(wb *WriteBatch) error {
return wb.WriteToDB(en.Raft)
}
func (en *Engines) Close() error {
if err := en.Kv.Close(); err != nil {
return err
}
if err := en.Raft.Close(); err != nil {
return err
}
return nil
}
func (en *Engines) Destroy() error {
if err := en.Close(); err != nil {
return err
}
if err := os.RemoveAll(en.KvPath); err != nil {
return err
}
if err := os.RemoveAll(en.RaftPath); err != nil {
return err
}
return nil
}
// CreateDB creates a new Badger DB on disk at subPath.
func CreateDB(subPath string, conf *config.Config) *badger.DB {
opts := badger.DefaultOptions
if subPath == "raft" {
// Do not need to write blob for raft engine because it will be deleted soon.
opts.ValueThreshold = 0
}
opts.Dir = filepath.Join(conf.DBPath, subPath)
opts.ValueDir = opts.Dir
if err := os.MkdirAll(opts.Dir, os.ModePerm); err != nil {
log.Fatal(err)
}
db, err := badger.Open(opts)
if err != nil {
log.Fatal(err)
}
return db
}