forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
84 lines (72 loc) · 1.43 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
package etcd
import (
"errors"
"sync"
etcd "github.com/coreos/etcd/client"
"github.com/micro/go-micro/registry"
"golang.org/x/net/context"
)
type etcdWatcher struct {
ctx context.Context
once sync.Once
stop chan bool
w etcd.Watcher
}
func newEtcdWatcher(r *etcdRegistry) (registry.Watcher, error) {
var once sync.Once
ctx, cancel := context.WithCancel(context.Background())
stop := make(chan bool, 1)
go func() {
<-stop
cancel()
}()
return &etcdWatcher{
ctx: ctx,
w: r.client.Watcher(prefix, &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
}
}
return nil, errors.New("could not get next")
}
func (ew *etcdWatcher) Stop() {
ew.once.Do(func() {
ew.stop <- true
})
}