forked from cortexproject/cortex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consul_client.go
375 lines (334 loc) · 9.56 KB
/
consul_client.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package ring
import (
"flag"
"fmt"
"net/http"
"time"
"github.com/golang/protobuf/proto"
"github.com/golang/snappy"
consul "github.com/hashicorp/consul/api"
cleanhttp "github.com/hashicorp/go-cleanhttp"
"github.com/prometheus/common/log"
)
const (
longPollDuration = 10 * time.Second
)
// ConsulConfig to create a ConsulClient
type ConsulConfig struct {
Host string
Prefix string
HTTPClientTimeout time.Duration
}
// RegisterFlags adds the flags required to config this to the given FlagSet
func (cfg *ConsulConfig) RegisterFlags(f *flag.FlagSet) {
f.StringVar(&cfg.Host, "consul.hostname", "localhost:8500", "Hostname and port of Consul.")
f.StringVar(&cfg.Prefix, "consul.prefix", "collectors/", "Prefix for keys in Consul.")
f.DurationVar(&cfg.HTTPClientTimeout, "consul.client-timeout", 2*longPollDuration, "HTTP timeout when talking to consul")
}
// KVClient is a high-level client for Consul, that exposes operations
// such as CAS and Watch which take callbacks. It also deals with serialisation
// by having an instance factory passed in to methods and deserialising into that.
type KVClient interface {
CAS(key string, f CASCallback) error
WatchPrefix(path string, done <-chan struct{}, f func(string, interface{}) bool)
WatchKey(key string, done <-chan struct{}, f func(interface{}) bool)
Get(key string) (interface{}, error)
PutBytes(key string, buf []byte) error
}
// CASCallback is the type of the callback to CAS. If err is nil, out must be non-nil.
type CASCallback func(in interface{}) (out interface{}, retry bool, err error)
// Codec allows the consult client to serialise and deserialise values.
type Codec interface {
Decode([]byte) (interface{}, error)
Encode(interface{}) ([]byte, error)
}
type kv interface {
CAS(p *consul.KVPair, q *consul.WriteOptions) (bool, *consul.WriteMeta, error)
Get(key string, q *consul.QueryOptions) (*consul.KVPair, *consul.QueryMeta, error)
List(path string, q *consul.QueryOptions) (consul.KVPairs, *consul.QueryMeta, error)
Put(p *consul.KVPair, q *consul.WriteOptions) (*consul.WriteMeta, error)
}
type consulClient struct {
kv
codec Codec
}
// NewConsulClient returns a new ConsulClient.
func NewConsulClient(cfg ConsulConfig, codec Codec) (KVClient, error) {
client, err := consul.NewClient(&consul.Config{
Address: cfg.Host,
Scheme: "http",
HttpClient: &http.Client{
Transport: cleanhttp.DefaultPooledTransport(),
// See https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts/
Timeout: cfg.HTTPClientTimeout,
},
})
if err != nil {
return nil, err
}
var c KVClient = &consulClient{
kv: client.KV(),
codec: codec,
}
if cfg.Prefix != "" {
c = PrefixClient(c, cfg.Prefix)
}
return c, nil
}
var (
queryOptions = &consul.QueryOptions{
RequireConsistent: true,
}
writeOptions = &consul.WriteOptions{}
// ErrNotFound is returned by ConsulClient.Get.
ErrNotFound = fmt.Errorf("Not found")
)
// ProtoCodec is a Codec for proto/snappy
type ProtoCodec struct {
Factory func() proto.Message
}
// Decode implements Codec
func (p ProtoCodec) Decode(bytes []byte) (interface{}, error) {
out := p.Factory()
bytes, err := snappy.Decode(nil, bytes)
if err != nil {
return nil, err
}
if err := proto.Unmarshal(bytes, out); err != nil {
return nil, err
}
return out, nil
}
// Encode implements Codec
func (p ProtoCodec) Encode(msg interface{}) ([]byte, error) {
bytes, err := proto.Marshal(msg.(proto.Message))
if err != nil {
return nil, err
}
return snappy.Encode(nil, bytes), nil
}
// CAS atomically modifies a value in a callback.
// If value doesn't exist you'll get nil as an argument to your callback.
func (c *consulClient) CAS(key string, f CASCallback) error {
var (
index = uint64(0)
retries = 10
retry = true
)
for i := 0; i < retries; i++ {
kvp, _, err := c.kv.Get(key, queryOptions)
if err != nil {
log.Errorf("Error getting %s: %v", key, err)
continue
}
var intermediate interface{}
if kvp != nil {
out, err := c.codec.Decode(kvp.Value)
if err != nil {
log.Errorf("Error decoding %s: %v", key, err)
continue
}
// If key doesn't exist, index will be 0.
index = kvp.ModifyIndex
intermediate = out
}
intermediate, retry, err = f(intermediate)
if err != nil {
log.Errorf("Error CASing %s: %v", key, err)
if !retry {
return err
}
continue
}
if intermediate == nil {
panic("Callback must instantiate value!")
}
bytes, err := c.codec.Encode(intermediate)
if err != nil {
log.Errorf("Error serialising value for %s: %v", key, err)
continue
}
ok, _, err := c.kv.CAS(&consul.KVPair{
Key: key,
Value: bytes,
ModifyIndex: index,
}, writeOptions)
if err != nil {
log.Errorf("Error CASing %s: %v", key, err)
continue
}
if !ok {
log.Errorf("Error CASing %s, trying again %d", key, index)
continue
}
return nil
}
return fmt.Errorf("failed to CAS %s", key)
}
const (
initialBackoff = 1 * time.Second
maxBackoff = 1 * time.Minute
)
type backoff struct {
done <-chan struct{}
backoff time.Duration
}
func newBackoff(done <-chan struct{}) *backoff {
return &backoff{
done: done,
backoff: initialBackoff,
}
}
func (b *backoff) reset() {
b.backoff = initialBackoff
}
func (b *backoff) wait() {
select {
case <-b.done:
case <-time.After(b.backoff):
b.backoff = b.backoff * 2
if b.backoff > maxBackoff {
b.backoff = maxBackoff
}
}
}
func isClosed(done <-chan struct{}) bool {
select {
case <-done:
return true
default:
return false
}
}
// WatchPrefix will watch a given prefix in consul for changes. When a value
// under said prefix changes, the f callback is called with the deserialised
// value. To construct the deserialised value, a factory function should be
// supplied which generates an empty struct for WatchPrefix to deserialise
// into. Values in Consul are assumed to be JSON. This function blocks until
// the done channel is closed.
func (c *consulClient) WatchPrefix(prefix string, done <-chan struct{}, f func(string, interface{}) bool) {
var (
backoff = newBackoff(done)
index = uint64(0)
)
for {
if isClosed(done) {
return
}
kvps, meta, err := c.kv.List(prefix, &consul.QueryOptions{
RequireConsistent: true,
WaitIndex: index,
WaitTime: longPollDuration,
})
if err != nil {
log.Errorf("Error getting path %s: %v", prefix, err)
backoff.wait()
continue
}
backoff.reset()
// Skip if the index is the same as last time, because the key value is
// guaranteed to be the same as last time
if index == meta.LastIndex {
continue
}
index = meta.LastIndex
for _, kvp := range kvps {
out, err := c.codec.Decode(kvp.Value)
if err != nil {
log.Errorf("Error decoding %s: %v", kvp.Key, err)
continue
}
if !f(kvp.Key, out) {
return
}
}
}
}
// WatchKey will watch a given key in consul for changes. When the value
// under said key changes, the f callback is called with the deserialised
// value. To construct the deserialised value, a factory function should be
// supplied which generates an empty struct for WatchKey to deserialise
// into. Values in Consul are assumed to be JSON. This function blocks until
// the done channel is closed.
func (c *consulClient) WatchKey(key string, done <-chan struct{}, f func(interface{}) bool) {
var (
backoff = newBackoff(done)
index = uint64(0)
)
for {
if isClosed(done) {
return
}
kvp, meta, err := c.kv.Get(key, &consul.QueryOptions{
RequireConsistent: true,
WaitIndex: index,
WaitTime: longPollDuration,
})
if err != nil {
log.Errorf("Error getting path %s: %v", key, err)
backoff.wait()
continue
}
backoff.reset()
// Skip if the index is the same as last time, because the key value is
// guaranteed to be the same as last time
if index == meta.LastIndex {
continue
}
index = meta.LastIndex
var out interface{}
if kvp != nil {
var err error
out, err = c.codec.Decode(kvp.Value)
if err != nil {
log.Errorf("Error decoding %s: %v", key, err)
continue
}
}
if !f(out) {
return
}
}
}
func (c *consulClient) PutBytes(key string, buf []byte) error {
_, err := c.kv.Put(&consul.KVPair{
Key: key,
Value: buf,
}, &consul.WriteOptions{})
return err
}
func (c *consulClient) Get(key string) (interface{}, error) {
kvp, _, err := c.kv.Get(key, &consul.QueryOptions{})
if err != nil {
return nil, err
}
return c.codec.Decode(kvp.Value)
}
type prefixedConsulClient struct {
prefix string
consul KVClient
}
// PrefixClient takes a ConsulClient and forces a prefix on all its operations.
func PrefixClient(client KVClient, prefix string) KVClient {
return &prefixedConsulClient{prefix, client}
}
// CAS atomically modifies a value in a callback. If the value doesn't exist,
// you'll get 'nil' as an argument to your callback.
func (c *prefixedConsulClient) CAS(key string, f CASCallback) error {
return c.consul.CAS(c.prefix+key, f)
}
// WatchPrefix watches a prefix. This is in addition to the prefix we already have.
func (c *prefixedConsulClient) WatchPrefix(path string, done <-chan struct{}, f func(string, interface{}) bool) {
c.consul.WatchPrefix(c.prefix+path, done, f)
}
// WatchKey watches a key.
func (c *prefixedConsulClient) WatchKey(key string, done <-chan struct{}, f func(interface{}) bool) {
c.consul.WatchKey(c.prefix+key, done, f)
}
// PutBytes writes bytes to Consul.
func (c *prefixedConsulClient) PutBytes(key string, buf []byte) error {
return c.consul.PutBytes(c.prefix+key, buf)
}
func (c *prefixedConsulClient) Get(key string) (interface{}, error) {
return c.consul.Get(c.prefix + key)
}