forked from hardcore-os/corekv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vlog.go
1267 lines (1150 loc) · 33.3 KB
/
vlog.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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 hardcore-os Project Authors
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package corekv
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"math"
"math/rand"
"os"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/hardcore-os/corekv/file"
"github.com/hardcore-os/corekv/utils"
"github.com/pkg/errors"
)
const discardStatsFlushThreshold = 100
var lfDiscardStatsKey = []byte("!corekv!discard") // For storing lfDiscardStats
// valueLog
type valueLog struct {
dirPath string
// guards our view of which files exist, which to be deleted, how many active iterators
filesLock sync.RWMutex
filesMap map[uint32]*file.LogFile
maxFid uint32
filesToBeDeleted []uint32
// A refcount of iterators -- when this hits zero, we can delete the filesToBeDeleted.
numActiveIterators int32
db *DB
writableLogOffset uint32 // read by read, written by write. Must access via atomics.
numEntriesWritten uint32
opt Options
garbageCh chan struct{}
lfDiscardStats *lfDiscardStats
}
func (vlog *valueLog) newValuePtr(e *utils.Entry) (*utils.ValuePtr, error) {
// TODO 尝试使用对象复用,后面entry对象也应该使用
req := requestPool.Get().(*request)
req.reset()
req.Entries = []*utils.Entry{e}
req.Wg.Add(1)
req.IncrRef() // for db write
defer req.DecrRef()
err := vlog.write([]*request{req})
return req.Ptrs[0], err
}
func (vlog *valueLog) open(db *DB, ptr *utils.ValuePtr, replayFn utils.LogEntry) error {
vlog.lfDiscardStats.closer.Add(1)
go vlog.flushDiscardStats()
if err := vlog.populateFilesMap(); err != nil {
return err
}
// If no files are found, then create a new file.
if len(vlog.filesMap) == 0 {
_, err := vlog.createVlogFile(0)
return utils.WarpErr("Error while creating log file in valueLog.open", err)
}
fids := vlog.sortedFids()
for _, fid := range fids {
lf, ok := vlog.filesMap[fid]
utils.CondPanic(!ok, fmt.Errorf("vlog.filesMap[fid] fid not found"))
var err error
if err = lf.Open(
&file.Options{
FID: uint64(fid),
FileName: vlog.fpath(fid),
Dir: vlog.dirPath,
Path: vlog.dirPath,
MaxSz: 2 * vlog.db.opt.ValueLogFileSize,
}); err != nil {
return errors.Wrapf(err, "Open existing file: %q", lf.FileName())
}
var offset uint32
// 从head处开始重放vlog日志,而不是从第一条日志
// head 相当于一个快照
if fid == ptr.Fid {
offset = ptr.Offset + ptr.Len
}
fmt.Printf("Replaying file id: %d at offset: %d\n", fid, offset)
now := time.Now()
// 重放日志
if err := vlog.replayLog(lf, offset, replayFn); err != nil {
// Log file is corrupted. Delete it.
if err == utils.ErrDeleteVlogFile {
delete(vlog.filesMap, fid)
// Close the fd of the file before deleting the file otherwise windows complaints.
if err := lf.Close(); err != nil {
return errors.Wrapf(err, "failed to close vlog file %s", lf.FileName())
}
path := vlog.fpath(lf.FID)
if err := os.Remove(path); err != nil {
return errors.Wrapf(err, "failed to delete empty value log file: %q", path)
}
continue
}
return err
}
fmt.Printf("Replay took: %s\n", time.Since(now))
if fid < vlog.maxFid {
// This file has been replayed. It can now be mmapped.
// For maxFid, the mmap would be done by the specially written code below.
if err := lf.Init(); err != nil {
return err
}
}
}
// Seek to the end to start writing.
last, ok := vlog.filesMap[vlog.maxFid]
utils.CondPanic(!ok, errors.New("vlog.filesMap[vlog.maxFid] not found"))
lastOffset, err := last.Seek(0, io.SeekEnd)
if err != nil {
return errors.Wrapf(err, fmt.Sprintf("file.Seek to end path:[%s]", last.FileName()))
}
vlog.writableLogOffset = uint32(lastOffset)
// head的设计起到check point的作用
vlog.db.vhead = &utils.ValuePtr{Fid: vlog.maxFid, Offset: uint32(lastOffset)}
if err := vlog.populateDiscardStats(); err != nil {
fmt.Errorf("Failed to populate discard stats: %s\n", err)
}
return nil
}
// Read reads the value log at a given location.
// TODO: Make this read private.
func (vlog *valueLog) read(vp *utils.ValuePtr) ([]byte, func(), error) {
buf, lf, err := vlog.readValueBytes(vp)
// log file is locked so, decide whether to lock immediately or let the caller to
// unlock it, after caller uses it.
cb := vlog.getUnlockCallback(lf)
if err != nil {
return nil, cb, err
}
if vlog.opt.VerifyValueChecksum {
hash := crc32.New(utils.CastagnoliCrcTable)
if _, err := hash.Write(buf[:len(buf)-crc32.Size]); err != nil {
utils.RunCallback(cb)
return nil, nil, errors.Wrapf(err, "failed to write hash for vp %+v", vp)
}
// Fetch checksum from the end of the buffer.
checksum := buf[len(buf)-crc32.Size:]
if hash.Sum32() != utils.BytesToU32(checksum) {
utils.RunCallback(cb)
return nil, nil, errors.Wrapf(utils.ErrChecksumMismatch, "value corrupted for vp: %+v", vp)
}
}
var h utils.Header
headerLen := h.Decode(buf)
kv := buf[headerLen:]
if uint32(len(kv)) < h.KLen+h.VLen {
fmt.Errorf("Invalid read: vp: %+v\n", vp)
return nil, nil, errors.Errorf("Invalid read: Len: %d read at:[%d:%d]",
len(kv), h.KLen, h.KLen+h.VLen)
}
return kv[h.KLen : h.KLen+h.VLen], cb, nil
}
// write 并不是并发安全的
func (vlog *valueLog) write(reqs []*request) error {
// 需要检查是否能够正确写入
if err := vlog.validateWrites(reqs); err != nil {
return err
}
vlog.filesLock.RLock()
maxFid := vlog.maxFid
curlf := vlog.filesMap[maxFid]
vlog.filesLock.RUnlock()
var buf bytes.Buffer
flushWrites := func() error {
if buf.Len() == 0 {
return nil
}
data := buf.Bytes()
offset := vlog.woffset()
if err := curlf.Write(offset, data); err != nil {
return errors.Wrapf(err, "Unable to write to value log file: %q", curlf.FileName())
}
buf.Reset()
atomic.AddUint32(&vlog.writableLogOffset, uint32(len(data)))
curlf.AddSize(vlog.writableLogOffset)
return nil
}
toDisk := func() error {
if err := flushWrites(); err != nil {
return err
}
// 切分vlog文件
if vlog.woffset() > uint32(vlog.opt.ValueLogFileSize) ||
vlog.numEntriesWritten > vlog.opt.ValueLogMaxEntries {
if err := curlf.DoneWriting(vlog.woffset()); err != nil {
return err
}
newid := atomic.AddUint32(&vlog.maxFid, 1)
utils.CondPanic(newid <= 0, fmt.Errorf("newid has overflown uint32: %v", newid))
newlf, err := vlog.createVlogFile(newid)
if err != nil {
return err
}
curlf = newlf
atomic.AddInt32(&vlog.db.logRotates, 1)
}
return nil
}
for i := range reqs {
b := reqs[i]
b.Ptrs = b.Ptrs[:0]
var written int
for j := range b.Entries {
e := b.Entries[j]
if vlog.db.shouldWriteValueToLSM(e) {
b.Ptrs = append(b.Ptrs, &utils.ValuePtr{})
continue
}
var p utils.ValuePtr
p.Fid = curlf.FID
// Use the offset including buffer length so far.
p.Offset = vlog.woffset() + uint32(buf.Len())
plen, err := curlf.EncodeEntry(e, &buf, p.Offset) // Now encode the entry into buffer.
if err != nil {
return err
}
p.Len = uint32(plen)
b.Ptrs = append(b.Ptrs, &p)
written++
if buf.Len() > vlog.db.opt.ValueLogFileSize {
if err := flushWrites(); err != nil {
return err
}
}
}
vlog.numEntriesWritten += uint32(written)
// We write to disk here so that all entries that are part of the same transaction are
// written to the same vlog file.
writeNow :=
vlog.woffset()+uint32(buf.Len()) > uint32(vlog.opt.ValueLogFileSize) ||
vlog.numEntriesWritten > uint32(vlog.opt.ValueLogMaxEntries)
if writeNow {
if err := toDisk(); err != nil {
return err
}
}
}
return toDisk()
}
func (vlog *valueLog) close() error {
if vlog == nil || vlog.db == nil {
return nil
}
// close flushDiscardStats.
<-vlog.lfDiscardStats.closer.CloseSignal
var err error
for id, f := range vlog.filesMap {
f.Lock.Lock() // We won’t release the lock.
maxFid := vlog.maxFid
if id == maxFid {
// truncate writable log file to correct offset.
if truncErr := f.Truncate(int64(vlog.woffset())); truncErr != nil && err == nil {
err = truncErr
}
}
if closeErr := f.Close(); closeErr != nil && err == nil {
err = closeErr
}
f.Lock.Unlock()
}
return err
}
func (vlog *valueLog) runGC(discardRatio float64, head *utils.ValuePtr) error {
select {
case vlog.garbageCh <- struct{}{}:
// Pick a log file for GC.
defer func() {
// 通过一个channel来控制一次仅运行一个GC任务
<-vlog.garbageCh
}()
var err error
files := vlog.pickLog(head)
if len(files) == 0 {
return utils.ErrNoRewrite
}
tried := make(map[uint32]bool)
for _, lf := range files {
//消重一下,防止随机策略和统计策略返回同一个fid
if _, done := tried[lf.FID]; done {
continue
}
tried[lf.FID] = true
if err = vlog.doRunGC(lf, discardRatio); err == nil {
return nil
}
}
return err
default:
return utils.ErrRejected
}
}
func (vlog *valueLog) doRunGC(lf *file.LogFile, discardRatio float64) (err error) {
// 退出的时候把统计的discard清空
defer func() {
if err == nil {
vlog.lfDiscardStats.Lock()
delete(vlog.lfDiscardStats.m, lf.FID)
vlog.lfDiscardStats.Unlock()
}
}()
s := &sampler{
lf: lf,
countRatio: 0.01, // 1% of num entries.
sizeRatio: 0.1, // 10% of the file as window.
fromBeginning: false,
}
if _, err = vlog.sample(s, discardRatio); err != nil {
return err
}
if err = vlog.rewrite(lf); err != nil {
return err
}
return nil
}
//重写
func (vlog *valueLog) rewrite(f *file.LogFile) error {
vlog.filesLock.RLock()
maxFid := vlog.maxFid
vlog.filesLock.RUnlock()
utils.CondPanic(uint32(f.FID) >= maxFid, fmt.Errorf("fid to move: %d. Current max fid: %d", f.FID, maxFid))
wb := make([]*utils.Entry, 0, 1000)
var size int64
var count, moved int
fe := func(e *utils.Entry) error {
count++
if count%100000 == 0 {
fmt.Printf("Processing entry %d\n", count)
}
vs, err := vlog.db.lsm.Get(e.Key)
if err != nil {
return err
}
if utils.DiscardEntry(e, vs) {
return nil
}
if len(vs.Value) == 0 {
return errors.Errorf("Empty value: %+v", vs)
}
var vp utils.ValuePtr
vp.Decode(vs.Value)
if vp.Fid > f.FID {
return nil
}
if vp.Offset > e.Offset {
return nil
}
// 如果从lsm和vlog的同一个位置读取带entry则重新写回,也有可能读取到旧的
if vp.Fid == f.FID && vp.Offset == e.Offset {
moved++
// This new entry only contains the key, and a pointer to the value.
ne := new(utils.Entry)
ne.Meta = 0 // Remove all bits. Different keyspace doesn't need these bits.
ne.ExpiresAt = e.ExpiresAt
ne.Key = append([]byte{}, e.Key...)
ne.Value = append([]byte{}, e.Value...)
es := int64(ne.EstimateSize(vlog.db.opt.ValueLogFileSize))
// Consider size of value as well while considering the total size
// of the batch. There have been reports of high memory usage in
// rewrite because we don't consider the value size. See #1292.
es += int64(len(e.Value))
// Ensure length and size of wb is within transaction limits.
if int64(len(wb)+1) >= vlog.opt.MaxBatchCount ||
size+es >= vlog.opt.MaxBatchSize {
if err := vlog.db.batchSet(wb); err != nil {
return err
}
size = 0
wb = wb[:0]
}
wb = append(wb, ne)
size += es
}
return nil
}
_, err := vlog.iterate(f, 0, func(e *utils.Entry, vp *utils.ValuePtr) error {
return fe(e)
})
if err != nil {
return err
}
batchSize := 1024
var loops int
for i := 0; i < len(wb); {
loops++
if batchSize == 0 {
return utils.ErrNoRewrite
}
end := i + batchSize
if end > len(wb) {
end = len(wb)
}
if err := vlog.db.batchSet(wb[i:end]); err != nil {
if err == utils.ErrTxnTooBig {
// Decrease the batch size to half.
batchSize = batchSize / 2
continue
}
return err
}
i += batchSize
}
var deleteFileNow bool
// Entries written to LSM. Remove the older file now.
{
vlog.filesLock.Lock()
// Just a sanity-check.
if _, ok := vlog.filesMap[f.FID]; !ok {
vlog.filesLock.Unlock()
return errors.Errorf("Unable to find fid: %d", f.FID)
}
if vlog.iteratorCount() == 0 {
delete(vlog.filesMap, f.FID)
//deleteFileNow = true
} else {
vlog.filesToBeDeleted = append(vlog.filesToBeDeleted, f.FID)
}
vlog.filesLock.Unlock()
}
if deleteFileNow {
if err := vlog.deleteLogFile(f); err != nil {
return err
}
}
return nil
}
func (vlog *valueLog) iteratorCount() int {
return int(atomic.LoadInt32(&vlog.numActiveIterators))
}
// TODO 在迭代器close时,需要调用此函数,关闭已经被判定需要移除的logfile
func (vlog *valueLog) decrIteratorCount() error {
num := atomic.AddInt32(&vlog.numActiveIterators, -1)
if num != 0 {
return nil
}
vlog.filesLock.Lock()
lfs := make([]*file.LogFile, 0, len(vlog.filesToBeDeleted))
for _, id := range vlog.filesToBeDeleted {
lfs = append(lfs, vlog.filesMap[id])
delete(vlog.filesMap, id)
}
vlog.filesToBeDeleted = nil
vlog.filesLock.Unlock()
for _, lf := range lfs {
if err := vlog.deleteLogFile(lf); err != nil {
return err
}
}
return nil
}
func (vlog *valueLog) deleteLogFile(lf *file.LogFile) error {
if lf == nil {
return nil
}
lf.Lock.Lock()
defer lf.Lock.Unlock()
utils.Err(lf.Close())
return os.Remove(lf.FileName())
}
// validateWrites 可以检查当前的req是否能写入vlog日志,一个vlog日志最大4GB
func (vlog *valueLog) validateWrites(reqs []*request) error {
vlogOffset := uint64(vlog.woffset())
for _, req := range reqs {
// calculate size of the request.
size := estimateRequestSize(req)
estimatedVlogOffset := vlogOffset + size
if estimatedVlogOffset > uint64(utils.MaxVlogFileSize) {
return errors.Errorf("Request size offset %d is bigger than maximum offset %d",
estimatedVlogOffset, utils.MaxVlogFileSize)
}
if estimatedVlogOffset >= uint64(vlog.opt.ValueLogFileSize) {
// We'll create a new vlog file if the estimated offset is greater or equal to
// max vlog size. So, resetting the vlogOffset.
vlogOffset = 0
continue
}
// Estimated vlog offset will become current vlog offset if the vlog is not rotated.
vlogOffset = estimatedVlogOffset
}
return nil
}
// estimateRequestSize returns the size that needed to be written for the given request.
func estimateRequestSize(req *request) uint64 {
size := uint64(0)
for _, e := range req.Entries {
size += uint64(utils.MaxHeaderSize + len(e.Key) + len(e.Value) + crc32.Size)
}
return size
}
// getUnlockCallback will returns a function which unlock the logfile if the logfile is mmaped.
// otherwise, it unlock the logfile and return nil.
func (vlog *valueLog) getUnlockCallback(lf *file.LogFile) func() {
if lf == nil {
return nil
}
return lf.Lock.RUnlock
}
// readValueBytes return vlog entry slice and read locked log file. Caller should take care of
// logFile unlocking.
func (vlog *valueLog) readValueBytes(vp *utils.ValuePtr) ([]byte, *file.LogFile, error) {
lf, err := vlog.getFileRLocked(vp)
if err != nil {
return nil, nil, err
}
buf, err := lf.Read(vp)
return buf, lf, err
}
// Gets the logFile and acquires and RLock() for the mmap. You must call RUnlock on the file
// (if non-nil)
func (vlog *valueLog) getFileRLocked(vp *utils.ValuePtr) (*file.LogFile, error) {
vlog.filesLock.RLock()
defer vlog.filesLock.RUnlock()
ret, ok := vlog.filesMap[vp.Fid]
if !ok {
// log file has gone away, we can't do anything. Return.
return nil, errors.Errorf("file with ID: %d not found", vp.Fid)
}
// Check for valid offset if we are reading from writable log.
maxFid := vlog.maxFid
if vp.Fid == maxFid {
currentOffset := vlog.woffset()
if vp.Offset >= currentOffset {
return nil, errors.Errorf(
"Invalid value pointer offset: %d greater than current offset: %d",
vp.Offset, currentOffset)
}
}
ret.Lock.RLock()
return ret, nil
}
func (vlog *valueLog) woffset() uint32 {
return atomic.LoadUint32(&vlog.writableLogOffset)
}
func (vlog *valueLog) populateFilesMap() error {
vlog.filesMap = make(map[uint32]*file.LogFile)
files, err := ioutil.ReadDir(vlog.dirPath)
if err != nil {
return utils.WarpErr(fmt.Sprintf("Unable to open log dir. path[%s]", vlog.dirPath), err)
}
found := make(map[uint64]struct{})
for _, f := range files {
if !strings.HasSuffix(f.Name(), ".vlog") {
continue
}
fsz := len(f.Name())
fid, err := strconv.ParseUint(f.Name()[:fsz-5], 10, 32)
if err != nil {
return utils.WarpErr(fmt.Sprintf("Unable to parse log id. name:[%s]", f.Name()), err)
}
if _, ok := found[fid]; ok {
return utils.WarpErr(fmt.Sprintf("Duplicate file found. Please delete one. name:[%s]", f.Name()), err)
}
found[fid] = struct{}{}
lf := &file.LogFile{
FID: uint32(fid),
Lock: sync.RWMutex{},
}
vlog.filesMap[uint32(fid)] = lf
if vlog.maxFid < uint32(fid) {
vlog.maxFid = uint32(fid)
}
}
return nil
}
func (vlog *valueLog) createVlogFile(fid uint32) (*file.LogFile, error) {
path := vlog.fpath(fid)
lf := &file.LogFile{
FID: fid,
Lock: sync.RWMutex{},
}
var err error
utils.Panic2(nil, lf.Open(&file.Options{
FID: uint64(fid),
FileName: path,
Dir: vlog.dirPath,
Path: vlog.dirPath,
MaxSz: 2 * vlog.db.opt.ValueLogFileSize,
}))
removeFile := func() {
// 如果处理出错 则直接删除文件
utils.Err(os.Remove(lf.FileName()))
}
if err = lf.Bootstrap(); err != nil {
removeFile()
return nil, err
}
if err = utils.SyncDir(vlog.dirPath); err != nil {
removeFile()
return nil, utils.WarpErr(fmt.Sprintf("Sync value log dir[%s]", vlog.dirPath), err)
}
vlog.filesLock.Lock()
vlog.filesMap[fid] = lf
vlog.maxFid = fid
// 现在header才是0
atomic.StoreUint32(&vlog.writableLogOffset, utils.VlogHeaderSize)
vlog.numEntriesWritten = 0
vlog.filesLock.Unlock()
return lf, nil
}
// sortedFids returns the file id's not pending deletion, sorted. Assumes we have shared access to
// filesMap.
func (vlog *valueLog) sortedFids() []uint32 {
toBeDeleted := make(map[uint32]struct{})
for _, fid := range vlog.filesToBeDeleted {
toBeDeleted[fid] = struct{}{}
}
ret := make([]uint32, 0, len(vlog.filesMap))
for fid := range vlog.filesMap {
if _, ok := toBeDeleted[fid]; !ok {
ret = append(ret, fid)
}
}
sort.Slice(ret, func(i, j int) bool {
return ret[i] < ret[j]
})
return ret
}
func (vlog *valueLog) replayLog(lf *file.LogFile, offset uint32, replayFn utils.LogEntry) error {
// Alright, let's iterate now.
endOffset, err := vlog.iterate(lf, offset, replayFn)
if err != nil {
return errors.Wrapf(err, "Unable to replay logfile:[%s]", lf.FileName())
}
if int64(endOffset) == int64(lf.Size()) {
return nil
}
// TODO: 如果vlog日志损坏怎么办? 当前默认是截断损坏的数据
// The entire file should be truncated (i.e. it should be deleted).
// If fid == maxFid then it's okay to truncate the entire file since it will be
// used for future additions. Also, it's okay if the last file has size zero.
// We mmap 2*opt.ValueLogSize for the last file. See vlog.Open() function
// if endOffset <= vlogHeaderSize && lf.fid != vlog.maxFid {
if endOffset <= utils.VlogHeaderSize {
if lf.FID != vlog.maxFid {
return utils.ErrDeleteVlogFile
}
return lf.Bootstrap()
}
fmt.Printf("Truncating vlog file %s to offset: %d\n", lf.FileName(), endOffset)
if err := lf.Truncate(int64(endOffset)); err != nil {
return utils.WarpErr(
fmt.Sprintf("Truncation needed at offset %d. Can be done manually as well.", endOffset), err)
}
return nil
}
// iterate iterates over log file. It doesn't not allocate new memory for every kv pair.
// Therefore, the kv pair is only valid for the duration of fn call.
func (vlog *valueLog) iterate(lf *file.LogFile, offset uint32, fn utils.LogEntry) (uint32, error) {
if offset == 0 {
offset = utils.VlogHeaderSize
}
if int64(offset) == int64(lf.Size()) {
// We're at the end of the file already. No need to do anything.
return offset, nil
}
// We're not at the end of the file. Let's Seek to the offset and start reading.
if _, err := lf.Seek(int64(offset), io.SeekStart); err != nil {
return 0, errors.Wrapf(err, "Unable to seek, name:%s", lf.FileName())
}
reader := bufio.NewReader(lf.FD())
read := &safeRead{
k: make([]byte, 10),
v: make([]byte, 10),
recordOffset: offset,
lf: lf,
}
var validEndOffset uint32 = offset
loop:
for {
e, err := read.Entry(reader)
switch {
case err == io.EOF:
break loop
case err == io.ErrUnexpectedEOF || err == utils.ErrTruncate:
break loop
case err != nil:
return 0, err
case e == nil:
continue
}
var vp utils.ValuePtr
vp.Len = uint32(int(e.Hlen) + len(e.Key) + len(e.Value) + crc32.Size)
read.recordOffset += vp.Len
vp.Offset = e.Offset
vp.Fid = lf.FID
validEndOffset = read.recordOffset
if err := fn(e, &vp); err != nil {
if err == utils.ErrStop {
break
}
return 0, utils.WarpErr(fmt.Sprintf("Iteration function %s", lf.FileName()), err)
}
}
return validEndOffset, nil
}
// 这个对象用来重放日志
type safeRead struct {
k []byte
v []byte
recordOffset uint32
lf *file.LogFile
}
// Entry reads an entry from the provided reader. It also validates the checksum for every entry
// read. Returns error on failure.
func (r *safeRead) Entry(reader io.Reader) (*utils.Entry, error) {
tee := utils.NewHashReader(reader)
var h utils.Header
hlen, err := h.DecodeFrom(tee)
if err != nil {
return nil, err
}
if h.KLen > uint32(1<<16) { // Key length must be below uint16.
return nil, utils.ErrTruncate
}
kl := int(h.KLen)
if cap(r.k) < kl {
r.k = make([]byte, 2*kl)
}
vl := int(h.VLen)
if cap(r.v) < vl {
r.v = make([]byte, 2*vl)
}
e := &utils.Entry{}
e.Offset = r.recordOffset
e.Hlen = hlen
buf := make([]byte, h.KLen+h.VLen)
if _, err := io.ReadFull(tee, buf[:]); err != nil {
if err == io.EOF {
err = utils.ErrTruncate
}
return nil, err
}
e.Key = buf[:h.KLen]
e.Value = buf[h.KLen:]
var crcBuf [crc32.Size]byte
if _, err := io.ReadFull(reader, crcBuf[:]); err != nil {
if err == io.EOF {
err = utils.ErrTruncate
}
return nil, err
}
crc := utils.BytesToU32(crcBuf[:])
if crc != tee.Sum32() {
return nil, utils.ErrTruncate
}
e.Meta = h.Meta
e.ExpiresAt = h.ExpiresAt
return e, nil
}
// 统计脏数据
func (vlog *valueLog) populateDiscardStats() error {
key := utils.KeyWithTs(lfDiscardStatsKey, math.MaxUint64)
var statsMap map[uint32]int64
vs, err := vlog.db.Get(key)
if err != nil {
return err
}
// Value doesn't exist.
if vs.Meta == 0 && len(vs.Value) == 0 {
return nil
}
val := vs.Value
// Entry is not stored in the LSM tree.
if utils.IsValuePtr(vs) {
var vp utils.ValuePtr
vp.Decode(val)
// Read entry from the value log.
result, cb, err := vlog.read(&vp)
// Copy it before we release the read lock.
val = utils.SafeCopy(nil, result)
utils.RunCallback(cb)
if err != nil {
return err
}
}
if len(val) == 0 {
return nil
}
if err := json.Unmarshal(val, &statsMap); err != nil {
return errors.Wrapf(err, "failed to unmarshal discard stats")
}
fmt.Printf("Value Log Discard stats: %v\n", statsMap)
vlog.lfDiscardStats.flushChan <- statsMap
return nil
}
func (vlog *valueLog) fpath(fid uint32) string {
return utils.VlogFilePath(vlog.dirPath, fid)
}
// initVLog
func (db *DB) initVLog() {
vp, _ := db.getHead()
vlog := &valueLog{
dirPath: db.opt.WorkDir,
filesToBeDeleted: make([]uint32, 0),
lfDiscardStats: &lfDiscardStats{
m: make(map[uint32]int64),
closer: utils.NewCloser(),
flushChan: make(chan map[uint32]int64, 16),
},
}
vlog.db = db
vlog.opt = *db.opt
vlog.garbageCh = make(chan struct{}, 1)
if err := vlog.open(db, vp, db.replayFunction()); err != nil {
utils.Panic(err)
}
db.vlog = vlog
}
// getHead prints all the head pointer in the DB and return the max value.
func (db *DB) getHead() (*utils.ValuePtr, uint64) {
var vptr utils.ValuePtr
return &vptr, 0
}
func (db *DB) replayFunction() func(*utils.Entry, *utils.ValuePtr) error {
toLSM := func(k []byte, vs utils.ValueStruct) {
db.lsm.Set(&utils.Entry{
Key: k,
Value: vs.Value,
ExpiresAt: vs.ExpiresAt,
Meta: vs.Meta,
})
}
return func(e *utils.Entry, vp *utils.ValuePtr) error { // Function for replaying.
nk := make([]byte, len(e.Key))
copy(nk, e.Key)
var nv []byte
meta := e.Meta
if db.shouldWriteValueToLSM(e) {
nv = make([]byte, len(e.Value))
copy(nv, e.Value)
} else {
nv = vp.Encode()
meta = meta | utils.BitValuePointer
}
// Update vhead. If the crash happens while replay was in progess
// and the head is not updated, we will end up replaying all the
// files starting from file zero, again.
db.updateHead([]*utils.ValuePtr{vp})
v := utils.ValueStruct{
Value: nv,
Meta: meta,
ExpiresAt: e.ExpiresAt,
}
// This entry is from a rewrite or via SetEntryAt(..).
toLSM(nk, v)
return nil
}
}
// updateHead should not be called without the db.Lock() since db.vhead is used
// by the writer go routines and memtable flushing goroutine.
func (db *DB) updateHead(ptrs []*utils.ValuePtr) {
var ptr *utils.ValuePtr
for i := len(ptrs) - 1; i >= 0; i-- {
p := ptrs[i]
if !p.IsZero() {
ptr = p
break
}
}
if ptr.IsZero() {
return
}
utils.CondPanic(ptr.Less(db.vhead), fmt.Errorf("ptr.Less(db.vhead) is true"))
db.vhead = ptr
}
// sync 同步一下,刷盘
func (vlog *valueLog) sync(fid uint32) error {
vlog.filesLock.RLock()
maxFid := vlog.maxFid
// During replay it is possible to get sync call with fid less than maxFid.
// Because older file has already been synced, we can return from here.
if fid < maxFid || len(vlog.filesMap) == 0 {
vlog.filesLock.RUnlock()
return nil
}
curlf := vlog.filesMap[maxFid]
// Sometimes it is possible that vlog.maxFid has been increased but file creation
// with same id is still in progress and this function is called. In those cases
// entry for the file might not be present in vlog.filesMap.
if curlf == nil {
vlog.filesLock.RUnlock()
return nil
}
curlf.Lock.RLock()
vlog.filesLock.RUnlock()
err := curlf.Sync()
curlf.Lock.RUnlock()
return err
}