-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkv_store.go
384 lines (343 loc) · 9.32 KB
/
kv_store.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
package mitkv
import (
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
sll "github.com/emirpasic/gods/lists/singlylinkedlist"
"github.com/emirpasic/gods/maps/treemap"
avl "github.com/emirpasic/gods/trees/avltree"
)
// KvStore KvStore
type KvStore interface {
Set(key string, value string)
Get(key string) (value string)
Del(key string)
}
// LSMKvStore LSMKvStore
type LSMKvStore struct {
Index *avl.Tree // 内存表
ImmutableIndex *avl.Tree // 不可变的内存表
SstTables *sll.List // sstTable列表
DataDir string // 目录
Lock sync.RWMutex
StoreThreshold int64
PartSize int64
WalFile *os.File
}
// InitLSMKvStore InitLSMKvStore
func InitLSMKvStore(dataDir string, storeThreshold int64, partSize int64) (lSMKvStore *LSMKvStore, err error) {
lSMKvStore = &LSMKvStore{
DataDir: dataDir,
StoreThreshold: storeThreshold,
PartSize: partSize,
SstTables: sll.New(),
Index: avl.NewWithStringComparator(),
ImmutableIndex: avl.NewWithStringComparator(),
Lock: sync.RWMutex{},
}
files, err := os.ReadDir(dataDir)
if err != nil {
files = make([]os.DirEntry, 0)
err = os.Mkdir(dataDir, os.ModePerm)
if err != nil {
return nil, err
}
}
if len(files) == 0 {
// dataDir + WAL
filePath := dataDir + "wal"
fileInfo, statErr := os.Stat(filePath)
var walFile *os.File
if statErr != nil {
walFile, err = os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
fmt.Printf("%v\n", err)
}
} else {
walFile, err = os.OpenFile(filePath, os.O_APPEND|os.O_RDWR, 0666)
if err != nil {
fmt.Printf("%v\n", err)
}
}
fmt.Printf("fileInfo %v\n", fileInfo)
lSMKvStore.WalFile = walFile
return lSMKvStore, nil
}
sstTreeMap := treemap.NewWithStringComparator()
for _, file := range files {
fileName := file.Name()
absolutePath := dataDir + fileName
// 从暂存的WAL中恢复数据,一般是持久化ssTable过程中
// 异常才会留下walTmp
if !file.IsDir() && fileName == "walTmp" {
walFile, openErr := os.OpenFile(absolutePath, os.O_RDWR, 0666)
if openErr != nil {
fmt.Printf("%v\n", err)
}
lSMKvStore.restoreFromWal(walFile)
}
// 加载ssTable
if !file.IsDir() && strings.HasSuffix(fileName, ".table") {
// file name format is ${timestamp}.${suffix}
fileNameSplit := strings.Split(fileName, ".")
if len(fileNameSplit) > 0 {
time := fileNameSplit[0]
sst, createSStErr := CreateFromFile(absolutePath)
if createSStErr != nil {
fmt.Errorf("ParseInt err %v\n", createSStErr)
}
// 从小到大的将sstTable存入到排序树中
sstTreeMap.Put(time, sst)
}
} else if !file.IsDir() && strings.HasSuffix(fileName, "wal") {
// 加载wal文件
walFile, openErr := os.OpenFile(absolutePath, os.O_RDWR, 0666)
if openErr != nil {
fmt.Printf("%v\n", err)
}
lSMKvStore.restoreFromWal(walFile)
lSMKvStore.WalFile = walFile
}
}
lSMKvStore.SstTables.Add(sstTreeMap.Values()...)
return lSMKvStore, nil
}
// restoreFromWal 从暂存数据中恢复数据
func (kv *LSMKvStore) restoreFromWal(file *os.File) {
fileStat, err := file.Stat()
if err != nil {
fmt.Errorf("get file stat err %v\n", err)
}
var start int64 = 0
file.Seek(start, 0)
for start < fileStat.Size() {
intLenBuff := make([]byte, 4)
file.Read(intLenBuff)
valLen := BytesToInt32(intLenBuff)
start = start + 4
file.Seek(start, 0)
valBytesBuf := make([]byte, valLen)
file.Read(valBytesBuf)
cmd := Cmd{}
if err = json.Unmarshal(valBytesBuf, &cmd); err != nil {
fmt.Errorf("Unmarshal err%v\n", err)
}
kv.Index.Put(cmd.Key, cmd)
start = start + int64(valLen)
}
fileStat, err = file.Stat()
if err != nil {
fmt.Errorf("get file stat err %v\n", err)
}
file.Seek(fileStat.Size(), 0)
}
// Set set data to db
func (kv *LSMKvStore) Set(key string, value string) {
kv.Lock.Lock()
cmd := Cmd{
Key: key,
Val: value,
CmdType: SET,
}
kv.writeWal(cmd)
kv.Index.Put(key, cmd)
kv.Lock.Unlock()
// 当内存表的大小大于写存储阈值,则将内存中的数据刷到磁盘
if int64(kv.Index.Size()) > kv.StoreThreshold {
kv.switchIndex()
kv.storeToSstTable()
}
}
// Get get val
func (kv *LSMKvStore) Get(key string) (value string) {
kv.Lock.RLock()
defer kv.Lock.RUnlock()
// 1 先从内存表中获取数据
cmdObj, find := kv.Index.Get(key)
if find {
res := &Cmd{}
jsonbyte, temerr := json.Marshal(cmdObj)
if temerr != nil {
fmt.Errorf("err %v\n", temerr)
}
if temerr = json.Unmarshal(jsonbyte, res); temerr != nil {
fmt.Errorf("err %v\n", temerr)
}
if res.CmdType == DEL {
return ""
} else if res.CmdType == SET {
return res.Val
}
}
// 2 再从暂存表中获取
cmdObj, find = kv.ImmutableIndex.Get(key)
if find {
res := &Cmd{}
jsonbyte, temerr := json.Marshal(cmdObj)
if temerr != nil {
fmt.Errorf("err %v\n", temerr)
}
if temerr = json.Unmarshal(jsonbyte, res); temerr != nil {
fmt.Errorf("err %v\n", temerr)
}
return res.Val
}
// 3 从sstTable中获取
// it := kv.SstTables.Iterator()
// sst table 问价是按照文件名字的时间顺序升序存在 SstTables 中
// 因此 查询 SstTables 文件的时候应该倒序查询
// 查询最新更新的key(最新的key覆盖旧值) 查询到则返回
for index := kv.SstTables.Size() - 1; index >= 0; index-- {
satval, findList := kv.SstTables.Get(index)
if !findList {
fmt.Errorf("get sst list err %v\n", findList)
}
sstTable := &SSTTable{}
data, ok := (satval).(*SSTTable)
if ok {
sstTable = data
}
cmd, err := sstTable.query(key)
if err != nil {
fmt.Errorf("sstTable.query err %v\n", err)
return ""
}
if cmd != nil && cmd.Key == key && cmd.CmdType == SET {
return cmd.Val
}
// 数据被删除 直接返回空
if cmd != nil && cmd.Key == key && cmd.CmdType == DEL {
return ""
}
}
return ""
}
// Del del val
func (kv *LSMKvStore) Del(key string) {
kv.Lock.Lock()
cmd := Cmd{
Key: key,
CmdType: DEL,
}
kv.writeWal(cmd)
kv.Index.Put(key, cmd)
kv.Lock.Unlock()
// 当内存表的大小大于写存储阈值,则将内存中的数据刷到磁盘
if int64(kv.Index.Size()) > kv.StoreThreshold {
kv.switchIndex()
kv.storeToSstTable()
}
}
// switchIndex 将达到存储阈值的内存表暂存,并生成新的wal文件与内存表
func (kv *LSMKvStore) switchIndex() {
kv.Lock.Lock()
defer kv.Lock.Unlock()
tempValTree, err := kv.Index.ToJSON()
if err != nil {
fmt.Errorf("kv.Index.ToJSON() err%v\n", err)
}
kv.ImmutableIndex.FromJSON(tempValTree)
kv.Index.Clear()
walTmpFilePath := kv.DataDir + "walTmp"
walFilePath := kv.DataDir + "wal"
_, statErr := os.Stat(walTmpFilePath)
if statErr != nil {
fmt.Errorf("check file stat err %v\n", statErr)
}
if statErr == nil {
// 如果文件存在 则删除文件
err := os.Remove(walTmpFilePath)
if err != nil {
fmt.Errorf("delete walTmp file err %v\n", err)
}
}
// 重命名文件 将 wal 重命名成 walTmp
err = os.Rename(walFilePath, walTmpFilePath)
if err != nil {
fmt.Errorf("rename wal file err %v\n", err)
}
}
// storeToSstTable 将暂存起来的数据落盘 写入到sstTable中
func (kv *LSMKvStore) storeToSstTable() {
kv.Lock.Lock()
defer kv.Lock.Unlock()
now := time.Now().UnixNano() / int64(time.Millisecond)
nowStr := strconv.FormatInt(now, 10)
fileName := strings.Join([]string{nowStr, "table"}, ".")
absolutePath := kv.DataDir + fileName
logjsonBytes, err := kv.ImmutableIndex.ToJSON()
if err != nil {
fmt.Errorf("ImmutableIndex ToJSON err %v\n", err)
}
fmt.Printf("ImmutableIndex %v\n", string(logjsonBytes))
sstTable, err := CreateFromIndex(absolutePath, int(kv.PartSize), *kv.ImmutableIndex)
if err != nil {
fmt.Errorf("CreateFromIndex err %v\n", err)
}
kv.SstTables.Add(sstTable)
kv.ImmutableIndex.Clear()
walTmpFilePath := kv.DataDir + "walTmp"
_, statErr := os.Stat(walTmpFilePath)
if statErr != nil {
fmt.Errorf("check file stat err %v\n", statErr)
}
if statErr == nil {
// 如果文件存在 则删除文件
err := os.Remove(walTmpFilePath)
if err != nil {
fmt.Errorf("delete walTmp file err %v\n", err)
}
}
walFilePath := kv.DataDir + "wal"
walFile, err := os.OpenFile(walFilePath, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
fmt.Errorf("open wal err %v\n", err)
}
kv.WalFile = walFile
}
func (kv *LSMKvStore) writeWal(cmd Cmd) {
fileInfo, err := kv.WalFile.Stat()
if err != nil {
fmt.Errorf("check wal file stat err %v\n", err)
return
}
fmt.Printf("wal file stat%v\n", fileInfo)
cmdBytes, err := json.Marshal(cmd)
if err != nil {
fmt.Errorf("Marshal get cmd err%v\n", err)
return
}
cmdBytesLen := len(cmdBytes)
cmdBytesLenBytes := Int32ToBytes(int32(cmdBytesLen))
_, errWriteLen := kv.WalFile.Write(cmdBytesLenBytes)
if errWriteLen != nil {
fmt.Errorf("write data len to wal err %v\n", errWriteLen)
}
_, errWriteData := kv.WalFile.Write(cmdBytes)
if errWriteData != nil {
fmt.Errorf("write data to wal err %v\n", errWriteData)
}
// 将数据落盘
flushErr := kv.WalFile.Sync()
if flushErr != nil {
fmt.Errorf("flush file err %v\n", flushErr)
}
}
// Close close file data
func (kv *LSMKvStore) Close() {
for _, sstVal := range kv.SstTables.Values() {
sstTable := &SSTTable{}
data, ok := (sstVal).(*SSTTable)
if ok {
sstTable = data
}
if sstTable == nil {
return
}
sstTable.Close()
}
}