blob: 14dfd9936b233f81e58fd6543c2a5557a28d6502 [file] [log] [blame]
Serge Bazanskic89df2f2021-04-27 15:51:37 +02001package etcd
2
3import (
Serge Bazanski832bc772022-04-07 12:33:01 +02004 "bytes"
Serge Bazanskic89df2f2021-04-27 15:51:37 +02005 "context"
6 "errors"
7 "fmt"
8 "sync"
9
10 "github.com/cenkalti/backoff/v4"
Lorenz Brund13c1c62022-03-30 19:58:58 +020011 clientv3 "go.etcd.io/etcd/client/v3"
Serge Bazanskic89df2f2021-04-27 15:51:37 +020012
13 "source.monogon.dev/metropolis/node/core/consensus/client"
14 "source.monogon.dev/metropolis/pkg/event"
15)
16
17var (
Serge Bazanskifac8b2e2021-05-04 12:23:26 +020018 // Type assert that *Value implements event.ValueWatcher. We do this
19 // artificially, as there currently is no code path that needs this to be
20 // strictly true. However, users of this library might want to rely on the
21 // Value type instead of particular Value implementations.
Serge Bazanski37110c32023-03-01 13:57:27 +000022 _ event.ValueWatch[StringAt] = &Value[StringAt]{}
Serge Bazanskic89df2f2021-04-27 15:51:37 +020023)
24
25// Value is an 'Event Value' backed in an etcd cluster, accessed over an
26// etcd client. This is a stateless handle and can be copied and shared across
27// goroutines.
Serge Bazanski37110c32023-03-01 13:57:27 +000028type Value[T any] struct {
29 decoder func(key, value []byte) (T, error)
Serge Bazanskic89df2f2021-04-27 15:51:37 +020030 etcd client.Namespaced
31 key string
Serge Bazanski8d45a052021-10-18 17:24:24 +020032 keyEnd string
Serge Bazanskic89df2f2021-04-27 15:51:37 +020033}
34
Serge Bazanski8d45a052021-10-18 17:24:24 +020035type Option struct {
36 rangeEnd string
37}
38
39// Range creates a Value that is backed a range of etcd key/value pairs from
40// 'key' passed to NewValue to 'end' passed to Range.
41//
42// The key range semantics (ie. lexicographic ordering) are the same as in etcd
43// ranges, so for example to retrieve all keys prefixed by `foo/` key should be
44// `foo/` and end should be `foo0`.
45//
46// For any update in the given range, the decoder will be called and its result
47// will trigger the return of a Get() call. The decoder should return a type
48// that lets the user distinguish which of the multiple objects in the range got
49// updated, as the Get() call returns no additional information about the
50// location of the retrieved object by itself.
51//
52// The order of values retrieved by Get() is currently fully arbitrary and must
53// not be relied on. It's possible that in the future the order of updates and
54// the blocking behaviour of Get will be formalized, but this is not yet the
55// case. Instead, the data returned should be treated as eventually consistent
56// with the etcd state.
57//
58// For some uses, it might be necessary to first retrieve all the objects
59// contained within the range before starting to block on updates - in this
60// case, the BacklogOnly option should be used when calling Get.
61func Range(end string) *Option {
62 return &Option{
63 rangeEnd: end,
Serge Bazanskic89df2f2021-04-27 15:51:37 +020064 }
65}
66
Serge Bazanski8d45a052021-10-18 17:24:24 +020067// NewValue creates a new Value for a given key(s) in an etcd client. The
68// given decoder will be used to convert bytes retrieved from etcd into the
69// interface{} value retrieved by Get by this value's watcher.
Serge Bazanski37110c32023-03-01 13:57:27 +000070func NewValue[T any](etcd client.Namespaced, key string, decoder func(key, value []byte) (T, error), options ...*Option) *Value[T] {
71 res := &Value[T]{
72 decoder: decoder,
Serge Bazanski8d45a052021-10-18 17:24:24 +020073 etcd: etcd,
74 key: key,
75 keyEnd: key,
Serge Bazanski8d45a052021-10-18 17:24:24 +020076 }
77
78 for _, opt := range options {
79 if end := opt.rangeEnd; end != "" {
80 res.keyEnd = end
81 }
82 }
83
84 return res
85}
86
Serge Bazanski37110c32023-03-01 13:57:27 +000087func DecoderNoop(_, value []byte) ([]byte, error) {
88 return value, nil
Serge Bazanskic89df2f2021-04-27 15:51:37 +020089}
90
Serge Bazanski37110c32023-03-01 13:57:27 +000091func DecoderStringAt(key, value []byte) (StringAt, error) {
92 return StringAt{
93 Key: string(key),
94 Value: string(value),
95 }, nil
96}
97
98type StringAt struct {
99 Key string
100 Value string
101}
102
103func (e *Value[T]) Watch() event.Watcher[T] {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200104 ctx, ctxC := context.WithCancel(context.Background())
Serge Bazanski37110c32023-03-01 13:57:27 +0000105 return &watcher[T]{
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200106 Value: *e,
107
108 ctx: ctx,
109 ctxC: ctxC,
110
Serge Bazanski832bc772022-04-07 12:33:01 +0200111 current: make(map[string][]byte),
112
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200113 getSem: make(chan struct{}, 1),
114 }
115}
116
Serge Bazanski37110c32023-03-01 13:57:27 +0000117type watcher[T any] struct {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200118 // Value copy, used to configure the behaviour of this watcher.
Serge Bazanski37110c32023-03-01 13:57:27 +0000119 Value[T]
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200120
121 // ctx is the context that expresses the liveness of this watcher. It is
122 // canceled when the watcher is closed, and the etcd Watch hangs off of it.
123 ctx context.Context
124 ctxC context.CancelFunc
125
126 // getSem is a semaphore used to limit concurrent Get calls and throw an
127 // error if concurrent access is attempted.
128 getSem chan struct{}
129
Serge Bazanski832bc772022-04-07 12:33:01 +0200130 // backlogged is a list of keys retrieved from etcd but not yet returned via
131 // Get. These items are not a replay of all the updates from etcd, but are
132 // already compacted to deduplicate updates to the same object (ie., if the
133 // update stream from etcd is for keys A, B, and A, the backlogged list will
Serge Bazanski8d45a052021-10-18 17:24:24 +0200134 // only contain one update for A and B each, with the first update for A being
135 // discarded upon arrival of the second update).
Serge Bazanski832bc772022-04-07 12:33:01 +0200136 //
137 // The keys are an index into the current map, which contains the values
138 // retrieved, including ones that have already been returned via Get. This
139 // persistence allows us to deduplicate spurious updates to the user, in which
140 // etcd returned a new revision of a key, but the data stayed the same.
141 backlogged [][]byte
142 // current map, keyed from etcd key into etcd value at said key. This map
143 // persists alongside an etcd connection, permitting deduplication of spurious
144 // etcd updates even across multiple Get calls.
145 current map[string][]byte
146
Serge Bazanski8d45a052021-10-18 17:24:24 +0200147 // prev is the etcd store revision of a previously completed etcd Get/Watch
148 // call, used to resume a Watch call in case of failures.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200149 prev *int64
150 // wc is the etcd watch channel, or nil if no channel is yet open.
151 wc clientv3.WatchChan
152
153 // testRaceWG is an optional WaitGroup that, if set, will be waited upon
154 // after the initial KV value retrieval, but before the watch is created.
155 // This is only used for testing.
156 testRaceWG *sync.WaitGroup
157 // testSetupWG is an optional WaitGroup that, if set, will be waited upon
158 // after the etcd watch is created.
159 // This is only used for testing.
160 testSetupWG *sync.WaitGroup
161}
162
Serge Bazanski8d45a052021-10-18 17:24:24 +0200163// setup initiates wc (the watch channel from etcd) after retrieving the initial
164// value(s) with a get operation.
Serge Bazanski37110c32023-03-01 13:57:27 +0000165func (w *watcher[T]) setup(ctx context.Context) error {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200166 if w.wc != nil {
167 return nil
168 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200169 ranged := w.key != w.keyEnd
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200170
Serge Bazanski8d45a052021-10-18 17:24:24 +0200171 // First, check if some data under this key/range already exists.
172
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200173 // We use an exponential backoff and retry here as the initial Get can fail
174 // if the cluster is unstable (eg. failing over). We only fail the retry if
175 // the context expires.
176 bo := backoff.NewExponentialBackOff()
177 bo.MaxElapsedTime = 0
Serge Bazanski8d45a052021-10-18 17:24:24 +0200178
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200179 err := backoff.Retry(func() error {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200180
181 var getOpts []clientv3.OpOption
182 if ranged {
183 getOpts = append(getOpts, clientv3.WithRange(w.keyEnd))
184 }
185 get, err := w.etcd.Get(ctx, w.key, getOpts...)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200186 if err != nil {
187 return fmt.Errorf("when retrieving initial value: %w", err)
188 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200189
190 // Assert that the etcd API is behaving as expected.
191 if !ranged && len(get.Kvs) > 1 {
192 panic("More than one key returned in unary GET response")
193 }
194
195 // After a successful Get, save the revision to watch from and re-build the
196 // backlog from scratch based on what was available in the etcd store at that
197 // time.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200198 w.prev = &get.Header.Revision
Serge Bazanski8d45a052021-10-18 17:24:24 +0200199
200 w.backlogged = nil
Serge Bazanski832bc772022-04-07 12:33:01 +0200201 w.current = make(map[string][]byte)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200202 for _, kv := range get.Kvs {
Serge Bazanski832bc772022-04-07 12:33:01 +0200203 w.backlogged = append(w.backlogged, kv.Key)
204 w.current[string(kv.Key)] = kv.Value
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200205 }
206 return nil
207
208 }, backoff.WithContext(bo, ctx))
209
210 if w.testRaceWG != nil {
211 w.testRaceWG.Wait()
212 }
213 if err != nil {
214 return err
215 }
216
Serge Bazanski8d45a052021-10-18 17:24:24 +0200217 watchOpts := []clientv3.OpOption{
218 clientv3.WithRev(*w.prev + 1),
219 }
220 if ranged {
221 watchOpts = append(watchOpts, clientv3.WithRange(w.keyEnd))
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200222 }
223 w.wc = w.etcd.Watch(w.ctx, w.key, watchOpts...)
224
225 if w.testSetupWG != nil {
226 w.testSetupWG.Wait()
227 }
228 return nil
229}
230
Serge Bazanski8d45a052021-10-18 17:24:24 +0200231// backfill blocks until a backlog of items is available. An error is returned
232// if the context is canceled.
Serge Bazanski37110c32023-03-01 13:57:27 +0000233func (w *watcher[T]) backfill(ctx context.Context) error {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200234 // Keep watching for watch events.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200235 for {
236 var resp *clientv3.WatchResponse
237 select {
238 case r := <-w.wc:
239 resp = &r
240 case <-ctx.Done():
Serge Bazanski8d45a052021-10-18 17:24:24 +0200241 return ctx.Err()
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200242 }
243
244 if resp.Canceled {
245 // Only allow for watches to be canceled due to context
246 // cancellations. Any other error is something we need to handle,
247 // eg. a client close or compaction error.
248 if errors.Is(resp.Err(), ctx.Err()) {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200249 return fmt.Errorf("watch canceled: %w", resp.Err())
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200250 }
251
252 // Attempt to reconnect.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200253 if w.wc != nil {
254 // If a wc already exists, close it. This forces a reconnection
255 // by the next setup call.
256 w.ctxC()
257 w.ctx, w.ctxC = context.WithCancel(context.Background())
258 w.wc = nil
259 }
260 if err := w.setup(ctx); err != nil {
261 return fmt.Errorf("failed to setup watcher: %w", err)
262 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200263 continue
264 }
265
Serge Bazanski8d45a052021-10-18 17:24:24 +0200266 w.prev = &resp.Header.Revision
267 // Spurious watch event with no update? Keep trying.
268 if len(resp.Events) == 0 {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200269 continue
270 }
271
Serge Bazanski8d45a052021-10-18 17:24:24 +0200272 // Process updates into compacted list, transforming deletions into value: nil
273 // keyValues. This maps an etcd key into a pointer in the already existing
274 // backlog list. It will then be used to compact all updates into the smallest
275 // backlog possible (by overriding previously backlogged items for a key if this
276 // key is encountered again).
277 //
278 // TODO(q3k): this could be stored in the watcher state to not waste time on
279 // each update, but it's good enough for now.
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200280
281 // Prepare a set of keys that already exist in the backlog. This will be used
282 // to make sure we don't duplicate backlog entries while maintaining a stable
283 // backlog order.
284 seen := make(map[string]bool)
285 for _, k := range w.backlogged {
286 seen[string(k)] = true
287 }
288
Serge Bazanski8d45a052021-10-18 17:24:24 +0200289 for _, ev := range resp.Events {
290 var value []byte
291 switch ev.Type {
292 case clientv3.EventTypeDelete:
293 case clientv3.EventTypePut:
294 value = ev.Kv.Value
295 default:
296 return fmt.Errorf("invalid event type %v", ev.Type)
297 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200298
Serge Bazanski8d45a052021-10-18 17:24:24 +0200299 keyS := string(ev.Kv.Key)
Serge Bazanski832bc772022-04-07 12:33:01 +0200300 prev := w.current[keyS]
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200301 // Short-circuit and skip updates with the same content as already present.
302 // These are sometimes emitted by etcd.
303 if bytes.Equal(prev, value) {
304 continue
Serge Bazanski8d45a052021-10-18 17:24:24 +0200305 }
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200306
307 // Only insert to backlog if not yet present, but maintain order.
308 if !seen[string(ev.Kv.Key)] {
309 w.backlogged = append(w.backlogged, ev.Kv.Key)
310 seen[string(ev.Kv.Key)] = true
311 }
312 // Regardless of backlog list, always update the key to its newest value.
313 w.current[keyS] = value
Serge Bazanski8d45a052021-10-18 17:24:24 +0200314 }
315
316 // Still nothing in backlog? Keep trying.
317 if len(w.backlogged) == 0 {
318 continue
319 }
320
321 return nil
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200322 }
323}
324
Serge Bazanski8d45a052021-10-18 17:24:24 +0200325type GetOption struct {
326 backlogOnly bool
327}
328
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200329// Get implements the Get method of the Watcher interface.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200330// It can return an error in three cases:
Serge Bazanski37110c32023-03-01 13:57:27 +0000331// - the given context is canceled (in which case, the given error will wrap
332// the context error)
333// - the watcher's BytesDecoder returned an error (in which case the error
334// returned by the BytesDecoder will be returned verbatim)
335// - it has been called with BacklogOnly and the Watcher has no more local
336// event data to return (see BacklogOnly for more information on the
337// semantics of this mode of operation)
338//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200339// Note that transient and permanent etcd errors are never returned, and the
340// Get call will attempt to recover from these errors as much as possible. This
341// also means that the user of the Watcher will not be notified if the
342// underlying etcd client disconnects from the cluster, or if the cluster loses
343// quorum.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200344//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200345// TODO(q3k): implement leases to allow clients to be notified when there are
346// transient cluster/quorum/partition errors, if needed.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200347//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200348// TODO(q3k): implement internal, limited buffering for backlogged data not yet
349// consumed by client, as etcd client library seems to use an unbound buffer in
350// case this happens ( see: watcherStream.buf in clientv3).
Serge Bazanski37110c32023-03-01 13:57:27 +0000351func (w *watcher[T]) Get(ctx context.Context, opts ...event.GetOption[T]) (T, error) {
352 var empty T
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200353 select {
354 case w.getSem <- struct{}{}:
355 default:
Serge Bazanski37110c32023-03-01 13:57:27 +0000356 return empty, fmt.Errorf("cannot Get() concurrently on a single waiter")
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200357 }
358 defer func() {
359 <-w.getSem
360 }()
361
Serge Bazanski8d45a052021-10-18 17:24:24 +0200362 backlogOnly := false
Serge Bazanski37110c32023-03-01 13:57:27 +0000363 var predicate func(t T) bool
364 for _, opt := range opts {
365 if opt.Predicate != nil {
366 predicate = opt.Predicate
Serge Bazanski8d45a052021-10-18 17:24:24 +0200367 }
Serge Bazanski37110c32023-03-01 13:57:27 +0000368 if opt.BacklogOnly {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200369 backlogOnly = true
370 }
371 }
372
Serge Bazanski37110c32023-03-01 13:57:27 +0000373 ranged := w.key != w.keyEnd
374 if ranged && predicate != nil {
375 return empty, errors.New("filtering unimplemented for ranged etcd values")
376 }
377 if backlogOnly && predicate != nil {
378 return empty, errors.New("filtering unimplemented for backlog-only requests")
379 }
380
381 for {
382 v, err := w.getUnlocked(ctx, ranged, backlogOnly)
383 if err != nil {
384 return empty, err
385 }
386 if predicate == nil || predicate(v) {
387 return v, nil
388 }
389 }
390}
391
392func (w *watcher[T]) getUnlocked(ctx context.Context, ranged, backlogOnly bool) (T, error) {
393 var empty T
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200394 // Early check for context cancelations, preventing spurious contact with etcd
395 // if there's no need to.
396 if w.ctx.Err() != nil {
Serge Bazanski37110c32023-03-01 13:57:27 +0000397 return empty, w.ctx.Err()
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200398 }
399
400 if err := w.setup(ctx); err != nil {
Serge Bazanski37110c32023-03-01 13:57:27 +0000401 return empty, fmt.Errorf("when setting up watcher: %w", err)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200402 }
403
Serge Bazanski8d45a052021-10-18 17:24:24 +0200404 if backlogOnly && len(w.backlogged) == 0 {
Serge Bazanski37110c32023-03-01 13:57:27 +0000405 return empty, event.BacklogDone
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200406 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200407
408 // Update backlog from etcd if needed.
409 if len(w.backlogged) < 1 {
410 err := w.backfill(ctx)
411 if err != nil {
Serge Bazanski37110c32023-03-01 13:57:27 +0000412 return empty, fmt.Errorf("when watching for new value: %w", err)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200413 }
414 }
415 // Backlog is now guaranteed to contain at least one element.
416
Serge Bazanski8d45a052021-10-18 17:24:24 +0200417 if !ranged {
418 // For non-ranged queries, drain backlog fully.
419 if len(w.backlogged) != 1 {
Serge Bazanski9d971182022-06-23 17:44:13 +0200420 panic(fmt.Sprintf("multiple keys in nonranged value: %v", w.backlogged))
Serge Bazanski8d45a052021-10-18 17:24:24 +0200421 }
Serge Bazanski832bc772022-04-07 12:33:01 +0200422 k := w.backlogged[0]
423 v := w.current[string(k)]
Serge Bazanski8d45a052021-10-18 17:24:24 +0200424 w.backlogged = nil
Serge Bazanski832bc772022-04-07 12:33:01 +0200425 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200426 } else {
427 // For ranged queries, pop one ranged query off the backlog.
Serge Bazanski832bc772022-04-07 12:33:01 +0200428 k := w.backlogged[0]
429 v := w.current[string(k)]
Serge Bazanski8d45a052021-10-18 17:24:24 +0200430 w.backlogged = w.backlogged[1:]
Serge Bazanski832bc772022-04-07 12:33:01 +0200431 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200432 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200433}
434
Serge Bazanski37110c32023-03-01 13:57:27 +0000435func (w *watcher[T]) Close() error {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200436 w.ctxC()
437 return nil
438}