blob: 7b914f71720a01f5f71a5b92867db2da1e908a60 [file] [log] [blame]
Serge Bazanskic89df2f2021-04-27 15:51:37 +02001package etcd
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "sync"
8
9 "github.com/cenkalti/backoff/v4"
10 "go.etcd.io/etcd/clientv3"
11
12 "source.monogon.dev/metropolis/node/core/consensus/client"
13 "source.monogon.dev/metropolis/pkg/event"
14)
15
16var (
Serge Bazanskifac8b2e2021-05-04 12:23:26 +020017 // Type assert that *Value implements event.ValueWatcher. We do this
18 // artificially, as there currently is no code path that needs this to be
19 // strictly true. However, users of this library might want to rely on the
20 // Value type instead of particular Value implementations.
21 _ event.ValueWatch = &Value{}
Serge Bazanskic89df2f2021-04-27 15:51:37 +020022)
23
24// Value is an 'Event Value' backed in an etcd cluster, accessed over an
25// etcd client. This is a stateless handle and can be copied and shared across
26// goroutines.
27type Value struct {
28 etcd client.Namespaced
29 key string
Serge Bazanski8d45a052021-10-18 17:24:24 +020030 keyEnd string
Serge Bazanskic89df2f2021-04-27 15:51:37 +020031 decoder BytesDecoder
32}
33
Serge Bazanski8d45a052021-10-18 17:24:24 +020034type Option struct {
35 rangeEnd string
36}
37
38// Range creates a Value that is backed a range of etcd key/value pairs from
39// 'key' passed to NewValue to 'end' passed to Range.
40//
41// The key range semantics (ie. lexicographic ordering) are the same as in etcd
42// ranges, so for example to retrieve all keys prefixed by `foo/` key should be
43// `foo/` and end should be `foo0`.
44//
45// For any update in the given range, the decoder will be called and its result
46// will trigger the return of a Get() call. The decoder should return a type
47// that lets the user distinguish which of the multiple objects in the range got
48// updated, as the Get() call returns no additional information about the
49// location of the retrieved object by itself.
50//
51// The order of values retrieved by Get() is currently fully arbitrary and must
52// not be relied on. It's possible that in the future the order of updates and
53// the blocking behaviour of Get will be formalized, but this is not yet the
54// case. Instead, the data returned should be treated as eventually consistent
55// with the etcd state.
56//
57// For some uses, it might be necessary to first retrieve all the objects
58// contained within the range before starting to block on updates - in this
59// case, the BacklogOnly option should be used when calling Get.
60func Range(end string) *Option {
61 return &Option{
62 rangeEnd: end,
Serge Bazanskic89df2f2021-04-27 15:51:37 +020063 }
64}
65
Serge Bazanski8d45a052021-10-18 17:24:24 +020066// NewValue creates a new Value for a given key(s) in an etcd client. The
67// given decoder will be used to convert bytes retrieved from etcd into the
68// interface{} value retrieved by Get by this value's watcher.
69func NewValue(etcd client.Namespaced, key string, decoder BytesDecoder, options ...*Option) *Value {
70 res := &Value{
71 etcd: etcd,
72 key: key,
73 keyEnd: key,
74 decoder: decoder,
75 }
76
77 for _, opt := range options {
78 if end := opt.rangeEnd; end != "" {
79 res.keyEnd = end
80 }
81 }
82
83 return res
84}
85
Serge Bazanskic89df2f2021-04-27 15:51:37 +020086// BytesDecoder is a function that converts bytes retrieved from etcd into an
Serge Bazanski8d45a052021-10-18 17:24:24 +020087// end-user facing value. Additionally, a key is available so that returned
88// values can be augmented with the location they were retrieved from. This is
89// especially useful when returning values resulting from an etcd range.
90//
91// If an error is returned, the Get call performed on a watcher configured with
92// this decoder will fail, swallowing that particular update, but the watcher
93// will continue to work. Any provided BytesDecoder implementations must be safe
94// to copy.
95type BytesDecoder = func(key []byte, data []byte) (interface{}, error)
Serge Bazanskic89df2f2021-04-27 15:51:37 +020096
97// NoDecoder is a no-op decoder which passes through the retrieved bytes as a
98// []byte type to the user.
Serge Bazanski8d45a052021-10-18 17:24:24 +020099func NoDecoder(key []byte, data []byte) (interface{}, error) {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200100 return data, nil
101}
102
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200103func (e *Value) Watch() event.Watcher {
104 ctx, ctxC := context.WithCancel(context.Background())
105 return &watcher{
106 Value: *e,
107
108 ctx: ctx,
109 ctxC: ctxC,
110
111 getSem: make(chan struct{}, 1),
112 }
113}
114
Serge Bazanski8d45a052021-10-18 17:24:24 +0200115// keyValue is an intermediate type used to keep etcd values in the watcher's
116// backlog.
117type keyValue struct {
118 key []byte
119 value []byte
120}
121
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200122type watcher struct {
123 // Value copy, used to configure the behaviour of this watcher.
124 Value
125
126 // ctx is the context that expresses the liveness of this watcher. It is
127 // canceled when the watcher is closed, and the etcd Watch hangs off of it.
128 ctx context.Context
129 ctxC context.CancelFunc
130
131 // getSem is a semaphore used to limit concurrent Get calls and throw an
132 // error if concurrent access is attempted.
133 getSem chan struct{}
134
Serge Bazanski8d45a052021-10-18 17:24:24 +0200135 // backlogged is a list of (key, value) pairs retrieved from etcd but not yet
136 // returned via Get. These items are not a replay of all the updates from etcd,
137 // but are already compacted to deduplicate updates to the same object (ie., if
138 // the update stream from etcd is for keys A, B, and A, the backlogged list will
139 // only contain one update for A and B each, with the first update for A being
140 // discarded upon arrival of the second update).
141 backlogged []*keyValue
142 // prev is the etcd store revision of a previously completed etcd Get/Watch
143 // call, used to resume a Watch call in case of failures.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200144 prev *int64
145 // wc is the etcd watch channel, or nil if no channel is yet open.
146 wc clientv3.WatchChan
147
148 // testRaceWG is an optional WaitGroup that, if set, will be waited upon
149 // after the initial KV value retrieval, but before the watch is created.
150 // This is only used for testing.
151 testRaceWG *sync.WaitGroup
152 // testSetupWG is an optional WaitGroup that, if set, will be waited upon
153 // after the etcd watch is created.
154 // This is only used for testing.
155 testSetupWG *sync.WaitGroup
156}
157
Serge Bazanski8d45a052021-10-18 17:24:24 +0200158// setup initiates wc (the watch channel from etcd) after retrieving the initial
159// value(s) with a get operation.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200160func (w *watcher) setup(ctx context.Context) error {
161 if w.wc != nil {
162 return nil
163 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200164 ranged := w.key != w.keyEnd
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200165
Serge Bazanski8d45a052021-10-18 17:24:24 +0200166 // First, check if some data under this key/range already exists.
167
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200168 // We use an exponential backoff and retry here as the initial Get can fail
169 // if the cluster is unstable (eg. failing over). We only fail the retry if
170 // the context expires.
171 bo := backoff.NewExponentialBackOff()
172 bo.MaxElapsedTime = 0
Serge Bazanski8d45a052021-10-18 17:24:24 +0200173
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200174 err := backoff.Retry(func() error {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200175
176 var getOpts []clientv3.OpOption
177 if ranged {
178 getOpts = append(getOpts, clientv3.WithRange(w.keyEnd))
179 }
180 get, err := w.etcd.Get(ctx, w.key, getOpts...)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200181 if err != nil {
182 return fmt.Errorf("when retrieving initial value: %w", err)
183 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200184
185 // Assert that the etcd API is behaving as expected.
186 if !ranged && len(get.Kvs) > 1 {
187 panic("More than one key returned in unary GET response")
188 }
189
190 // After a successful Get, save the revision to watch from and re-build the
191 // backlog from scratch based on what was available in the etcd store at that
192 // time.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200193 w.prev = &get.Header.Revision
Serge Bazanski8d45a052021-10-18 17:24:24 +0200194
195 w.backlogged = nil
196 for _, kv := range get.Kvs {
197 w.backlogged = append(w.backlogged, &keyValue{
198 key: kv.Key,
199 value: kv.Value,
200 })
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200201 }
202 return nil
203
204 }, backoff.WithContext(bo, ctx))
205
206 if w.testRaceWG != nil {
207 w.testRaceWG.Wait()
208 }
209 if err != nil {
210 return err
211 }
212
Serge Bazanski8d45a052021-10-18 17:24:24 +0200213 watchOpts := []clientv3.OpOption{
214 clientv3.WithRev(*w.prev + 1),
215 }
216 if ranged {
217 watchOpts = append(watchOpts, clientv3.WithRange(w.keyEnd))
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200218 }
219 w.wc = w.etcd.Watch(w.ctx, w.key, watchOpts...)
220
221 if w.testSetupWG != nil {
222 w.testSetupWG.Wait()
223 }
224 return nil
225}
226
Serge Bazanski8d45a052021-10-18 17:24:24 +0200227// backfill blocks until a backlog of items is available. An error is returned
228// if the context is canceled.
229func (w *watcher) backfill(ctx context.Context) error {
230 // Keep watching for watch events.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200231 for {
232 var resp *clientv3.WatchResponse
233 select {
234 case r := <-w.wc:
235 resp = &r
236 case <-ctx.Done():
Serge Bazanski8d45a052021-10-18 17:24:24 +0200237 return ctx.Err()
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200238 }
239
240 if resp.Canceled {
241 // Only allow for watches to be canceled due to context
242 // cancellations. Any other error is something we need to handle,
243 // eg. a client close or compaction error.
244 if errors.Is(resp.Err(), ctx.Err()) {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200245 return fmt.Errorf("watch canceled: %w", resp.Err())
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200246 }
247
248 // Attempt to reconnect.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200249 if w.wc != nil {
250 // If a wc already exists, close it. This forces a reconnection
251 // by the next setup call.
252 w.ctxC()
253 w.ctx, w.ctxC = context.WithCancel(context.Background())
254 w.wc = nil
255 }
256 if err := w.setup(ctx); err != nil {
257 return fmt.Errorf("failed to setup watcher: %w", err)
258 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200259 continue
260 }
261
Serge Bazanski8d45a052021-10-18 17:24:24 +0200262 w.prev = &resp.Header.Revision
263 // Spurious watch event with no update? Keep trying.
264 if len(resp.Events) == 0 {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200265 continue
266 }
267
Serge Bazanski8d45a052021-10-18 17:24:24 +0200268 // Process updates into compacted list, transforming deletions into value: nil
269 // keyValues. This maps an etcd key into a pointer in the already existing
270 // backlog list. It will then be used to compact all updates into the smallest
271 // backlog possible (by overriding previously backlogged items for a key if this
272 // key is encountered again).
273 //
274 // TODO(q3k): this could be stored in the watcher state to not waste time on
275 // each update, but it's good enough for now.
276 lastUpdate := make(map[string]*keyValue)
277 for _, kv := range w.backlogged {
278 kv := kv
279 lastUpdate[string(kv.key)] = kv
280 }
281 for _, ev := range resp.Events {
282 var value []byte
283 switch ev.Type {
284 case clientv3.EventTypeDelete:
285 case clientv3.EventTypePut:
286 value = ev.Kv.Value
287 default:
288 return fmt.Errorf("invalid event type %v", ev.Type)
289 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200290
Serge Bazanski8d45a052021-10-18 17:24:24 +0200291 keyS := string(ev.Kv.Key)
292 prev := lastUpdate[keyS]
293 if prev == nil {
294 kv := &keyValue{
295 key: ev.Kv.Key,
296 }
297 w.backlogged = append(w.backlogged, kv)
298 prev = kv
299 }
300 prev.value = value
301 }
302
303 // Still nothing in backlog? Keep trying.
304 if len(w.backlogged) == 0 {
305 continue
306 }
307
308 return nil
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200309 }
310}
311
Serge Bazanski8d45a052021-10-18 17:24:24 +0200312type GetOption struct {
313 backlogOnly bool
314}
315
316var (
317 // BacklogOnly will prevent Get from blocking on waiting for more updates from
318 // etcd, by instead returning BacklogDone whenever no more data is currently
319 // locally available. This is different however, from establishing that there
320 // are no more pending updates from the etcd cluster - the only way to ensure
321 // the local client is up to date is by performing Get calls without this option
322 // set.
323 //
324 // This mode of retrieval should only be used for the retrieval of the existing
325 // data in the etcd cluster on the initial creation of the Watcher (by
326 // repeatedly calling Get until BacklogDone isreturned), and shouldn't be set
327 // for any subsequent call. Any use of this option after that initial fetch is
328 // undefined behaviour that exposes the internals of the Get implementation, and
329 // must not be relied on. However, in the future, this behaviour might be
330 // formalized.
331 //
332 // This mode is particularly useful for ranged watchers. Non-ranged watchers can
333 // still use this option to distinguish between blocking because of the
334 // nonexistence of an object vs. blocking because of networking issues. However,
335 // non-ranged retrieval semantics generally will rarely need to make this
336 // distinction.
337 BacklogOnly = GetOption{backlogOnly: true}
338
339 // BacklogDone is returned by Get when BacklogOnly is set and there is no more
340 // event data stored in the Watcher client, ie. when the initial cluster state
341 // of the requested key has been retrieved.
342 BacklogDone = errors.New("no more backlogged data")
343)
344
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200345// Get implements the Get method of the Watcher interface.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200346// It can return an error in three cases:
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200347// - the given context is canceled (in which case, the given error will wrap
348// the context error)
349// - the watcher's BytesDecoder returned an error (in which case the error
350// returned by the BytesDecoder will be returned verbatim)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200351// - it has been called with BacklogOnly and the Watcher has no more local
352// event data to return (see BacklogOnly for more information on the
353// semantics of this mode of operation)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200354// Note that transient and permanent etcd errors are never returned, and the
355// Get call will attempt to recover from these errors as much as possible. This
356// also means that the user of the Watcher will not be notified if the
357// underlying etcd client disconnects from the cluster, or if the cluster loses
358// quorum.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200359//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200360// TODO(q3k): implement leases to allow clients to be notified when there are
361// transient cluster/quorum/partition errors, if needed.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200362//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200363// TODO(q3k): implement internal, limited buffering for backlogged data not yet
364// consumed by client, as etcd client library seems to use an unbound buffer in
365// case this happens ( see: watcherStream.buf in clientv3).
Serge Bazanski8d45a052021-10-18 17:24:24 +0200366func (w *watcher) Get(ctx context.Context, opts ...event.GetOption) (interface{}, error) {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200367 select {
368 case w.getSem <- struct{}{}:
369 default:
370 return nil, fmt.Errorf("cannot Get() concurrently on a single waiter")
371 }
372 defer func() {
373 <-w.getSem
374 }()
375
Serge Bazanski8d45a052021-10-18 17:24:24 +0200376 backlogOnly := false
377 for _, optI := range opts {
378 opt, ok := optI.(GetOption)
379 if !ok {
380 return nil, fmt.Errorf("get options must be of type etcd.GetOption")
381 }
382 if opt.backlogOnly {
383 backlogOnly = true
384 }
385 }
386
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200387 // Early check for context cancelations, preventing spurious contact with etcd
388 // if there's no need to.
389 if w.ctx.Err() != nil {
390 return nil, w.ctx.Err()
391 }
392
393 if err := w.setup(ctx); err != nil {
394 return nil, fmt.Errorf("when setting up watcher: %w", err)
395 }
396
Serge Bazanski8d45a052021-10-18 17:24:24 +0200397 if backlogOnly && len(w.backlogged) == 0 {
398 return nil, BacklogDone
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200399 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200400
401 // Update backlog from etcd if needed.
402 if len(w.backlogged) < 1 {
403 err := w.backfill(ctx)
404 if err != nil {
405 return nil, fmt.Errorf("when watching for new value: %w", err)
406 }
407 }
408 // Backlog is now guaranteed to contain at least one element.
409
410 ranged := w.key != w.keyEnd
411 if !ranged {
412 // For non-ranged queries, drain backlog fully.
413 if len(w.backlogged) != 1 {
414 panic("multiple keys in nonranged value")
415 }
416 kv := w.backlogged[0]
417 w.backlogged = nil
418 return w.decoder(kv.key, kv.value)
419 } else {
420 // For ranged queries, pop one ranged query off the backlog.
421 kv := w.backlogged[0]
422 w.backlogged = w.backlogged[1:]
423 return w.decoder(kv.key, kv.value)
424 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200425}
426
427func (w *watcher) Close() error {
428 w.ctxC()
429 return nil
430}