-
Notifications
You must be signed in to change notification settings - Fork 639
/
db.go
719 lines (651 loc) · 19.8 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
package rosedb
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sync"
"time"
"github.com/bwmarrin/snowflake"
"github.com/gofrs/flock"
"github.com/robfig/cron/v3"
"github.com/rosedblabs/rosedb/v2/index"
"github.com/rosedblabs/rosedb/v2/utils"
"github.com/rosedblabs/wal"
)
const (
fileLockName = "FLOCK"
dataFileNameSuffix = ".SEG"
hintFileNameSuffix = ".HINT"
mergeFinNameSuffix = ".MERGEFIN"
)
// DB represents a ROSEDB database instance.
// It is built on the bitcask model, which is a log-structured storage.
// It uses WAL to write data, and uses an in-memory index to store the key
// and the position of the data in the WAL,
// the index will be rebuilt when the database is opened.
//
// The main advantage of ROSEDB is that it is very fast to write, read, and delete data.
// Because it only needs one disk IO to complete a single operation.
//
// But since we should store all keys and their positions(index) in memory,
// our total data size is limited by the memory size.
//
// So if your memory can almost hold all the keys, ROSEDB is the perfect storage engine for you.
type DB struct {
dataFiles *wal.WAL // data files are a sets of segment files in WAL.
hintFile *wal.WAL // hint file is used to store the key and the position for fast startup.
index index.Indexer
options Options
fileLock *flock.Flock
mu sync.RWMutex
closed bool
mergeRunning uint32 // indicate if the database is merging
batchPool sync.Pool
recordPool sync.Pool
encodeHeader []byte
watchCh chan *Event // user consume channel for watch events
watcher *Watcher
expiredCursorKey []byte // the location to which DeleteExpiredKeys executes.
cronScheduler *cron.Cron // cron scheduler for auto merge task
}
// Stat represents the statistics of the database.
type Stat struct {
// Total number of keys
KeysNum int
// Total disk size of database directory
DiskSize int64
}
// Open a database with the specified options.
// If the database directory does not exist, it will be created automatically.
//
// Multiple processes can not use the same database directory at the same time,
// otherwise it will return ErrDatabaseIsUsing.
//
// It will open the wal files in the database directory and load the index from them.
// Return the DB instance, or an error if any.
func Open(options Options) (*DB, error) {
// check options
if err := checkOptions(options); err != nil {
return nil, err
}
// create data directory if not exist
if _, err := os.Stat(options.DirPath); err != nil {
if err := os.MkdirAll(options.DirPath, os.ModePerm); err != nil {
return nil, err
}
}
// create file lock, prevent multiple processes from using the same database directory
fileLock := flock.New(filepath.Join(options.DirPath, fileLockName))
hold, err := fileLock.TryLock()
if err != nil {
return nil, err
}
if !hold {
return nil, ErrDatabaseIsUsing
}
// load merge files if exists
if err = loadMergeFiles(options.DirPath); err != nil {
return nil, err
}
// init DB instance
db := &DB{
index: index.NewIndexer(),
options: options,
fileLock: fileLock,
batchPool: sync.Pool{New: newBatch},
recordPool: sync.Pool{New: newRecord},
encodeHeader: make([]byte, maxLogRecordHeaderSize),
}
// open data files
if db.dataFiles, err = db.openWalFiles(); err != nil {
return nil, err
}
// load index
if err = db.loadIndex(); err != nil {
return nil, err
}
// enable watch
if options.WatchQueueSize > 0 {
db.watchCh = make(chan *Event, 100)
db.watcher = NewWatcher(options.WatchQueueSize)
// run a goroutine to synchronize event information
go db.watcher.sendEvent(db.watchCh)
}
// enable auto merge task
if len(options.AutoMergeCronExpr) > 0 {
db.cronScheduler = cron.New(
cron.WithParser(
cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour |
cron.Dom | cron.Month | cron.Dow | cron.Descriptor),
),
)
_, err = db.cronScheduler.AddFunc(options.AutoMergeCronExpr, func() {
// maybe we should deal with different errors with different logic, but a background task can't omit its error.
// after auto merge, we should close and reopen the db.
_ = db.Merge(true)
})
if err != nil {
return nil, err
}
db.cronScheduler.Start()
}
return db, nil
}
func (db *DB) openWalFiles() (*wal.WAL, error) {
// open data files from WAL
walFiles, err := wal.Open(wal.Options{
DirPath: db.options.DirPath,
SegmentSize: db.options.SegmentSize,
SegmentFileExt: dataFileNameSuffix,
Sync: db.options.Sync,
BytesPerSync: db.options.BytesPerSync,
})
if err != nil {
return nil, err
}
return walFiles, nil
}
func (db *DB) loadIndex() error {
// load index frm hint file
if err := db.loadIndexFromHintFile(); err != nil {
return err
}
// load index from data files
if err := db.loadIndexFromWAL(); err != nil {
return err
}
return nil
}
// Close the database, close all data files and release file lock.
// Set the closed flag to true.
// The DB instance cannot be used after closing.
func (db *DB) Close() error {
db.mu.Lock()
defer db.mu.Unlock()
if err := db.closeFiles(); err != nil {
return err
}
// release file lock
if err := db.fileLock.Unlock(); err != nil {
return err
}
// close watch channel
if db.options.WatchQueueSize > 0 {
close(db.watchCh)
}
// close auto merge cron scheduler
if db.cronScheduler != nil {
db.cronScheduler.Stop()
}
db.closed = true
return nil
}
// closeFiles close all data files and hint file
func (db *DB) closeFiles() error {
// 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
}
}
return nil
}
// Sync all data files to the underlying storage.
func (db *DB) Sync() error {
db.mu.Lock()
defer db.mu.Unlock()
return db.dataFiles.Sync()
}
// Stat returns the statistics of the database.
func (db *DB) Stat() *Stat {
db.mu.Lock()
defer db.mu.Unlock()
diskSize, err := utils.DirSize(db.options.DirPath)
if err != nil {
panic(fmt.Sprintf("rosedb: get database directory size error: %v", err))
}
return &Stat{
KeysNum: db.index.Size(),
DiskSize: diskSize,
}
}
// Put a key-value pair into the database.
// Actually, it will open a new batch and commit it.
// You can think the batch has only one Put operation.
func (db *DB) Put(key []byte, value []byte) error {
batch := db.batchPool.Get().(*Batch)
defer func() {
batch.reset()
db.batchPool.Put(batch)
}()
// This is a single put operation, we can set Sync to false.
// Because the data will be written to the WAL,
// and the WAL file will be synced to disk according to the DB options.
batch.init(false, false, db)
if err := batch.Put(key, value); err != nil {
_ = batch.Rollback()
return err
}
return batch.Commit()
}
// PutWithTTL a key-value pair into the database, with a ttl.
// Actually, it will open a new batch and commit it.
// You can think the batch has only one PutWithTTL operation.
func (db *DB) PutWithTTL(key []byte, value []byte, ttl time.Duration) error {
batch := db.batchPool.Get().(*Batch)
defer func() {
batch.reset()
db.batchPool.Put(batch)
}()
// This is a single put operation, we can set Sync to false.
// Because the data will be written to the WAL,
// and the WAL file will be synced to disk according to the DB options.
batch.init(false, false, db)
if err := batch.PutWithTTL(key, value, ttl); err != nil {
_ = batch.Rollback()
return err
}
return batch.Commit()
}
// Get the value of the specified key from the database.
// Actually, it will open a new batch and commit it.
// You can think the batch has only one Get operation.
func (db *DB) Get(key []byte) ([]byte, 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 the specified key from the database.
// Actually, it will open a new batch and commit it.
// You can think the batch has only one Delete operation.
func (db *DB) Delete(key []byte) error {
batch := db.batchPool.Get().(*Batch)
defer func() {
batch.reset()
db.batchPool.Put(batch)
}()
// This is a single delete operation, we can set Sync to false.
// Because the data will be written to the WAL,
// and the WAL file will be synced to disk according to the DB options.
batch.init(false, false, db)
if err := batch.Delete(key); err != nil {
_ = batch.Rollback()
return err
}
return batch.Commit()
}
// Exist checks if the specified key exists in the database.
// Actually, it will open a new batch and commit it.
// You can think the batch has only one Exist operation.
func (db *DB) Exist(key []byte) (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)
}
// Expire sets the ttl of the key.
func (db *DB) Expire(key []byte, ttl time.Duration) error {
batch := db.batchPool.Get().(*Batch)
defer func() {
batch.reset()
db.batchPool.Put(batch)
}()
// This is a single expire operation, we can set Sync to false.
// Because the data will be written to the WAL,
// and the WAL file will be synced to disk according to the DB options.
batch.init(false, false, db)
if err := batch.Expire(key, ttl); err != nil {
_ = batch.Rollback()
return err
}
return batch.Commit()
}
// TTL get the ttl of the key.
func (db *DB) TTL(key []byte) (time.Duration, error) {
batch := db.batchPool.Get().(*Batch)
batch.init(true, false, db)
defer func() {
_ = batch.Commit()
batch.reset()
db.batchPool.Put(batch)
}()
return batch.TTL(key)
}
// Persist removes the ttl of the key.
// If the key does not exist or expired, it will return ErrKeyNotFound.
func (db *DB) Persist(key []byte) error {
batch := db.batchPool.Get().(*Batch)
defer func() {
batch.reset()
db.batchPool.Put(batch)
}()
// This is a single persist operation, we can set Sync to false.
// Because the data will be written to the WAL,
// and the WAL file will be synced to disk according to the DB options.
batch.init(false, false, db)
if err := batch.Persist(key); err != nil {
_ = batch.Rollback()
return err
}
return batch.Commit()
}
func (db *DB) Watch() (<-chan *Event, error) {
if db.options.WatchQueueSize <= 0 {
return nil, ErrWatchDisabled
}
return db.watchCh, nil
}
// Ascend calls handleFn for each key/value pair in the db in ascending order.
func (db *DB) Ascend(handleFn func(k []byte, v []byte) (bool, error)) {
db.mu.RLock()
defer db.mu.RUnlock()
db.index.Ascend(func(key []byte, pos *wal.ChunkPosition) (bool, error) {
chunk, err := db.dataFiles.Read(pos)
if err != nil {
return false, err
}
if value := db.checkValue(chunk); value != nil {
return handleFn(key, value)
}
return true, nil
})
}
// AscendRange calls handleFn for each key/value pair in the db within the range [startKey, endKey] in ascending order.
func (db *DB) AscendRange(startKey, endKey []byte, handleFn func(k []byte, v []byte) (bool, error)) {
db.mu.RLock()
defer db.mu.RUnlock()
db.index.AscendRange(startKey, endKey, func(key []byte, pos *wal.ChunkPosition) (bool, error) {
chunk, err := db.dataFiles.Read(pos)
if err != nil {
return false, nil
}
if value := db.checkValue(chunk); value != nil {
return handleFn(key, value)
}
return true, nil
})
}
// AscendGreaterOrEqual calls handleFn for each key/value pair in the db with keys greater than or equal to the given key.
func (db *DB) AscendGreaterOrEqual(key []byte, handleFn func(k []byte, v []byte) (bool, error)) {
db.mu.RLock()
defer db.mu.RUnlock()
db.index.AscendGreaterOrEqual(key, func(key []byte, pos *wal.ChunkPosition) (bool, error) {
chunk, err := db.dataFiles.Read(pos)
if err != nil {
return false, nil
}
if value := db.checkValue(chunk); value != nil {
return handleFn(key, value)
}
return true, nil
})
}
// AscendKeys calls handleFn for each key in the db in ascending order.
// Since our expiry time is stored in the value, if you want to filter expired keys,
// you need to set parameter filterExpired to true. But the performance will be affected.
// Because we need to read the value of each key to determine if it is expired.
func (db *DB) AscendKeys(pattern []byte, filterExpired bool, handleFn func(k []byte) (bool, error)) {
db.mu.RLock()
defer db.mu.RUnlock()
var reg *regexp.Regexp
if len(pattern) > 0 {
reg = regexp.MustCompile(string(pattern))
}
db.index.Ascend(func(key []byte, pos *wal.ChunkPosition) (bool, error) {
if reg == nil || reg.Match(key) {
var invalid bool
if filterExpired {
chunk, err := db.dataFiles.Read(pos)
if err != nil {
return false, err
}
if value := db.checkValue(chunk); value == nil {
invalid = true
}
}
if invalid {
return true, nil
}
return handleFn(key)
}
return true, nil
})
}
// Descend calls handleFn for each key/value pair in the db in descending order.
func (db *DB) Descend(handleFn func(k []byte, v []byte) (bool, error)) {
db.mu.RLock()
defer db.mu.RUnlock()
db.index.Descend(func(key []byte, pos *wal.ChunkPosition) (bool, error) {
chunk, err := db.dataFiles.Read(pos)
if err != nil {
return false, nil
}
if value := db.checkValue(chunk); value != nil {
return handleFn(key, value)
}
return true, nil
})
}
// DescendRange calls handleFn for each key/value pair in the db within the range [startKey, endKey] in descending order.
func (db *DB) DescendRange(startKey, endKey []byte, handleFn func(k []byte, v []byte) (bool, error)) {
db.mu.RLock()
defer db.mu.RUnlock()
db.index.DescendRange(startKey, endKey, func(key []byte, pos *wal.ChunkPosition) (bool, error) {
chunk, err := db.dataFiles.Read(pos)
if err != nil {
return false, nil
}
if value := db.checkValue(chunk); value != nil {
return handleFn(key, value)
}
return true, nil
})
}
// DescendLessOrEqual calls handleFn for each key/value pair in the db with keys less than or equal to the given key.
func (db *DB) DescendLessOrEqual(key []byte, handleFn func(k []byte, v []byte) (bool, error)) {
db.mu.RLock()
defer db.mu.RUnlock()
db.index.DescendLessOrEqual(key, func(key []byte, pos *wal.ChunkPosition) (bool, error) {
chunk, err := db.dataFiles.Read(pos)
if err != nil {
return false, nil
}
if value := db.checkValue(chunk); value != nil {
return handleFn(key, value)
}
return true, nil
})
}
// DescendKeys calls handleFn for each key in the db in descending order.
// Since our expiry time is stored in the value, if you want to filter expired keys,
// you need to set parameter filterExpired to true. But the performance will be affected.
// Because we need to read the value of each key to determine if it is expired.
func (db *DB) DescendKeys(pattern []byte, filterExpired bool, handleFn func(k []byte) (bool, error)) {
db.mu.RLock()
defer db.mu.RUnlock()
var reg *regexp.Regexp
if len(pattern) > 0 {
reg = regexp.MustCompile(string(pattern))
}
db.index.Descend(func(key []byte, pos *wal.ChunkPosition) (bool, error) {
if reg == nil || reg.Match(key) {
var invalid bool
if filterExpired {
chunk, err := db.dataFiles.Read(pos)
if err != nil {
return false, err
}
if value := db.checkValue(chunk); value == nil {
invalid = true
}
}
if invalid {
return true, nil
}
return handleFn(key)
}
return true, nil
})
}
func (db *DB) checkValue(chunk []byte) []byte {
record := decodeLogRecord(chunk)
now := time.Now().UnixNano()
if record.Type != LogRecordDeleted && !record.IsExpired(now) {
return record.Value
}
return nil
}
func checkOptions(options Options) error {
if options.DirPath == "" {
return errors.New("database dir path is empty")
}
if options.SegmentSize <= 0 {
return errors.New("database data file size must be greater than 0")
}
if len(options.AutoMergeCronExpr) > 0 {
if _, err := cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor).
Parse(options.AutoMergeCronExpr); err != nil {
return fmt.Errorf("database auto merge cron expression is invalid, err: %s", err)
}
}
return nil
}
// loadIndexFromWAL loads index from WAL.
// It will iterate over all the WAL files and read data
// from them to rebuild the index.
func (db *DB) loadIndexFromWAL() error {
mergeFinSegmentId, err := getMergeFinSegmentId(db.options.DirPath)
if err != nil {
return err
}
indexRecords := make(map[uint64][]*IndexRecord)
now := time.Now().UnixNano()
// get a reader for WAL
reader := db.dataFiles.NewReader()
db.dataFiles.SetIsStartupTraversal(true)
for {
// if the current segment id is less than the mergeFinSegmentId,
// we can skip this segment because it has been merged,
// and we can load index from the hint file directly.
if reader.CurrentSegmentId() <= mergeFinSegmentId {
reader.SkipCurrentSegment()
continue
}
chunk, position, err := reader.Next()
if err != nil {
if err == io.EOF {
break
}
return err
}
// decode and get log record
record := decodeLogRecord(chunk)
// if we get the end of a batch,
// all records in this batch are ready to be indexed.
if record.Type == LogRecordBatchFinished {
batchId, err := snowflake.ParseBytes(record.Key)
if err != nil {
return err
}
for _, idxRecord := range indexRecords[uint64(batchId)] {
if idxRecord.recordType == LogRecordNormal {
db.index.Put(idxRecord.key, idxRecord.position)
}
if idxRecord.recordType == LogRecordDeleted {
db.index.Delete(idxRecord.key)
}
}
// delete indexRecords according to batchId after indexing
delete(indexRecords, uint64(batchId))
} else if record.Type == LogRecordNormal && record.BatchId == mergeFinishedBatchID {
// if the record is a normal record and the batch id is 0,
// it means that the record is involved in the merge operation.
// so put the record into index directly.
db.index.Put(record.Key, position)
} else {
// expired records should not be indexed
if record.IsExpired(now) {
db.index.Delete(record.Key)
continue
}
// put the record into the temporary indexRecords
indexRecords[record.BatchId] = append(indexRecords[record.BatchId],
&IndexRecord{
key: record.Key,
recordType: record.Type,
position: position,
})
}
}
db.dataFiles.SetIsStartupTraversal(false)
return nil
}
// DeleteExpiredKeys scan the entire index in ascending order to delete expired keys.
// It is a time-consuming operation, so we need to specify a timeout
// to prevent the DB from being unavailable for a long time.
func (db *DB) DeleteExpiredKeys(timeout time.Duration) error {
// set timeout
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
done := make(chan struct{}, 1)
var innerErr error
now := time.Now().UnixNano()
go func(ctx context.Context) {
db.mu.Lock()
defer db.mu.Unlock()
for {
// select 100 keys from the db.index
positions := make([]*wal.ChunkPosition, 0, 100)
db.index.AscendGreaterOrEqual(db.expiredCursorKey, func(k []byte, pos *wal.ChunkPosition) (bool, error) {
positions = append(positions, pos)
if len(positions) >= 100 {
return false, nil
}
return true, nil
})
// If keys in the db.index has been traversed, len(positions) will be 0.
if len(positions) == 0 {
db.expiredCursorKey = nil
done <- struct{}{}
return
}
// delete from index if the key is expired.
for _, pos := range positions {
chunk, err := db.dataFiles.Read(pos)
if err != nil {
innerErr = err
done <- struct{}{}
return
}
record := decodeLogRecord(chunk)
if record.IsExpired(now) {
db.index.Delete(record.Key)
}
db.expiredCursorKey = record.Key
}
}
}(ctx)
select {
case <-ctx.Done():
return innerErr
case <-done:
return nil
}
}