micro/registry/etcd/watcher.go

89 lines
1.4 KiB
Go
Raw Normal View History

2015-05-28 00:22:02 +03:00
package etcd
import (
etcd "github.com/coreos/etcd/client"
2015-05-28 00:22:02 +03:00
"github.com/myodc/go-micro/registry"
"golang.org/x/net/context"
2015-05-28 00:22:02 +03:00
)
type etcdWatcher struct {
registry *etcdRegistry
stop chan bool
}
func newEtcdWatcher(r *etcdRegistry) (registry.Watcher, error) {
2015-05-28 00:22:02 +03:00
ew := &etcdWatcher{
registry: r,
stop: make(chan bool),
}
w := r.client.Watcher(prefix, &etcd.WatcherOptions{AfterIndex: 0, Recursive: true})
2015-05-28 00:22:02 +03:00
c := context.Background()
ctx, cancel := context.WithCancel(c)
go func() {
<-ew.stop
cancel()
}()
go ew.watch(ctx, w)
2015-05-28 00:22:02 +03:00
return ew, nil
}
2015-05-28 00:22:02 +03:00
func (e *etcdWatcher) watch(ctx context.Context, w etcd.Watcher) {
for {
rsp, err := w.Next(ctx)
if err != nil && ctx.Err() != nil {
return
}
if rsp.Node.Dir {
continue
}
2015-05-28 00:22:02 +03:00
s := decode(rsp.Node.Value)
if s == nil {
continue
}
2015-05-28 00:22:02 +03:00
e.registry.Lock()
service, ok := e.registry.services[s.Name]
if !ok {
if rsp.Action == "create" {
e.registry.services[s.Name] = s
2015-05-28 00:22:02 +03:00
}
e.registry.Unlock()
continue
}
2015-05-28 00:22:02 +03:00
switch rsp.Action {
case "delete":
var nodes []*registry.Node
for _, node := range service.Nodes {
var seen bool
for _, n := range s.Nodes {
if node.Id == n.Id {
seen = true
break
2015-05-28 00:22:02 +03:00
}
}
if !seen {
nodes = append(nodes, node)
}
2015-05-28 00:22:02 +03:00
}
service.Nodes = nodes
case "create":
service.Nodes = append(service.Nodes, s.Nodes...)
2015-05-28 00:22:02 +03:00
}
e.registry.Unlock()
}
2015-05-28 00:22:02 +03:00
}
func (ew *etcdWatcher) Stop() {
ew.stop <- true
}