-
Notifications
You must be signed in to change notification settings - Fork 289
/
Copy pathupstream.go
322 lines (284 loc) · 8.35 KB
/
upstream.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
// Copyright 2022 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package upstream
import (
"context"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/benbjohnson/clock"
"github.com/pingcap/errors"
"github.com/pingcap/log"
tidbkv "github.com/pingcap/tidb/kv"
"github.com/pingcap/tiflow/cdc/kv"
"github.com/pingcap/tiflow/pkg/config"
"github.com/pingcap/tiflow/pkg/etcd"
"github.com/pingcap/tiflow/pkg/pdutil"
"github.com/pingcap/tiflow/pkg/txnutil/gc"
"github.com/pingcap/tiflow/pkg/version"
tikvconfig "github.com/tikv/client-go/v2/config"
"github.com/tikv/client-go/v2/tikv"
pd "github.com/tikv/pd/client"
uatomic "github.com/uber-go/atomic"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
)
const (
// indicate an upstream is created but not initialized.
uninit int32 = iota
// indicate an upstream is initialized and can work normally.
normal
// indicate an upstream is closing
closing
// indicate an upstream is closed.
closed
maxIdleDuration = time.Minute * 30
)
// Upstream holds resources of a TiDB cluster, it can be shared by many changefeeds
// and processors. All public fields and method of an upstream should be thread-safe.
// Please be careful that never change any exported field of an Upstream.
type Upstream struct {
ID uint64
PdEndpoints []string
SecurityConfig *config.SecurityConfig
PDClient pd.Client
KVStorage tidbkv.Storage
GrpcPool kv.GrpcPool
RegionCache *tikv.RegionCache
PDClock pdutil.Clock
GCManager gc.Manager
// Only use in Close().
cancel func()
mu sync.Mutex
// record the time when Upstream.hc becomes zero.
idleTime time.Time
// use clock to facilitate unit test
clock clock.Clock
wg *sync.WaitGroup
status int32
err uatomic.Error
isDefaultUpstream bool
}
func newUpstream(pdEndpoints []string,
securityConfig *config.SecurityConfig,
) *Upstream {
return &Upstream{
PdEndpoints: pdEndpoints, status: uninit,
SecurityConfig: securityConfig, wg: new(sync.WaitGroup), clock: clock.New(),
}
}
// NewUpstream4Test new an upstream for unit test.
func NewUpstream4Test(pdClient pd.Client) *Upstream {
pdClock := pdutil.NewClock4Test()
gcManager := gc.NewManager(
etcd.GcServiceIDForTest(),
pdClient, pdClock)
res := &Upstream{
ID: testUpstreamID,
PDClient: pdClient,
PDClock: pdClock,
GCManager: gcManager,
status: normal,
wg: new(sync.WaitGroup),
clock: clock.New(),
SecurityConfig: &config.SecurityConfig{},
cancel: func() {},
}
return res
}
// init initializes the upstream
func initUpstream(ctx context.Context, up *Upstream, gcServiceID string) error {
ctx, cancel := context.WithCancel(ctx)
up.cancel = cancel
grpcTLSOption, err := up.SecurityConfig.ToGRPCDialOption()
if err != nil {
up.err.Store(err)
return errors.Trace(err)
}
// init the tikv client tls global config
initGlobalConfig(up.SecurityConfig)
up.PDClient, err = pd.NewClientWithContext(
ctx, up.PdEndpoints, up.SecurityConfig.PDSecurityOption(),
// the default `timeout` is 3s, maybe too small if the pd is busy,
// set to 10s to avoid frequent timeout.
pd.WithCustomTimeoutOption(10*time.Second),
pd.WithGRPCDialOptions(
grpcTLSOption,
grpc.WithBlock(),
grpc.WithConnectParams(grpc.ConnectParams{
Backoff: backoff.Config{
BaseDelay: time.Second,
Multiplier: 1.1,
Jitter: 0.1,
MaxDelay: 3 * time.Second,
},
MinConnectTimeout: 3 * time.Second,
}),
))
if err != nil {
up.err.Store(err)
return errors.Trace(err)
}
clusterID := up.PDClient.GetClusterID(ctx)
if up.ID != 0 && up.ID != clusterID {
err := fmt.Errorf("upstream id missmatch expected %d, actual: %d",
up.ID, clusterID)
up.err.Store(err)
return errors.Trace(err)
}
up.ID = clusterID
// To not block CDC server startup, we need to warn instead of error
// when TiKV is incompatible.
errorTiKVIncompatible := false
err = version.CheckClusterVersion(ctx, up.PDClient,
up.PdEndpoints, up.SecurityConfig, errorTiKVIncompatible)
if err != nil {
up.err.Store(err)
log.Error("init upstream error", zap.Error(err))
return errors.Trace(err)
}
up.KVStorage, err = kv.CreateTiStore(strings.Join(up.PdEndpoints, ","), up.SecurityConfig)
if err != nil {
up.err.Store(err)
return errors.Trace(err)
}
up.GrpcPool = kv.NewGrpcPoolImpl(ctx, up.SecurityConfig)
up.RegionCache = tikv.NewRegionCache(up.PDClient)
up.PDClock, err = pdutil.NewClock(ctx, up.PDClient)
if err != nil {
up.err.Store(err)
return errors.Trace(err)
}
up.GCManager = gc.NewManager(gcServiceID, up.PDClient, up.PDClock)
// Update meta-region label to ensure that meta region isolated from data regions.
pc, err := pdutil.NewPDAPIClient(up.PDClient, up.SecurityConfig)
if err != nil {
log.Error("create pd api client failed", zap.Error(err))
return errors.Trace(err)
}
defer pc.Close()
err = pc.UpdateMetaLabel(ctx)
if err != nil {
log.Warn("Fail to verify region label rule",
zap.Error(err),
zap.Uint64("upstreamID", up.ID),
zap.Strings("upstreamEndpoints", up.PdEndpoints))
}
up.wg.Add(1)
go func() {
defer up.wg.Done()
up.PDClock.Run(ctx)
}()
up.wg.Add(1)
go func() {
defer up.wg.Done()
up.GrpcPool.RecycleConn(ctx)
}()
log.Info("upstream initialize successfully", zap.Uint64("upstreamID", up.ID))
atomic.StoreInt32(&up.status, normal)
return nil
}
// initGlobalConfig initializes the global config for tikv client tls.
// region cache health check will use the global config.
// TODO: remove this function after tikv client tls is refactored.
func initGlobalConfig(secCfg *config.SecurityConfig) {
if secCfg.CAPath != "" || secCfg.CertPath != "" || secCfg.KeyPath != "" {
conf := tikvconfig.GetGlobalConfig()
conf.Security.ClusterSSLCA = secCfg.CAPath
conf.Security.ClusterSSLCert = secCfg.CertPath
conf.Security.ClusterSSLKey = secCfg.KeyPath
conf.Security.ClusterVerifyCN = secCfg.CertAllowedCN
tikvconfig.StoreGlobalConfig(conf)
}
}
// Close all resources.
func (up *Upstream) Close() {
up.mu.Lock()
defer up.mu.Unlock()
up.cancel()
if atomic.LoadInt32(&up.status) == closed ||
atomic.LoadInt32(&up.status) == closing {
return
}
atomic.StoreInt32(&up.status, closing)
if up.PDClient != nil {
up.PDClient.Close()
}
if up.KVStorage != nil {
err := up.KVStorage.Close()
if err != nil {
log.Warn("kv store close failed", zap.Error(err))
}
}
if up.GrpcPool != nil {
up.GrpcPool.Close()
}
if up.RegionCache != nil {
up.RegionCache.Close()
}
if up.PDClock != nil {
up.PDClock.Stop()
}
up.wg.Wait()
atomic.StoreInt32(&up.status, closed)
log.Info("upstream closed", zap.Uint64("upstreamID", up.ID))
}
// Error returns the error during init this stream
func (up *Upstream) Error() error {
return up.err.Load()
}
// IsNormal returns true if the upstream is normal.
func (up *Upstream) IsNormal() bool {
return atomic.LoadInt32(&up.status) == normal && up.err.Load() == nil
}
// IsClosed returns true if the upstream is closed.
func (up *Upstream) IsClosed() bool {
return atomic.LoadInt32(&up.status) == closed
}
// resetIdleTime set the upstream idle time to true
func (up *Upstream) resetIdleTime() {
up.mu.Lock()
defer up.mu.Unlock()
if !up.idleTime.IsZero() {
log.Info("upstream idle time is set to 0",
zap.Uint64("id", up.ID))
up.idleTime = time.Time{}
}
}
// trySetIdleTime set the upstream idle time if it's not zero
func (up *Upstream) trySetIdleTime() {
up.mu.Lock()
defer up.mu.Unlock()
// reset idleTime
if up.idleTime.IsZero() {
log.Info("upstream idle time is set to current time",
zap.Uint64("id", up.ID))
up.idleTime = up.clock.Now()
}
}
// shouldClose returns true if
// this upstream idleTime reaches maxIdleDuration.
func (up *Upstream) shouldClose() bool {
// default upstream should never be closed.
if up.isDefaultUpstream {
return false
}
if !up.idleTime.IsZero() &&
up.clock.Since(up.idleTime) >= maxIdleDuration {
return true
}
return false
}