-
Notifications
You must be signed in to change notification settings - Fork 131
/
node.go
341 lines (293 loc) · 8.67 KB
/
node.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
// Copyright 2019 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 pump
import (
"crypto/tls"
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/log"
pb "github.com/pingcap/tipb/go-binlog"
"go.uber.org/zap"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"github.com/pingcap/tidb-binlog/pkg/etcd"
"github.com/pingcap/tidb-binlog/pkg/file"
"github.com/pingcap/tidb-binlog/pkg/flags"
"github.com/pingcap/tidb-binlog/pkg/node"
"github.com/pingcap/tidb-binlog/pkg/util"
)
const (
shortIDLen = 8
nodeIDFile = ".node"
lockFile = ".lock"
)
var nodePrefix = "pumps"
type pumpNode struct {
sync.RWMutex
*node.EtcdRegistry
status *node.Status
heartbeatInterval time.Duration
tls *tls.Config
// latestTS and latestTime is used for get approach ts
latestTS int64
latestTime time.Time
// use this function to update max commit ts
getMaxCommitTs func() int64
}
var _ node.Node = &pumpNode{}
// NewPumpNode returns a pumpNode obj that initialized by server config
func NewPumpNode(cfg *Config, getMaxCommitTs func() int64) (node.Node, error) {
if err := checkExclusive(cfg.DataDir); err != nil {
return nil, errors.Trace(err)
}
urlv, err := flags.NewURLsValue(cfg.EtcdURLs)
if err != nil {
return nil, errors.Trace(err)
}
cli, err := etcd.NewClientFromCfg(urlv.StringSlice(), cfg.EtcdDialTimeout, node.DefaultRootPath, cfg.tls)
if err != nil {
return nil, errors.Trace(err)
}
nodeID, err := readLocalNodeID(cfg.DataDir)
if err != nil {
if cfg.NodeID != "" {
nodeID = cfg.NodeID
} else if errors.IsNotFound(err) {
nodeID, err = generateLocalNodeID(cfg.DataDir, cfg.ListenAddr)
if err != nil {
return nil, errors.Trace(err)
}
} else {
return nil, errors.Trace(err)
}
} else if cfg.NodeID != "" {
log.Warn("you had a node ID in local file.[if you want to change the node ID, you should delete the file data-dir/.node file]")
}
advURL, err := url.Parse(cfg.AdvertiseAddr)
if err != nil {
return nil, errors.Annotatef(err, "invalid configuration of advertise addr(%s)", cfg.AdvertiseAddr)
}
// get node's previous status
etcdRegistry := node.NewEtcdRegistry(cli, cfg.EtcdDialTimeout)
previousStatus, err := etcdRegistry.Node(context.Background(), "pumps", nodeID)
if err != nil && !strings.Contains(err.Error(), "in etcd not found") {
return nil, errors.Annotate(err, "fail to get previous node status")
}
state := node.Offline
if previousStatus != nil {
state = previousStatus.State
}
status := &node.Status{
NodeID: nodeID,
Addr: advURL.Host,
State: state,
IsAlive: true,
}
node := &pumpNode{
tls: cfg.tls,
EtcdRegistry: etcdRegistry,
status: status,
heartbeatInterval: time.Duration(cfg.HeartbeatInterval) * time.Second,
getMaxCommitTs: getMaxCommitTs,
}
return node, nil
}
func (p *pumpNode) ID() string {
return p.status.NodeID
}
func (p *pumpNode) Close() error {
return errors.Trace(p.EtcdRegistry.Close())
}
func (p *pumpNode) ShortID() string {
if len(p.status.NodeID) <= shortIDLen {
return p.status.NodeID
}
return p.status.NodeID[0:shortIDLen]
}
func (p *pumpNode) RefreshStatus(ctx context.Context, status *node.Status) error {
p.Lock()
defer p.Unlock()
p.status = status
if p.status.UpdateTS != 0 {
p.latestTS = p.status.UpdateTS
p.latestTime = time.Now()
} else {
p.updateStatus()
}
err := p.UpdateNode(ctx, nodePrefix, status)
if err != nil {
return errors.Trace(err)
}
return nil
}
func (p *pumpNode) Notify(ctx context.Context) error {
drainers, err := p.Nodes(ctx, "drainers")
if err != nil {
return errors.Trace(err)
}
dialerOpts := []grpc.DialOption{
grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
dialer := net.Dialer{}
return dialer.DialContext(ctx, "tcp", addr)
}),
grpc.WithBlock(),
}
var tlsCredential credentials.TransportCredentials
if p.tls != nil {
tlsCredential = credentials.NewTLS(p.tls)
} else {
tlsCredential = insecure.NewCredentials()
}
dialerOpts = append(dialerOpts, grpc.WithTransportCredentials(tlsCredential))
for _, c := range drainers {
if c.State != node.Online {
continue
}
if err := notifyDrainer(ctx, c, dialerOpts); err != nil {
return errors.Trace(err)
}
}
return nil
}
func notifyDrainer(ctx context.Context, c *node.Status, dialerOpts []grpc.DialOption) error {
log.Info("Start trying to notify drainer", zap.String("addr", c.Addr))
var clientConn *grpc.ClientConn
err := util.RetryContext(ctx, 3, time.Second, 2, func(ictx context.Context) error {
log.Info("Connecting drainer", zap.String("addr", c.Addr))
var err error
clientConn, err = grpc.DialContext(ictx, c.Addr, dialerOpts...)
return err
})
if err != nil {
return errors.Annotatef(err, "connect drainer(%s)", c.Addr)
}
defer clientConn.Close()
drainer := pb.NewCisternClient(clientConn)
err = util.RetryContext(ctx, 3, time.Second, 2, func(ictx context.Context) error {
log.Info("Notifying drainer", zap.String("addr", c.Addr))
in := &pb.NotifyReq{}
_, err := drainer.Notify(ictx, in)
return err
})
if err != nil {
return errors.Annotatef(err, "notify drainer(%s)", c.Addr)
}
return nil
}
func (p *pumpNode) NodeStatus() *node.Status {
return p.status
}
func (p *pumpNode) NodesStatus(ctx context.Context) ([]*node.Status, error) {
return p.Nodes(ctx, nodePrefix)
}
func (p *pumpNode) Heartbeat(ctx context.Context) <-chan error {
errc := make(chan error, 1)
go func() {
defer func() {
close(errc)
log.Info("Heartbeat goroutine exited")
}()
for {
select {
case <-ctx.Done():
return
case <-time.After(p.heartbeatInterval):
p.Lock()
p.updateStatus()
if err := p.UpdateNode(ctx, nodePrefix, p.status); err != nil {
errc <- errors.Trace(err)
}
p.Unlock()
}
}
}()
return errc
}
func (p *pumpNode) updateStatus() {
p.status.UpdateTS = util.GetApproachTS(p.latestTS, p.latestTime)
p.status.MaxCommitTS = p.getMaxCommitTs()
}
func (p *pumpNode) Quit() error {
return errors.Trace(p.Close())
}
// readLocalNodeID reads nodeID from a local file
// returns a NotFound error if the nodeID file not exist
// in this case, the caller should invoke generateLocalNodeID()
func readLocalNodeID(dataDir string) (string, error) {
nodeIDPath := filepath.Join(dataDir, nodeIDFile)
if fi, err := os.Stat(nodeIDPath); err != nil {
if os.IsNotExist(err) {
return "", errors.NotFoundf("Local nodeID file not exist: %v", err)
}
return "", err
} else if fi.IsDir() {
return "", errors.Errorf("Local nodeID path is a directory: %s", dataDir)
}
data, err := os.ReadFile(nodeIDPath)
if err != nil {
return "", errors.Annotate(err, "local nodeID file is collapsed")
}
nodeID := FormatNodeID(string(data))
return nodeID, nil
}
func generateLocalNodeID(dataDir string, listenAddr string) (string, error) {
if err := os.MkdirAll(dataDir, file.PrivateDirMode); err != nil {
return "", errors.Trace(err)
}
urllis, err := url.Parse(listenAddr)
if err != nil {
return "", errors.Trace(err)
}
_, port, err := net.SplitHostPort(urllis.Host)
if err != nil {
return "", errors.Trace(err)
}
hostname, err := os.Hostname()
if err != nil {
return "", errors.Trace(err)
}
id := fmt.Sprintf("%s:%s", hostname, port)
nodeID := FormatNodeID(id)
nodeIDPath := filepath.Join(dataDir, nodeIDFile)
if err := os.WriteFile(nodeIDPath, []byte(nodeID), file.PrivateFileMode); err != nil {
return "", errors.Trace(err)
}
return id, nil
}
// checkExclusive tries to get filelock of dataDir in exclusive mode
// if get lock fails, maybe some other pump is running
func checkExclusive(dataDir string) error {
err := os.MkdirAll(dataDir, file.PrivateDirMode)
if err != nil {
return errors.Trace(err)
}
lockPath := filepath.Join(dataDir, lockFile)
// when the process exits, the lockfile will be closed by system
// and automatically release the lock
_, err = file.TryLockFile(lockPath, os.O_WRONLY|os.O_CREATE, file.PrivateFileMode)
return errors.Trace(err)
}
// FormatNodeID formats the nodeID, the nodeID should looks like "host:port"
func FormatNodeID(nodeID string) string {
newNodeID := strings.TrimSpace(nodeID)
return newNodeID
}