forked from st3v/go-plugins
/
watcher.go
94 lines (80 loc) · 1.59 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
package etcd
import (
"context"
"sync"
etcd "github.com/coreos/etcd/client"
"github.com/micro/go-micro/registry"
)
type etcdWatcher struct {
ctx context.Context
once *sync.Once
stop chan bool
w etcd.Watcher
}
func newEtcdWatcher(r *etcdRegistry, opts ...registry.WatchOption) (registry.Watcher, error) {
var wo registry.WatchOptions
for _, o := range opts {
o(&wo)
}
var once sync.Once
ctx, cancel := context.WithCancel(context.Background())
stop := make(chan bool, 1)
go func() {
<-stop
cancel()
}()
// watch everything by default
watchPath := prefix
// watch a service
if len(wo.Service) > 0 {
watchPath = servicePath(wo.Service)
}
return &etcdWatcher{
ctx: ctx,
w: r.client.Watcher(watchPath, &etcd.WatcherOptions{AfterIndex: 0, Recursive: true}),
once: &once,
stop: stop,
}, nil
}
func (ew *etcdWatcher) Next() (*registry.Result, error) {
for {
rsp, err := ew.w.Next(ew.ctx)
if err != nil && ew.ctx.Err() != nil {
return nil, err
}
if rsp.Node.Dir {
continue
}
service := decode(rsp.Node.Value)
if service == nil {
switch {
case rsp.Action != "delete":
continue
case rsp.PrevNode == nil:
continue
}
// last ditch effort
service = decode(rsp.PrevNode.Value)
if service == nil {
continue
}
}
switch rsp.Action {
case "set", "delete", "create", "update":
if rsp.Action == "set" {
rsp.Action = "update"
}
return ®istry.Result{
Action: rsp.Action,
Service: service,
}, nil
default:
continue
}
}
}
func (ew *etcdWatcher) Stop() {
ew.once.Do(func() {
ew.stop <- true
})
}