-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwatch.go
333 lines (276 loc) · 7.52 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright © 2022 Roberto Hidalgo <coredns-consul@un.rob.mx>
// Contributions by Charles Powell, 2023
// SPDX-License-Identifier: Apache-2.0
package catalog
import (
"encoding/json"
"fmt"
"net"
"regexp"
"strings"
"sync"
"time"
"github.com/hashicorp/consul/api"
)
const ServiceProxyTag = "@service_proxy"
type WatchType interface {
Name() string
Fetch(*Catalog, *api.QueryOptions) (uint64, error)
Process(*Catalog) (ServiceMap, []string, error)
}
type Watch struct {
sync.RWMutex
LastIndex uint64
services ServiceMap
refreshed time.Time
watcher WatchType
ready bool
}
func NewWatch(impl WatchType) *Watch {
w := &Watch{
watcher: impl,
}
return w
}
func (w *Watch) Resolve(catalog *Catalog) (bool, error) {
w.RLock()
lastIndex := w.LastIndex
w.RUnlock()
opts := &api.QueryOptions{
WaitTime: watchTimeout,
WaitIndex: lastIndex,
}
nextIndex, err := w.watcher.Fetch(catalog, opts)
if err != nil {
return false, err
}
if nextIndex == opts.WaitIndex {
// watch timed out, safe to retry
Log.Debugf("No changes found, %d", nextIndex)
w.Lock()
w.refreshed = time.Now()
w.Unlock()
return false, nil
}
// reset the index if it goes backwards
// https://www.consul.io/api/features/blocking.html#implementation-details
if nextIndex < opts.WaitIndex {
Log.Debugf("Resetting consul kv watch index")
nextIndex = 0
}
services, found, err := w.watcher.Process(catalog)
if err != nil {
return false, err
}
w.Lock()
w.ready = true
w.services = services
w.LastIndex = nextIndex
w.refreshed = time.Now()
w.Unlock()
Log.Debugf("Serving %d records from %s: %s", len(found), w.watcher.Name(), strings.Join(found, ","))
return true, nil
}
func (w *Watch) Name() string {
return w.watcher.Name()
}
func (w *Watch) Get(name string) *Service {
return w.services.Find(name)
}
func (w *Watch) Known() ServiceMap {
return w.services
}
func (w *Watch) Ready() bool {
return w.ready
}
func staticEntriesToServiceMap(c *Catalog, entries StaticEntries) (ServiceMap, []string) {
services := ServiceMap{}
found := []string{}
for name, entry := range entries {
target := entry.Target
addresses := entry.Addresses
if len(addresses) == 0 && target == "" {
Log.Warningf("Ignoring service %s, no target or addresses found!", name)
continue
}
if target != "" {
if target == ServiceProxyTag {
if c.ProxyService == "" {
Log.Warningf("Ignoring service %s. Requested service proxy but none is configured", name)
continue
}
}
}
service := NewService(name, target)
if len(addresses) > 0 {
for _, addrStr := range addresses {
ip := net.ParseIP(addrStr)
if ip == nil {
Log.Warningf("Ignoring address %s for static service %s: could not parse IP", addrStr, name)
continue
}
service.Addresses = append(service.Addresses, ip)
}
}
if c.ACLTag != "" {
err := c.parseACL(service, entry.ACL)
if err != nil {
Log.Warningf("Ignoring service %s. Could not parse ACL: %s", name, err)
continue
}
}
if c.AliasTag != "" && len(entry.Aliases) > 0 {
for _, alias := range entry.Aliases {
services[alias] = aliasForService(alias, service)
found = append(found, alias)
}
}
if previous, ok := services[service.Name]; ok {
Log.Warningf("Replacing service %s. Duplicate entry configured. Had: %+v, now: %+v", name, previous, service)
}
services[name] = service
found = append(found, name)
}
return services, found
}
type WatcKVPrefix struct {
Prefix string
entries api.KVPairs
}
func (src *WatcKVPrefix) Name() string {
return fmt.Sprintf("static services at prefix %s", src.Prefix)
}
func (src *WatcKVPrefix) Fetch(catalog *Catalog, qo *api.QueryOptions) (uint64, error) {
entryPairs, meta, err := catalog.kv.List(src.Prefix, qo)
if err != nil {
return qo.WaitIndex, err
}
src.entries = entryPairs
return meta.LastIndex, nil
}
func (src *WatcKVPrefix) Process(catalog *Catalog) (ServiceMap, []string, error) {
entries := StaticEntries{}
for _, entry := range src.entries {
e := &StaticEntry{}
err := json.Unmarshal(entry.Value, &e)
if err != nil {
return nil, nil, err
}
parts := strings.Split(entry.Key, "/")
name := parts[len(parts)-1]
entries[name] = e
}
services, found := staticEntriesToServiceMap(catalog, entries)
return services, found, nil
}
type WatchKVPath struct {
Key string
data *api.KVPair
}
func (src *WatchKVPath) Name() string {
return fmt.Sprintf("static services from key %s", src.Key)
}
func (src *WatchKVPath) Fetch(catalog *Catalog, qo *api.QueryOptions) (uint64, error) {
configPair, meta, err := catalog.kv.Get(src.Key, qo)
if err != nil {
return qo.WaitIndex, err
}
src.data = configPair
return meta.LastIndex, nil
}
func (src *WatchKVPath) Process(catalog *Catalog) (ServiceMap, []string, error) {
entries := StaticEntries{}
err := json.Unmarshal(src.data.Value, &entries)
if err != nil {
return nil, nil, err
}
services, found := staticEntriesToServiceMap(catalog, entries)
return services, found, nil
}
type WatchConsulCatalog struct {
Tag string
data map[string][]string
}
func (src *WatchConsulCatalog) Name() string {
return fmt.Sprintf("consul catalog services tagged %s", src.Tag)
}
func (src *WatchConsulCatalog) Fetch(catalog *Catalog, qo *api.QueryOptions) (uint64, error) {
svcs, meta, err := catalog.client.Services(qo)
if err != nil {
return qo.WaitIndex, err
}
src.data = svcs
return meta.LastIndex, nil
}
func (src *WatchConsulCatalog) Process(catalog *Catalog) (ServiceMap, []string, error) {
services := ServiceMap{}
found := []string{}
for svc, serviceTags := range src.data {
target := svc
exposed := false
for _, tag := range serviceTags {
switch tag {
case catalog.ProxyTag:
if catalog.ProxyTag != "" {
target = ServiceProxyTag
}
case src.Tag:
exposed = true
default:
Log.Debugf("ignoring unknown tag %s for svc %s", tag, svc)
}
}
// do not publish services without the tag
if !exposed {
continue
}
hydratedServices, _, err := catalog.client.Service(svc, "", nil)
if err != nil {
// couldn't find service, ignore
Log.Debugf("Failed to fetch service info for %s: %e", svc, err)
continue
}
service := NewService(svc, target)
if len(hydratedServices) > 0 {
for _, svc := range hydratedServices {
service.Addresses = append(service.Addresses, net.ParseIP(svc.Address))
}
metadata := hydratedServices[0].ServiceMeta
if catalog.ACLTag != "" {
acl, exists := metadata[catalog.ACLTag]
if !exists {
Log.Warningf("No ACL found for %s", svc)
continue
}
if err := catalog.parseACLString(service, acl); err != nil {
Log.Warningf("Ignoring service %s: %s", service.Name, err)
}
}
if catalog.AliasTag != "" {
if aliases, exists := metadata[catalog.AliasTag]; exists {
matches := multiValueMetadataSplitter.Split(aliases, -1)
for _, match := range matches {
services[match] = aliasForService(match, service)
}
found = append(found, matches...)
}
}
} else {
Log.Warningf("No services found for %s, check the permissions for your token", svc)
}
services[svc] = service
Log.Debugf("serving: %+v", service)
found = append(found, svc)
}
return services, found, nil
}
var multiValueMetadataSplitter = regexp.MustCompile(`;\s*`)
func aliasForService(name string, service *Service) *Service {
alias := NewService(name, service.Target)
alias.ACL = service.ACL
alias.Addresses = service.Addresses
return alias
}
var _ WatchType = &WatchConsulCatalog{}
var _ WatchType = &WatchKVPath{}
var _ WatchType = &WatcKVPrefix{}