forked from pingcap/br
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.go
483 lines (450 loc) · 13.7 KB
/
import.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
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package restore
import (
"bytes"
"context"
"crypto/tls"
"sync"
"time"
"github.com/google/uuid"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
backuppb "github.com/pingcap/kvproto/pkg/backup"
"github.com/pingcap/kvproto/pkg/import_sstpb"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pingcap/log"
"github.com/tikv/pd/pkg/codec"
"go.uber.org/multierr"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
berrors "github.com/pingcap/br/pkg/errors"
"github.com/pingcap/br/pkg/logutil"
"github.com/pingcap/br/pkg/summary"
"github.com/pingcap/br/pkg/utils"
)
const (
importScanRegionTime = 10 * time.Second
gRPCBackOffMaxDelay = 3 * time.Second
)
// ImporterClient is used to import a file to TiKV.
type ImporterClient interface {
DownloadSST(
ctx context.Context,
storeID uint64,
req *import_sstpb.DownloadRequest,
) (*import_sstpb.DownloadResponse, error)
IngestSST(
ctx context.Context,
storeID uint64,
req *import_sstpb.IngestRequest,
) (*import_sstpb.IngestResponse, error)
SetDownloadSpeedLimit(
ctx context.Context,
storeID uint64,
req *import_sstpb.SetDownloadSpeedLimitRequest,
) (*import_sstpb.SetDownloadSpeedLimitResponse, error)
GetImportClient(
ctx context.Context,
storeID uint64,
) (import_sstpb.ImportSSTClient, error)
}
type importClient struct {
mu sync.Mutex
metaClient SplitClient
clients map[uint64]import_sstpb.ImportSSTClient
tlsConf *tls.Config
keepaliveConf keepalive.ClientParameters
}
// NewImportClient returns a new ImporterClient.
func NewImportClient(metaClient SplitClient, tlsConf *tls.Config, keepaliveConf keepalive.ClientParameters) ImporterClient {
return &importClient{
metaClient: metaClient,
clients: make(map[uint64]import_sstpb.ImportSSTClient),
tlsConf: tlsConf,
keepaliveConf: keepaliveConf,
}
}
func (ic *importClient) DownloadSST(
ctx context.Context,
storeID uint64,
req *import_sstpb.DownloadRequest,
) (*import_sstpb.DownloadResponse, error) {
client, err := ic.GetImportClient(ctx, storeID)
if err != nil {
return nil, errors.Trace(err)
}
return client.Download(ctx, req)
}
func (ic *importClient) SetDownloadSpeedLimit(
ctx context.Context,
storeID uint64,
req *import_sstpb.SetDownloadSpeedLimitRequest,
) (*import_sstpb.SetDownloadSpeedLimitResponse, error) {
client, err := ic.GetImportClient(ctx, storeID)
if err != nil {
return nil, errors.Trace(err)
}
return client.SetDownloadSpeedLimit(ctx, req)
}
func (ic *importClient) IngestSST(
ctx context.Context,
storeID uint64,
req *import_sstpb.IngestRequest,
) (*import_sstpb.IngestResponse, error) {
client, err := ic.GetImportClient(ctx, storeID)
if err != nil {
return nil, errors.Trace(err)
}
return client.Ingest(ctx, req)
}
func (ic *importClient) GetImportClient(
ctx context.Context,
storeID uint64,
) (import_sstpb.ImportSSTClient, error) {
ic.mu.Lock()
defer ic.mu.Unlock()
client, ok := ic.clients[storeID]
if ok {
return client, nil
}
store, err := ic.metaClient.GetStore(ctx, storeID)
if err != nil {
return nil, errors.Trace(err)
}
opt := grpc.WithInsecure()
if ic.tlsConf != nil {
opt = grpc.WithTransportCredentials(credentials.NewTLS(ic.tlsConf))
}
addr := store.GetPeerAddress()
if addr == "" {
addr = store.GetAddress()
}
bfConf := backoff.DefaultConfig
bfConf.MaxDelay = gRPCBackOffMaxDelay
conn, err := grpc.DialContext(
ctx,
addr,
opt,
grpc.WithConnectParams(grpc.ConnectParams{Backoff: bfConf}),
grpc.WithKeepaliveParams(ic.keepaliveConf),
)
if err != nil {
return nil, errors.Trace(err)
}
client = import_sstpb.NewImportSSTClient(conn)
ic.clients[storeID] = client
return client, errors.Trace(err)
}
// FileImporter used to import a file to TiKV.
type FileImporter struct {
metaClient SplitClient
importClient ImporterClient
backend *backuppb.StorageBackend
rateLimit uint64
isRawKvMode bool
rawStartKey []byte
rawEndKey []byte
}
// NewFileImporter returns a new file importClient.
func NewFileImporter(
metaClient SplitClient,
importClient ImporterClient,
backend *backuppb.StorageBackend,
isRawKvMode bool,
rateLimit uint64,
) FileImporter {
return FileImporter{
metaClient: metaClient,
backend: backend,
importClient: importClient,
isRawKvMode: isRawKvMode,
rateLimit: rateLimit,
}
}
// SetRawRange sets the range to be restored in raw kv mode.
func (importer *FileImporter) SetRawRange(startKey, endKey []byte) error {
if !importer.isRawKvMode {
return errors.Annotate(berrors.ErrRestoreModeMismatch, "file importer is not in raw kv mode")
}
importer.rawStartKey = startKey
importer.rawEndKey = endKey
return nil
}
// Import tries to import a file.
// All rules must contain encoded keys.
func (importer *FileImporter) Import(
ctx context.Context,
file *backuppb.File,
rewriteRules *RewriteRules,
) error {
log.Debug("import file", logutil.File(file))
// Rewrite the start key and end key of file to scan regions
var startKey, endKey []byte
var err error
if importer.isRawKvMode {
startKey = file.StartKey
endKey = file.EndKey
} else {
startKey, endKey, err = rewriteFileKeys(file, rewriteRules)
}
if err != nil {
return errors.Trace(err)
}
log.Debug("rewrite file keys",
logutil.File(file),
logutil.Key("startKey", startKey),
logutil.Key("endKey", endKey))
err = utils.WithRetry(ctx, func() error {
tctx, cancel := context.WithTimeout(ctx, importScanRegionTime)
defer cancel()
// Scan regions covered by the file range
regionInfos, errScanRegion := PaginateScanRegion(
tctx, importer.metaClient, startKey, endKey, ScanRegionPaginationLimit)
if errScanRegion != nil {
return errors.Trace(errScanRegion)
}
log.Debug("scan regions", logutil.File(file), zap.Int("count", len(regionInfos)))
// Try to download and ingest the file in every region
regionLoop:
for _, regionInfo := range regionInfos {
info := regionInfo
// Try to download file.
var downloadMeta *import_sstpb.SSTMeta
errDownload := utils.WithRetry(ctx, func() error {
var e error
if importer.isRawKvMode {
downloadMeta, e = importer.downloadRawKVSST(ctx, info, file)
} else {
downloadMeta, e = importer.downloadSST(ctx, info, file, rewriteRules)
}
failpoint.Inject("restore-storage-error", func(val failpoint.Value) {
msg := val.(string)
log.Debug("failpoint restore-storage-error injected.", zap.String("msg", msg))
e = errors.Annotate(e, msg)
})
return errors.Trace(e)
}, newDownloadSSTBackoffer())
if errDownload != nil {
for _, e := range multierr.Errors(errDownload) {
switch errors.Cause(e) { // nolint:errorlint
case berrors.ErrKVRewriteRuleNotFound, berrors.ErrKVRangeIsEmpty:
// Skip this region
log.Warn("download file skipped",
logutil.File(file),
logutil.Region(info.Region),
logutil.Key("startKey", startKey),
logutil.Key("endKey", endKey),
logutil.ShortError(e))
continue regionLoop
}
}
log.Error("download file failed",
logutil.File(file),
logutil.Region(info.Region),
logutil.Key("startKey", startKey),
logutil.Key("endKey", endKey),
logutil.ShortError(errDownload))
return errors.Trace(errDownload)
}
ingestResp, errIngest := importer.ingestSST(ctx, downloadMeta, info)
ingestRetry:
for errIngest == nil {
errPb := ingestResp.GetError()
if errPb == nil {
// Ingest success
break ingestRetry
}
switch {
case errPb.NotLeader != nil:
// If error is `NotLeader`, update the region info and retry
var newInfo *RegionInfo
if newLeader := errPb.GetNotLeader().GetLeader(); newLeader != nil {
newInfo = &RegionInfo{
Leader: newLeader,
Region: info.Region,
}
} else {
// Slow path, get region from PD
newInfo, errIngest = importer.metaClient.GetRegion(
ctx, info.Region.GetStartKey())
if errIngest != nil {
break ingestRetry
}
// do not get region info, wait a second and continue
if newInfo == nil {
log.Warn("get region by key return nil", logutil.Region(info.Region))
time.Sleep(time.Second)
continue
}
}
log.Debug("ingest sst returns not leader error, retry it",
logutil.Region(info.Region),
zap.Stringer("newLeader", newInfo.Leader))
if !checkRegionEpoch(newInfo, info) {
errIngest = errors.Trace(berrors.ErrKVEpochNotMatch)
break ingestRetry
}
ingestResp, errIngest = importer.ingestSST(ctx, downloadMeta, newInfo)
case errPb.EpochNotMatch != nil:
// TODO handle epoch not match error
// 1. retry download if needed
// 2. retry ingest
errIngest = errors.Trace(berrors.ErrKVEpochNotMatch)
break ingestRetry
case errPb.KeyNotInRegion != nil:
errIngest = errors.Trace(berrors.ErrKVKeyNotInRegion)
break ingestRetry
default:
// Other errors like `ServerIsBusy`, `RegionNotFound`, etc. should be retryable
errIngest = errors.Annotatef(berrors.ErrKVIngestFailed, "ingest error %s", errPb)
break ingestRetry
}
}
if errIngest != nil {
log.Error("ingest file failed",
logutil.File(file),
logutil.SSTMeta(downloadMeta),
logutil.Region(info.Region),
zap.Error(errIngest))
return errors.Trace(errIngest)
}
}
summary.CollectSuccessUnit(summary.TotalKV, 1, file.TotalKvs)
summary.CollectSuccessUnit(summary.TotalBytes, 1, file.TotalBytes)
return nil
}, newImportSSTBackoffer())
return errors.Trace(err)
}
func (importer *FileImporter) setDownloadSpeedLimit(ctx context.Context, storeID uint64) error {
req := &import_sstpb.SetDownloadSpeedLimitRequest{
SpeedLimit: importer.rateLimit,
}
_, err := importer.importClient.SetDownloadSpeedLimit(ctx, storeID, req)
return errors.Trace(err)
}
func (importer *FileImporter) downloadSST(
ctx context.Context,
regionInfo *RegionInfo,
file *backuppb.File,
rewriteRules *RewriteRules,
) (*import_sstpb.SSTMeta, error) {
uid := uuid.New()
id := uid[:]
// Assume one region reflects to one rewrite rule
_, key, err := codec.DecodeBytes(regionInfo.Region.GetStartKey())
if err != nil {
return nil, errors.Trace(err)
}
regionRule := matchNewPrefix(key, rewriteRules)
if regionRule == nil {
return nil, errors.Trace(berrors.ErrKVRewriteRuleNotFound)
}
rule := import_sstpb.RewriteRule{
OldKeyPrefix: encodeKeyPrefix(regionRule.GetOldKeyPrefix()),
NewKeyPrefix: encodeKeyPrefix(regionRule.GetNewKeyPrefix()),
}
sstMeta := GetSSTMetaFromFile(id, file, regionInfo.Region, &rule)
req := &import_sstpb.DownloadRequest{
Sst: sstMeta,
StorageBackend: importer.backend,
Name: file.GetName(),
RewriteRule: rule,
}
log.Debug("download SST",
logutil.SSTMeta(&sstMeta),
logutil.File(file),
logutil.Region(regionInfo.Region),
)
var resp *import_sstpb.DownloadResponse
for _, peer := range regionInfo.Region.GetPeers() {
resp, err = importer.importClient.DownloadSST(ctx, peer.GetStoreId(), req)
if err != nil {
return nil, errors.Trace(err)
}
if resp.GetError() != nil {
return nil, errors.Annotate(berrors.ErrKVDownloadFailed, resp.GetError().GetMessage())
}
if resp.GetIsEmpty() {
return nil, errors.Trace(berrors.ErrKVRangeIsEmpty)
}
}
sstMeta.Range.Start = truncateTS(resp.Range.GetStart())
sstMeta.Range.End = truncateTS(resp.Range.GetEnd())
return &sstMeta, nil
}
func (importer *FileImporter) downloadRawKVSST(
ctx context.Context,
regionInfo *RegionInfo,
file *backuppb.File,
) (*import_sstpb.SSTMeta, error) {
uid := uuid.New()
id := uid[:]
// Empty rule
var rule import_sstpb.RewriteRule
sstMeta := GetSSTMetaFromFile(id, file, regionInfo.Region, &rule)
// Cut the SST file's range to fit in the restoring range.
if bytes.Compare(importer.rawStartKey, sstMeta.Range.GetStart()) > 0 {
sstMeta.Range.Start = importer.rawStartKey
}
if len(importer.rawEndKey) > 0 &&
(len(sstMeta.Range.GetEnd()) == 0 || bytes.Compare(importer.rawEndKey, sstMeta.Range.GetEnd()) <= 0) {
sstMeta.Range.End = importer.rawEndKey
sstMeta.EndKeyExclusive = true
}
if bytes.Compare(sstMeta.Range.GetStart(), sstMeta.Range.GetEnd()) > 0 {
return nil, errors.Trace(berrors.ErrKVRangeIsEmpty)
}
req := &import_sstpb.DownloadRequest{
Sst: sstMeta,
StorageBackend: importer.backend,
Name: file.GetName(),
RewriteRule: rule,
IsRawKv: true,
}
log.Debug("download SST", logutil.SSTMeta(&sstMeta), logutil.Region(regionInfo.Region))
var err error
var resp *import_sstpb.DownloadResponse
for _, peer := range regionInfo.Region.GetPeers() {
resp, err = importer.importClient.DownloadSST(ctx, peer.GetStoreId(), req)
if err != nil {
return nil, errors.Trace(err)
}
if resp.GetError() != nil {
return nil, errors.Annotate(berrors.ErrKVDownloadFailed, resp.GetError().GetMessage())
}
if resp.GetIsEmpty() {
return nil, errors.Trace(berrors.ErrKVRangeIsEmpty)
}
}
sstMeta.Range.Start = resp.Range.GetStart()
sstMeta.Range.End = resp.Range.GetEnd()
return &sstMeta, nil
}
func (importer *FileImporter) ingestSST(
ctx context.Context,
sstMeta *import_sstpb.SSTMeta,
regionInfo *RegionInfo,
) (*import_sstpb.IngestResponse, error) {
leader := regionInfo.Leader
if leader == nil {
leader = regionInfo.Region.GetPeers()[0]
}
reqCtx := &kvrpcpb.Context{
RegionId: regionInfo.Region.GetId(),
RegionEpoch: regionInfo.Region.GetRegionEpoch(),
Peer: leader,
}
req := &import_sstpb.IngestRequest{
Context: reqCtx,
Sst: sstMeta,
}
log.Debug("ingest SST", logutil.SSTMeta(sstMeta), logutil.Leader(leader))
resp, err := importer.importClient.IngestSST(ctx, leader.GetStoreId(), req)
if err != nil {
return nil, errors.Trace(err)
}
return resp, nil
}