/
storage.go
1470 lines (1237 loc) · 39.4 KB
/
storage.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 2019 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package storage
import (
"context"
"encoding/binary"
"math"
"os"
"path"
"reflect"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pingcap/log"
"github.com/pingcap/tidb/kv"
pb "github.com/pingcap/tipb/go-binlog"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/iterator"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/util"
"github.com/tikv/client-go/v2/oracle"
"github.com/tikv/client-go/v2/tikv"
"github.com/tikv/client-go/v2/txnkv/txnlock"
"go.uber.org/zap"
"golang.org/x/sys/unix"
pkgutil "github.com/pingcap/tidb-binlog/pkg/util"
)
const (
maxTxnTimeoutSecond int64 = 600
chanCapacity = 1 << 20
// if pump takes a long time to write binlog, pump will display the binlog meta information (unit: Second)
slowWriteThreshold = 1.0
defaultStopWriteAtAvailableSpace = 10 * (1 << 30)
physicalShiftBits = 18
)
var (
// save gcTS, the max TS we have gc, for binlog not greater than gcTS, we can delete it from storage
gcTSKey = []byte("!binlog!gcts")
// save maxCommitTS, we can get binlog in range [gcTS, maxCommitTS] from PullCommitBinlog
maxCommitTSKey = []byte("!binlog!maxCommitTS")
// save the valuePointer we should start push binlog item to sorter when restart
handlePointerKey = []byte("!binlog!handlePointer")
// save valuePointer headPointer, for binlog in vlog not after headPointer, we have save it in metadata db
// at start up, we can scan the vlog from headPointer and save the ts -> valuePointer to metadata db
headPointerKey = []byte("!binlog!headPointer")
// If the kv channel blocks for more than this value, turn on the slow chaser
slowChaserThreshold = 3 * time.Second
// Values of handlePointer and MaxCommitTS will be saved at most once per interval
handlePtrSaveInterval = time.Second
)
// Storage is the interface to handle binlog storage
type Storage interface {
WriteBinlog(binlog *pb.Binlog) error
// delete <= ts
GC(ts int64)
GetGCTS() int64
// AllMatched return if all the P-binlog have the matching C-binlog
AllMatched() bool
MaxCommitTS() int64
// GetBinlog return the binlog of ts
GetBinlog(ts int64) (binlog *pb.Binlog, err error)
// PullCommitBinlog return the chan to consume the binlog
PullCommitBinlog(ctx context.Context, last int64) <-chan *pb.Entity
Close() error
}
var _ Storage = &Append{}
// Append implement the Storage interface
type Append struct {
dir string
vlog *valueLog
storageSize storageSize
metadata *leveldb.DB
sorter *sorter
tiStore kv.Storage
helper *Helper
tiLockResolver *txnlock.LockResolver
latestTS int64
gcWorking int32
gcTS int64
maxCommitTS int64
headPointer valuePointer
handlePointer valuePointer
sortItems chan sortItem
handleSortItemQuit chan struct{}
writeCh chan *request
options *Options
close chan struct{}
wg sync.WaitGroup
}
// NewAppend returns a instance of Append
func NewAppend(dir string, options *Options) (append *Append, err error) {
return NewAppendWithResolver(dir, options, nil, nil)
}
// NewAppendWithResolver returns a instance of Append
// if tiStore and tiLockResolver is not nil, we will try to query tikv to know whether a txn is committed
func NewAppendWithResolver(dir string, options *Options, tiStore kv.Storage, tiLockResolver *txnlock.LockResolver) (append *Append, err error) {
if options == nil {
options = DefaultOptions()
}
log.Info("NewAppendWithResolver", zap.Reflect("options", options))
valueDir := path.Join(dir, "value")
err = os.MkdirAll(valueDir, 0755)
if err != nil {
return nil, errors.Trace(err)
}
vlog, err := newValueLog(valueDir, options)
if err != nil {
return nil, errors.Trace(err)
}
kvDir := path.Join(dir, "kv")
metadata, err := openMetadataDB(kvDir, options.KVConfig)
if err != nil {
return nil, errors.Trace(err)
}
writeCh := make(chan *request, chanCapacity)
append = &Append{
dir: dir,
vlog: vlog,
metadata: metadata,
writeCh: writeCh,
options: options,
tiStore: tiStore,
tiLockResolver: tiLockResolver,
close: make(chan struct{}),
sortItems: make(chan sortItem, 1024),
}
append.gcTS, err = append.readGCTSFromDB()
if err != nil {
return nil, errors.Trace(err)
}
gcTSGauge.Set(float64(oracle.ExtractPhysical(uint64(append.gcTS))))
append.maxCommitTS, err = append.readInt64(maxCommitTSKey)
if err != nil {
return nil, errors.Trace(err)
}
maxCommitTSGauge.Set(float64(oracle.ExtractPhysical(uint64(append.maxCommitTS))))
append.headPointer, err = append.readPointer(headPointerKey)
if err != nil {
return nil, errors.Trace(err)
}
append.handlePointer, err = append.readPointer(handlePointerKey)
if err != nil {
return nil, errors.Trace(err)
}
append.handleSortItemQuit = append.handleSortItem(append.sortItems)
sorter := newSorter(func(item sortItem) {
log.Debug("sorter get item", zap.Stringer("item", &item))
append.sortItems <- item
})
if tiStore != nil {
tikvStorage, ok := tiStore.(tikv.Storage)
if !ok {
return nil, errors.New("not tikv.Storage")
}
append.helper = &Helper{
Store: tikvStorage,
RegionCache: tikvStorage.GetRegionCache(),
}
sorter.setResolver(append.resolve)
}
append.sorter = sorter
minPointer := append.headPointer
if append.handlePointer.less(minPointer) {
minPointer = append.handlePointer
}
log.Info("Append info", zap.Int64("gcTS", append.gcTS),
zap.Int64("maxCommitTS", append.maxCommitTS),
zap.Reflect("headPointer", append.headPointer),
zap.Reflect("handlePointer", append.handlePointer))
toKV := append.writeToValueLog(writeCh)
append.wg.Add(1)
go append.writeToSorter(append.writeToKV(toKV))
// for handlePointer and headPointer, it's safe to start at a forward point, so we just chose a min point between handlePointer and headPointer, and wirte to KV, will push to sorter after write to KV too
err = append.vlog.scanRequests(minPointer, func(req *request) error {
toKV <- req
return nil
})
if err != nil {
return nil, errors.Trace(err)
}
append.wg.Add(1)
err = append.updateSize()
if err != nil {
return nil, errors.Trace(err)
}
go append.updateStatus()
return
}
func (a *Append) persistHandlePointer(item sortItem) error {
log.Debug("persist item", zap.Stringer("item", &item))
tsKey := encodeTSKey(item.commit)
pointerData, err := a.metadata.Get(tsKey, nil)
if err != nil {
return errors.Trace(err)
}
var pointer valuePointer
err = pointer.UnmarshalBinary(pointerData)
if err != nil {
return errors.Trace(err)
}
var batch leveldb.Batch
maxCommitTS := make([]byte, 8)
binary.LittleEndian.PutUint64(maxCommitTS, uint64(item.commit))
batch.Put(maxCommitTSKey, maxCommitTS)
batch.Put(handlePointerKey, pointerData)
err = a.metadata.Write(&batch, nil)
if err != nil {
return errors.Trace(err)
}
a.handlePointer = pointer
return nil
}
func (a *Append) handleSortItem(items <-chan sortItem) (quit chan struct{}) {
quit = make(chan struct{})
go func() {
defer close(quit)
var toSaveItem sortItem
var toSave <-chan time.Time
for {
select {
case item, ok := <-items:
if !ok {
if toSave != nil {
err := a.persistHandlePointer(toSaveItem)
if err != nil {
log.Error(errors.ErrorStack(err))
}
}
return
}
// the commitTS we get from sorter is monotonic increasing, unless we forward the handlePointer at start up
// or this should never happen
if item.commit < atomic.LoadInt64(&a.maxCommitTS) {
log.Warn("sortItem's commit ts less than append.maxCommitTS",
zap.Int64("ts", item.commit),
zap.Int64("maxCommitTS", a.maxCommitTS))
continue
}
atomic.StoreInt64(&a.maxCommitTS, item.commit)
maxCommitTSGauge.Set(float64(oracle.ExtractPhysical(uint64(item.commit))))
toSaveItem = item
if toSave == nil {
toSave = time.After(handlePtrSaveInterval)
}
log.Debug("get sort item", zap.Stringer("item", &item))
case <-toSave:
err := a.persistHandlePointer(toSaveItem)
if err != nil {
log.Error(errors.ErrorStack(err))
}
toSave = nil
}
}
}()
return quit
}
func (a *Append) updateSize() error {
size, err := getStorageSize(a.dir)
if err != nil {
return errors.Annotatef(err, "update storage size failed, dir: %s", a.dir)
}
storageSizeGauge.WithLabelValues("capacity").Set(float64(size.capacity))
storageSizeGauge.WithLabelValues("available").Set(float64(size.available))
atomic.StoreUint64(&a.storageSize.available, size.available)
atomic.StoreUint64(&a.storageSize.capacity, size.capacity)
if !a.writableOfSpace() {
log.Warn("no available space, you may want to free up some space or decrease `stop-write-at-available-space` configuration",
zap.Uint64("available", size.available),
zap.Uint64("StopWriteAtAvailableSpace", a.options.StopWriteAtAvailableSpace))
}
return nil
}
func (a *Append) updateStatus() {
defer a.wg.Done()
var updateLatest <-chan time.Time
if a.tiStore != nil {
updateLatestTicker := time.NewTicker(time.Second)
defer updateLatestTicker.Stop()
updateLatest = updateLatestTicker.C
}
updateSizeTicker := time.NewTicker(time.Second * 3)
defer updateSizeTicker.Stop()
updateSize := updateSizeTicker.C
logStatsTicker := time.NewTicker(time.Second * 10)
defer logStatsTicker.Stop()
for {
select {
case <-a.close:
return
case <-updateLatest:
ts, err := pkgutil.QueryLatestTsFromPD(a.tiStore)
if err != nil {
log.Error("QueryLatestTSFromPD failed", zap.Error(err))
} else {
atomic.StoreInt64(&a.latestTS, ts)
}
case <-updateSize:
err := a.updateSize()
if err != nil {
log.Error("update size failed", zap.Error(err))
}
case <-logStatsTicker.C:
var stats leveldb.DBStats
err := a.metadata.Stats(&stats)
if err != nil {
log.Error("get Stats failed", zap.Error(err))
} else {
log.Info("DBStats", zap.Reflect("DBStats", stats))
if stats.WritePaused {
log.Warn("in WritePaused stat")
}
}
}
}
}
func (a *Append) writableOfSpace() bool {
return atomic.LoadUint64(&a.storageSize.available) > a.options.StopWriteAtAvailableSpace
}
// Write a commit binlog myself if the status is committed,
// otherwise we can just ignore it, we will not get the commit binlog while iterating the kv by ts
func (a *Append) writeCBinlog(pbinlog *pb.Binlog, commitTS int64) error {
// write the commit binlog myself
cbinlog := new(pb.Binlog)
cbinlog.Tp = pb.BinlogType_Commit
cbinlog.StartTs = pbinlog.StartTs
cbinlog.CommitTs = commitTS
req := a.writeBinlog(cbinlog)
if req.err != nil {
return errors.Annotate(req.err, "writeBinlog failed")
}
// when writeBinlog return success, the pointer will be write to kv async,
// but we need to make sure it has been write to kv when we return true in the func, then we can get this commit binlog when
// we update maxCommitTS
// write the ts -> pointer to KV here to make sure it.
pointer, err := req.valuePointer.MarshalBinary()
if err != nil {
panic(err)
}
err = a.metadata.Put(encodeTSKey(req.ts()), pointer, nil)
if err != nil {
return errors.Annotate(req.err, "put into metadata failed")
}
return nil
}
func (a *Append) resolve(startTS int64) bool {
latestTS := atomic.LoadInt64(&a.latestTS)
if latestTS <= 0 {
return false
}
pbinlog, err := a.readBinlogByTS(startTS)
if err != nil {
log.Error(errors.ErrorStack(err))
return false
}
resp, err := a.helper.GetMvccByEncodedKey(pbinlog.PrewriteKey)
if err != nil {
log.Error("GetMvccByEncodedKey failed", zap.Int64("start ts", startTS), zap.Error(err))
} else if resp.RegionError != nil {
log.Error("GetMvccByEncodedKey failed", zap.Int64("start ts", startTS), zap.Stringer("RegionError", resp.RegionError))
} else if len(resp.Error) > 0 {
log.Error("GetMvccByEncodedKey failed", zap.Int64("start ts", startTS), zap.String("Error", resp.Error))
} else {
for _, w := range resp.Info.Writes {
if int64(w.StartTs) != startTS {
continue
}
if w.Type != kvrpcpb.Op_Rollback {
// Sanity checks
if int64(w.CommitTs) <= startTS {
log.Error("op type not Rollback, but have unexpect commit ts",
zap.Int64("startTS", startTS),
zap.Uint64("commitTS", w.CommitTs))
break
}
err := a.writeCBinlog(pbinlog, int64(w.CommitTs))
if err != nil {
log.Error("writeCBinlog failed", zap.Int64("start ts", startTS), zap.Error(err))
return false
}
} else {
// Will get the same value as start ts if it's rollback, set to 0 for log
w.CommitTs = 0
}
log.Info("known txn is committed or rollback from tikv",
zap.Int64("start ts", startTS),
zap.Uint64("commit ts", w.CommitTs))
return true
}
}
startSecond := oracle.ExtractPhysical(uint64(startTS)) / int64(time.Second/time.Millisecond)
maxSecond := oracle.ExtractPhysical(uint64(latestTS)) / int64(time.Second/time.Millisecond)
elapseSecond := maxSecond - startSecond
// `GetTxnStatus` will not abort valid txn now, but we still keep this logic and only `GetTxnStatus` after `maxTxnTimeoutSecond`.
// for expired locks, Pump and/or TiDB try to cleanup them should have no side effects.
if elapseSecond <= maxTxnTimeoutSecond {
log.Info(
"Find no MVCC record for a young txn",
zap.Int64("start ts", startTS),
zap.Int64("elapse sec", elapseSecond),
)
return false
}
tikvQueryCount.Add(1.0)
primaryKey := pbinlog.GetPrewriteKey()
status, err := a.tiLockResolver.GetTxnStatus(uint64(pbinlog.StartTs), uint64(pbinlog.StartTs), primaryKey)
if err != nil {
log.Error("get commit status failed for unknown txn", zap.Int64("start ts", startTS), zap.Error(err))
return false
}
log.Info("got commit status for unknown txn",
zap.Int64("start ts", startTS),
zap.Uint64("commit ts", status.CommitTS()),
zap.Uint64("ttl", status.TTL()),
zap.Reflect("action", status.Action()),
zap.Bool("isDDL", pbinlog.GetDdlJobId() > 0))
// check TTL (whether the lock is valid)
if status.TTL() > 0 {
log.Warn("the txn lock is still valid, will retry later", zap.Int64("start ts", startTS), zap.Uint64("ttl", status.TTL()))
return false
}
// Write a commit binlog myself if the status is committed,
// otherwise we can just ignore it, we will not get the commit binlog while iterator the kv by ts
if status.IsCommitted() {
// write the commit binlog myself
cbinlog := new(pb.Binlog)
cbinlog.Tp = pb.BinlogType_Commit
cbinlog.StartTs = pbinlog.StartTs
cbinlog.CommitTs = int64(status.CommitTS())
req := a.writeBinlog(cbinlog)
if req.err != nil {
log.Error("write missing committed binlog failed",
zap.Int64("start ts", startTS),
zap.Uint64("commit ts", status.CommitTS()),
zap.Bool("isDDL", pbinlog.GetDdlJobId() > 0),
zap.Error(req.err))
return false
}
// when writeBinlog return success, the pointer will be write to kv async,
// but we need to make sure it has been write to kv when we return true in the func, then we can get this commit binlog when
// we update maxCommitTS
// write the ts -> pointer to KV here to make sure it.
pointer, err := req.valuePointer.MarshalBinary()
if err != nil {
panic(err)
}
err = a.metadata.Put(encodeTSKey(req.ts()), pointer, nil)
if err != nil {
log.Error("put missing committed binlog into metadata failed",
zap.Int64("start ts", startTS),
zap.Uint64("commit ts", status.CommitTS()),
zap.Bool("isDDL", pbinlog.GetDdlJobId() > 0),
zap.Error(err))
return false
}
}
return true
}
// GetBinlog gets binlog by ts
func (a *Append) GetBinlog(ts int64) (*pb.Binlog, error) {
return a.readBinlogByTS(ts)
}
func (a *Append) readBinlogByTS(ts int64) (*pb.Binlog, error) {
var vp valuePointer
vpData, err := a.metadata.Get(encodeTSKey(ts), nil)
if err != nil {
return nil, errors.Annotatef(err, "fail read binlog by ts: %d", ts)
}
err = vp.UnmarshalBinary(vpData)
if err != nil {
return nil, errors.Annotatef(err, "fail read binlog by ts: %d", ts)
}
pvalue, err := a.vlog.readValue(vp)
if err != nil {
return nil, errors.Annotatef(err, "fail read binlog by ts: %d", ts)
}
binlog := new(pb.Binlog)
err = binlog.Unmarshal(pvalue)
if err != nil {
return nil, errors.Annotatef(err, "fail read binlog by ts: %d", ts)
}
return binlog, nil
}
// if the key not exist, return 0, nil
func (a *Append) readInt64(key []byte) (int64, error) {
value, err := a.metadata.Get(key, nil)
if err != nil {
if err == leveldb.ErrNotFound {
return 0, nil
}
return 0, errors.Trace(err)
}
return int64(binary.LittleEndian.Uint64(value)), nil
}
func (a *Append) readGCTSFromDB() (int64, error) {
return a.readInt64(gcTSKey)
}
func (a *Append) saveGCTSToDB(ts int64) error {
var value = make([]byte, 8)
binary.LittleEndian.PutUint64(value, uint64(ts))
return a.metadata.Put(gcTSKey, value, nil)
}
func (a *Append) isClosed() bool {
select {
case <-a.close:
return true
default:
return false
}
}
// Close release resource of Append
func (a *Append) Close() error {
log.Debug("close Append")
close(a.close)
close(a.writeCh)
// wait for all binlog write to vlog -> KV -> sorter
// after this, writeToValueLog, writeToKV, writeToSorter has quit sequently
a.wg.Wait()
log.Debug("wait group done")
// note the call back func will use a.metadata, so we should close sorter before a.metadata
a.sorter.close()
log.Debug("sorter is closed")
close(a.sortItems)
<-a.handleSortItemQuit
log.Debug("handle sort item quit")
err := a.metadata.Close()
if err != nil {
log.Error("close metadata failed", zap.Error(err))
}
err = a.vlog.close()
if err != nil {
log.Error("close vlog failed", zap.Error(err))
}
return err
}
// GetGCTS implement Storage.GetGCTS
func (a *Append) GetGCTS() int64 {
return atomic.LoadInt64(&a.gcTS)
}
// GC implement Storage.GC
func (a *Append) GC(ts int64) {
lastTS := atomic.LoadInt64(&a.gcTS)
if ts <= lastTS {
log.Info("ignore gc request", zap.Int64("ts", ts), zap.Int64("lastTS", lastTS))
return
}
if atomic.LoadInt64(&a.maxCommitTS) <= ts {
log.Info("Ignore unsafe gc request, may affect unsorted binlogs",
zap.Int64("ts", ts),
zap.Int64("lastTS", lastTS),
)
return
}
atomic.StoreInt64(&a.gcTS, ts)
if err := a.saveGCTSToDB(ts); err != nil {
log.Error("Failed to save GCTS", zap.Int64("ts", ts), zap.Error(err))
}
gcTSGauge.Set(float64(oracle.ExtractPhysical(uint64(ts))))
if !atomic.CompareAndSwapInt32(&a.gcWorking, 0, 1) {
return
}
go func() {
defer atomic.StoreInt32(&a.gcWorking, 0)
// for commit binlog TS ts_c, we may need to get the according P binlog ts_p(ts_p < ts_c
// so we forward a little bit to make sure we can get the according P binlog
a.doGCTS(ts - int64(EncodeTSO(maxTxnTimeoutSecond*1000)))
}()
}
func (a *Append) doGCTS(ts int64) {
log.Info("Starting GC", zap.Int64("ts", ts))
var wg sync.WaitGroup
wg.Add(1)
go func() {
a.vlog.gcTS(ts)
log.Info("Finish VLog GC", zap.Int64("ts", ts))
wg.Done()
}()
batch := new(leveldb.Batch)
l0Trigger := defaultStorageKVConfig.CompactionL0Trigger
if a.options.KVConfig != nil && a.options.KVConfig.CompactionL0Trigger > 0 {
l0Trigger = a.options.KVConfig.CompactionL0Trigger
}
deleteNum := 0
irange := &util.Range{
Start: encodeTSKey(0),
Limit: encodeTSKey(ts + 1),
}
var iter iterator.Iterator
defer func() {
if iter != nil {
iter.Release()
iter = nil
}
}()
for {
nStr, err := a.metadata.GetProperty("leveldb.num-files-at-level0")
if err != nil {
log.Error("get `leveldb.num-files-at-level0` property failed", zap.Error(err))
break
}
l0Num, err := strconv.Atoi(nStr)
if err != nil {
log.Error("parse `leveldb.num-files-at-level0` result to int failed", zap.String("str", nStr), zap.Error(err))
break
}
if l0Num >= l0Trigger {
log.Info("wait some time to gc cause too many L0 file", zap.Int("files", l0Num))
if iter != nil {
iter.Release()
iter = nil
}
time.Sleep(5 * time.Second)
continue
}
deleteBatch := 0
var lastKey []byte
if iter == nil {
log.Info("New LevelDB iterator created for GC", zap.Int64("ts", ts),
zap.Int64("start", decodeTSKey(irange.Start)),
zap.Int64("limit", decodeTSKey(irange.Limit)))
iter = a.metadata.NewIterator(irange, nil)
}
for deleteBatch < 100 && iter.Next() {
batch.Delete(iter.Key())
deleteNum++
lastKey = iter.Key()
if batch.Len() == 1024 {
err := a.metadata.Write(batch, nil)
if err != nil {
log.Error("write batch failed", zap.Error(err))
}
deletedKv.Add(float64(batch.Len()))
batch.Reset()
deleteBatch++
}
}
if deleteBatch < 100 {
if batch.Len() > 0 {
err := a.metadata.Write(batch, nil)
if err != nil {
log.Error("write batch failed", zap.Error(err))
}
deletedKv.Add(float64(batch.Len()))
batch.Reset()
}
log.Info("Finish KV GC", zap.Int64("ts", ts), zap.Int("delete num", deleteNum))
break
}
if len(lastKey) > 0 {
irange.Start = lastKey
doneGcTSGauge.Set(float64(oracle.ExtractPhysical(uint64(decodeTSKey(lastKey)))))
}
log.Info("has delete", zap.Int("delete num", deleteNum))
}
wg.Wait()
doneGcTSGauge.Set(float64(oracle.ExtractPhysical(uint64(ts))))
}
// MaxCommitTS implement Storage.MaxCommitTS
func (a *Append) MaxCommitTS() int64 {
return atomic.LoadInt64(&a.maxCommitTS)
}
func isFakeBinlog(binlog *pb.Binlog) bool {
return binlog.StartTs > 0 && binlog.StartTs == binlog.CommitTs
}
// WriteBinlog implement Storage.WriteBinlog
func (a *Append) WriteBinlog(binlog *pb.Binlog) error {
if !a.writableOfSpace() {
// still accept fake binlog, so will not block drainer if fake binlog writes success
if !isFakeBinlog(binlog) {
return errors.Errorf("no available space, available: %d, StopWriteAtAvailableSpace: %d", atomic.LoadUint64(&a.storageSize.available), a.options.StopWriteAtAvailableSpace)
}
}
// pump client will write some empty Payload to detect whether pump is working, should avoid this
// Unmarshal(nil) will success...
if binlog.StartTs == 0 && binlog.CommitTs == 0 {
return nil
}
return errors.Trace(a.writeBinlog(binlog).err)
}
func (a *Append) writeBinlog(binlog *pb.Binlog) *request {
beginTime := time.Now()
request := new(request)
defer func() {
duration := time.Since(beginTime).Seconds()
writeBinlogTimeHistogram.WithLabelValues("single").Observe(duration)
if request.err != nil {
errorCount.WithLabelValues("write_binlog").Add(1.0)
}
if duration > a.options.SlowWriteThreshold {
log.Warn("take a long time to write binlog", zap.Stringer("binlog type", binlog.Tp), zap.Int64("commit TS", binlog.CommitTs), zap.Int64("start TS", binlog.StartTs), zap.Int("length", len(binlog.PrewriteValue)), zap.Float64("cost time", duration))
}
}()
payload, err := binlog.Marshal()
if err != nil {
request.err = errors.Trace(err)
return request
}
writeBinlogSizeHistogram.WithLabelValues("single").Observe(float64(len(payload)))
request.payload = payload
request.startTS = binlog.StartTs
request.commitTS = binlog.CommitTs
request.tp = binlog.Tp
request.wg.Add(1)
a.writeCh <- request
request.wg.Wait()
return request
}
func (a *Append) writeToSorter(reqs chan *request) {
defer a.wg.Done()
for req := range reqs {
log.Debug("write request to sorter", zap.Stringer("request", req))
var item sortItem
item.start = req.startTS
item.commit = req.commitTS
item.tp = req.tp
a.sorter.pushTSItem(item)
}
}
func (a *Append) writeToKV(reqs chan *request) chan *request {
done := make(chan *request, chanCapacity)
batchReqs := a.batchRequest(reqs, 128)
go func() {
defer close(done)
for bufReqs := range batchReqs {
if err := a.writeBatchToKV(bufReqs); err != nil {
return
}
for _, req := range bufReqs {
done <- req
}
}
}()
return done
}
func (a *Append) batchRequest(reqs chan *request, maxBatchNum int) chan []*request {
done := make(chan []*request, 1024)
var bufReqs []*request
go func() {
defer close(done)
for {
if len(bufReqs) >= maxBatchNum {
done <- bufReqs
bufReqs = make([]*request, 0, maxBatchNum)
}
select {
case req, ok := <-reqs:
if !ok {
if len(bufReqs) > 0 {
done <- bufReqs
}
return
}
bufReqs = append(bufReqs, req)
default:
if len(bufReqs) > 0 {
done <- bufReqs
bufReqs = make([]*request, 0, maxBatchNum)
} else { // get first req
req, ok := <-reqs
if !ok {
return
}
bufReqs = append(bufReqs, req)
}
}
}
}()
return done
}
func (a *Append) writeToValueLog(reqs chan *request) chan *request {
ctx, cancel := context.WithCancel(context.Background())
done := make(chan *request, a.options.KVChanCapacity)
slowChaser := newSlowChaser(a.vlog, time.Second, done)
slowChaserStopped := make(chan struct{})
go func() {
slowChaser.Run(ctx)
close(slowChaserStopped)
}()
go func() {
defer func() {
cancel()
<-slowChaserStopped
close(done)
}()
var bufReqs []*request
var size int
write := func(batch []*request) {
slowChaser.WriteLock.Lock()
defer slowChaser.WriteLock.Unlock()
if len(batch) == 0 {
return
}
br := batchRequest(batch)
log.Debug("write requests to value log", zap.Stringer("requests", &br))
beginTime := time.Now()
writeBinlogSizeHistogram.WithLabelValues("batch").Observe(float64(size))
err := a.vlog.write(batch)
writeBinlogTimeHistogram.WithLabelValues("batch").Observe(time.Since(beginTime).Seconds())
if err != nil {
for _, req := range batch {
req.err = err
req.wg.Done()
}
errorCount.WithLabelValues("write_binlog_batch").Add(1.0)
return
}
for _, req := range batch {
log.Debug("request done", zap.Int64("startTS", req.startTS), zap.Int64("commitTS", req.commitTS))
req.wg.Done()
// payload is useless anymore, let it GC ASAP
req.payload = nil
}
if slowChaser.IsOn() {
return
}
SEND:
for _, req := range batch {
select {
case done <- req:
case <-time.After(slowChaserThreshold):
slowChaser.TurnOn(&req.valuePointer)
break SEND
}
}