2015-05-27 22:22:02 +01:00
|
|
|
package etcd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/coreos/go-etcd/etcd"
|
|
|
|
"github.com/myodc/go-micro/registry"
|
|
|
|
)
|
|
|
|
|
|
|
|
type etcdWatcher struct {
|
|
|
|
registry *etcdRegistry
|
|
|
|
stop chan bool
|
|
|
|
}
|
|
|
|
|
2015-06-01 18:55:27 +01:00
|
|
|
func newEtcdWatcher(r *etcdRegistry) (registry.Watcher, error) {
|
2015-05-27 22:22:02 +01:00
|
|
|
ew := &etcdWatcher{
|
|
|
|
registry: r,
|
|
|
|
stop: make(chan bool),
|
|
|
|
}
|
|
|
|
|
|
|
|
ch := make(chan *etcd.Response)
|
|
|
|
|
|
|
|
go r.client.Watch(prefix, 0, true, ch, ew.stop)
|
2015-06-01 18:55:27 +01:00
|
|
|
go ew.watch(ch)
|
2015-05-27 22:22:02 +01:00
|
|
|
|
2015-06-01 18:55:27 +01:00
|
|
|
return ew, nil
|
|
|
|
}
|
2015-05-27 22:22:02 +01:00
|
|
|
|
2015-06-01 18:55:27 +01:00
|
|
|
func (e *etcdWatcher) watch(ch chan *etcd.Response) {
|
|
|
|
for rsp := range ch {
|
|
|
|
if rsp.Node.Dir {
|
|
|
|
continue
|
|
|
|
}
|
2015-05-27 22:22:02 +01:00
|
|
|
|
2015-06-01 18:55:27 +01:00
|
|
|
s := decode(rsp.Node.Value)
|
|
|
|
if s == nil {
|
|
|
|
continue
|
|
|
|
}
|
2015-05-27 22:22:02 +01:00
|
|
|
|
2015-06-01 18:55:27 +01: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-27 22:22:02 +01:00
|
|
|
}
|
2015-06-01 18:55:27 +01:00
|
|
|
e.registry.Unlock()
|
|
|
|
continue
|
|
|
|
}
|
2015-05-27 22:22:02 +01:00
|
|
|
|
2015-06-01 18:55:27 +01: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-27 22:22:02 +01:00
|
|
|
}
|
|
|
|
}
|
2015-06-01 18:55:27 +01:00
|
|
|
if !seen {
|
|
|
|
nodes = append(nodes, node)
|
|
|
|
}
|
2015-05-27 22:22:02 +01:00
|
|
|
}
|
2015-06-01 18:55:27 +01:00
|
|
|
service.Nodes = nodes
|
|
|
|
case "create":
|
|
|
|
service.Nodes = append(service.Nodes, s.Nodes...)
|
2015-05-27 22:22:02 +01:00
|
|
|
}
|
|
|
|
|
2015-06-01 18:55:27 +01:00
|
|
|
e.registry.Unlock()
|
|
|
|
}
|
2015-05-27 22:22:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ew *etcdWatcher) Stop() {
|
|
|
|
ew.stop <- true
|
|
|
|
}
|