blob: 3d554f13b893d164b9f82bd1b6e1d40f47f4b902 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Serge Bazanskic89df2f2021-04-27 15:51:37 +02004package etcd
5
6import (
Serge Bazanski832bc772022-04-07 12:33:01 +02007 "bytes"
Serge Bazanskic89df2f2021-04-27 15:51:37 +02008 "context"
9 "errors"
10 "fmt"
11 "sync"
12
13 "github.com/cenkalti/backoff/v4"
Lorenz Brund13c1c62022-03-30 19:58:58 +020014 clientv3 "go.etcd.io/etcd/client/v3"
Serge Bazanskic89df2f2021-04-27 15:51:37 +020015
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020016 "source.monogon.dev/osbase/event"
Serge Bazanskic89df2f2021-04-27 15:51:37 +020017)
18
19var (
Serge Bazanskifac8b2e2021-05-04 12:23:26 +020020 // Type assert that *Value implements event.ValueWatcher. We do this
21 // artificially, as there currently is no code path that needs this to be
22 // strictly true. However, users of this library might want to rely on the
23 // Value type instead of particular Value implementations.
Serge Bazanski37110c32023-03-01 13:57:27 +000024 _ event.ValueWatch[StringAt] = &Value[StringAt]{}
Serge Bazanskic89df2f2021-04-27 15:51:37 +020025)
26
Tim Windelschmidtda1c9502024-05-08 01:24:29 +020027// ThinClient is a small wrapper interface to combine
28// clientv3.KV and clientv3.Watcher.
29type ThinClient interface {
30 clientv3.KV
31 clientv3.Watcher
32}
33
Serge Bazanskic89df2f2021-04-27 15:51:37 +020034// Value is an 'Event Value' backed in an etcd cluster, accessed over an
35// etcd client. This is a stateless handle and can be copied and shared across
36// goroutines.
Serge Bazanski37110c32023-03-01 13:57:27 +000037type Value[T any] struct {
38 decoder func(key, value []byte) (T, error)
Tim Windelschmidtda1c9502024-05-08 01:24:29 +020039 etcd ThinClient
Serge Bazanskic89df2f2021-04-27 15:51:37 +020040 key string
Serge Bazanski8d45a052021-10-18 17:24:24 +020041 keyEnd string
Serge Bazanskic89df2f2021-04-27 15:51:37 +020042}
43
Serge Bazanski8d45a052021-10-18 17:24:24 +020044type Option struct {
45 rangeEnd string
46}
47
48// Range creates a Value that is backed a range of etcd key/value pairs from
49// 'key' passed to NewValue to 'end' passed to Range.
50//
51// The key range semantics (ie. lexicographic ordering) are the same as in etcd
52// ranges, so for example to retrieve all keys prefixed by `foo/` key should be
53// `foo/` and end should be `foo0`.
54//
55// For any update in the given range, the decoder will be called and its result
56// will trigger the return of a Get() call. The decoder should return a type
57// that lets the user distinguish which of the multiple objects in the range got
58// updated, as the Get() call returns no additional information about the
59// location of the retrieved object by itself.
60//
61// The order of values retrieved by Get() is currently fully arbitrary and must
62// not be relied on. It's possible that in the future the order of updates and
63// the blocking behaviour of Get will be formalized, but this is not yet the
64// case. Instead, the data returned should be treated as eventually consistent
65// with the etcd state.
66//
67// For some uses, it might be necessary to first retrieve all the objects
68// contained within the range before starting to block on updates - in this
69// case, the BacklogOnly option should be used when calling Get.
70func Range(end string) *Option {
71 return &Option{
72 rangeEnd: end,
Serge Bazanskic89df2f2021-04-27 15:51:37 +020073 }
74}
75
Serge Bazanski8d45a052021-10-18 17:24:24 +020076// NewValue creates a new Value for a given key(s) in an etcd client. The
77// given decoder will be used to convert bytes retrieved from etcd into the
78// interface{} value retrieved by Get by this value's watcher.
Tim Windelschmidtda1c9502024-05-08 01:24:29 +020079func NewValue[T any](etcd ThinClient, key string, decoder func(key, value []byte) (T, error), options ...*Option) *Value[T] {
Serge Bazanski37110c32023-03-01 13:57:27 +000080 res := &Value[T]{
81 decoder: decoder,
Serge Bazanski8d45a052021-10-18 17:24:24 +020082 etcd: etcd,
83 key: key,
84 keyEnd: key,
Serge Bazanski8d45a052021-10-18 17:24:24 +020085 }
86
87 for _, opt := range options {
88 if end := opt.rangeEnd; end != "" {
89 res.keyEnd = end
90 }
91 }
92
93 return res
94}
95
Serge Bazanski37110c32023-03-01 13:57:27 +000096func DecoderNoop(_, value []byte) ([]byte, error) {
97 return value, nil
Serge Bazanskic89df2f2021-04-27 15:51:37 +020098}
99
Serge Bazanski37110c32023-03-01 13:57:27 +0000100func DecoderStringAt(key, value []byte) (StringAt, error) {
101 return StringAt{
102 Key: string(key),
103 Value: string(value),
104 }, nil
105}
106
107type StringAt struct {
108 Key string
109 Value string
110}
111
112func (e *Value[T]) Watch() event.Watcher[T] {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200113 ctx, ctxC := context.WithCancel(context.Background())
Serge Bazanski37110c32023-03-01 13:57:27 +0000114 return &watcher[T]{
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200115 Value: *e,
116
117 ctx: ctx,
118 ctxC: ctxC,
119
Serge Bazanski832bc772022-04-07 12:33:01 +0200120 current: make(map[string][]byte),
121
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200122 getSem: make(chan struct{}, 1),
123 }
124}
125
Serge Bazanski37110c32023-03-01 13:57:27 +0000126type watcher[T any] struct {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200127 // Value copy, used to configure the behaviour of this watcher.
Serge Bazanski37110c32023-03-01 13:57:27 +0000128 Value[T]
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200129
130 // ctx is the context that expresses the liveness of this watcher. It is
131 // canceled when the watcher is closed, and the etcd Watch hangs off of it.
132 ctx context.Context
133 ctxC context.CancelFunc
134
135 // getSem is a semaphore used to limit concurrent Get calls and throw an
136 // error if concurrent access is attempted.
137 getSem chan struct{}
138
Serge Bazanski832bc772022-04-07 12:33:01 +0200139 // backlogged is a list of keys retrieved from etcd but not yet returned via
140 // Get. These items are not a replay of all the updates from etcd, but are
141 // already compacted to deduplicate updates to the same object (ie., if the
142 // update stream from etcd is for keys A, B, and A, the backlogged list will
Serge Bazanski8d45a052021-10-18 17:24:24 +0200143 // only contain one update for A and B each, with the first update for A being
144 // discarded upon arrival of the second update).
Serge Bazanski832bc772022-04-07 12:33:01 +0200145 //
146 // The keys are an index into the current map, which contains the values
147 // retrieved, including ones that have already been returned via Get. This
148 // persistence allows us to deduplicate spurious updates to the user, in which
149 // etcd returned a new revision of a key, but the data stayed the same.
150 backlogged [][]byte
151 // current map, keyed from etcd key into etcd value at said key. This map
152 // persists alongside an etcd connection, permitting deduplication of spurious
153 // etcd updates even across multiple Get calls.
154 current map[string][]byte
155
Serge Bazanski8d45a052021-10-18 17:24:24 +0200156 // prev is the etcd store revision of a previously completed etcd Get/Watch
157 // call, used to resume a Watch call in case of failures.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200158 prev *int64
159 // wc is the etcd watch channel, or nil if no channel is yet open.
160 wc clientv3.WatchChan
161
162 // testRaceWG is an optional WaitGroup that, if set, will be waited upon
163 // after the initial KV value retrieval, but before the watch is created.
164 // This is only used for testing.
165 testRaceWG *sync.WaitGroup
166 // testSetupWG is an optional WaitGroup that, if set, will be waited upon
167 // after the etcd watch is created.
168 // This is only used for testing.
169 testSetupWG *sync.WaitGroup
170}
171
Serge Bazanski8d45a052021-10-18 17:24:24 +0200172// setup initiates wc (the watch channel from etcd) after retrieving the initial
173// value(s) with a get operation.
Serge Bazanski37110c32023-03-01 13:57:27 +0000174func (w *watcher[T]) setup(ctx context.Context) error {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200175 if w.wc != nil {
176 return nil
177 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200178 ranged := w.key != w.keyEnd
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200179
Serge Bazanski8d45a052021-10-18 17:24:24 +0200180 // First, check if some data under this key/range already exists.
181
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200182 // We use an exponential backoff and retry here as the initial Get can fail
183 // if the cluster is unstable (eg. failing over). We only fail the retry if
184 // the context expires.
185 bo := backoff.NewExponentialBackOff()
186 bo.MaxElapsedTime = 0
Serge Bazanski8d45a052021-10-18 17:24:24 +0200187
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200188 err := backoff.Retry(func() error {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200189
190 var getOpts []clientv3.OpOption
191 if ranged {
192 getOpts = append(getOpts, clientv3.WithRange(w.keyEnd))
193 }
194 get, err := w.etcd.Get(ctx, w.key, getOpts...)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200195 if err != nil {
196 return fmt.Errorf("when retrieving initial value: %w", err)
197 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200198
199 // Assert that the etcd API is behaving as expected.
200 if !ranged && len(get.Kvs) > 1 {
201 panic("More than one key returned in unary GET response")
202 }
203
204 // After a successful Get, save the revision to watch from and re-build the
205 // backlog from scratch based on what was available in the etcd store at that
206 // time.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200207 w.prev = &get.Header.Revision
Serge Bazanski8d45a052021-10-18 17:24:24 +0200208
209 w.backlogged = nil
Serge Bazanski832bc772022-04-07 12:33:01 +0200210 w.current = make(map[string][]byte)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200211 for _, kv := range get.Kvs {
Serge Bazanski832bc772022-04-07 12:33:01 +0200212 w.backlogged = append(w.backlogged, kv.Key)
213 w.current[string(kv.Key)] = kv.Value
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200214 }
215 return nil
216
217 }, backoff.WithContext(bo, ctx))
218
219 if w.testRaceWG != nil {
220 w.testRaceWG.Wait()
221 }
222 if err != nil {
223 return err
224 }
225
Serge Bazanski8d45a052021-10-18 17:24:24 +0200226 watchOpts := []clientv3.OpOption{
227 clientv3.WithRev(*w.prev + 1),
228 }
229 if ranged {
230 watchOpts = append(watchOpts, clientv3.WithRange(w.keyEnd))
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200231 }
232 w.wc = w.etcd.Watch(w.ctx, w.key, watchOpts...)
233
234 if w.testSetupWG != nil {
235 w.testSetupWG.Wait()
236 }
237 return nil
238}
239
Serge Bazanski8d45a052021-10-18 17:24:24 +0200240// backfill blocks until a backlog of items is available. An error is returned
241// if the context is canceled.
Serge Bazanski37110c32023-03-01 13:57:27 +0000242func (w *watcher[T]) backfill(ctx context.Context) error {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200243 // Keep watching for watch events.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200244 for {
245 var resp *clientv3.WatchResponse
246 select {
247 case r := <-w.wc:
248 resp = &r
249 case <-ctx.Done():
Serge Bazanski8d45a052021-10-18 17:24:24 +0200250 return ctx.Err()
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200251 }
252
253 if resp.Canceled {
254 // Only allow for watches to be canceled due to context
255 // cancellations. Any other error is something we need to handle,
256 // eg. a client close or compaction error.
257 if errors.Is(resp.Err(), ctx.Err()) {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200258 return fmt.Errorf("watch canceled: %w", resp.Err())
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200259 }
260
261 // Attempt to reconnect.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200262 if w.wc != nil {
263 // If a wc already exists, close it. This forces a reconnection
264 // by the next setup call.
265 w.ctxC()
266 w.ctx, w.ctxC = context.WithCancel(context.Background())
267 w.wc = nil
268 }
269 if err := w.setup(ctx); err != nil {
270 return fmt.Errorf("failed to setup watcher: %w", err)
271 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200272 continue
273 }
274
Serge Bazanski8d45a052021-10-18 17:24:24 +0200275 w.prev = &resp.Header.Revision
276 // Spurious watch event with no update? Keep trying.
277 if len(resp.Events) == 0 {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200278 continue
279 }
280
Serge Bazanski8d45a052021-10-18 17:24:24 +0200281 // Process updates into compacted list, transforming deletions into value: nil
282 // keyValues. This maps an etcd key into a pointer in the already existing
283 // backlog list. It will then be used to compact all updates into the smallest
284 // backlog possible (by overriding previously backlogged items for a key if this
285 // key is encountered again).
286 //
287 // TODO(q3k): this could be stored in the watcher state to not waste time on
288 // each update, but it's good enough for now.
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200289
290 // Prepare a set of keys that already exist in the backlog. This will be used
291 // to make sure we don't duplicate backlog entries while maintaining a stable
292 // backlog order.
293 seen := make(map[string]bool)
294 for _, k := range w.backlogged {
295 seen[string(k)] = true
296 }
297
Serge Bazanski8d45a052021-10-18 17:24:24 +0200298 for _, ev := range resp.Events {
299 var value []byte
300 switch ev.Type {
301 case clientv3.EventTypeDelete:
302 case clientv3.EventTypePut:
303 value = ev.Kv.Value
304 default:
305 return fmt.Errorf("invalid event type %v", ev.Type)
306 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200307
Serge Bazanski8d45a052021-10-18 17:24:24 +0200308 keyS := string(ev.Kv.Key)
Serge Bazanski832bc772022-04-07 12:33:01 +0200309 prev := w.current[keyS]
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200310 // Short-circuit and skip updates with the same content as already present.
311 // These are sometimes emitted by etcd.
312 if bytes.Equal(prev, value) {
313 continue
Serge Bazanski8d45a052021-10-18 17:24:24 +0200314 }
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200315
316 // Only insert to backlog if not yet present, but maintain order.
317 if !seen[string(ev.Kv.Key)] {
318 w.backlogged = append(w.backlogged, ev.Kv.Key)
319 seen[string(ev.Kv.Key)] = true
320 }
321 // Regardless of backlog list, always update the key to its newest value.
322 w.current[keyS] = value
Serge Bazanski8d45a052021-10-18 17:24:24 +0200323 }
324
325 // Still nothing in backlog? Keep trying.
326 if len(w.backlogged) == 0 {
327 continue
328 }
329
330 return nil
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200331 }
332}
333
Serge Bazanski8d45a052021-10-18 17:24:24 +0200334type GetOption struct {
335 backlogOnly bool
336}
337
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200338// Get implements the Get method of the Watcher interface.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200339// It can return an error in three cases:
Serge Bazanski37110c32023-03-01 13:57:27 +0000340// - the given context is canceled (in which case, the given error will wrap
341// the context error)
342// - the watcher's BytesDecoder returned an error (in which case the error
343// returned by the BytesDecoder will be returned verbatim)
344// - it has been called with BacklogOnly and the Watcher has no more local
345// event data to return (see BacklogOnly for more information on the
346// semantics of this mode of operation)
347//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200348// Note that transient and permanent etcd errors are never returned, and the
349// Get call will attempt to recover from these errors as much as possible. This
350// also means that the user of the Watcher will not be notified if the
351// underlying etcd client disconnects from the cluster, or if the cluster loses
352// quorum.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200353//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200354// TODO(q3k): implement leases to allow clients to be notified when there are
355// transient cluster/quorum/partition errors, if needed.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200356//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200357// TODO(q3k): implement internal, limited buffering for backlogged data not yet
358// consumed by client, as etcd client library seems to use an unbound buffer in
359// case this happens ( see: watcherStream.buf in clientv3).
Serge Bazanski37110c32023-03-01 13:57:27 +0000360func (w *watcher[T]) Get(ctx context.Context, opts ...event.GetOption[T]) (T, error) {
361 var empty T
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200362 select {
363 case w.getSem <- struct{}{}:
364 default:
Serge Bazanski37110c32023-03-01 13:57:27 +0000365 return empty, fmt.Errorf("cannot Get() concurrently on a single waiter")
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200366 }
367 defer func() {
368 <-w.getSem
369 }()
370
Serge Bazanski8d45a052021-10-18 17:24:24 +0200371 backlogOnly := false
Serge Bazanski37110c32023-03-01 13:57:27 +0000372 var predicate func(t T) bool
373 for _, opt := range opts {
374 if opt.Predicate != nil {
375 predicate = opt.Predicate
Serge Bazanski8d45a052021-10-18 17:24:24 +0200376 }
Serge Bazanski37110c32023-03-01 13:57:27 +0000377 if opt.BacklogOnly {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200378 backlogOnly = true
379 }
380 }
381
Serge Bazanski37110c32023-03-01 13:57:27 +0000382 ranged := w.key != w.keyEnd
383 if ranged && predicate != nil {
384 return empty, errors.New("filtering unimplemented for ranged etcd values")
385 }
386 if backlogOnly && predicate != nil {
387 return empty, errors.New("filtering unimplemented for backlog-only requests")
388 }
389
390 for {
391 v, err := w.getUnlocked(ctx, ranged, backlogOnly)
392 if err != nil {
393 return empty, err
394 }
395 if predicate == nil || predicate(v) {
396 return v, nil
397 }
398 }
399}
400
401func (w *watcher[T]) getUnlocked(ctx context.Context, ranged, backlogOnly bool) (T, error) {
402 var empty T
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200403 // Early check for context cancelations, preventing spurious contact with etcd
404 // if there's no need to.
405 if w.ctx.Err() != nil {
Serge Bazanski37110c32023-03-01 13:57:27 +0000406 return empty, w.ctx.Err()
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200407 }
408
409 if err := w.setup(ctx); err != nil {
Serge Bazanski37110c32023-03-01 13:57:27 +0000410 return empty, fmt.Errorf("when setting up watcher: %w", err)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200411 }
412
Serge Bazanski8d45a052021-10-18 17:24:24 +0200413 if backlogOnly && len(w.backlogged) == 0 {
Tim Windelschmidt513df182024-04-18 23:44:50 +0200414 return empty, event.ErrBacklogDone
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200415 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200416
417 // Update backlog from etcd if needed.
418 if len(w.backlogged) < 1 {
419 err := w.backfill(ctx)
420 if err != nil {
Serge Bazanski37110c32023-03-01 13:57:27 +0000421 return empty, fmt.Errorf("when watching for new value: %w", err)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200422 }
423 }
424 // Backlog is now guaranteed to contain at least one element.
425
Serge Bazanski8d45a052021-10-18 17:24:24 +0200426 if !ranged {
427 // For non-ranged queries, drain backlog fully.
428 if len(w.backlogged) != 1 {
Serge Bazanski9d971182022-06-23 17:44:13 +0200429 panic(fmt.Sprintf("multiple keys in nonranged value: %v", w.backlogged))
Serge Bazanski8d45a052021-10-18 17:24:24 +0200430 }
Serge Bazanski832bc772022-04-07 12:33:01 +0200431 k := w.backlogged[0]
432 v := w.current[string(k)]
Serge Bazanski8d45a052021-10-18 17:24:24 +0200433 w.backlogged = nil
Serge Bazanski832bc772022-04-07 12:33:01 +0200434 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200435 } else {
436 // For ranged queries, pop one ranged query off the backlog.
Serge Bazanski832bc772022-04-07 12:33:01 +0200437 k := w.backlogged[0]
438 v := w.current[string(k)]
Serge Bazanski8d45a052021-10-18 17:24:24 +0200439 w.backlogged = w.backlogged[1:]
Serge Bazanski832bc772022-04-07 12:33:01 +0200440 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200441 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200442}
443
Serge Bazanski37110c32023-03-01 13:57:27 +0000444func (w *watcher[T]) Close() error {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200445 w.ctxC()
446 return nil
447}