forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
1568 lines (1395 loc) · 52.6 KB
/
client.go
File metadata and controls
1568 lines (1395 loc) · 52.6 KB
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 2024 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 snapclient
import (
"bytes"
"cmp"
"context"
"crypto/tls"
"encoding/json"
"math"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
backuppb "github.com/pingcap/kvproto/pkg/brpb"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/log"
"github.com/pingcap/tidb/br/pkg/checkpoint"
"github.com/pingcap/tidb/br/pkg/checksum"
"github.com/pingcap/tidb/br/pkg/conn"
"github.com/pingcap/tidb/br/pkg/conn/util"
berrors "github.com/pingcap/tidb/br/pkg/errors"
"github.com/pingcap/tidb/br/pkg/glue"
"github.com/pingcap/tidb/br/pkg/logutil"
"github.com/pingcap/tidb/br/pkg/metautil"
"github.com/pingcap/tidb/br/pkg/pdutil"
"github.com/pingcap/tidb/br/pkg/restore"
importclient "github.com/pingcap/tidb/br/pkg/restore/internal/import_client"
tidallocdb "github.com/pingcap/tidb/br/pkg/restore/internal/prealloc_db"
tidalloc "github.com/pingcap/tidb/br/pkg/restore/internal/prealloc_table_id"
"github.com/pingcap/tidb/br/pkg/restore/split"
restoreutils "github.com/pingcap/tidb/br/pkg/restore/utils"
"github.com/pingcap/tidb/br/pkg/stream"
"github.com/pingcap/tidb/br/pkg/summary"
"github.com/pingcap/tidb/br/pkg/utils"
"github.com/pingcap/tidb/br/pkg/version"
"github.com/pingcap/tidb/pkg/ddl/label"
"github.com/pingcap/tidb/pkg/domain"
"github.com/pingcap/tidb/pkg/domain/infosync"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/meta"
"github.com/pingcap/tidb/pkg/meta/model"
"github.com/pingcap/tidb/pkg/metrics"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/parser/mysql"
tidbutil "github.com/pingcap/tidb/pkg/util"
"github.com/pingcap/tidb/pkg/util/redact"
kvutil "github.com/tikv/client-go/v2/util"
pd "github.com/tikv/pd/client"
pdhttp "github.com/tikv/pd/client/http"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc/keepalive"
)
const (
strictPlacementPolicyMode = "STRICT"
ignorePlacementPolicyMode = "IGNORE"
resetSpeedLimitRetryTimes = 3
defaultDDLConcurrency = 64
maxSplitKeysOnce = 10240
)
const minBatchDdlSize = 1
type SnapClient struct {
restorer restore.SstRestorer
importer *SnapFileImporter
// Use a closure to lazy load checkpoint runner
getRestorerFn func(*checkpoint.CheckpointRunner[checkpoint.RestoreKeyType, checkpoint.RestoreValueType]) restore.SstRestorer
// Tool clients used by SnapClient
pdClient pd.Client
pdHTTPClient pdhttp.Client
// User configurable parameters
cipher *backuppb.CipherInfo
concurrencyPerStore uint
regionScanConcurrency uint
keepaliveConf keepalive.ClientParameters
rateLimit uint64
tlsConf *tls.Config
switchCh chan struct{}
storeCount int
supportPolicy bool
workerPool *tidbutil.WorkerPool
noSchema bool
databases map[string]*metautil.Database
ddlJobs []*model.Job
// store tables need to rebase info like auto id and random id and so on after create table
rebasedTablesMap map[restore.UniqueTableName]bool
backupMeta *backuppb.BackupMeta
// TODO Remove this field or replace it with a []*DB,
// since https://github.com/pingcap/br/pull/377 needs more DBs to speed up DDL execution.
// And for now, we must inject a pool of DBs to `Client.GoCreateTables`, otherwise there would be a race condition.
// This is dirty: why we need DBs from different sources?
// By replace it with a []*DB, we can remove the dirty parameter of `Client.GoCreateTable`,
// along with them in some private functions.
// Before you do it, you can firstly read discussions at
// https://github.com/pingcap/br/pull/377#discussion_r446594501,
// this probably isn't as easy as it seems like (however, not hard, too :D)
db *tidallocdb.DB
// use db pool to speed up restoration in BR binary mode.
dbPool []*tidallocdb.DB
preallocedIDs *tidalloc.PreallocIDs
dom *domain.Domain
// correspond to --tidb-placement-mode config.
// STRICT(default) means policy related SQL can be executed in tidb.
// IGNORE means policy related SQL will be ignored.
policyMode string
// policy name -> policy info
policyMap *sync.Map
batchDdlSize uint
txnTotalSizeLimit uint64
// if fullClusterRestore = true:
// - if there's system tables in the backup(backup data since br 5.1.0), the cluster should be a fresh cluster
// without user database or table. and system tables about privileges is restored together with user data.
// - if there no system tables in the backup(backup data from br < 5.1.0), restore all user data just like
// previous version did.
// if fullClusterRestore = false, restore all user data just like previous version did.
// fullClusterRestore = true when there is no explicit filter setting, and it's full restore or point command
// with a full backup data.
// todo: maybe change to an enum
// this feature is controlled by flag with-sys-table
fullClusterRestore bool
// see RestoreCommonConfig.WithSysTable
withSysTable bool
// the rewrite mode of the downloaded SST files in TiKV.
rewriteMode RewriteMode
// checkpoint information for snapshot restore
checkpointRunner *checkpoint.CheckpointRunner[checkpoint.RestoreKeyType, checkpoint.RestoreValueType]
checkpointChecksum map[int64]*checkpoint.ChecksumItem
temporarySystemTablesRenamed bool
// restoreUUID is the UUID of this restore.
// restore from a checkpoint inherits the same restoreUUID.
restoreUUID uuid.UUID
checkPrivilegeTableRowsCollateCompatiblity bool
}
// NewRestoreClient returns a new RestoreClient.
func NewRestoreClient(
pdClient pd.Client,
pdHTTPCli pdhttp.Client,
tlsConf *tls.Config,
keepaliveConf keepalive.ClientParameters,
) *SnapClient {
return &SnapClient{
pdClient: pdClient,
pdHTTPClient: pdHTTPCli,
tlsConf: tlsConf,
keepaliveConf: keepaliveConf,
switchCh: make(chan struct{}),
}
}
func (rc *SnapClient) GetRestorer(checkpointRunner *checkpoint.CheckpointRunner[checkpoint.RestoreKeyType, checkpoint.RestoreValueType]) restore.SstRestorer {
if rc.restorer == nil {
rc.restorer = rc.getRestorerFn(checkpointRunner)
}
return rc.restorer
}
func (rc *SnapClient) CreatePreallocIDCheckpoint() *checkpoint.PreallocIDs {
if rc.preallocedIDs == nil {
return nil
}
return rc.preallocedIDs.CreateCheckpoint()
}
func (rc *SnapClient) closeConn() {
// rc.db can be nil in raw kv mode.
if rc.db != nil {
rc.db.Close()
}
for _, db := range rc.dbPool {
db.Close()
}
}
// Close a client.
func (rc *SnapClient) Close() {
// close the connection, and it must be succeed when in SQL mode.
rc.closeConn()
if rc.restorer != nil {
if err := rc.restorer.Close(); err != nil {
log.Warn("failed to close file restorer")
}
}
log.Info("Restore client closed")
}
func (rc *SnapClient) SetRateLimit(rateLimit uint64) {
rc.rateLimit = rateLimit
}
func (rc *SnapClient) SetCrypter(crypter *backuppb.CipherInfo) {
rc.cipher = crypter
}
func (rc *SnapClient) CleanTablesIfTemporarySystemTablesRenamed(loadStatsPhysical, loadSysTablePhysical bool, tables []*metautil.Table) []*metautil.Table {
if !rc.temporarySystemTablesRenamed {
return tables
}
newTables := make([]*metautil.Table, 0, len(tables))
temporaryTableChecker := &TemporaryTableChecker{
loadStatsPhysical: loadStatsPhysical,
loadSysTablePhysical: loadSysTablePhysical,
}
for _, table := range tables {
if _, ok := temporaryTableChecker.CheckTemporaryTables(table.DB.Name.O, table.Info.Name.O); ok {
continue
}
newTables = append(newTables, table)
}
return newTables
}
// GetClusterID gets the cluster id from down-stream cluster.
func (rc *SnapClient) GetClusterID(ctx context.Context) uint64 {
return rc.pdClient.GetClusterID(ctx)
}
func (rc *SnapClient) GetDomain() *domain.Domain {
return rc.dom
}
// GetTLSConfig returns the tls config.
func (rc *SnapClient) GetTLSConfig() *tls.Config {
return rc.tlsConf
}
// GetSupportPolicy tells whether target tidb support placement policy.
func (rc *SnapClient) GetSupportPolicy() bool {
return rc.supportPolicy
}
// SetCheckPrivilegeTableRowsCollateCompatiblity set switch to check
// privilege tables with different collate columns
func (rc *SnapClient) SetCheckPrivilegeTableRowsCollateCompatiblity(v bool) {
rc.checkPrivilegeTableRowsCollateCompatiblity = v
}
// GetCheckPrivilegeTableRowsCollateCompatiblity get switch to check
// privilege tables with different collate columns
func (rc *SnapClient) GetCheckPrivilegeTableRowsCollateCompatiblity() bool {
return rc.checkPrivilegeTableRowsCollateCompatiblity
}
func (rc *SnapClient) updateConcurrency() {
// we believe 32 is large enough for download worker pool.
// it won't reach the limit if sst files distribute evenly.
// when restore memory usage is still too high, we should reduce concurrencyPerStore
// to sarifice some speed to reduce memory usage.
count := uint(rc.storeCount) * rc.concurrencyPerStore * 32
log.Info("download coarse worker pool", zap.Uint("size", count))
rc.workerPool = tidbutil.NewWorkerPool(count, "file")
}
// SetConcurrencyPerStore sets the concurrency of download files for each store.
func (rc *SnapClient) SetConcurrencyPerStore(c uint) {
log.Info("per-store download worker pool", zap.Uint("size", c))
rc.concurrencyPerStore = c
}
// SetRegionScanConcurrency sets max in-flight region scan requests during import.
func (rc *SnapClient) SetRegionScanConcurrency(c uint) {
log.Info("region scan request concurrency", zap.Uint("size", c))
rc.regionScanConcurrency = c
}
// GetRegionScanConcurrency returns max in-flight region scan requests during import.
func (rc *SnapClient) GetRegionScanConcurrency() uint {
return rc.regionScanConcurrency
}
func (rc *SnapClient) SetBatchDdlSize(batchDdlsize uint) {
rc.batchDdlSize = batchDdlsize
}
func (rc *SnapClient) SetTxnTotalSizeLimit(txnTotalSizeLimit uint64) {
rc.txnTotalSizeLimit = txnTotalSizeLimit
}
func (rc *SnapClient) GetBatchDdlSize() uint {
return rc.batchDdlSize
}
func (rc *SnapClient) SetWithSysTable(withSysTable bool) {
rc.withSysTable = withSysTable
}
// TODO: remove this check and return RewriteModeKeyspace
func (rc *SnapClient) SetRewriteMode(ctx context.Context) {
if err := version.CheckClusterVersion(ctx, rc.pdClient, version.CheckVersionForKeyspaceBR); err != nil {
log.Warn("Keyspace BR is not supported in this cluster, fallback to legacy restore", zap.Error(err))
rc.rewriteMode = RewriteModeLegacy
} else {
rc.rewriteMode = RewriteModeKeyspace
}
}
func (rc *SnapClient) GetRewriteMode() RewriteMode {
return rc.rewriteMode
}
// SetPlacementPolicyMode to policy mode.
func (rc *SnapClient) SetPlacementPolicyMode(withPlacementPolicy string) {
switch strings.ToUpper(withPlacementPolicy) {
case strictPlacementPolicyMode:
rc.policyMode = strictPlacementPolicyMode
case ignorePlacementPolicyMode:
rc.policyMode = ignorePlacementPolicyMode
default:
rc.policyMode = strictPlacementPolicyMode
}
log.Info("set placement policy mode", zap.String("mode", rc.policyMode))
}
func getMinUserTableID(tables []*metautil.Table) int64 {
minUserTableID := int64(math.MaxInt64)
for _, table := range tables {
if !utils.IsSysOrTempSysDB(table.DB.Name.O) {
if table.Info.ID < minUserTableID {
minUserTableID = table.Info.ID
}
if table.Info.Partition != nil && table.Info.Partition.Definitions != nil {
for _, part := range table.Info.Partition.Definitions {
if part.ID < minUserTableID {
minUserTableID = part.ID
}
}
}
}
}
return minUserTableID
}
// AllocTableIDs would pre-allocate the table's origin ID if exists, so that the TiKV doesn't need to rewrite the key in
// the download stage.
// It returns whether any user table ID is not reused when need check.
func (rc *SnapClient) AllocTableIDs(
ctx context.Context,
tables []*metautil.Table,
loadStatsPhysical, loadSysTablePhysical bool,
reusePreallocIDs *checkpoint.PreallocIDs,
) (bool, error) {
var preallocedTableIDs *tidalloc.PreallocIDs
var err error
if reusePreallocIDs == nil {
ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnBR)
err := kv.RunInNewTxn(ctx, rc.GetDomain().Store(), true, func(_ context.Context, txn kv.Transaction) error {
preallocedTableIDs, err = tidalloc.NewAndPrealloc(tables, meta.NewMutator(txn))
return err
})
if err != nil {
return false, err
}
} else {
preallocedTableIDs, err = tidalloc.ReuseCheckpoint(reusePreallocIDs, tables)
if err != nil {
return false, errors.Trace(err)
}
}
userTableIDNotReusedWhenNeedCheck := false
if loadStatsPhysical {
minUserTableID := getMinUserTableID(tables)
start, _ := preallocedTableIDs.GetIDRange()
if minUserTableID != int64(math.MaxInt64) && minUserTableID < start {
userTableIDNotReusedWhenNeedCheck = true
loadStatsPhysical = false
}
}
if reusePreallocIDs != nil && (loadStatsPhysical || loadSysTablePhysical) {
temporaryTableChecker := &TemporaryTableChecker{
loadStatsPhysical: loadStatsPhysical,
loadSysTablePhysical: loadSysTablePhysical,
}
for _, table := range tables {
if dbName, ok := temporaryTableChecker.CheckTemporaryTables(table.DB.Name.O, table.Info.Name.O); ok {
downstreamId, err := preallocedTableIDs.AllocID(table.Info.ID)
if err != nil {
return false, errors.Trace(err)
}
if tableInfo, err := rc.dom.InfoSchema().TableInfoByName(ast.NewCIStr(dbName), table.Info.Name); err == nil {
if tableInfo.ID == downstreamId {
rc.temporarySystemTablesRenamed = true
}
break
}
}
}
}
log.Info("registering the table IDs", zap.Stringer("ids", preallocedTableIDs))
for i := range rc.dbPool {
rc.dbPool[i].RegisterPreallocatedIDs(preallocedTableIDs)
}
if rc.db != nil {
rc.db.RegisterPreallocatedIDs(preallocedTableIDs)
}
rc.preallocedIDs = preallocedTableIDs
return userTableIDNotReusedWhenNeedCheck, nil
}
func (rc *SnapClient) GetPreAllocedTableIDRange() ([2]int64, error) {
if rc.preallocedIDs == nil {
return [2]int64{}, errors.Errorf("No preAlloced IDs")
}
start, end := rc.preallocedIDs.GetIDRange()
if start >= end {
log.Warn("PreAlloced IDs range is empty, no table to restore")
return [2]int64{}, nil
}
return [2]int64{start, end}, nil
}
// InitCheckpoint initialize the checkpoint status for the cluster. If the cluster is
// restored for the first time, it will initialize the checkpoint metadata. Otherwrise,
// it will load checkpoint metadata and checkpoint ranges/checksum from the external
// storage.
func (rc *SnapClient) InitCheckpoint(
ctx context.Context,
snapshotCheckpointMetaManager checkpoint.SnapshotMetaManagerT,
config *pdutil.ClusterConfig,
restoreStartTS uint64,
logRestoredTS uint64,
hash []byte,
checkpointExists bool,
) (
checkpointSetWithTableID map[int64]map[string]struct{},
checkpointClusterConfig *pdutil.ClusterConfig,
newRestoreStartTS uint64,
err error,
) {
// checkpoint sets distinguished by range key
checkpointSetWithTableID = make(map[int64]map[string]struct{})
if checkpointExists {
// load the checkpoint since this is not the first time to restore
meta, err := snapshotCheckpointMetaManager.LoadCheckpointMetadata(ctx)
if err != nil {
return checkpointSetWithTableID, nil, 0, errors.Trace(err)
}
rc.restoreUUID = meta.RestoreUUID
if meta.UpstreamClusterID != rc.backupMeta.ClusterId {
return checkpointSetWithTableID, nil, 0, errors.Errorf(
"The upstream cluster id[%d] of the current snapshot restore does not match that[%d] recorded in checkpoint. "+
"Perhaps you should specify the last full backup storage instead, "+
"or just clean the checkpoint %v if the cluster has been cleaned up.",
rc.backupMeta.ClusterId, meta.UpstreamClusterID, snapshotCheckpointMetaManager)
}
if !bytes.Equal(meta.Hash, hash) {
return checkpointSetWithTableID, nil, 0, errors.Errorf(
"The hash of the current snapshot restore does not match that recorded in checkpoint. "+
"Please don't use the checkpoint, "+
"or use the the same restore command. checkpoint manager: %v",
snapshotCheckpointMetaManager)
}
if meta.RestoredTS != rc.backupMeta.EndVersion {
return checkpointSetWithTableID, nil, 0, errors.Errorf(
"The current snapshot restore want to restore cluster to the BackupTS[%d], which is different from that[%d] recorded in checkpoint. "+
"Perhaps you should specify the last full backup storage instead, "+
"or just clean the checkpoint %s if the cluster has been cleaned up.",
rc.backupMeta.EndVersion, meta.RestoredTS, snapshotCheckpointMetaManager,
)
}
// The filter feature is determined by the PITR restored ts, so the snapshot
// restore checkpoint should check whether the PITR restored ts is changed.
// Notice that if log restore checkpoint metadata is not stored, BR always enters
// snapshot restore.
if meta.LogRestoredTS != logRestoredTS {
return checkpointSetWithTableID, nil, 0, errors.Errorf(
"The current PITR want to restore cluster to the log restored ts[%d], which is different from that[%d] recorded in checkpoint. "+
"Perhaps you shoud specify the log restored ts instead, "+
"or just clean the checkpoint database[%s] if the cluster has been cleaned up.",
logRestoredTS, meta.LogRestoredTS, snapshotCheckpointMetaManager,
)
}
newRestoreStartTS = meta.RestoreStartTS
// The schedulers config is nil, so the restore-schedulers operation is just nil.
// Then the undo function would use the result undo of `remove schedulers` operation,
// instead of that in checkpoint meta.
if meta.SchedulersConfig != nil {
checkpointClusterConfig = meta.SchedulersConfig
}
// t1 is the latest time the checkpoint ranges persisted to the external storage.
t1, err := snapshotCheckpointMetaManager.LoadCheckpointData(ctx, func(tableID int64, v checkpoint.RestoreValueType) error {
checkpointSet, exists := checkpointSetWithTableID[tableID]
if !exists {
checkpointSet = make(map[string]struct{})
checkpointSetWithTableID[tableID] = checkpointSet
}
checkpointSet[v.RangeKey] = struct{}{}
return nil
})
if err != nil {
return checkpointSetWithTableID, nil, 0, errors.Trace(err)
}
// t2 is the latest time the checkpoint checksum persisted to the external storage.
checkpointChecksum, t2, err := snapshotCheckpointMetaManager.LoadCheckpointChecksum(ctx)
if err != nil {
return checkpointSetWithTableID, nil, 0, errors.Trace(err)
}
rc.checkpointChecksum = checkpointChecksum
// use the later time to adjust the summary elapsed time.
if t1 > t2 {
summary.AdjustStartTimeToEarlierTime(t1)
} else {
summary.AdjustStartTimeToEarlierTime(t2)
}
} else {
// initialize the checkpoint metadata since it is the first time to restore.
restoreID := uuid.New()
meta := &checkpoint.CheckpointMetadataForSnapshotRestore{
UpstreamClusterID: rc.backupMeta.ClusterId,
RestoreStartTS: restoreStartTS,
RestoredTS: rc.backupMeta.EndVersion,
LogRestoredTS: logRestoredTS,
Hash: hash,
PreallocIDs: rc.CreatePreallocIDCheckpoint(),
RestoreUUID: restoreID,
}
rc.restoreUUID = restoreID
newRestoreStartTS = restoreStartTS
// a nil config means undo function
if config != nil {
meta.SchedulersConfig = &pdutil.ClusterConfig{Schedulers: config.Schedulers, ScheduleCfg: config.ScheduleCfg, RuleID: config.RuleID}
}
if err := snapshotCheckpointMetaManager.SaveCheckpointMetadata(ctx, meta); err != nil {
return checkpointSetWithTableID, nil, 0, errors.Trace(err)
}
}
rc.checkpointRunner, err = checkpoint.StartCheckpointRunnerForRestore(ctx, snapshotCheckpointMetaManager)
if err != nil {
return checkpointSetWithTableID, nil, 0, errors.Trace(err)
}
return checkpointSetWithTableID, checkpointClusterConfig, newRestoreStartTS, nil
}
func (rc *SnapClient) WaitForFinishCheckpoint(ctx context.Context, flush bool) {
if rc.checkpointRunner != nil {
rc.checkpointRunner.WaitForFinish(ctx, flush)
}
}
// makeDBPool makes a session pool with specficated size by sessionFactory.
func makeDBPool(size uint, dbFactory func() (*tidallocdb.DB, error)) ([]*tidallocdb.DB, error) {
dbPool := make([]*tidallocdb.DB, 0, size)
for range size {
db, e := dbFactory()
if e != nil {
return dbPool, e
}
if db != nil {
dbPool = append(dbPool, db)
}
}
return dbPool, nil
}
func (rc *SnapClient) InstallPiTRSupport(ctx context.Context, deps PiTRCollDep) error {
if err := deps.LoadMaxCopyConcurrency(ctx, rc.concurrencyPerStore); err != nil {
return errors.Trace(err)
}
collector, err := newPiTRColl(ctx, deps)
if err != nil {
return errors.Trace(err)
}
if !collector.enabled {
return nil
}
if rc.IsIncremental() {
// Even there were an error, don't return it to confuse the user...
_ = collector.close()
return errors.Annotatef(berrors.ErrStreamLogTaskExist, "it seems there is a log backup task exists, "+
"if an incremental restore were performed to such cluster, log backup cannot properly handle this, "+
"the restore will be aborted, you may stop the log backup task, then restore, finally restart the task")
}
collector.restoreUUID = rc.restoreUUID
if collector.restoreUUID == (uuid.UUID{}) {
collector.restoreUUID = uuid.New()
log.Warn("UUID not found(checkpoint not enabled?), generating a new UUID for backup.",
zap.Stringer("uuid", collector.restoreUUID))
}
rc.importer.beforeIngestCallbacks = append(rc.importer.beforeIngestCallbacks, collector.onBatch)
rc.importer.closeCallbacks = append(rc.importer.closeCallbacks, func(sfi *SnapFileImporter) error {
return collector.close()
})
return nil
}
// InitConnections create db connection and domain for storage.
func (rc *SnapClient) InitConnections(g glue.Glue, store kv.Storage) error {
// setDB must happen after set PolicyMode.
// we will use policyMode to set session variables.
var err error
rc.db, rc.supportPolicy, err = tidallocdb.NewDB(g, store, rc.policyMode)
if err != nil {
return errors.Trace(err)
}
rc.dom, err = g.GetDomain(store)
if err != nil {
return errors.Trace(err)
}
// init backupMeta only for passing unit test
if rc.backupMeta == nil {
rc.backupMeta = new(backuppb.BackupMeta)
}
// There are different ways to create session between in binary and in SQL.
//
// Maybe allow user modify the DDL concurrency isn't necessary,
// because executing DDL is really I/O bound (or, algorithm bound?),
// and we cost most of time at waiting DDL jobs be enqueued.
// So these jobs won't be faster or slower when machine become faster or slower,
// hence make it a fixed value would be fine.
rc.dbPool, err = makeDBPool(defaultDDLConcurrency, func() (*tidallocdb.DB, error) {
db, _, err := tidallocdb.NewDB(g, store, rc.policyMode)
return db, err
})
if err != nil {
log.Warn("create session pool failed, we will send DDLs only by created sessions",
zap.Error(err),
zap.Int("sessionCount", len(rc.dbPool)),
)
}
return errors.Trace(err)
}
func SetSpeedLimitFn(ctx context.Context, stores []*metapb.Store, pool *tidbutil.WorkerPool) func(*SnapFileImporter, uint64) error {
return func(importer *SnapFileImporter, limit uint64) error {
eg, ectx := errgroup.WithContext(ctx)
for _, store := range stores {
if err := ectx.Err(); err != nil {
return errors.Trace(err)
}
finalStore := store
pool.ApplyOnErrorGroup(eg,
func() error {
err := importer.SetDownloadSpeedLimit(ectx, finalStore.GetId(), limit)
if err != nil {
return errors.Trace(err)
}
return nil
})
}
return eg.Wait()
}
}
func (rc *SnapClient) initClients(ctx context.Context, backend *backuppb.StorageBackend, isRawKvMode bool, isTxnKvMode bool,
RawStartKey, RawEndKey []byte) error {
stores, err := conn.GetAllTiKVStoresWithRetry(ctx, rc.pdClient, util.SkipTiFlash)
if err != nil {
return errors.Annotate(err, "failed to get stores")
}
rc.storeCount = len(stores)
rc.updateConcurrency()
var createCallBacks []func(*SnapFileImporter) error
var closeCallBacks []func(*SnapFileImporter) error
var splitClientOpts []split.ClientOptionalParameter
if isRawKvMode {
splitClientOpts = append(splitClientOpts, split.WithRawKV())
createCallBacks = append(createCallBacks, func(importer *SnapFileImporter) error {
return importer.SetRawRange(RawStartKey, RawEndKey)
})
}
createCallBacks = append(createCallBacks, func(importer *SnapFileImporter) error {
return importer.CheckMultiIngestSupport(ctx, stores)
})
if rc.rateLimit != 0 {
setFn := SetSpeedLimitFn(ctx, stores, rc.workerPool)
createCallBacks = append(createCallBacks, func(importer *SnapFileImporter) error {
return setFn(importer, rc.rateLimit)
})
closeCallBacks = append(closeCallBacks, func(importer *SnapFileImporter) error {
// In future we may need a mechanism to set speed limit in ttl. like what we do in switchmode. TODO
var resetErr error
for retry := range resetSpeedLimitRetryTimes {
resetErr = setFn(importer, 0)
if resetErr != nil {
log.Warn("failed to reset speed limit, retry it",
zap.Int("retry time", retry), logutil.ShortError(resetErr))
time.Sleep(time.Duration(retry+3) * time.Second)
continue
}
break
}
if resetErr != nil {
log.Error("failed to reset speed limit, please reset it manually", zap.Error(resetErr))
}
return resetErr
})
}
metaClient := split.NewClient(rc.pdClient, rc.pdHTTPClient, rc.tlsConf, maxSplitKeysOnce, rc.storeCount+1, splitClientOpts...)
importCli := importclient.NewImportClient(metaClient, rc.tlsConf, rc.keepaliveConf)
opt := NewSnapFileImporterOptions(
rc.cipher, metaClient, importCli, backend,
rc.rewriteMode, stores, rc.concurrencyPerStore, rc.regionScanConcurrency, createCallBacks, closeCallBacks,
)
if isRawKvMode || isTxnKvMode {
mode := Raw
if isTxnKvMode {
mode = Txn
}
// for raw/txn mode. use backupMeta.ApiVersion to create fileImporter
rc.importer, err = NewSnapFileImporter(ctx, rc.backupMeta.ApiVersion, mode, opt)
if err != nil {
return errors.Trace(err)
}
// Raw/Txn restore are not support checkpoint for now
rc.getRestorerFn = func(checkpointRunner *checkpoint.CheckpointRunner[checkpoint.RestoreKeyType, checkpoint.RestoreValueType]) restore.SstRestorer {
return restore.NewSimpleSstRestorer(ctx, rc.importer, rc.workerPool, nil)
}
} else {
// or create a fileImporter with the cluster API version
rc.importer, err = NewSnapFileImporter(
ctx, rc.dom.Store().GetCodec().GetAPIVersion(), TiDBFull, opt)
if err != nil {
return errors.Trace(err)
}
rc.getRestorerFn = func(checkpointRunner *checkpoint.CheckpointRunner[checkpoint.RestoreKeyType, checkpoint.RestoreValueType]) restore.SstRestorer {
return restore.NewMultiTablesRestorer(ctx, rc.importer, rc.workerPool, checkpointRunner)
}
}
return nil
}
func needLoadSchemas(backupMeta *backuppb.BackupMeta) bool {
return !(backupMeta.IsRawKv || backupMeta.IsTxnKv)
}
// LoadSchemaIfNeededAndInitClient loads schemas from BackupMeta to initialize RestoreClient.
func (rc *SnapClient) LoadSchemaIfNeededAndInitClient(
c context.Context,
backupMeta *backuppb.BackupMeta,
backend *backuppb.StorageBackend,
reader *metautil.MetaReader,
loadStats bool,
RawStartKey []byte,
RawEndKey []byte,
hasExplicitFilter bool,
isFullRestore bool,
withSys bool,
) error {
if needLoadSchemas(backupMeta) {
databases, err := metautil.LoadBackupTables(c, reader, loadStats)
if err != nil {
return errors.Trace(err)
}
rc.databases = databases
var ddlJobs []*model.Job
// ddls is the bytes of json.Marshal
ddls, err := reader.ReadDDLs(c)
if err != nil {
return errors.Trace(err)
}
if len(ddls) != 0 {
err = json.Unmarshal(ddls, &ddlJobs)
if err != nil {
return errors.Trace(err)
}
}
rc.ddlJobs = ddlJobs
log.Info("loaded backup meta", zap.Int("databases", len(rc.databases)), zap.Int("jobs", len(rc.ddlJobs)))
}
rc.backupMeta = backupMeta
if err := rc.initClients(c, backend, backupMeta.IsRawKv, backupMeta.IsTxnKv, RawStartKey, RawEndKey); err != nil {
return errors.Trace(err)
}
rc.InitFullClusterRestore(hasExplicitFilter, isFullRestore, withSys)
return nil
}
// IsRawKvMode checks whether the backup data is in raw kv format, in which case transactional recover is forbidden.
func (rc *SnapClient) IsRawKvMode() bool {
return rc.backupMeta.IsRawKv
}
// GetFilesInRawRange gets all files that are in the given range or intersects with the given range.
func (rc *SnapClient) GetFilesInRawRange(startKey []byte, endKey []byte, cf string) ([]*backuppb.File, error) {
if !rc.IsRawKvMode() {
return nil, errors.Annotate(berrors.ErrRestoreModeMismatch, "the backup data is not in raw kv mode")
}
for _, rawRange := range rc.backupMeta.RawRanges {
// First check whether the given range is backup-ed. If not, we cannot perform the restore.
if rawRange.Cf != cf {
continue
}
if (len(rawRange.EndKey) > 0 && bytes.Compare(startKey, rawRange.EndKey) >= 0) ||
(len(endKey) > 0 && bytes.Compare(rawRange.StartKey, endKey) >= 0) {
// The restoring range is totally out of the current range. Skip it.
continue
}
if bytes.Compare(startKey, rawRange.StartKey) < 0 ||
utils.CompareEndKey(endKey, rawRange.EndKey) > 0 {
// Only partial of the restoring range is in the current backup-ed range. So the given range can't be fully
// restored.
return nil, errors.Annotatef(berrors.ErrRestoreRangeMismatch,
"the given range to restore [%s, %s) is not fully covered by the range that was backed up [%s, %s)",
redact.Key(startKey), redact.Key(endKey), redact.Key(rawRange.StartKey), redact.Key(rawRange.EndKey),
)
}
// We have found the range that contains the given range. Find all necessary files.
files := make([]*backuppb.File, 0)
for _, file := range rc.backupMeta.Files {
if file.Cf != cf {
continue
}
if len(file.EndKey) > 0 && bytes.Compare(file.EndKey, startKey) < 0 {
// The file is before the range to be restored.
continue
}
if len(endKey) > 0 && bytes.Compare(endKey, file.StartKey) <= 0 {
// The file is after the range to be restored.
// The specified endKey is exclusive, so when it equals to a file's startKey, the file is still skipped.
continue
}
files = append(files, file)
}
// There should be at most one backed up range that covers the restoring range.
return files, nil
}
return nil, errors.Annotate(berrors.ErrRestoreRangeMismatch, "no backup data in the range")
}
// ResetTS resets the timestamp of PD to a bigger value.
func (rc *SnapClient) ResetTS(ctx context.Context, pdCtrl *pdutil.PdController) error {
restoreTS := rc.backupMeta.GetEndVersion()
log.Info("reset pd timestamp", zap.Uint64("ts", restoreTS))
return utils.WithRetry(ctx, func() error {
return pdCtrl.ResetTS(ctx, restoreTS)
}, utils.NewAggressivePDBackoffStrategy())
}
// GetDatabases returns all databases.
func (rc *SnapClient) GetDatabases() []*metautil.Database {
dbs := make([]*metautil.Database, 0, len(rc.databases))
for _, db := range rc.databases {
dbs = append(dbs, db)
}
return dbs
}
// GetDatabaseMap returns all databases in a map indexed by db id
func (rc *SnapClient) GetDatabaseMap() map[int64]*metautil.Database {
dbMap := make(map[int64]*metautil.Database)
for _, db := range rc.databases {
dbMap[db.Info.ID] = db
}
return dbMap
}
// GetTableMap returns all tables in a map indexed by table id
func (rc *SnapClient) GetTableMap() map[int64]*metautil.Table {
tableMap := make(map[int64]*metautil.Table)
for _, db := range rc.databases {
for _, table := range db.Tables {
if table.Info == nil {
continue
}
tableMap[table.Info.ID] = table
}
}
return tableMap
}
// GetPartitionMap returns all partitions with their related information indexed by partition ID
func (rc *SnapClient) GetPartitionMap() map[int64]*stream.TableLocationInfo {
partitionMap := make(map[int64]*stream.TableLocationInfo)
for _, db := range rc.databases {
for _, table := range db.Tables {
if table.Info == nil {
continue
}
// Skip if the table doesn't have partition info
if table.Info.Partition == nil || table.Info.Partition.Definitions == nil {
continue
}
// Iterate through all partitions in the table
for _, part := range table.Info.Partition.Definitions {
// Create the partition info with all required details
partInfo := &stream.TableLocationInfo{
ParentTableID: table.Info.ID,
TableName: table.Info.Name.O,
DbID: db.Info.ID,
IsPartition: true,
}
// Add to the map with partition ID as key
partitionMap[part.ID] = partInfo
}
}
}
return partitionMap
}
// HasBackedUpSysDB whether we have backed up system tables
// br backs system tables up since 5.1.0
func (rc *SnapClient) HasBackedUpSysDB() bool {
sysDBs := []string{mysql.SystemDB, mysql.SysDB, mysql.WorkloadSchema}
for _, db := range sysDBs {
temporaryDB := utils.TemporaryDBName(db)
_, backedUp := rc.databases[temporaryDB.O]
if backedUp {
return true
}
}
return false
}
// GetPlacementPolicies returns policies.
func (rc *SnapClient) GetPlacementPolicies() (*sync.Map, error) {
policies := &sync.Map{}
for _, p := range rc.backupMeta.Policies {
policyInfo := &model.PolicyInfo{}
err := json.Unmarshal(p.Info, policyInfo)
if err != nil {
return nil, errors.Trace(err)
}
policies.Store(policyInfo.Name.L, policyInfo)
}
return policies, nil
}