-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
331 lines (290 loc) · 6.96 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package yojoudb
import (
"fmt"
"io"
"os"
"path/filepath"
"sync"
"github.com/berylyvos/yojoudb/meta"
"github.com/berylyvos/yojoudb/utils"
"github.com/berylyvos/yojoudb/wal"
"github.com/bwmarrin/snowflake"
"github.com/gofrs/flock"
)
const (
fileLockName = "FLOCK"
dataFileSuffix = ".SEG"
hintFileSuffix = ".HINT"
mergeFinSuffix = ".MERGE_FIN"
)
// DB is a database instance.
// It's built on a log-structured model, the Bitcask.
// Read and write data based on WAL(Write-Ahead Log).
// An in-memory index is for holding the keys and the
// corresponding locations. The index is rebuilt each
// time the database is restarted.
type DB struct {
dataFiles *wal.WAL
hintFile *wal.WAL
index meta.Indexer
options Options
fileLock *flock.Flock
mu sync.RWMutex
closed bool
mergeRunning uint32
reclaimSize int64
batchPool sync.Pool
}
type Stat struct {
KeyNum uint64
DataFileNum uint32
ReclaimableSize int64
DiskSize int64
}
// K key alias for []byte
type K = []byte
// V value alias for []byte
type V = []byte
// LR alias for LogRecord
type LR = LogRecord
// Loc alias for wal.ChunkLoc
type Loc = wal.ChunkLoc
// Open opens a db instance with specified options.
// It will open the WAL files and build the index.
func Open(options Options) (*DB, error) {
if err := checkOptions(options); err != nil {
return nil, err
}
if _, err := os.Stat(options.DirPath); os.IsNotExist(err) {
if err = os.MkdirAll(options.DirPath, os.ModePerm); err != nil {
return nil, err
}
}
// prevent multiple processes from occupying the same database.
fileLock := flock.New(filepath.Join(options.DirPath, fileLockName))
hold, err := fileLock.TryLock()
if err != nil {
return nil, err
}
if !hold {
return nil, ErrDatabaseIsUsing
}
// load merged files if exists
if err := loadMergedFiles(options.DirPath); err != nil {
return nil, err
}
// open data files in WAL
dataFiles, err := wal.Open(wal.Options{
DirPath: options.DirPath,
SegmentSize: options.SegmentSize,
SegmentFileExt: dataFileSuffix,
Sync: options.Sync,
BytesPerSync: options.BytesPerSync,
})
if err != nil {
return nil, err
}
// init db instance
db := &DB{
dataFiles: dataFiles,
options: options,
index: meta.NewIndexer(options.IndexType),
fileLock: fileLock,
batchPool: sync.Pool{New: makeBatch},
}
// load index from hint file if there's a merged db
if err := db.loadIndexerFromHint(); err != nil {
return nil, err
}
// load index from data files
if err := db.loadIndexer(); err != nil {
return nil, err
}
return db, nil
}
func (db *DB) Stat() *Stat {
db.mu.RLock()
defer db.mu.RUnlock()
dirSize, err := utils.DirSize(db.options.DirPath)
if err != nil {
panic(fmt.Sprintf("failed to get dir size : %v", err))
}
return &Stat{
KeyNum: uint64(uint(db.index.Size())),
ReclaimableSize: db.reclaimSize,
DiskSize: dirSize,
}
}
// Close closes the db instance.
func (db *DB) Close() error {
db.mu.Lock()
defer db.mu.Unlock()
// close wal
if err := db.dataFiles.Close(); err != nil {
return err
}
// close hint file if exists
if db.hintFile != nil {
if err := db.hintFile.Close(); err != nil {
return err
}
}
// release file lock
if err := db.fileLock.Unlock(); err != nil {
return err
}
db.closed = true
return nil
}
// Sync syncs all data files into disk.
func (db *DB) Sync() error {
db.mu.Lock()
defer db.mu.Unlock()
return db.dataFiles.Sync()
}
// Put puts the given key/val.
func (db *DB) Put(key K, val V) error {
batch := db.batchPool.Get().(*Batch)
defer func() {
batch.reset()
db.batchPool.Put(batch)
}()
batch.init(false, false, db).withPendingWrites()
if err := batch.Put(key, val); err != nil {
_ = batch.Rollback()
return err
}
return batch.Commit()
}
// Get gets the value of the given key.
// Returns nil if key is not found.
func (db *DB) Get(key K) (V, error) {
batch := db.batchPool.Get().(*Batch)
batch.init(true, false, db)
defer func() {
_ = batch.Commit()
batch.reset()
db.batchPool.Put(batch)
}()
return batch.Get(key)
}
// Delete deletes the given key.
func (db *DB) Delete(key K) error {
batch := db.batchPool.Get().(*Batch)
defer func() {
batch.reset()
db.batchPool.Put(batch)
}()
batch.init(false, false, db).withPendingWrites()
if err := batch.Delete(key); err != nil {
_ = batch.Rollback()
return err
}
return batch.Commit()
}
// Exist checks if the given key exists.
func (db *DB) Exist(key K) (bool, error) {
batch := db.batchPool.Get().(*Batch)
batch.init(true, false, db)
defer func() {
_ = batch.Commit()
batch.reset()
db.batchPool.Put(batch)
}()
return batch.Exist(key)
}
// ListKeys returns all keys in db instance.
func (db *DB) ListKeys() [][]byte {
keys := make([][]byte, db.index.Size())
it := db.NewIterator(DefaultIteratorOptions)
defer it.Close()
idx := 0
for it.Rewind(); it.Valid(); it.Next() {
keys[idx] = it.Key()
idx++
}
return keys
}
// Fold iterates every key/val, executes func on it, stops when func return false.
func (db *DB) Fold(fn func(key []byte, value []byte) bool) error {
db.mu.RLock()
defer db.mu.RUnlock()
it := db.NewIterator(DefaultIteratorOptions)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
val, err := it.Value()
if err != nil {
return err
}
if !fn(it.Key(), val) {
break
}
}
return nil
}
// loadIndexer loads index from WAL.
// It will iterate all over the WAL files and
// read data from them to rebuild the index.
func (db *DB) loadIndexer() error {
mergeFinSegId, err := getMergeFinSegId(db.options.DirPath)
if err != nil {
return err
}
// batchId => indexRecords
indexRecords := make(map[uint64][]*IndexRecord)
reader := db.dataFiles.NewReader()
for {
// skip the segments which segId is less than or equal to mergeFinSegId,
// their indexes has already been loaded through hint file.
if reader.CurrSegId() <= mergeFinSegId {
reader.Skip()
continue
}
chunk, loc, err := reader.Next()
if err != nil {
if err == io.EOF {
break
}
return err
}
record := decodeLR(chunk)
// if reaching to end-of-batch,
// put or delete all records in the batch to index.
if record.Type == LRBatchFin {
snowflakeId, err := snowflake.ParseBytes(record.Key)
if err != nil {
return err
}
batchId := uint64(snowflakeId)
for _, idxRec := range indexRecords[batchId] {
if idxRec.typ == LRNormal {
db.index.Put(idxRec.key, idxRec.loc)
}
if idxRec.typ == LRDeleted {
db.index.Delete(idxRec.key)
}
}
delete(indexRecords, batchId)
} else {
indexRecords[record.BatchId] = append(indexRecords[record.BatchId],
&IndexRecord{
key: record.Key,
typ: record.Type,
loc: loc,
})
}
}
return nil
}
func checkOptions(options Options) error {
if options.DirPath == "" {
return ErrDirPathIsEmpty
}
if options.SegmentSize <= 0 {
return ErrDataFileSizeNotPositive
}
return nil
}
func (db *DB) GetDirPath() string {
return db.options.DirPath
}