-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathgc_worker.go
1767 lines (1584 loc) · 57.1 KB
/
gc_worker.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 2017 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,
// 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 gcworker
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/errorpb"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/tidb/pkg/ddl"
"github.com/pingcap/tidb/pkg/ddl/label"
"github.com/pingcap/tidb/pkg/ddl/placement"
"github.com/pingcap/tidb/pkg/ddl/util"
"github.com/pingcap/tidb/pkg/domain/infosync"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/metrics"
"github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/terror"
"github.com/pingcap/tidb/pkg/privilege"
"github.com/pingcap/tidb/pkg/session"
sessiontypes "github.com/pingcap/tidb/pkg/session/types"
"github.com/pingcap/tidb/pkg/sessionctx/variable"
"github.com/pingcap/tidb/pkg/tablecodec"
"github.com/pingcap/tidb/pkg/util/codec"
"github.com/pingcap/tidb/pkg/util/dbterror"
"github.com/pingcap/tidb/pkg/util/logutil"
tikverr "github.com/tikv/client-go/v2/error"
tikvstore "github.com/tikv/client-go/v2/kv"
"github.com/tikv/client-go/v2/oracle"
"github.com/tikv/client-go/v2/tikv"
"github.com/tikv/client-go/v2/tikvrpc"
"github.com/tikv/client-go/v2/txnkv/rangetask"
tikvutil "github.com/tikv/client-go/v2/util"
pd "github.com/tikv/pd/client"
"go.uber.org/zap"
)
// GCWorker periodically triggers GC process on tikv server.
type GCWorker struct {
uuid string
desc string
store kv.Storage
tikvStore tikv.Storage
pdClient pd.Client
gcIsRunning bool
lastFinish time.Time
cancel context.CancelFunc
done chan error
regionLockResolver tikv.RegionLockResolver
}
// NewGCWorker creates a GCWorker instance.
func NewGCWorker(store kv.Storage, pdClient pd.Client) (*GCWorker, error) {
ver, err := store.CurrentVersion(kv.GlobalTxnScope)
if err != nil {
return nil, errors.Trace(err)
}
hostName, err := os.Hostname()
if err != nil {
hostName = "unknown"
}
tikvStore, ok := store.(tikv.Storage)
if !ok {
return nil, errors.New("GC should run against TiKV storage")
}
uuid := strconv.FormatUint(ver.Ver, 16)
resolverIdentifier := fmt.Sprintf("gc-worker-%s", uuid)
worker := &GCWorker{
uuid: uuid,
desc: fmt.Sprintf("host:%s, pid:%d, start at %s", hostName, os.Getpid(), time.Now()),
store: store,
tikvStore: tikvStore,
pdClient: pdClient,
gcIsRunning: false,
lastFinish: time.Now(),
regionLockResolver: tikv.NewRegionLockResolver(resolverIdentifier, tikvStore),
done: make(chan error),
}
variable.RegisterStatistics(worker)
return worker, nil
}
// Start starts the worker.
func (w *GCWorker) Start() {
var ctx context.Context
ctx, w.cancel = context.WithCancel(context.Background())
ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnGC)
var wg sync.WaitGroup
wg.Add(1)
go w.start(ctx, &wg)
wg.Wait() // Wait create session finish in worker, some test code depend on this to avoid race.
}
// Close stops background goroutines.
func (w *GCWorker) Close() {
w.cancel()
}
const (
booleanTrue = "true"
booleanFalse = "false"
gcWorkerTickInterval = time.Minute
gcWorkerLease = time.Minute * 2
gcLeaderUUIDKey = "tikv_gc_leader_uuid"
gcLeaderDescKey = "tikv_gc_leader_desc"
gcLeaderLeaseKey = "tikv_gc_leader_lease"
gcLastRunTimeKey = "tikv_gc_last_run_time"
gcRunIntervalKey = "tikv_gc_run_interval"
gcDefaultRunInterval = time.Minute * 10
gcWaitTime = time.Minute * 1
gcRedoDeleteRangeDelay = 24 * time.Hour
gcLifeTimeKey = "tikv_gc_life_time"
gcDefaultLifeTime = time.Minute * 10
gcMinLifeTime = time.Minute * 10
gcSafePointKey = "tikv_gc_safe_point"
gcConcurrencyKey = "tikv_gc_concurrency"
gcDefaultConcurrency = 2
gcMinConcurrency = 1
gcMaxConcurrency = 128
gcEnableKey = "tikv_gc_enable"
gcDefaultEnableValue = true
gcModeKey = "tikv_gc_mode"
gcModeCentral = "central"
gcModeDistributed = "distributed"
gcModeDefault = gcModeDistributed
gcScanLockModeKey = "tikv_gc_scan_lock_mode"
gcAutoConcurrencyKey = "tikv_gc_auto_concurrency"
gcDefaultAutoConcurrency = true
gcWorkerServiceSafePointID = "gc_worker"
// Status var names start with tidb_%
tidbGCLastRunTime = "tidb_gc_last_run_time"
tidbGCLeaderDesc = "tidb_gc_leader_desc"
tidbGCLeaderLease = "tidb_gc_leader_lease"
tidbGCLeaderUUID = "tidb_gc_leader_uuid"
tidbGCSafePoint = "tidb_gc_safe_point"
)
var gcSafePointCacheInterval = tikv.GcSafePointCacheInterval
var gcVariableComments = map[string]string{
gcLeaderUUIDKey: "Current GC worker leader UUID. (DO NOT EDIT)",
gcLeaderDescKey: "Host name and pid of current GC leader. (DO NOT EDIT)",
gcLeaderLeaseKey: "Current GC worker leader lease. (DO NOT EDIT)",
gcLastRunTimeKey: "The time when last GC starts. (DO NOT EDIT)",
gcRunIntervalKey: "GC run interval, at least 10m, in Go format.",
gcLifeTimeKey: "All versions within life time will not be collected by GC, at least 10m, in Go format.",
gcSafePointKey: "All versions after safe point can be accessed. (DO NOT EDIT)",
gcConcurrencyKey: "How many goroutines used to do GC parallel, [1, 128], default 2",
gcEnableKey: "Current GC enable status",
gcModeKey: "Mode of GC, \"central\" or \"distributed\"",
gcAutoConcurrencyKey: "Let TiDB pick the concurrency automatically. If set false, tikv_gc_concurrency will be used",
gcScanLockModeKey: "Mode of scanning locks, \"physical\" or \"legacy\".(Deprecated)",
}
const (
unsafeDestroyRangeTimeout = 5 * time.Minute
gcTimeout = 5 * time.Minute
)
func (w *GCWorker) start(ctx context.Context, wg *sync.WaitGroup) {
logutil.Logger(ctx).Info("start", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid))
w.tick(ctx) // Immediately tick once to initialize configs.
wg.Done()
ticker := time.NewTicker(gcWorkerTickInterval)
defer ticker.Stop()
defer func() {
r := recover()
if r != nil {
logutil.Logger(ctx).Error("gcWorker",
zap.Any("r", r),
zap.Stack("stack"))
metrics.PanicCounter.WithLabelValues(metrics.LabelGCWorker).Inc()
}
}()
for {
select {
case <-ticker.C:
w.tick(ctx)
case err := <-w.done:
w.gcIsRunning = false
w.lastFinish = time.Now()
if err != nil {
logutil.Logger(ctx).Error("runGCJob", zap.String("category", "gc worker"), zap.Error(err))
}
case <-ctx.Done():
logutil.Logger(ctx).Info("quit", zap.String("category", "gc worker"), zap.String("uuid", w.uuid))
return
}
}
}
func createSession(store kv.Storage) sessiontypes.Session {
for {
se, err := session.CreateSession(store)
if err != nil {
logutil.BgLogger().Warn("create session", zap.String("category", "gc worker"), zap.Error(err))
continue
}
// Disable privilege check for gc worker session.
privilege.BindPrivilegeManager(se, nil)
se.GetSessionVars().CommonGlobalLoaded = true
se.GetSessionVars().InRestrictedSQL = true
se.GetSessionVars().SetDiskFullOpt(kvrpcpb.DiskFullOpt_AllowedOnAlmostFull)
return se
}
}
// GetScope gets the status variables scope.
func (w *GCWorker) GetScope(status string) variable.ScopeFlag {
return variable.DefaultStatusVarScopeFlag
}
// Stats returns the server statistics.
func (w *GCWorker) Stats(vars *variable.SessionVars) (map[string]any, error) {
m := make(map[string]any)
if v, err := w.loadValueFromSysTable(gcLeaderUUIDKey); err == nil {
m[tidbGCLeaderUUID] = v
}
if v, err := w.loadValueFromSysTable(gcLeaderDescKey); err == nil {
m[tidbGCLeaderDesc] = v
}
if v, err := w.loadValueFromSysTable(gcLeaderLeaseKey); err == nil {
m[tidbGCLeaderLease] = v
}
if v, err := w.loadValueFromSysTable(gcLastRunTimeKey); err == nil {
m[tidbGCLastRunTime] = v
}
if v, err := w.loadValueFromSysTable(gcSafePointKey); err == nil {
m[tidbGCSafePoint] = v
}
return m, nil
}
func (w *GCWorker) tick(ctx context.Context) {
isLeader, err := w.checkLeader(ctx)
if err != nil {
logutil.Logger(ctx).Warn("check leader", zap.String("category", "gc worker"), zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("check_leader").Inc()
return
}
if isLeader {
err = w.leaderTick(ctx)
if err != nil {
logutil.Logger(ctx).Warn("leader tick", zap.String("category", "gc worker"), zap.Error(err))
}
} else {
// Config metrics should always be updated by leader, set them to 0 when current instance is not leader.
metrics.GCConfigGauge.WithLabelValues(gcRunIntervalKey).Set(0)
metrics.GCConfigGauge.WithLabelValues(gcLifeTimeKey).Set(0)
}
}
// getGCSafePoint returns the current gc safe point.
func getGCSafePoint(ctx context.Context, pdClient pd.Client) (uint64, error) {
// If there is try to set gc safepoint is 0, the interface will not set gc safepoint to 0,
// it will return current gc safepoint.
safePoint, err := pdClient.UpdateGCSafePoint(ctx, 0)
if err != nil {
return 0, errors.Trace(err)
}
return safePoint, nil
}
func (w *GCWorker) logIsGCSafePointTooEarly(ctx context.Context, safePoint uint64) error {
now, err := w.getOracleTime()
if err != nil {
return errors.Trace(err)
}
checkTs := oracle.GoTimeToTS(now.Add(-gcDefaultLifeTime * 2))
if checkTs > safePoint {
logutil.Logger(ctx).Info("gc safepoint is too early. "+
"Maybe there is a bit BR/Lightning/CDC task, "+
"or a long transaction is running "+
"or need a tidb without setting keyspace-name to calculate and update gc safe point.",
zap.String("category", "gc worker"))
}
return nil
}
func (w *GCWorker) runKeyspaceDeleteRange(ctx context.Context, concurrency int) error {
// Get safe point from PD.
// The GC safe point is updated only after the global GC have done resolveLocks phase globally.
// So, in the following code, resolveLocks must have been done by the global GC on the ranges to be deleted,
// so its safe to delete the ranges.
safePoint, err := getGCSafePoint(ctx, w.pdClient)
if err != nil {
logutil.Logger(ctx).Info("get gc safe point error", zap.String("category", "gc worker"), zap.Error(errors.Trace(err)))
return nil
}
if safePoint == 0 {
logutil.Logger(ctx).Info("skip keyspace delete range, because gc safe point is 0", zap.String("category", "gc worker"))
return nil
}
err = w.logIsGCSafePointTooEarly(ctx, safePoint)
if err != nil {
logutil.Logger(ctx).Info("log is gc safe point is too early error", zap.String("category", "gc worker"), zap.Error(errors.Trace(err)))
return nil
}
keyspaceID := w.store.GetCodec().GetKeyspaceID()
logutil.Logger(ctx).Info("start keyspace delete range", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Int("concurrency", concurrency),
zap.Uint32("keyspaceID", uint32(keyspaceID)),
zap.Uint64("GCSafepoint", safePoint))
// Do deleteRanges.
err = w.deleteRanges(ctx, safePoint, concurrency)
if err != nil {
logutil.Logger(ctx).Error("delete range returns an error", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("delete_range").Inc()
return errors.Trace(err)
}
// Do redoDeleteRanges.
err = w.redoDeleteRanges(ctx, safePoint, concurrency)
if err != nil {
logutil.Logger(ctx).Error("redo-delete range returns an error", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("redo_delete_range").Inc()
return errors.Trace(err)
}
return nil
}
// leaderTick of GC worker checks if it should start a GC job every tick.
func (w *GCWorker) leaderTick(ctx context.Context) error {
if w.gcIsRunning {
logutil.Logger(ctx).Info("there's already a gc job running, skipped", zap.String("category", "gc worker"),
zap.String("leaderTick on", w.uuid))
return nil
}
concurrency, err := w.getGCConcurrency(ctx)
if err != nil {
logutil.Logger(ctx).Info("failed to get gc concurrency.", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
return errors.Trace(err)
}
// Gc safe point is not separated by keyspace now. The whole cluster has only one global gc safe point.
// So at least one TiDB with `keyspace-name` not set is required in the whole cluster to calculate and update gc safe point.
// If `keyspace-name` is set, the TiDB node will only do its own delete range, and will not calculate gc safe point and resolve locks.
// Note that when `keyspace-name` is set, `checkLeader` will be done within the key space.
// Therefore only one TiDB node in each key space will be responsible to do delete range.
if w.store.GetCodec().GetKeyspace() != nil {
err = w.runKeyspaceGCJob(ctx, concurrency)
if err != nil {
return errors.Trace(err)
}
return nil
}
ok, safePoint, err := w.prepare(ctx)
if err != nil {
metrics.GCJobFailureCounter.WithLabelValues("prepare").Inc()
return errors.Trace(err)
} else if !ok {
return nil
}
// When the worker is just started, or an old GC job has just finished,
// wait a while before starting a new job.
if time.Since(w.lastFinish) < gcWaitTime {
logutil.Logger(ctx).Info("another gc job has just finished, skipped.", zap.String("category", "gc worker"),
zap.String("leaderTick on ", w.uuid))
return nil
}
w.gcIsRunning = true
logutil.Logger(ctx).Info("starts the whole job", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Uint64("safePoint", safePoint),
zap.Int("concurrency", concurrency))
go func() {
w.done <- w.runGCJob(ctx, safePoint, concurrency)
}()
return nil
}
func (w *GCWorker) runKeyspaceGCJob(ctx context.Context, concurrency int) error {
// When the worker is just started, or an old GC job has just finished,
// wait a while before starting a new job.
if time.Since(w.lastFinish) < gcWaitTime {
logutil.Logger(ctx).Info("another keyspace gc job has just finished, skipped.", zap.String("category", "gc worker"),
zap.String("leaderTick on ", w.uuid))
return nil
}
now, err := w.getOracleTime()
if err != nil {
return errors.Trace(err)
}
ok, err := w.checkGCInterval(now)
if err != nil || !ok {
return errors.Trace(err)
}
go func() {
w.done <- w.runKeyspaceDeleteRange(ctx, concurrency)
}()
err = w.saveTime(gcLastRunTimeKey, now)
if err != nil {
return errors.Trace(err)
}
return nil
}
// prepare checks preconditions for starting a GC job. It returns a bool
// that indicates whether the GC job should start and the new safePoint.
func (w *GCWorker) prepare(ctx context.Context) (bool, uint64, error) {
// Add a transaction here is to prevent following situations:
// 1. GC check gcEnable is true, continue to do GC
// 2. The user sets gcEnable to false
// 3. The user gets `tikv_gc_safe_point` value is t1, then the user thinks the data after time t1 won't be clean by GC.
// 4. GC update `tikv_gc_safe_point` value to t2, continue do GC in this round.
// Then the data record that has been dropped between time t1 and t2, will be cleaned by GC, but the user thinks the data after t1 won't be clean by GC.
se := createSession(w.store)
defer se.Close()
_, err := se.ExecuteInternal(ctx, "BEGIN")
if err != nil {
return false, 0, errors.Trace(err)
}
doGC, safePoint, err := w.checkPrepare(ctx)
if doGC {
err = se.CommitTxn(ctx)
if err != nil {
return false, 0, errors.Trace(err)
}
} else {
se.RollbackTxn(ctx)
}
return doGC, safePoint, errors.Trace(err)
}
func (w *GCWorker) checkPrepare(ctx context.Context) (bool, uint64, error) {
enable, err := w.checkGCEnable()
if err != nil {
return false, 0, errors.Trace(err)
}
if !enable {
logutil.Logger(ctx).Warn("gc status is disabled.", zap.String("category", "gc worker"))
return false, 0, nil
}
now, err := w.getOracleTime()
if err != nil {
return false, 0, errors.Trace(err)
}
ok, err := w.checkGCInterval(now)
if err != nil || !ok {
return false, 0, errors.Trace(err)
}
newSafePoint, newSafePointValue, err := w.calcNewSafePoint(ctx, now)
if err != nil || newSafePoint == nil {
return false, 0, errors.Trace(err)
}
err = w.saveTime(gcLastRunTimeKey, now)
if err != nil {
return false, 0, errors.Trace(err)
}
err = w.saveTime(gcSafePointKey, *newSafePoint)
if err != nil {
return false, 0, errors.Trace(err)
}
return true, newSafePointValue, nil
}
func (w *GCWorker) calcGlobalMinStartTS(ctx context.Context) (uint64, error) {
kvs, err := w.tikvStore.GetSafePointKV().GetWithPrefix(infosync.ServerMinStartTSPath)
if err != nil {
return 0, err
}
var globalMinStartTS uint64 = math.MaxUint64
for _, v := range kvs {
minStartTS, err := strconv.ParseUint(string(v.Value), 10, 64)
if err != nil {
logutil.Logger(ctx).Warn("parse minStartTS failed", zap.Error(err))
continue
}
if minStartTS < globalMinStartTS {
globalMinStartTS = minStartTS
}
}
return globalMinStartTS, nil
}
// calcNewSafePoint uses the current global transaction min start timestamp to calculate the new safe point.
func (w *GCWorker) calcSafePointByMinStartTS(ctx context.Context, safePoint uint64) uint64 {
globalMinStartTS, err := w.calcGlobalMinStartTS(ctx)
if err != nil {
logutil.Logger(ctx).Warn("get all minStartTS failed", zap.Error(err))
return safePoint
}
// If the lock.ts <= max_ts(safePoint), it will be collected and resolved by the gc worker,
// the locks of ongoing pessimistic transactions could be resolved by the gc worker and then
// the transaction is aborted, decrement the value by 1 to avoid this.
globalMinStartAllowedTS := globalMinStartTS
if globalMinStartTS > 0 {
globalMinStartAllowedTS = globalMinStartTS - 1
}
if globalMinStartAllowedTS < safePoint {
logutil.Logger(ctx).Info("gc safepoint blocked by a running session", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Uint64("globalMinStartTS", globalMinStartTS),
zap.Uint64("globalMinStartAllowedTS", globalMinStartAllowedTS),
zap.Uint64("safePoint", safePoint))
safePoint = globalMinStartAllowedTS
}
return safePoint
}
func (w *GCWorker) getOracleTime() (time.Time, error) {
currentVer, err := w.store.CurrentVersion(kv.GlobalTxnScope)
if err != nil {
return time.Time{}, errors.Trace(err)
}
return oracle.GetTimeFromTS(currentVer.Ver), nil
}
func (w *GCWorker) checkGCEnable() (bool, error) {
return w.loadBooleanWithDefault(gcEnableKey, gcDefaultEnableValue)
}
func (w *GCWorker) checkUseAutoConcurrency() (bool, error) {
return w.loadBooleanWithDefault(gcAutoConcurrencyKey, gcDefaultAutoConcurrency)
}
func (w *GCWorker) loadBooleanWithDefault(key string, defaultValue bool) (bool, error) {
str, err := w.loadValueFromSysTable(key)
if err != nil {
return false, errors.Trace(err)
}
if str == "" {
// Save default value for gc enable key. The default value is always true.
defaultValueStr := booleanFalse
if defaultValue {
defaultValueStr = booleanTrue
}
err = w.saveValueToSysTable(key, defaultValueStr)
if err != nil {
return defaultValue, errors.Trace(err)
}
return defaultValue, nil
}
return strings.EqualFold(str, booleanTrue), nil
}
func (w *GCWorker) getGCConcurrency(ctx context.Context) (int, error) {
useAutoConcurrency, err := w.checkUseAutoConcurrency()
if err != nil {
logutil.Logger(ctx).Error("failed to load config gc_auto_concurrency. use default value.", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
useAutoConcurrency = gcDefaultAutoConcurrency
}
if !useAutoConcurrency {
return w.loadGCConcurrencyWithDefault()
}
stores, err := w.getStoresForGC(ctx)
concurrency := len(stores)
if err != nil {
logutil.Logger(ctx).Error("failed to get up stores to calculate concurrency. use config.", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
concurrency, err = w.loadGCConcurrencyWithDefault()
if err != nil {
logutil.Logger(ctx).Error("failed to load gc concurrency from config. use default value.", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
concurrency = gcDefaultConcurrency
}
}
if concurrency == 0 {
logutil.Logger(ctx).Error("no store is up", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid))
return 0, errors.New("[gc worker] no store is up")
}
return concurrency, nil
}
func (w *GCWorker) checkGCInterval(now time.Time) (bool, error) {
runInterval, err := w.loadDurationWithDefault(gcRunIntervalKey, gcDefaultRunInterval)
if err != nil {
return false, errors.Trace(err)
}
metrics.GCConfigGauge.WithLabelValues(gcRunIntervalKey).Set(runInterval.Seconds())
lastRun, err := w.loadTime(gcLastRunTimeKey)
if err != nil {
return false, errors.Trace(err)
}
if lastRun != nil && lastRun.Add(*runInterval).After(now) {
logutil.BgLogger().Debug("skipping garbage collection because gc interval hasn't elapsed since last run", zap.String("category", "gc worker"),
zap.String("leaderTick on", w.uuid),
zap.Duration("interval", *runInterval),
zap.Time("last run", *lastRun))
return false, nil
}
return true, nil
}
// validateGCLifeTime checks whether life time is small than min gc life time.
func (w *GCWorker) validateGCLifeTime(lifeTime time.Duration) (time.Duration, error) {
if lifeTime >= gcMinLifeTime {
return lifeTime, nil
}
logutil.BgLogger().Info("invalid gc life time", zap.String("category", "gc worker"),
zap.Duration("get gc life time", lifeTime),
zap.Duration("min gc life time", gcMinLifeTime))
err := w.saveDuration(gcLifeTimeKey, gcMinLifeTime)
return gcMinLifeTime, err
}
func (w *GCWorker) calcNewSafePoint(ctx context.Context, now time.Time) (*time.Time, uint64, error) {
lifeTime, err := w.loadDurationWithDefault(gcLifeTimeKey, gcDefaultLifeTime)
if err != nil {
return nil, 0, errors.Trace(err)
}
*lifeTime, err = w.validateGCLifeTime(*lifeTime)
if err != nil {
return nil, 0, err
}
metrics.GCConfigGauge.WithLabelValues(gcLifeTimeKey).Set(lifeTime.Seconds())
lastSafePoint, err := w.loadTime(gcSafePointKey)
if err != nil {
return nil, 0, errors.Trace(err)
}
safePointValue := w.calcSafePointByMinStartTS(ctx, oracle.GoTimeToTS(now.Add(-*lifeTime)))
safePointValue, err = w.setGCWorkerServiceSafePoint(ctx, safePointValue)
if err != nil {
return nil, 0, errors.Trace(err)
}
// safepoint is recorded in time.Time format which strips the logical part of the timestamp.
// To prevent the GC worker from keeping working due to the loss of logical part when the
// safe point isn't changed, we should compare them in time.Time format.
safePoint := oracle.GetTimeFromTS(safePointValue)
// We should never decrease safePoint.
if lastSafePoint != nil && !safePoint.After(*lastSafePoint) {
logutil.BgLogger().Info("last safe point is later than current one."+
"No need to gc."+
"This might be caused by manually enlarging gc lifetime",
zap.String("category", "gc worker"),
zap.String("leaderTick on", w.uuid),
zap.Time("last safe point", *lastSafePoint),
zap.Time("current safe point", safePoint))
return nil, 0, nil
}
return &safePoint, safePointValue, nil
}
// setGCWorkerServiceSafePoint sets the given safePoint as TiDB's service safePoint to PD, and returns the current minimal
// service safePoint among all services.
func (w *GCWorker) setGCWorkerServiceSafePoint(ctx context.Context, safePoint uint64) (uint64, error) {
// Sets TTL to MAX to make it permanently valid.
minSafePoint, err := w.pdClient.UpdateServiceGCSafePoint(ctx, gcWorkerServiceSafePointID, math.MaxInt64, safePoint)
if err != nil {
logutil.Logger(ctx).Error("failed to update service safe point", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("update_service_safe_point").Inc()
return 0, errors.Trace(err)
}
if minSafePoint < safePoint {
logutil.Logger(ctx).Info("there's another service in the cluster requires an earlier safe point. "+
"gc will continue with the earlier one",
zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Uint64("ourSafePoint", safePoint),
zap.Uint64("minSafePoint", minSafePoint),
)
safePoint = minSafePoint
}
return safePoint, nil
}
func (w *GCWorker) runGCJob(ctx context.Context, safePoint uint64, concurrency int) error {
failpoint.Inject("mockRunGCJobFail", func() {
failpoint.Return(errors.New("mock failure of runGCJoB"))
})
metrics.GCWorkerCounter.WithLabelValues("run_job").Inc()
err := w.resolveLocks(ctx, safePoint, concurrency)
if err != nil {
logutil.Logger(ctx).Error("resolve locks returns an error", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("resolve_lock").Inc()
return errors.Trace(err)
}
// Save safe point to pd.
err = w.saveSafePoint(w.tikvStore.GetSafePointKV(), safePoint)
if err != nil {
logutil.Logger(ctx).Error("failed to save safe point to PD", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("save_safe_point").Inc()
return errors.Trace(err)
}
// Sleep to wait for all other tidb instances update their safepoint cache.
time.Sleep(gcSafePointCacheInterval)
err = w.deleteRanges(ctx, safePoint, concurrency)
if err != nil {
logutil.Logger(ctx).Error("delete range returns an error", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("delete_range").Inc()
return errors.Trace(err)
}
err = w.redoDeleteRanges(ctx, safePoint, concurrency)
if err != nil {
logutil.Logger(ctx).Error("redo-delete range returns an error", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("redo_delete_range").Inc()
return errors.Trace(err)
}
if w.checkUseDistributedGC() {
err = w.uploadSafePointToPD(ctx, safePoint)
if err != nil {
logutil.Logger(ctx).Error("failed to upload safe point to PD", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("upload_safe_point").Inc()
return errors.Trace(err)
}
} else {
err = w.doGC(ctx, safePoint, concurrency)
if err != nil {
logutil.Logger(ctx).Error("do GC returns an error", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCJobFailureCounter.WithLabelValues("gc").Inc()
return errors.Trace(err)
}
}
return nil
}
// deleteRanges processes all delete range records whose ts < safePoint in table `gc_delete_range`
// `concurrency` specifies the concurrency to send NotifyDeleteRange.
func (w *GCWorker) deleteRanges(ctx context.Context, safePoint uint64, concurrency int) error {
metrics.GCWorkerCounter.WithLabelValues("delete_range").Inc()
se := createSession(w.store)
defer se.Close()
ranges, err := util.LoadDeleteRanges(ctx, se, safePoint)
if err != nil {
return errors.Trace(err)
}
v2, err := util.IsRaftKv2(ctx, se)
if err != nil {
return errors.Trace(err)
}
// Cache table ids on which placement rules have been GC-ed, to avoid redundantly GC the same table id multiple times.
gcPlacementRuleCache := make(map[int64]any, len(ranges))
logutil.Logger(ctx).Info("start delete ranges", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Int("ranges", len(ranges)))
startTime := time.Now()
for _, r := range ranges {
startKey, endKey := r.Range()
if v2 {
// In raftstore-v2, we use delete range instead to avoid deletion omission
task := rangetask.NewDeleteRangeTask(w.tikvStore, startKey, endKey, concurrency)
err = task.Execute(ctx)
} else {
err = w.doUnsafeDestroyRangeRequest(ctx, startKey, endKey, concurrency)
}
failpoint.Inject("ignoreDeleteRangeFailed", func() {
err = nil
})
if err != nil {
logutil.Logger(ctx).Error("delete range failed on range", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Stringer("startKey", startKey),
zap.Stringer("endKey", endKey),
zap.Error(err))
continue
}
if err := w.doGCPlacementRules(se, safePoint, r, gcPlacementRuleCache); err != nil {
logutil.Logger(ctx).Error("gc placement rules failed on range", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Int64("jobID", r.JobID),
zap.Int64("elementID", r.ElementID),
zap.Error(err))
continue
}
if err := w.doGCLabelRules(r); err != nil {
logutil.Logger(ctx).Error("gc label rules failed on range", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Int64("jobID", r.JobID),
zap.Int64("elementID", r.ElementID),
zap.Error(err))
continue
}
err = util.CompleteDeleteRange(se, r, !v2)
if err != nil {
logutil.Logger(ctx).Error("failed to mark delete range task done", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Stringer("startKey", startKey),
zap.Stringer("endKey", endKey),
zap.Error(err))
metrics.GCUnsafeDestroyRangeFailuresCounterVec.WithLabelValues("save").Inc()
}
}
logutil.Logger(ctx).Info("finish delete ranges", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Int("num of ranges", len(ranges)),
zap.Duration("cost time", time.Since(startTime)))
metrics.GCHistogram.WithLabelValues("delete_ranges").Observe(time.Since(startTime).Seconds())
return nil
}
// redoDeleteRanges checks all deleted ranges whose ts is at least `lifetime + 24h` ago. See TiKV RFC #2.
// `concurrency` specifies the concurrency to send NotifyDeleteRange.
func (w *GCWorker) redoDeleteRanges(ctx context.Context, safePoint uint64, concurrency int) error {
metrics.GCWorkerCounter.WithLabelValues("redo_delete_range").Inc()
// We check delete range records that are deleted about 24 hours ago.
redoDeleteRangesTs := safePoint - oracle.ComposeTS(int64(gcRedoDeleteRangeDelay.Seconds())*1000, 0)
se := createSession(w.store)
ranges, err := util.LoadDoneDeleteRanges(ctx, se, redoDeleteRangesTs)
se.Close()
if err != nil {
return errors.Trace(err)
}
logutil.Logger(ctx).Info("start redo-delete ranges", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Int("num of ranges", len(ranges)))
startTime := time.Now()
for _, r := range ranges {
startKey, endKey := r.Range()
err = w.doUnsafeDestroyRangeRequest(ctx, startKey, endKey, concurrency)
if err != nil {
logutil.Logger(ctx).Error("redo-delete range failed on range", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Stringer("startKey", startKey),
zap.Stringer("endKey", endKey),
zap.Error(err))
continue
}
se := createSession(w.store)
err := util.DeleteDoneRecord(se, r)
se.Close()
if err != nil {
logutil.Logger(ctx).Error("failed to remove delete_range_done record", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Stringer("startKey", startKey),
zap.Stringer("endKey", endKey),
zap.Error(err))
metrics.GCUnsafeDestroyRangeFailuresCounterVec.WithLabelValues("save_redo").Inc()
}
}
logutil.Logger(ctx).Info("finish redo-delete ranges", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Int("num of ranges", len(ranges)),
zap.Duration("cost time", time.Since(startTime)))
metrics.GCHistogram.WithLabelValues("redo_delete_ranges").Observe(time.Since(startTime).Seconds())
return nil
}
func (w *GCWorker) doUnsafeDestroyRangeRequest(ctx context.Context, startKey []byte, endKey []byte, concurrency int) error {
// Get all stores every time deleting a region. So the store list is less probably to be stale.
stores, err := w.getStoresForGC(ctx)
if err != nil {
logutil.Logger(ctx).Error("delete ranges: got an error while trying to get store list from PD", zap.String("category", "gc worker"),
zap.String("uuid", w.uuid),
zap.Error(err))
metrics.GCUnsafeDestroyRangeFailuresCounterVec.WithLabelValues("get_stores").Inc()
return errors.Trace(err)
}
req := tikvrpc.NewRequest(tikvrpc.CmdUnsafeDestroyRange, &kvrpcpb.UnsafeDestroyRangeRequest{
StartKey: startKey,
EndKey: endKey,
}, kvrpcpb.Context{DiskFullOpt: kvrpcpb.DiskFullOpt_AllowedOnAlmostFull})
var wg sync.WaitGroup
errChan := make(chan error, len(stores))
for _, store := range stores {
address := store.Address
storeID := store.Id
wg.Add(1)
go func() {
defer wg.Done()
resp, err1 := w.tikvStore.GetTiKVClient().SendRequest(ctx, address, req, unsafeDestroyRangeTimeout)
if err1 == nil {
if resp == nil || resp.Resp == nil {
err1 = errors.Errorf("unsafe destroy range returns nil response from store %v", storeID)
} else {
errStr := (resp.Resp.(*kvrpcpb.UnsafeDestroyRangeResponse)).Error
if len(errStr) > 0 {
err1 = errors.Errorf("unsafe destroy range failed on store %v: %s", storeID, errStr)
}
}
}
if err1 != nil {
metrics.GCUnsafeDestroyRangeFailuresCounterVec.WithLabelValues("send").Inc()
}
errChan <- err1
}()
}
var errs []string
for range stores {
err1 := <-errChan
if err1 != nil {
errs = append(errs, err1.Error())
}
}
wg.Wait()
if len(errs) > 0 {
return errors.Errorf("[gc worker] destroy range finished with errors: %v", errs)
}
return nil
}
// needsGCOperationForStore checks if the store-level requests related to GC needs to be sent to the store. The store-level
// requests includes UnsafeDestroyRange, PhysicalScanLock, etc.
func needsGCOperationForStore(store *metapb.Store) (bool, error) {
// TombStone means the store has been removed from the cluster and there isn't any peer on the store, so needn't do GC for it.