-
Notifications
You must be signed in to change notification settings - Fork 44
/
etcd.go
417 lines (375 loc) · 10.5 KB
/
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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// Copyright (C) 2015 NTT Innovation Institute, 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package etcdv3
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"sort"
"strings"
syn "sync"
"time"
"github.com/cloudwan/gohan/metrics"
"github.com/cloudwan/gohan/sync"
etcd "github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/clientv3/concurrency"
pb "github.com/coreos/etcd/mvcc/mvccpb"
"github.com/streamrail/concurrent-map"
"github.com/twinj/uuid"
)
const (
processPath = "/gohan/cluster/process"
masterTTL = 10
)
//Sync is struct for etcd based sync
type Sync struct {
locks cmap.ConcurrentMap
timeout time.Duration
etcdClient *etcd.Client
processID string
}
func (s *Sync) withTimeout() context.Context {
ctx, _ := context.WithTimeout(context.Background(), s.timeout)
return ctx
}
//NewSync initialize new etcd sync
func NewSync(etcdServers []string, timeout time.Duration) (*Sync, error) {
sync := &Sync{
locks: cmap.New(),
timeout: timeout,
}
client, err := etcd.New(
etcd.Config{
Endpoints: etcdServers,
DialTimeout: timeout,
},
)
if err != nil {
return nil, err
}
sync.etcdClient = client
hostname, _ := os.Hostname()
sync.processID = hostname + uuid.NewV4().String()
return sync, nil
}
//GetProcessID returns processID
func (s *Sync) GetProcessID() string {
return s.processID
}
func measureTime(timeStarted time.Time, action string) {
metrics.UpdateTimer(timeStarted, "sync.v3.%s", action)
}
func updateCounter(delta int64, counter string) {
metrics.UpdateCounter(delta, "sync.v3.%s", counter)
}
//Update sync update sync
//When jsonString is empty, this method do nothing because
//etcd v3 doesn't support directories.
func (s *Sync) Update(key, jsonString string) error {
defer measureTime(time.Now(), "update")
var err error
if jsonString == "" {
// do nothing, because clientv3 doesn't have directories
return nil
}
_, err = s.etcdClient.Put(s.withTimeout(), key, jsonString)
if err != nil {
log.Error(fmt.Sprintf("failed to sync with backend %s", err))
updateCounter(1, "update.error")
return err
}
return nil
}
//Delete sync update sync
func (s *Sync) Delete(key string, prefix bool) error {
defer measureTime(time.Now(), "delete")
opts := []etcd.OpOption{}
if prefix {
opts = append(opts, etcd.WithPrefix())
}
_, err := s.etcdClient.Delete(s.withTimeout(), key, opts...)
if err != nil {
updateCounter(1, "delete.error")
}
return err
}
//Fetch data from sync
func (s *Sync) Fetch(key string) (*sync.Node, error) {
defer measureTime(time.Now(), "fetch")
dir, err := s.etcdClient.Get(s.withTimeout(), key, etcd.WithPrefix(), etcd.WithSort(etcd.SortByKey, etcd.SortAscend))
if err != nil {
updateCounter(1, "fetch.dir.error")
return nil, err
}
sep := "/"
curr := strings.Count(key, sep)
if curr == 0 {
curr = 1
}
children := recursiveFetch(curr, dir.Kvs, key, sep)
if children == nil {
return nil, fmt.Errorf("Key not found (%s)", key)
}
return children, nil
}
func recursiveFetch(curr int, children []*pb.KeyValue, rootKey, sep string) *sync.Node {
if len(children) == 0 {
return nil
}
if len(children) == 1 {
return handleSingleChild(curr, children[0], rootKey, sep)
}
key := substrN(string(children[0].Key), sep, curr)
commonChild := make(map[string][]*pb.KeyValue)
for _, child := range children {
val := substrN(string(child.Key), sep, curr+1)
commonChild[val] = append(commonChild[val], child)
}
// children nodes has to be alphabetically sorted
keys := make([]string, 0, len(commonChild))
for k, v := range commonChild {
if len(v) != 0 {
keys = append(keys, k)
}
}
sort.Strings(keys)
nodes := make([]*sync.Node, 0, len(keys))
for _, key := range keys {
v := commonChild[key]
if node := recursiveFetch(curr+1, v, rootKey, sep); node != nil {
nodes = append(nodes, node)
}
}
node := &sync.Node{Key: key, Children: nodes}
return node
}
func handleSingleChild(curr int, child *pb.KeyValue, rootKey, sep string) *sync.Node {
key := substrN(string(child.Key), sep, curr)
if string(child.Key) == key {
if string(child.Key) != rootKey && string(child.Key[:len(rootKey)+1]) != rootKey+sep { // remove invalid keys
return nil
}
return &sync.Node{Key: string(child.Key), Value: string(child.Value), Revision: child.ModRevision}
}
nodes := handleSingleChild(curr+1, child, rootKey, sep)
return &sync.Node{Key: key, Children: []*sync.Node{nodes}}
}
func substrN(s, substr string, n int) string {
idx := 1
for i := 0; i < n; i++ {
tmp := strings.Index(s[idx:], substr)
if tmp == -1 {
return s
}
idx += tmp + 1
}
return s[0 : idx-1]
}
//HasLock checks current process owns lock or not
func (s *Sync) HasLock(path string) bool {
return s.locks.Has(path)
}
// Lock locks resources on sync
// This call blocks until you can get lock
func (s *Sync) Lock(path string, block bool) (chan struct{}, error) {
defer measureTime(time.Now(), "lock")
updateCounter(1, "lock.waiting")
defer updateCounter(-1, "lock.waiting")
for {
var err error
lease, err := s.etcdClient.Grant(s.withTimeout(), masterTTL)
var resp *etcd.TxnResponse
if err == nil {
cmp := etcd.Compare(etcd.CreateRevision(path), "=", 0)
put := etcd.OpPut(path, s.processID, etcd.WithLease(lease.ID))
resp, err = s.etcdClient.Txn(s.withTimeout()).If(cmp).Then(put).Commit()
}
if err != nil || !resp.Succeeded {
msg := fmt.Sprintf("failed to lock path %s", path)
if err != nil {
updateCounter(1, "lock.error")
msg = fmt.Sprintf("failed to lock path %s: %s", path, err)
}
log.Notice(msg)
if !block {
return nil, errors.New(msg)
}
time.Sleep(masterTTL * time.Second)
continue
}
s.locks.Set(path, lease.ID)
log.Info("Locked %s", path)
updateCounter(1, "lock.granted")
//Refresh master token
lost := make(chan struct{})
go func() {
defer s.abortLock(path)
defer close(lost)
defer updateCounter(-1, "lock.granted")
for s.HasLock(path) {
resp, err := s.etcdClient.KeepAliveOnce(s.withTimeout(), lease.ID)
if err != nil || resp.TTL <= 0 {
updateCounter(1, "lock.keepalive.error")
log.Notice("failed to keepalive lock for %s %s", path, err)
return
}
time.Sleep(masterTTL / 2 * time.Second)
}
}()
return lost, nil
}
}
func (s *Sync) abortLock(path string) etcd.LeaseID {
leaseID, ok := s.locks.Get(path)
if !ok {
return 0
}
s.locks.Remove(path)
log.Info("Unlocked path %s", path)
return leaseID.(etcd.LeaseID)
}
//Unlock path
func (s *Sync) Unlock(path string) error {
defer measureTime(time.Now(), "unlock")
leaseID := s.abortLock(path)
if leaseID > 0 {
s.etcdClient.Revoke(s.withTimeout(), leaseID)
cmp := etcd.Compare(etcd.Value(path), "=", s.processID)
del := etcd.OpDelete(path)
s.etcdClient.Txn(s.withTimeout()).If(cmp).Then(del).Commit()
}
return nil
}
func eventsFromNode(action string, kvs []*pb.KeyValue, responseChan chan *sync.Event, stopChan chan bool) {
for _, kv := range kvs {
event := &sync.Event{
Action: action,
Key: string(kv.Key),
Revision: kv.ModRevision,
}
if kv.Value != nil {
err := json.Unmarshal(kv.Value, &event.Data)
if err != nil {
log.Warning("failed to unmarshal watch response value %s: %s", kv.Value, err)
}
}
select {
case <-stopChan:
log.Debug("Events from node interrupted by stop")
return
case responseChan <- event:
}
}
}
//Watch keep watch update under the path
func (s *Sync) Watch(path string, responseChan chan *sync.Event, stopChan chan bool, revision int64) error {
options := []etcd.OpOption{etcd.WithPrefix(), etcd.WithSort(etcd.SortByModRevision, etcd.SortAscend)}
if revision != sync.RevisionCurrent {
options = append(options, etcd.WithMinModRev(revision))
}
node, err := s.etcdClient.Get(s.withTimeout(), path, options...)
if err != nil {
updateCounter(1, "watch.get.error")
return err
}
eventsFromNode("get", node.Kvs, responseChan, stopChan)
revision = node.Header.Revision + 1
ctx, cancel := context.WithCancel(context.Background())
errors := make(chan error, 1)
var wg syn.WaitGroup
wg.Add(1)
go func() {
updateCounter(1, "watch.active")
defer updateCounter(-1, "watch.active")
defer wg.Done()
err := func() error {
rch := s.etcdClient.Watch(ctx, path, etcd.WithPrefix(), etcd.WithRev(revision))
for wresp := range rch {
err := wresp.Err()
if err != nil {
updateCounter(1, "watch.client_watch.error")
return err
}
for _, ev := range wresp.Events {
action := "unknown"
switch ev.Type {
case etcd.EventTypePut:
action = "set"
case etcd.EventTypeDelete:
action = "delete"
}
eventsFromNode(action, []*pb.KeyValue{ev.Kv}, responseChan, stopChan)
}
}
return nil
}()
errors <- err
}()
defer func() {
cancel()
wg.Wait()
}()
// since Watch() doesn't close the returning channel even when
// it gets an error, we need a side channel to see the connection state.
session, err := concurrency.NewSession(s.etcdClient, concurrency.WithTTL(masterTTL))
if err != nil {
updateCounter(1, "watch.session.error")
return err
}
defer session.Close()
select {
case <-session.Done():
return fmt.Errorf("Watch aborted by etcd session close")
case <-stopChan:
return nil
case err := <-errors:
return err
}
}
// WatchContext keep watch update under the path until context is canceled
func (s *Sync) WatchContext(ctx context.Context, path string, revision int64) <-chan *sync.Event {
eventCh := make(chan *sync.Event, 32)
stopCh := make(chan bool)
errCh := make(chan error, 1)
go func() {
errCh <- s.Watch(path, eventCh, stopCh, revision)
}()
go func() {
defer close(eventCh)
select {
case <-ctx.Done():
close(stopCh)
// don't return without ensuring Watch finished or we risk panic: send on closed channel
<-errCh
case err := <-errCh:
close(stopCh)
if err != nil {
select {
case eventCh <- &sync.Event{Err: err}:
default:
log.Debug("Unable to send error: '%s' via response chan. Don't linger.", err)
}
}
}
}()
return eventCh
}
// Close closes etcd client
func (s *Sync) Close() {
defer measureTime(time.Now(), "close")
s.etcdClient.Close()
}