forked from pingcap/br
-
Notifications
You must be signed in to change notification settings - Fork 0
/
split_client.go
executable file
·551 lines (517 loc) · 16.7 KB
/
split_client.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
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package restore
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"path"
"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/kvproto/pkg/pdpb"
"github.com/pingcap/kvproto/pkg/tikvpb"
"github.com/pingcap/log"
pd "github.com/tikv/pd/client"
"github.com/tikv/pd/server/schedule/placement"
"go.uber.org/multierr"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/status"
berrors "github.com/pingcap/br/pkg/errors"
"github.com/pingcap/br/pkg/httputil"
"github.com/pingcap/br/pkg/logutil"
)
const (
splitRegionMaxRetryTime = 4
)
// SplitClient is an external client used by RegionSplitter.
type SplitClient interface {
// GetStore gets a store by a store id.
GetStore(ctx context.Context, storeID uint64) (*metapb.Store, error)
// GetRegion gets a region which includes a specified key.
GetRegion(ctx context.Context, key []byte) (*RegionInfo, error)
// GetRegionByID gets a region by a region id.
GetRegionByID(ctx context.Context, regionID uint64) (*RegionInfo, error)
// SplitRegion splits a region from a key, if key is not included in the region, it will return nil.
// note: the key should not be encoded
SplitRegion(ctx context.Context, regionInfo *RegionInfo, key []byte) (*RegionInfo, error)
// BatchSplitRegions splits a region from a batch of keys.
// note: the keys should not be encoded
BatchSplitRegions(ctx context.Context, regionInfo *RegionInfo, keys [][]byte) ([]*RegionInfo, error)
// BatchSplitRegionsWithOrigin splits a region from a batch of keys and return the original region and split new regions
BatchSplitRegionsWithOrigin(ctx context.Context, regionInfo *RegionInfo, keys [][]byte) (*RegionInfo, []*RegionInfo, error)
// ScatterRegion scatters a specified region.
ScatterRegion(ctx context.Context, regionInfo *RegionInfo) error
// GetOperator gets the status of operator of the specified region.
GetOperator(ctx context.Context, regionID uint64) (*pdpb.GetOperatorResponse, error)
// ScanRegion gets a list of regions, starts from the region that contains key.
// Limit limits the maximum number of regions returned.
ScanRegions(ctx context.Context, key, endKey []byte, limit int) ([]*RegionInfo, error)
// GetPlacementRule loads a placement rule from PD.
GetPlacementRule(ctx context.Context, groupID, ruleID string) (placement.Rule, error)
// SetPlacementRule insert or update a placement rule to PD.
SetPlacementRule(ctx context.Context, rule placement.Rule) error
// DeletePlacementRule removes a placement rule from PD.
DeletePlacementRule(ctx context.Context, groupID, ruleID string) error
// SetStoreLabel add or update specified label of stores. If labelValue
// is empty, it clears the label.
SetStoresLabel(ctx context.Context, stores []uint64, labelKey, labelValue string) error
}
// pdClient is a wrapper of pd client, can be used by RegionSplitter.
type pdClient struct {
mu sync.Mutex
client pd.Client
tlsConf *tls.Config
storeCache map[uint64]*metapb.Store
}
// NewSplitClient returns a client used by RegionSplitter.
func NewSplitClient(client pd.Client, tlsConf *tls.Config) SplitClient {
return &pdClient{
client: client,
tlsConf: tlsConf,
storeCache: make(map[uint64]*metapb.Store),
}
}
func (c *pdClient) GetStore(ctx context.Context, storeID uint64) (*metapb.Store, error) {
c.mu.Lock()
defer c.mu.Unlock()
store, ok := c.storeCache[storeID]
if ok {
return store, nil
}
store, err := c.client.GetStore(ctx, storeID)
if err != nil {
return nil, errors.Trace(err)
}
c.storeCache[storeID] = store
return store, nil
}
func (c *pdClient) GetRegion(ctx context.Context, key []byte) (*RegionInfo, error) {
region, err := c.client.GetRegion(ctx, key)
if err != nil {
return nil, errors.Trace(err)
}
if region == nil {
return nil, nil
}
return &RegionInfo{
Region: region.Meta,
Leader: region.Leader,
}, nil
}
func (c *pdClient) GetRegionByID(ctx context.Context, regionID uint64) (*RegionInfo, error) {
region, err := c.client.GetRegionByID(ctx, regionID)
if err != nil {
return nil, errors.Trace(err)
}
if region == nil {
return nil, nil
}
return &RegionInfo{
Region: region.Meta,
Leader: region.Leader,
}, nil
}
func (c *pdClient) SplitRegion(ctx context.Context, regionInfo *RegionInfo, key []byte) (*RegionInfo, error) {
var peer *metapb.Peer
if regionInfo.Leader != nil {
peer = regionInfo.Leader
} else {
if len(regionInfo.Region.Peers) == 0 {
return nil, errors.Annotate(berrors.ErrRestoreNoPeer, "region does not have peer")
}
peer = regionInfo.Region.Peers[0]
}
storeID := peer.GetStoreId()
store, err := c.GetStore(ctx, storeID)
if err != nil {
return nil, errors.Trace(err)
}
conn, err := grpc.Dial(store.GetAddress(), grpc.WithInsecure())
if err != nil {
return nil, errors.Trace(err)
}
defer conn.Close()
client := tikvpb.NewTikvClient(conn)
resp, err := client.SplitRegion(ctx, &kvrpcpb.SplitRegionRequest{
Context: &kvrpcpb.Context{
RegionId: regionInfo.Region.Id,
RegionEpoch: regionInfo.Region.RegionEpoch,
Peer: peer,
},
SplitKey: key,
})
if err != nil {
return nil, errors.Trace(err)
}
if resp.RegionError != nil {
log.Error("fail to split region",
logutil.Region(regionInfo.Region),
logutil.Key("key", key),
zap.Stringer("regionErr", resp.RegionError))
return nil, errors.Annotatef(berrors.ErrRestoreSplitFailed, "err=%v", resp.RegionError)
}
// BUG: Left is deprecated, it may be nil even if split is succeed!
// Assume the new region is the left one.
newRegion := resp.GetLeft()
if newRegion == nil {
regions := resp.GetRegions()
for _, r := range regions {
if bytes.Equal(r.GetStartKey(), regionInfo.Region.GetStartKey()) {
newRegion = r
break
}
}
}
if newRegion == nil {
return nil, errors.Annotate(berrors.ErrRestoreSplitFailed, "new region is nil")
}
var leader *metapb.Peer
// Assume the leaders will be at the same store.
if regionInfo.Leader != nil {
for _, p := range newRegion.GetPeers() {
if p.GetStoreId() == regionInfo.Leader.GetStoreId() {
leader = p
break
}
}
}
return &RegionInfo{
Region: newRegion,
Leader: leader,
}, nil
}
func splitRegionWithFailpoint(
ctx context.Context,
regionInfo *RegionInfo,
peer *metapb.Peer,
client tikvpb.TikvClient,
keys [][]byte,
) (*kvrpcpb.SplitRegionResponse, error) {
failpoint.Inject("not-leader-error", func(injectNewLeader failpoint.Value) {
log.Debug("failpoint not-leader-error injected.")
resp := &kvrpcpb.SplitRegionResponse{
RegionError: &errorpb.Error{
NotLeader: &errorpb.NotLeader{
RegionId: regionInfo.Region.Id,
},
},
}
if injectNewLeader.(bool) {
resp.RegionError.NotLeader.Leader = regionInfo.Leader
}
failpoint.Return(resp, nil)
})
failpoint.Inject("somewhat-retryable-error", func() {
log.Debug("failpoint somewhat-retryable-error injected.")
failpoint.Return(&kvrpcpb.SplitRegionResponse{
RegionError: &errorpb.Error{
ServerIsBusy: &errorpb.ServerIsBusy{},
},
}, nil)
})
return client.SplitRegion(ctx, &kvrpcpb.SplitRegionRequest{
Context: &kvrpcpb.Context{
RegionId: regionInfo.Region.Id,
RegionEpoch: regionInfo.Region.RegionEpoch,
Peer: peer,
},
SplitKeys: keys,
})
}
func (c *pdClient) sendSplitRegionRequest(
ctx context.Context, regionInfo *RegionInfo, keys [][]byte,
) (*kvrpcpb.SplitRegionResponse, error) {
var splitErrors error
for i := 0; i < splitRegionMaxRetryTime; i++ {
var peer *metapb.Peer
// scanRegions may return empty Leader in https://github.com/tikv/pd/blob/v4.0.8/server/grpc_service.go#L524
// so wee also need check Leader.Id != 0
if regionInfo.Leader != nil && regionInfo.Leader.Id != 0 {
peer = regionInfo.Leader
} else {
if len(regionInfo.Region.Peers) == 0 {
return nil, multierr.Append(splitErrors,
errors.Annotatef(berrors.ErrRestoreNoPeer, "region[%d] doesn't have any peer", regionInfo.Region.GetId()))
}
peer = regionInfo.Region.Peers[0]
}
storeID := peer.GetStoreId()
store, err := c.GetStore(ctx, storeID)
if err != nil {
return nil, multierr.Append(splitErrors, err)
}
opt := grpc.WithInsecure()
if c.tlsConf != nil {
opt = grpc.WithTransportCredentials(credentials.NewTLS(c.tlsConf))
}
conn, err := grpc.Dial(store.GetAddress(), opt)
if err != nil {
return nil, multierr.Append(splitErrors, err)
}
defer conn.Close()
client := tikvpb.NewTikvClient(conn)
resp, err := splitRegionWithFailpoint(ctx, regionInfo, peer, client, keys)
if err != nil {
return nil, multierr.Append(splitErrors, err)
}
if resp.RegionError != nil {
log.Error("fail to split region",
logutil.Region(regionInfo.Region),
zap.Stringer("regionErr", resp.RegionError))
splitErrors = multierr.Append(splitErrors,
errors.Annotatef(berrors.ErrRestoreSplitFailed, "split region failed: err=%v", resp.RegionError))
if nl := resp.RegionError.NotLeader; nl != nil {
if leader := nl.GetLeader(); leader != nil {
regionInfo.Leader = leader
} else {
newRegionInfo, findLeaderErr := c.GetRegionByID(ctx, nl.RegionId)
if findLeaderErr != nil {
return nil, multierr.Append(splitErrors, findLeaderErr)
}
if !checkRegionEpoch(newRegionInfo, regionInfo) {
return nil, multierr.Append(splitErrors, berrors.ErrKVEpochNotMatch)
}
log.Info("find new leader", zap.Uint64("new leader", newRegionInfo.Leader.Id))
regionInfo = newRegionInfo
}
log.Info("split region meet not leader error, retrying",
zap.Int("retry times", i),
zap.Uint64("regionID", regionInfo.Region.Id),
zap.Any("new leader", regionInfo.Leader),
)
continue
}
// TODO: we don't handle RegionNotMatch and RegionNotFound here,
// because I think we don't have enough information to retry.
// But maybe we can handle them here by some information the error itself provides.
if resp.RegionError.ServerIsBusy != nil ||
resp.RegionError.StaleCommand != nil {
log.Warn("a error occurs on split region",
zap.Int("retry times", i),
zap.Uint64("regionID", regionInfo.Region.Id),
zap.String("error", resp.RegionError.Message),
zap.Any("error verbose", resp.RegionError),
)
continue
}
return nil, errors.Trace(splitErrors)
}
return resp, nil
}
return nil, errors.Trace(splitErrors)
}
func (c *pdClient) BatchSplitRegionsWithOrigin(
ctx context.Context, regionInfo *RegionInfo, keys [][]byte,
) (*RegionInfo, []*RegionInfo, error) {
resp, err := c.sendSplitRegionRequest(ctx, regionInfo, keys)
if err != nil {
return nil, nil, errors.Trace(err)
}
regions := resp.GetRegions()
newRegionInfos := make([]*RegionInfo, 0, len(regions))
var originRegion *RegionInfo
for _, region := range regions {
var leader *metapb.Peer
// Assume the leaders will be at the same store.
if regionInfo.Leader != nil {
for _, p := range region.GetPeers() {
if p.GetStoreId() == regionInfo.Leader.GetStoreId() {
leader = p
break
}
}
}
// original region
if region.GetId() == regionInfo.Region.GetId() {
originRegion = &RegionInfo{
Region: region,
Leader: leader,
}
continue
}
newRegionInfos = append(newRegionInfos, &RegionInfo{
Region: region,
Leader: leader,
})
}
return originRegion, newRegionInfos, nil
}
func (c *pdClient) BatchSplitRegions(
ctx context.Context, regionInfo *RegionInfo, keys [][]byte,
) ([]*RegionInfo, error) {
_, newRegions, err := c.BatchSplitRegionsWithOrigin(ctx, regionInfo, keys)
return newRegions, err
}
func (c *pdClient) ScatterRegion(ctx context.Context, regionInfo *RegionInfo) error {
return c.client.ScatterRegion(ctx, regionInfo.Region.GetId())
}
func (c *pdClient) GetOperator(ctx context.Context, regionID uint64) (*pdpb.GetOperatorResponse, error) {
return c.client.GetOperator(ctx, regionID)
}
func (c *pdClient) ScanRegions(ctx context.Context, key, endKey []byte, limit int) ([]*RegionInfo, error) {
regions, err := c.client.ScanRegions(ctx, key, endKey, limit)
if err != nil {
return nil, errors.Trace(err)
}
regionInfos := make([]*RegionInfo, 0, len(regions))
for _, region := range regions {
regionInfos = append(regionInfos, &RegionInfo{
Region: region.Meta,
Leader: region.Leader,
})
}
return regionInfos, nil
}
func (c *pdClient) GetPlacementRule(ctx context.Context, groupID, ruleID string) (placement.Rule, error) {
var rule placement.Rule
addr := c.getPDAPIAddr()
if addr == "" {
return rule, errors.Annotate(berrors.ErrRestoreSplitFailed, "failed to add stores labels: no leader")
}
req, err := http.NewRequestWithContext(ctx, "GET", addr+path.Join("/pd/api/v1/config/rule", groupID, ruleID), nil)
if err != nil {
return rule, errors.Trace(err)
}
res, err := httputil.NewClient(c.tlsConf).Do(req)
if err != nil {
return rule, errors.Trace(err)
}
b, err := io.ReadAll(res.Body)
if err != nil {
return rule, errors.Trace(err)
}
res.Body.Close()
err = json.Unmarshal(b, &rule)
if err != nil {
return rule, errors.Trace(err)
}
return rule, nil
}
func (c *pdClient) SetPlacementRule(ctx context.Context, rule placement.Rule) error {
addr := c.getPDAPIAddr()
if addr == "" {
return errors.Annotate(berrors.ErrPDLeaderNotFound, "failed to add stores labels")
}
m, _ := json.Marshal(rule)
req, err := http.NewRequestWithContext(ctx, "POST", addr+path.Join("/pd/api/v1/config/rule"), bytes.NewReader(m))
if err != nil {
return errors.Trace(err)
}
res, err := httputil.NewClient(c.tlsConf).Do(req)
if err != nil {
return errors.Trace(err)
}
return errors.Trace(res.Body.Close())
}
func (c *pdClient) DeletePlacementRule(ctx context.Context, groupID, ruleID string) error {
addr := c.getPDAPIAddr()
if addr == "" {
return errors.Annotate(berrors.ErrPDLeaderNotFound, "failed to add stores labels")
}
req, err := http.NewRequestWithContext(ctx, "DELETE", addr+path.Join("/pd/api/v1/config/rule", groupID, ruleID), nil)
if err != nil {
return errors.Trace(err)
}
res, err := httputil.NewClient(c.tlsConf).Do(req)
if err != nil {
return errors.Trace(err)
}
return errors.Trace(res.Body.Close())
}
func (c *pdClient) SetStoresLabel(
ctx context.Context, stores []uint64, labelKey, labelValue string,
) error {
b := []byte(fmt.Sprintf(`{"%s": "%s"}`, labelKey, labelValue))
addr := c.getPDAPIAddr()
if addr == "" {
return errors.Annotate(berrors.ErrPDLeaderNotFound, "failed to add stores labels")
}
httpCli := httputil.NewClient(c.tlsConf)
for _, id := range stores {
req, err := http.NewRequestWithContext(
ctx, "POST",
addr+path.Join("/pd/api/v1/store", strconv.FormatUint(id, 10), "label"),
bytes.NewReader(b),
)
if err != nil {
return errors.Trace(err)
}
res, err := httpCli.Do(req)
if err != nil {
return errors.Trace(err)
}
err = res.Body.Close()
if err != nil {
return errors.Trace(err)
}
}
return nil
}
func (c *pdClient) getPDAPIAddr() string {
addr := c.client.GetLeaderAddr()
if addr != "" && !strings.HasPrefix(addr, "http") {
addr = "http://" + addr
}
return strings.TrimRight(addr, "/")
}
func checkRegionEpoch(new, old *RegionInfo) bool {
return new.Region.GetId() == old.Region.GetId() &&
new.Region.GetRegionEpoch().GetVersion() == old.Region.GetRegionEpoch().GetVersion() &&
new.Region.GetRegionEpoch().GetConfVer() == old.Region.GetRegionEpoch().GetConfVer()
}
type scatterBackoffer struct {
attempt int
baseBackoff time.Duration
}
func (b *scatterBackoffer) exponentialBackoff() time.Duration {
bo := b.baseBackoff
b.attempt--
if b.attempt == 0 {
return 0
}
b.baseBackoff *= 2
return bo
}
func (b *scatterBackoffer) giveUp() time.Duration {
b.attempt = 0
return 0
}
// NextBackoff returns a duration to wait before retrying again
func (b *scatterBackoffer) NextBackoff(err error) time.Duration {
// There are 3 type of reason that PD would reject a `scatter` request:
// (1) region %d has no leader
// (2) region %d is hot
// (3) region %d is not fully replicated
//
// (2) shouldn't happen in a recently splitted region.
// (1) and (3) might happen, and should be retried.
grpcErr := status.Convert(err)
if grpcErr == nil {
return b.giveUp()
}
if strings.Contains(grpcErr.Message(), "is not fully replicated") {
log.Info("scatter region failed, retring", logutil.ShortError(err), zap.Int("attempt-remain", b.attempt))
return b.exponentialBackoff()
}
if strings.Contains(grpcErr.Message(), "has no leader") {
log.Info("scatter region failed, retring", logutil.ShortError(err), zap.Int("attempt-remain", b.attempt))
return b.exponentialBackoff()
}
return b.giveUp()
}
// Attempt returns the remain attempt times
func (b *scatterBackoffer) Attempt() int {
return b.attempt
}