-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlsm.go
149 lines (121 loc) · 2.43 KB
/
lsm.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
package lsm
import (
"context"
"fmt"
"os"
"slices"
"sync"
"time"
"github.com/xgzlucario/LSM/level"
"github.com/xgzlucario/LSM/memdb"
"github.com/xgzlucario/LSM/option"
"github.com/xgzlucario/LSM/table"
)
// LSM-Tree defination.
type LSM struct {
*option.Option
dir string
ctx context.Context
cancel context.CancelFunc
// guards db and dbList.
mu sync.RWMutex
db *memdb.DB
dbList []*memdb.DB
// index controller.
index *level.Controller
tableWriter *table.Writer
compactC chan struct{}
}
// NewLSM
func NewLSM(dir string, opt *option.Option) (*LSM, error) {
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
lsm := &LSM{
Option: opt,
dir: dir,
ctx: ctx,
cancel: cancel,
db: memdb.New(opt.MemDBSize),
dbList: make([]*memdb.DB, 0, 16),
index: level.NewController(dir, opt),
tableWriter: table.NewWriter(opt),
compactC: make(chan struct{}, 1),
}
// build index.
if err := lsm.index.BuildFromDisk(); err != nil {
panic(err)
}
// start minor compaction.
go func() {
for {
select {
case <-time.After(lsm.MinorCompactInterval):
lsm.MinorCompact()
case <-lsm.ctx.Done():
return
}
}
}()
// start major compaction.
go func() {
for {
select {
case <-time.After(lsm.MajorCompactInterval):
lsm.MajorCompact()
case <-lsm.ctx.Done():
return
}
}
}()
fmt.Println("LSM-Tree started.")
return lsm, nil
}
// Put
func (lsm *LSM) Put(key, value []byte) {
// memdb is full.
if lsm.db.Put(key, value, 1) {
lsm.mu.Lock()
lsm.dbList = append(lsm.dbList, lsm.db)
lsm.db = memdb.New(lsm.MemDBSize)
lsm.mu.Unlock()
lsm.db.Put(key, value, 1)
}
}
// Close
func (lsm *LSM) Close() error {
select {
case <-lsm.ctx.Done():
return nil
default:
lsm.cancel()
}
return nil
}
// MinorCompact
func (lsm *LSM) MinorCompact() {
lsm.compactC <- struct{}{}
lsm.mu.Lock()
// need dump list.
list := slices.Clone(lsm.dbList)
lsm.dbList = lsm.dbList[:0]
lsm.mu.Unlock()
for _, db := range list {
if err := lsm.index.AddLevel0Table(db); err != nil {
panic(err)
}
}
lsm.index.Print()
<-lsm.compactC
}
// MajorCompact
func (lsm *LSM) MajorCompact() {
lsm.compactC <- struct{}{}
start := time.Now()
if err := lsm.index.Compact(); err != nil {
panic(err)
}
fmt.Println("major compact cost:", time.Since(start))
<-lsm.compactC
}