-
Notifications
You must be signed in to change notification settings - Fork 0
/
leader.go
391 lines (341 loc) · 10.1 KB
/
leader.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
// Copyright 2016 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 server
import (
"context"
"fmt"
"math/rand"
"path"
"strings"
"time"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/pingcap/kvproto/pkg/pdpb"
"github.com/pingcap/pd/pkg/etcdutil"
"github.com/pingcap/pd/pkg/logutil"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// The timeout to wait transfer etcd leader to complete.
const moveLeaderTimeout = 5 * time.Second
// IsLeader returns whether the server is leader or not.
func (s *Server) IsLeader() bool {
// If server is not started. Both leaderID and ID could be 0.
return !s.isClosed() && s.GetLeaderID() == s.ID()
}
// GetLeaderID returns current leader's member ID.
func (s *Server) GetLeaderID() uint64 {
return s.GetLeader().GetMemberId()
}
// GetLeader returns current leader of pd cluster.
func (s *Server) GetLeader() *pdpb.Member {
leader := s.leader.Load()
if leader == nil {
return nil
}
member := leader.(*pdpb.Member)
if member.GetMemberId() == 0 {
return nil
}
return member
}
func (s *Server) enableLeader() {
s.leader.Store(s.member)
}
func (s *Server) disableLeader() {
s.leader.Store(&pdpb.Member{})
}
func (s *Server) getLeaderPath() string {
return path.Join(s.rootPath, "leader")
}
func (s *Server) leaderLoop() {
defer logutil.LogPanic()
defer s.serverLoopWg.Done()
for {
if s.isClosed() {
log.Infof("server is closed, return leader loop")
return
}
if s.GetEtcdLeader() == 0 {
log.Error("no etcd leader, check leader later")
time.Sleep(200 * time.Millisecond)
continue
}
leader, rev, err := getLeader(s.client, s.getLeaderPath())
if err != nil {
log.Errorf("get leader err %v", err)
time.Sleep(200 * time.Millisecond)
continue
}
if leader != nil {
if s.isSameLeader(leader) {
// oh, we are already leader, we may meet something wrong
// in previous campaignLeader. we can delete and campaign again.
log.Warnf("leader is still %s, delete and campaign again", leader)
if err = s.deleteLeaderKey(); err != nil {
log.Errorf("delete leader key err %s", err)
time.Sleep(200 * time.Millisecond)
continue
}
} else {
log.Infof("leader is %s, watch it", leader)
s.watchLeader(leader, rev)
log.Info("leader changed, try to campaign leader")
}
}
etcdLeader := s.GetEtcdLeader()
if etcdLeader != s.ID() {
log.Infof("%v is not etcd leader, skip campaign leader and check later", s.Name())
time.Sleep(200 * time.Millisecond)
continue
}
if err = s.campaignLeader(); err != nil {
log.Errorf("campaign leader err %s", fmt.Sprintf("%+v", err))
}
}
}
func (s *Server) etcdLeaderLoop() {
defer logutil.LogPanic()
defer s.serverLoopWg.Done()
ctx, cancel := context.WithCancel(s.serverLoopCtx)
defer cancel()
for {
select {
case <-time.After(s.cfg.leaderPriorityCheckInterval.Duration):
etcdLeader := s.GetEtcdLeader()
if etcdLeader == s.ID() || etcdLeader == 0 {
break
}
myPriority, err := s.GetMemberLeaderPriority(s.ID())
if err != nil {
log.Errorf("failed to load leader priority: %v", err)
break
}
leaderPriority, err := s.GetMemberLeaderPriority(etcdLeader)
if err != nil {
log.Errorf("failed to load leader priority: %v", err)
break
}
if myPriority > leaderPriority {
err := s.MoveEtcdLeader(ctx, etcdLeader, s.ID())
if err != nil {
log.Errorf("failed to transfer etcd leader: %v", err)
} else {
log.Infof("etcd leader moved from %v to %v", etcdLeader, s.ID())
}
}
case <-ctx.Done():
log.Info("server is closed, exit etcd leader loop")
return
}
}
}
// MoveEtcdLeader tries to transfer etcd leader.
func (s *Server) MoveEtcdLeader(ctx context.Context, old, new uint64) error {
moveCtx, cancel := context.WithTimeout(ctx, moveLeaderTimeout)
defer cancel()
return errors.WithStack(s.etcd.Server.MoveLeader(moveCtx, old, new))
}
// getLeader gets server leader from etcd.
func getLeader(c *clientv3.Client, leaderPath string) (*pdpb.Member, int64, error) {
leader := &pdpb.Member{}
ok, rev, err := getProtoMsgWithModRev(c, leaderPath, leader)
if err != nil {
return nil, 0, err
}
if !ok {
return nil, 0, nil
}
return leader, rev, nil
}
// GetEtcdLeader returns the etcd leader ID.
func (s *Server) GetEtcdLeader() uint64 {
return s.etcd.Server.Lead()
}
func (s *Server) isSameLeader(leader *pdpb.Member) bool {
return leader.GetMemberId() == s.ID()
}
func (s *Server) memberInfo() (member *pdpb.Member, marshalStr string) {
leader := &pdpb.Member{
Name: s.Name(),
MemberId: s.ID(),
ClientUrls: strings.Split(s.cfg.AdvertiseClientUrls, ","),
PeerUrls: strings.Split(s.cfg.AdvertisePeerUrls, ","),
}
data, err := leader.Marshal()
if err != nil {
// can't fail, so panic here.
log.Fatalf("marshal leader %s err %v", leader, err)
}
return leader, string(data)
}
func (s *Server) campaignLeader() error {
log.Infof("start to campaign leader %s", s.Name())
lessor := clientv3.NewLease(s.client)
defer func() {
lessor.Close()
log.Info("exit campaign leader")
}()
start := time.Now()
ctx, cancel := context.WithTimeout(s.client.Ctx(), requestTimeout)
leaseResp, err := lessor.Grant(ctx, s.cfg.LeaderLease)
cancel()
if cost := time.Since(start); cost > slowRequestTime {
log.Warnf("lessor grants too slow, cost %s", cost)
}
if err != nil {
return errors.WithStack(err)
}
leaderKey := s.getLeaderPath()
// The leader key must not exist, so the CreateRevision is 0.
resp, err := s.txn().
If(clientv3.Compare(clientv3.CreateRevision(leaderKey), "=", 0)).
Then(clientv3.OpPut(leaderKey, s.memberValue, clientv3.WithLease(leaseResp.ID))).
Commit()
if err != nil {
return errors.WithStack(err)
}
if !resp.Succeeded {
return errors.New("failed to campaign leader, other server may campaign ok")
}
// Make the leader keepalived.
ctx, cancel = context.WithCancel(s.serverLoopCtx)
defer cancel()
ch, err := lessor.KeepAlive(ctx, leaseResp.ID)
if err != nil {
return errors.WithStack(err)
}
log.Infof("campaign leader ok %s", s.Name())
err = s.scheduleOpt.reload(s.kv)
if err != nil {
return err
}
// Try to create raft cluster.
err = s.createRaftCluster()
if err != nil {
return err
}
defer s.stopRaftCluster()
log.Debug("sync timestamp for tso")
if err = s.syncTimestamp(); err != nil {
return err
}
defer s.ts.Store(&atomicObject{
physical: zeroTime,
})
s.enableLeader()
defer s.disableLeader()
log.Infof("cluster version is %s", s.scheduleOpt.loadClusterVersion())
log.Infof("PD cluster leader %s is ready to serve", s.Name())
CheckPDVersion(s.scheduleOpt)
tsTicker := time.NewTicker(updateTimestampStep)
defer tsTicker.Stop()
for {
select {
case _, ok := <-ch:
if !ok {
log.Info("keep alive channel is closed")
return nil
}
case <-tsTicker.C:
if err = s.updateTimestamp(); err != nil {
log.Info("failed to update timestamp")
return err
}
etcdLeader := s.GetEtcdLeader()
if etcdLeader != s.ID() {
log.Infof("etcd leader changed, %s resigns leadership", s.Name())
return nil
}
case <-ctx.Done():
return errors.New("server closed")
}
}
}
func (s *Server) watchLeader(leader *pdpb.Member, revision int64) {
s.leader.Store(leader)
defer s.leader.Store(&pdpb.Member{})
watcher := clientv3.NewWatcher(s.client)
defer watcher.Close()
ctx, cancel := context.WithCancel(s.serverLoopCtx)
defer cancel()
// The revision is the revision of last modification on this key.
// If the revision is compacted, will meet required revision has been compacted error.
// In this case, use the compact revision to re-watch the key.
for {
// gofail: var delayWatcher struct{}
rch := watcher.Watch(ctx, s.getLeaderPath(), clientv3.WithRev(revision))
for wresp := range rch {
// meet compacted error, use the compact revision.
if wresp.CompactRevision != 0 {
log.Warnf("required revision %d has been compacted, use the compact revision %d", revision, wresp.CompactRevision)
revision = wresp.CompactRevision
break
}
if wresp.Canceled {
log.Errorf("leader watcher is canceled with revision: %d, error: %s", revision, wresp.Err())
return
}
for _, ev := range wresp.Events {
if ev.Type == mvccpb.DELETE {
log.Info("leader is deleted")
return
}
}
}
select {
case <-ctx.Done():
// server closed, return
return
default:
}
}
}
// ResignLeader resigns current PD's leadership. If nextLeader is empty, all
// other pd-servers can campaign.
func (s *Server) ResignLeader(nextLeader string) error {
log.Infof("%s tries to resign leader with next leader directive: %v", s.Name(), nextLeader)
// Determine next leaders.
var leaderIDs []uint64
res, err := etcdutil.ListEtcdMembers(s.client)
if err != nil {
return err
}
for _, member := range res.Members {
if (nextLeader == "" && member.ID != s.id) || (nextLeader != "" && member.Name == nextLeader) {
leaderIDs = append(leaderIDs, member.GetID())
}
}
if len(leaderIDs) == 0 {
return errors.New("no valid pd to transfer leader")
}
nextLeaderID := leaderIDs[rand.Intn(len(leaderIDs))]
log.Infof("%s ready to resign leader, next leader: %v", s.Name(), nextLeaderID)
err = s.MoveEtcdLeader(s.serverLoopCtx, s.ID(), nextLeaderID)
return errors.WithStack(err)
}
func (s *Server) deleteLeaderKey() error {
// delete leader itself and let others start a new election again.
leaderKey := s.getLeaderPath()
resp, err := s.leaderTxn().Then(clientv3.OpDelete(leaderKey)).Commit()
if err != nil {
return errors.WithStack(err)
}
if !resp.Succeeded {
return errors.New("resign leader failed, we are not leader already")
}
return nil
}
func (s *Server) leaderCmp() clientv3.Cmp {
return clientv3.Compare(clientv3.Value(s.getLeaderPath()), "=", s.memberValue)
}