forked from pingcap/tidb
/
store_manager.go
249 lines (223 loc) · 6.13 KB
/
store_manager.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
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package utils
import (
"context"
"crypto/tls"
"os"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
backuppb "github.com/pingcap/kvproto/pkg/brpb"
"github.com/pingcap/log"
pd "github.com/tikv/pd/client"
berrors "github.com/twotigers93/tidb/br/pkg/errors"
"github.com/twotigers93/tidb/br/pkg/logutil"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
)
const (
dialTimeout = 30 * time.Second
resetRetryTimes = 3
)
// Pool is a lazy pool of gRPC channels.
// When `Get` called, it lazily allocates new connection if connection not full.
// If it's full, then it will return allocated channels round-robin.
type Pool struct {
mu sync.Mutex
conns []*grpc.ClientConn
next int
cap int
newConn func(ctx context.Context) (*grpc.ClientConn, error)
}
func (p *Pool) takeConns() (conns []*grpc.ClientConn) {
p.mu.Lock()
defer p.mu.Unlock()
p.conns, conns = nil, p.conns
p.next = 0
return conns
}
// Close closes the conn pool.
func (p *Pool) Close() {
for _, c := range p.takeConns() {
if err := c.Close(); err != nil {
log.Warn("failed to close clientConn", zap.String("target", c.Target()), zap.Error(err))
}
}
}
// Get tries to get an existing connection from the pool, or make a new one if the pool not full.
func (p *Pool) Get(ctx context.Context) (*grpc.ClientConn, error) {
p.mu.Lock()
defer p.mu.Unlock()
if len(p.conns) < p.cap {
c, err := p.newConn(ctx)
if err != nil {
return nil, err
}
p.conns = append(p.conns, c)
return c, nil
}
conn := p.conns[p.next]
p.next = (p.next + 1) % p.cap
return conn, nil
}
// NewConnPool creates a new Pool by the specified conn factory function and capacity.
func NewConnPool(capacity int, newConn func(ctx context.Context) (*grpc.ClientConn, error)) *Pool {
return &Pool{
cap: capacity,
conns: make([]*grpc.ClientConn, 0, capacity),
newConn: newConn,
mu: sync.Mutex{},
}
}
type StoreManager struct {
pdClient pd.Client
grpcClis struct {
mu sync.Mutex
clis map[uint64]*grpc.ClientConn
}
keepalive keepalive.ClientParameters
tlsConf *tls.Config
}
func (mgr *StoreManager) GetKeepalive() keepalive.ClientParameters {
return mgr.keepalive
}
// NewStoreManager create a new manager for gRPC connections to stores.
func NewStoreManager(pdCli pd.Client, kl keepalive.ClientParameters, tlsConf *tls.Config) *StoreManager {
return &StoreManager{
pdClient: pdCli,
grpcClis: struct {
mu sync.Mutex
clis map[uint64]*grpc.ClientConn
}{clis: make(map[uint64]*grpc.ClientConn)},
keepalive: kl,
tlsConf: tlsConf,
}
}
func (mgr *StoreManager) PDClient() pd.Client {
return mgr.pdClient
}
func (mgr *StoreManager) getGrpcConnLocked(ctx context.Context, storeID uint64) (*grpc.ClientConn, error) {
failpoint.Inject("hint-get-backup-client", func(v failpoint.Value) {
log.Info("failpoint hint-get-backup-client injected, "+
"process will notify the shell.", zap.Uint64("store", storeID))
if sigFile, ok := v.(string); ok {
file, err := os.Create(sigFile)
if err != nil {
log.Warn("failed to create file for notifying, skipping notify", zap.Error(err))
}
if file != nil {
file.Close()
}
}
time.Sleep(3 * time.Second)
})
store, err := mgr.pdClient.GetStore(ctx, storeID)
if err != nil {
return nil, errors.Trace(err)
}
opt := grpc.WithTransportCredentials(insecure.NewCredentials())
if mgr.tlsConf != nil {
opt = grpc.WithTransportCredentials(credentials.NewTLS(mgr.tlsConf))
}
ctx, cancel := context.WithTimeout(ctx, dialTimeout)
bfConf := backoff.DefaultConfig
bfConf.MaxDelay = time.Second * 3
addr := store.GetPeerAddress()
if addr == "" {
addr = store.GetAddress()
}
conn, err := grpc.DialContext(
ctx,
addr,
opt,
grpc.WithBlock(),
grpc.WithConnectParams(grpc.ConnectParams{Backoff: bfConf}),
grpc.WithKeepaliveParams(mgr.keepalive),
)
cancel()
if err != nil {
return nil, berrors.ErrFailedToConnect.Wrap(err).GenWithStack("failed to make connection to store %d", storeID)
}
return conn, nil
}
func (mgr *StoreManager) WithConn(ctx context.Context, storeID uint64, f func(*grpc.ClientConn)) error {
if ctx.Err() != nil {
return errors.Trace(ctx.Err())
}
mgr.grpcClis.mu.Lock()
defer mgr.grpcClis.mu.Unlock()
if conn, ok := mgr.grpcClis.clis[storeID]; ok {
// Find a cached backup client.
f(conn)
return nil
}
conn, err := mgr.getGrpcConnLocked(ctx, storeID)
if err != nil {
return errors.Trace(err)
}
// Cache the conn.
mgr.grpcClis.clis[storeID] = conn
f(conn)
return nil
}
// ResetBackupClient reset the connection for backup client.
func (mgr *StoreManager) ResetBackupClient(ctx context.Context, storeID uint64) (backuppb.BackupClient, error) {
if ctx.Err() != nil {
return nil, errors.Trace(ctx.Err())
}
mgr.grpcClis.mu.Lock()
defer mgr.grpcClis.mu.Unlock()
if conn, ok := mgr.grpcClis.clis[storeID]; ok {
// Find a cached backup client.
log.Info("Reset backup client", zap.Uint64("storeID", storeID))
err := conn.Close()
if err != nil {
log.Warn("close backup connection failed, ignore it", zap.Uint64("storeID", storeID))
}
delete(mgr.grpcClis.clis, storeID)
}
var (
conn *grpc.ClientConn
err error
)
for retry := 0; retry < resetRetryTimes; retry++ {
conn, err = mgr.getGrpcConnLocked(ctx, storeID)
if err != nil {
log.Warn("failed to reset grpc connection, retry it",
zap.Int("retry time", retry), logutil.ShortError(err))
time.Sleep(time.Duration(retry+3) * time.Second)
continue
}
mgr.grpcClis.clis[storeID] = conn
break
}
if err != nil {
return nil, errors.Trace(err)
}
return backuppb.NewBackupClient(conn), nil
}
// Close closes all client in Mgr.
func (mgr *StoreManager) Close() {
if mgr == nil {
return
}
mgr.grpcClis.mu.Lock()
for _, cli := range mgr.grpcClis.clis {
err := cli.Close()
if err != nil {
log.Error("fail to close Mgr", zap.Error(err))
}
}
mgr.grpcClis.mu.Unlock()
}
func (mgr *StoreManager) TLSConfig() *tls.Config {
if mgr == nil {
return nil
}
return mgr.tlsConf
}