-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
90 lines (74 loc) · 1.72 KB
/
watch.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
package watch
import (
"net"
"strconv"
"sync"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/api/watch"
"go.uber.org/zap"
)
type (
Address = string
Watcher interface {
Watch() (<-chan []Address, error)
}
ConsulWatcher struct {
logger *zap.Logger
plan *watch.Plan
consulAddr Address
once sync.Once
ch chan []Address
err error
}
logger struct {
logger *zap.Logger
}
)
var _ Watcher = (*ConsulWatcher)(nil)
func (w *logger) Write(data []byte) (int, error) {
w.logger.Warn(string(data))
return len(data), nil
}
func NewConsulWatcher(log *zap.Logger, consulAddr, name, dc, tag string) (*ConsulWatcher, error) {
plan, err := watch.Parse(map[string]interface{}{
"type": "service",
"service": name,
"datacenter": dc,
"tag": tag,
"passingonly": true,
})
if err != nil {
return nil, err
}
w := &ConsulWatcher{
logger: log,
consulAddr: consulAddr,
plan: plan,
ch: make(chan []Address),
}
w.plan.LogOutput = &logger{log.With(zap.String("module", "consul_watcher"))}
w.plan.Handler = func(i uint64, data interface{}) {
var addrs []Address
for _, srv := range data.([]*api.ServiceEntry) {
host := srv.Service.Address
if host == "" {
host = srv.Node.Address
}
addrs = append(addrs, net.JoinHostPort(host, strconv.Itoa(srv.Service.Port)))
}
w.ch <- addrs
}
return w, nil
}
func (w *ConsulWatcher) Watch() (<-chan []Address, error) {
w.once.Do(func() {
go func() {
defer func() { close(w.ch) }()
if err := w.plan.Run(w.consulAddr); err != nil {
w.err = err
w.logger.Error("running watch plan error", zap.String("consul_address", w.consulAddr), zap.Error(w.err))
}
}()
})
return w.ch, w.err
}