-
Notifications
You must be signed in to change notification settings - Fork 1
/
store_etcd.go
366 lines (300 loc) · 8.07 KB
/
store_etcd.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
package election
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/clientv3/concurrency"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/fagongzi/log"
"github.com/fagongzi/util/format"
)
var (
defaultRequestTimeout = time.Second * 10
defaultSlowRequestTime = time.Second * 10
)
type store struct {
sync.RWMutex
opts options
client *clientv3.Client
watchers map[uint64]clientv3.Watcher
watcheCancels map[uint64]context.CancelFunc
leasors map[uint64]clientv3.Lease
}
func (s *store) currentLeader(frag uint64) (uint64, error) {
value, err := s.getValue(getFragPath(s.opts.leaderPath, frag))
if err != nil {
return 0, err
}
if len(value) == 0 {
return 0, nil
}
return format.ParseStrUInt64(string(value))
}
func (s *store) resignLeader(frag, leaderPeerID uint64) error {
resp, err := s.leaderTxn(frag, leaderPeerID).Then(clientv3.OpDelete(getFragPath(s.opts.leaderPath, frag))).Commit()
if err != nil {
return err
}
if !resp.Succeeded {
return errors.New("resign leader failed, we are not leader already")
}
return nil
}
func (s *store) watchLeader(frag uint64) {
watcher := clientv3.NewWatcher(s.client)
ctx, cancel := context.WithCancel(s.client.Ctx())
s.addWatcher(frag, watcher, cancel)
defer s.closeWatcher(frag)
for {
rch := watcher.Watch(ctx, getFragPath(s.opts.leaderPath, frag))
for wresp := range rch {
if wresp.Canceled {
return
}
for _, ev := range wresp.Events {
if ev.Type == mvccpb.DELETE {
return
}
}
}
select {
case <-ctx.Done():
log.Infof("[frag-%d]: leader watcher exit",
frag)
return
default:
}
}
}
func (s *store) campaignLeader(frag, leaderPeerID uint64, becomeLeader, becomeFollower func()) error {
// check expect leader exists
err := s.checkExpectLeader(frag, leaderPeerID)
if err != nil {
return err
}
path := getFragPath(s.opts.leaderPath, frag)
lessor := clientv3.NewLease(s.client)
s.addLessor(frag, lessor)
defer s.closeLessor(frag)
start := time.Now()
ctx, cancel := context.WithTimeout(s.client.Ctx(), defaultRequestTimeout)
leaseResp, err := lessor.Grant(ctx, s.opts.leaseSec)
cancel()
if cost := time.Now().Sub(start); cost > defaultSlowRequestTime {
log.Warnf("lessor grants too slow, cost=<%s>", cost)
}
if err != nil {
return err
}
// The leader key must not exist, so the CreateRevision is 0.
resp, err := s.txn().
If(clientv3.Compare(clientv3.CreateRevision(path), "=", 0)).
Then(clientv3.OpPut(path,
fmt.Sprintf("%d", leaderPeerID),
clientv3.WithLease(clientv3.LeaseID(leaseResp.ID)))).
Commit()
if err != nil {
return err
}
if !resp.Succeeded {
return errors.New("campaign leader failed, other server may campaign ok")
}
ch, err := lessor.KeepAlive(s.client.Ctx(), clientv3.LeaseID(leaseResp.ID))
if err != nil {
log.Errorf("etcd KeepAlive failed with %+v", err)
return err
}
session, err := concurrency.NewSession(s.client,
concurrency.WithLease(clientv3.LeaseID(leaseResp.ID)))
if err != nil {
log.Errorf("create etcd concurrency lock session failed with %+v", err)
return err
}
defer session.Close()
// distributed lock to make sure last leader complete async tasks
lock := concurrency.NewMutex(session, getFragPath(s.opts.lockPath, frag))
for {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
err = lock.Lock(ctx)
if err != nil {
cancel()
log.Errorf("get election lock failed with %+v", err)
continue
}
cancel()
break
}
becomeLeader()
defer func() {
becomeFollower()
lock.Unlock(context.Background())
log.Infof("[frag-%d]: lock released",
frag)
}()
for {
select {
case _, ok := <-ch:
if !ok {
log.Infof("[frag-%d]: channel that keep alive for leader lease is closed",
frag)
return nil
}
case <-s.client.Ctx().Done():
return errors.New("server closed")
}
}
}
func (s *store) closeWatcher(frag uint64) {
s.Lock()
defer s.Unlock()
if watcher, ok := s.watchers[frag]; ok {
watcher.Close()
delete(s.watchers, frag)
}
if cancel, ok := s.watcheCancels[frag]; ok {
cancel()
delete(s.watcheCancels, frag)
}
}
func (s *store) addWatcher(frag uint64, watcher clientv3.Watcher, cancel context.CancelFunc) {
s.Lock()
defer s.Unlock()
s.watchers[frag] = watcher
s.watcheCancels[frag] = cancel
}
func (s *store) checkExpectLeader(frag uint64, leader uint64) error {
value, err := s.getValue(getFragExpectPath(s.opts.leaderPath, frag))
if err != nil {
return err
}
if len(value) == 0 {
return nil
}
if string(value) != fmt.Sprintf("%d", leader) {
return fmt.Errorf("expect leader is %s", string(value))
}
return nil
}
func (s *store) addExpectLeader(frag uint64, oldLeaderPeerID, newLeaderPeerID uint64) error {
lessor := clientv3.NewLease(s.client)
defer lessor.Close()
ctx, cancel := context.WithTimeout(s.client.Ctx(), defaultRequestTimeout)
leaseResp, err := lessor.Grant(ctx, s.opts.leaseSec)
cancel()
if err != nil {
return err
}
resp, err := s.leaderTxn(frag, oldLeaderPeerID).Then(clientv3.OpPut(getFragExpectPath(s.opts.leaderPath, frag),
fmt.Sprintf("%d", newLeaderPeerID),
clientv3.WithLease(leaseResp.ID))).Commit()
if err != nil {
return err
}
if !resp.Succeeded {
return fmt.Errorf("not leader")
}
log.Infof("[frag-%d]: new expect leader %d added, with %d secs ttl",
frag,
newLeaderPeerID,
s.opts.leaseSec)
return nil
}
func (s *store) closeLessor(frag uint64) {
s.Lock()
defer s.Unlock()
if lessor, ok := s.leasors[frag]; ok {
lessor.Close()
delete(s.leasors, frag)
}
}
func (s *store) addLessor(frag uint64, lessor clientv3.Lease) {
s.Lock()
defer s.Unlock()
s.leasors[frag] = lessor
}
func (s *store) getValue(key string, opts ...clientv3.OpOption) ([]byte, error) {
resp, err := s.get(key, opts...)
if err != nil {
return nil, err
}
if resp.Count == 0 {
return nil, nil
} else if resp.Count > 1 {
return nil, fmt.Errorf("invalid get value resp %v, must only one", resp.Kvs)
}
return resp.Kvs[0].Value, nil
}
func (s *store) get(key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error) {
ctx, cancel := context.WithTimeout(s.client.Ctx(), defaultRequestTimeout)
defer cancel()
start := time.Now()
resp, err := clientv3.NewKV(s.client).Get(ctx, key, opts...)
if err != nil {
log.Errorf("read option failure, key=<%s>, errors:\n %+v",
key,
err)
return resp, err
}
if cost := time.Since(start); cost > defaultSlowRequestTime {
log.Warnf("read option is too slow, key=<%s>, cost=<%d>",
key,
cost)
}
return resp, nil
}
func (s *store) leaderTxn(frag, leaderPeerID uint64, cs ...clientv3.Cmp) clientv3.Txn {
return newSlowLogTxn(s.client).If(append(cs, s.leaderCmp(frag, leaderPeerID))...)
}
func (s *store) txn() clientv3.Txn {
return newSlowLogTxn(s.client)
}
func (s *store) leaderCmp(frag, leaderPeerID uint64) clientv3.Cmp {
return clientv3.Compare(clientv3.Value(getFragPath(s.opts.leaderPath, frag)), "=", fmt.Sprintf("%d", leaderPeerID))
}
// slowLogTxn wraps etcd transaction and log slow one.
type slowLogTxn struct {
clientv3.Txn
cancel context.CancelFunc
}
func newSlowLogTxn(client *clientv3.Client) clientv3.Txn {
ctx, cancel := context.WithTimeout(client.Ctx(), defaultRequestTimeout)
return &slowLogTxn{
Txn: client.Txn(ctx),
cancel: cancel,
}
}
func (t *slowLogTxn) If(cs ...clientv3.Cmp) clientv3.Txn {
return &slowLogTxn{
Txn: t.Txn.If(cs...),
cancel: t.cancel,
}
}
func (t *slowLogTxn) Then(ops ...clientv3.Op) clientv3.Txn {
return &slowLogTxn{
Txn: t.Txn.Then(ops...),
cancel: t.cancel,
}
}
// Commit implements Txn Commit interface.
func (t *slowLogTxn) Commit() (*clientv3.TxnResponse, error) {
start := time.Now()
resp, err := t.Txn.Commit()
t.cancel()
cost := time.Now().Sub(start)
if cost > defaultSlowRequestTime {
log.Warnf("txn runs too slow, resp=<%+v> cost=<%s> errors:\n %+v",
resp,
cost,
err)
}
return resp, err
}
func getFragPath(prefix string, frag uint64) string {
return fmt.Sprintf("%s/%d", prefix, frag)
}
func getFragExpectPath(prefix string, frag uint64) string {
return fmt.Sprintf("%s/expect-%d", prefix, frag)
}