-
Notifications
You must be signed in to change notification settings - Fork 1
/
watcher.go
executable file
·112 lines (100 loc) · 2.58 KB
/
watcher.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
/*
* Copyright (c) 2018, https://github.com/airwide-code/airwide.datacenter
* All rights reserved.
*
*
*
*/
package etcd3
import (
"encoding/json"
etcd3 "github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"golang.org/x/net/context"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/naming"
)
// EtcdWatcher is the implementation of grpc.naming.Watcher
type EtcdWatcher struct {
key string
client *etcd3.Client
updates []*naming.Update
ctx context.Context
cancel context.CancelFunc
}
func (w *EtcdWatcher) Close() {
w.cancel()
}
func newEtcdWatcher(key string, cli *etcd3.Client) naming.Watcher {
ctx, cancel := context.WithCancel(context.Background())
w := &EtcdWatcher{
key: key,
client: cli,
ctx: ctx,
updates: make([]*naming.Update, 0),
cancel: cancel,
}
return w
}
func (w *EtcdWatcher) Next() ([]*naming.Update, error) {
updates := make([]*naming.Update, 0)
if len(w.updates) == 0 {
// query addresses from etcd
resp, err := w.client.Get(w.ctx, w.key, etcd3.WithPrefix())
if err == nil {
addrs := extractAddrs(resp)
if len(addrs) > 0 {
for _, v := range addrs {
updates = append(updates, &naming.Update{Op: naming.Add, Addr: v.Addr, Metadata: &v.Metadata})
}
w.updates = updates
return updates, nil
}
} else {
grpclog.Println("Etcd Watcher Get key error:", err)
}
}
// generate etcd Watcher
rch := w.client.Watch(w.ctx, w.key, etcd3.WithPrefix())
for wresp := range rch {
for _, ev := range wresp.Events {
switch ev.Type {
case mvccpb.PUT:
nodeData := NodeData{}
err := json.Unmarshal([]byte(ev.Kv.Value), &nodeData)
if err != nil {
grpclog.Println("Parse node data error:", err)
continue
}
updates = append(updates, &naming.Update{Op: naming.Add, Addr: nodeData.Addr, Metadata: &nodeData.Metadata})
case mvccpb.DELETE:
nodeData := NodeData{}
err := json.Unmarshal([]byte(ev.Kv.Value), &nodeData)
if err != nil {
grpclog.Println("Parse node data error:", err)
continue
}
updates = append(updates, &naming.Update{Op: naming.Delete, Addr: nodeData.Addr, Metadata: &nodeData.Metadata})
}
}
}
return updates, nil
}
func extractAddrs(resp *etcd3.GetResponse) []NodeData {
addrs := []NodeData{}
if resp == nil || resp.Kvs == nil {
return addrs
}
for i := range resp.Kvs {
if v := resp.Kvs[i].Value; v != nil {
nodeData := NodeData{}
err := json.Unmarshal(v, &nodeData)
if err != nil {
grpclog.Println("Parse node data error:", err)
continue
}
addrs = append(addrs, nodeData)
}
}
return addrs
}