blob: afcea35559574d804432be09d5e646b6df1a0714 [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
Serge Bazanskic89df2f2021-04-27 15:51:37 +020013 "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.
Serge Bazanski37110c32023-03-01 13:57:27 +000021 _ event.ValueWatch[StringAt] = &Value[StringAt]{}
Serge Bazanskic89df2f2021-04-27 15:51:37 +020022)
23
Tim Windelschmidtda1c9502024-05-08 01:24:29 +020024// ThinClient is a small wrapper interface to combine
25// clientv3.KV and clientv3.Watcher.
26type ThinClient interface {
27 clientv3.KV
28 clientv3.Watcher
29}
30
Serge Bazanskic89df2f2021-04-27 15:51:37 +020031// Value is an 'Event Value' backed in an etcd cluster, accessed over an
32// etcd client. This is a stateless handle and can be copied and shared across
33// goroutines.
Serge Bazanski37110c32023-03-01 13:57:27 +000034type Value[T any] struct {
35 decoder func(key, value []byte) (T, error)
Tim Windelschmidtda1c9502024-05-08 01:24:29 +020036 etcd ThinClient
Serge Bazanskic89df2f2021-04-27 15:51:37 +020037 key string
Serge Bazanski8d45a052021-10-18 17:24:24 +020038 keyEnd string
Serge Bazanskic89df2f2021-04-27 15:51:37 +020039}
40
Serge Bazanski8d45a052021-10-18 17:24:24 +020041type Option struct {
42 rangeEnd string
43}
44
45// Range creates a Value that is backed a range of etcd key/value pairs from
46// 'key' passed to NewValue to 'end' passed to Range.
47//
48// The key range semantics (ie. lexicographic ordering) are the same as in etcd
49// ranges, so for example to retrieve all keys prefixed by `foo/` key should be
50// `foo/` and end should be `foo0`.
51//
52// For any update in the given range, the decoder will be called and its result
53// will trigger the return of a Get() call. The decoder should return a type
54// that lets the user distinguish which of the multiple objects in the range got
55// updated, as the Get() call returns no additional information about the
56// location of the retrieved object by itself.
57//
58// The order of values retrieved by Get() is currently fully arbitrary and must
59// not be relied on. It's possible that in the future the order of updates and
60// the blocking behaviour of Get will be formalized, but this is not yet the
61// case. Instead, the data returned should be treated as eventually consistent
62// with the etcd state.
63//
64// For some uses, it might be necessary to first retrieve all the objects
65// contained within the range before starting to block on updates - in this
66// case, the BacklogOnly option should be used when calling Get.
67func Range(end string) *Option {
68 return &Option{
69 rangeEnd: end,
Serge Bazanskic89df2f2021-04-27 15:51:37 +020070 }
71}
72
Serge Bazanski8d45a052021-10-18 17:24:24 +020073// NewValue creates a new Value for a given key(s) in an etcd client. The
74// given decoder will be used to convert bytes retrieved from etcd into the
75// interface{} value retrieved by Get by this value's watcher.
Tim Windelschmidtda1c9502024-05-08 01:24:29 +020076func 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 +000077 res := &Value[T]{
78 decoder: decoder,
Serge Bazanski8d45a052021-10-18 17:24:24 +020079 etcd: etcd,
80 key: key,
81 keyEnd: key,
Serge Bazanski8d45a052021-10-18 17:24:24 +020082 }
83
84 for _, opt := range options {
85 if end := opt.rangeEnd; end != "" {
86 res.keyEnd = end
87 }
88 }
89
90 return res
91}
92
Serge Bazanski37110c32023-03-01 13:57:27 +000093func DecoderNoop(_, value []byte) ([]byte, error) {
94 return value, nil
Serge Bazanskic89df2f2021-04-27 15:51:37 +020095}
96
Serge Bazanski37110c32023-03-01 13:57:27 +000097func DecoderStringAt(key, value []byte) (StringAt, error) {
98 return StringAt{
99 Key: string(key),
100 Value: string(value),
101 }, nil
102}
103
104type StringAt struct {
105 Key string
106 Value string
107}
108
109func (e *Value[T]) Watch() event.Watcher[T] {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200110 ctx, ctxC := context.WithCancel(context.Background())
Serge Bazanski37110c32023-03-01 13:57:27 +0000111 return &watcher[T]{
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200112 Value: *e,
113
114 ctx: ctx,
115 ctxC: ctxC,
116
Serge Bazanski832bc772022-04-07 12:33:01 +0200117 current: make(map[string][]byte),
118
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200119 getSem: make(chan struct{}, 1),
120 }
121}
122
Serge Bazanski37110c32023-03-01 13:57:27 +0000123type watcher[T any] struct {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200124 // Value copy, used to configure the behaviour of this watcher.
Serge Bazanski37110c32023-03-01 13:57:27 +0000125 Value[T]
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200126
127 // ctx is the context that expresses the liveness of this watcher. It is
128 // canceled when the watcher is closed, and the etcd Watch hangs off of it.
129 ctx context.Context
130 ctxC context.CancelFunc
131
132 // getSem is a semaphore used to limit concurrent Get calls and throw an
133 // error if concurrent access is attempted.
134 getSem chan struct{}
135
Serge Bazanski832bc772022-04-07 12:33:01 +0200136 // backlogged is a list of keys retrieved from etcd but not yet returned via
137 // Get. These items are not a replay of all the updates from etcd, but are
138 // already compacted to deduplicate updates to the same object (ie., if the
139 // update stream from etcd is for keys A, B, and A, the backlogged list will
Serge Bazanski8d45a052021-10-18 17:24:24 +0200140 // only contain one update for A and B each, with the first update for A being
141 // discarded upon arrival of the second update).
Serge Bazanski832bc772022-04-07 12:33:01 +0200142 //
143 // The keys are an index into the current map, which contains the values
144 // retrieved, including ones that have already been returned via Get. This
145 // persistence allows us to deduplicate spurious updates to the user, in which
146 // etcd returned a new revision of a key, but the data stayed the same.
147 backlogged [][]byte
148 // current map, keyed from etcd key into etcd value at said key. This map
149 // persists alongside an etcd connection, permitting deduplication of spurious
150 // etcd updates even across multiple Get calls.
151 current map[string][]byte
152
Serge Bazanski8d45a052021-10-18 17:24:24 +0200153 // prev is the etcd store revision of a previously completed etcd Get/Watch
154 // call, used to resume a Watch call in case of failures.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200155 prev *int64
156 // wc is the etcd watch channel, or nil if no channel is yet open.
157 wc clientv3.WatchChan
158
159 // testRaceWG is an optional WaitGroup that, if set, will be waited upon
160 // after the initial KV value retrieval, but before the watch is created.
161 // This is only used for testing.
162 testRaceWG *sync.WaitGroup
163 // testSetupWG is an optional WaitGroup that, if set, will be waited upon
164 // after the etcd watch is created.
165 // This is only used for testing.
166 testSetupWG *sync.WaitGroup
167}
168
Serge Bazanski8d45a052021-10-18 17:24:24 +0200169// setup initiates wc (the watch channel from etcd) after retrieving the initial
170// value(s) with a get operation.
Serge Bazanski37110c32023-03-01 13:57:27 +0000171func (w *watcher[T]) setup(ctx context.Context) error {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200172 if w.wc != nil {
173 return nil
174 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200175 ranged := w.key != w.keyEnd
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200176
Serge Bazanski8d45a052021-10-18 17:24:24 +0200177 // First, check if some data under this key/range already exists.
178
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200179 // We use an exponential backoff and retry here as the initial Get can fail
180 // if the cluster is unstable (eg. failing over). We only fail the retry if
181 // the context expires.
182 bo := backoff.NewExponentialBackOff()
183 bo.MaxElapsedTime = 0
Serge Bazanski8d45a052021-10-18 17:24:24 +0200184
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200185 err := backoff.Retry(func() error {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200186
187 var getOpts []clientv3.OpOption
188 if ranged {
189 getOpts = append(getOpts, clientv3.WithRange(w.keyEnd))
190 }
191 get, err := w.etcd.Get(ctx, w.key, getOpts...)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200192 if err != nil {
193 return fmt.Errorf("when retrieving initial value: %w", err)
194 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200195
196 // Assert that the etcd API is behaving as expected.
197 if !ranged && len(get.Kvs) > 1 {
198 panic("More than one key returned in unary GET response")
199 }
200
201 // After a successful Get, save the revision to watch from and re-build the
202 // backlog from scratch based on what was available in the etcd store at that
203 // time.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200204 w.prev = &get.Header.Revision
Serge Bazanski8d45a052021-10-18 17:24:24 +0200205
206 w.backlogged = nil
Serge Bazanski832bc772022-04-07 12:33:01 +0200207 w.current = make(map[string][]byte)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200208 for _, kv := range get.Kvs {
Serge Bazanski832bc772022-04-07 12:33:01 +0200209 w.backlogged = append(w.backlogged, kv.Key)
210 w.current[string(kv.Key)] = kv.Value
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200211 }
212 return nil
213
214 }, backoff.WithContext(bo, ctx))
215
216 if w.testRaceWG != nil {
217 w.testRaceWG.Wait()
218 }
219 if err != nil {
220 return err
221 }
222
Serge Bazanski8d45a052021-10-18 17:24:24 +0200223 watchOpts := []clientv3.OpOption{
224 clientv3.WithRev(*w.prev + 1),
225 }
226 if ranged {
227 watchOpts = append(watchOpts, clientv3.WithRange(w.keyEnd))
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200228 }
229 w.wc = w.etcd.Watch(w.ctx, w.key, watchOpts...)
230
231 if w.testSetupWG != nil {
232 w.testSetupWG.Wait()
233 }
234 return nil
235}
236
Serge Bazanski8d45a052021-10-18 17:24:24 +0200237// backfill blocks until a backlog of items is available. An error is returned
238// if the context is canceled.
Serge Bazanski37110c32023-03-01 13:57:27 +0000239func (w *watcher[T]) backfill(ctx context.Context) error {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200240 // Keep watching for watch events.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200241 for {
242 var resp *clientv3.WatchResponse
243 select {
244 case r := <-w.wc:
245 resp = &r
246 case <-ctx.Done():
Serge Bazanski8d45a052021-10-18 17:24:24 +0200247 return ctx.Err()
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200248 }
249
250 if resp.Canceled {
251 // Only allow for watches to be canceled due to context
252 // cancellations. Any other error is something we need to handle,
253 // eg. a client close or compaction error.
254 if errors.Is(resp.Err(), ctx.Err()) {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200255 return fmt.Errorf("watch canceled: %w", resp.Err())
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200256 }
257
258 // Attempt to reconnect.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200259 if w.wc != nil {
260 // If a wc already exists, close it. This forces a reconnection
261 // by the next setup call.
262 w.ctxC()
263 w.ctx, w.ctxC = context.WithCancel(context.Background())
264 w.wc = nil
265 }
266 if err := w.setup(ctx); err != nil {
267 return fmt.Errorf("failed to setup watcher: %w", err)
268 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200269 continue
270 }
271
Serge Bazanski8d45a052021-10-18 17:24:24 +0200272 w.prev = &resp.Header.Revision
273 // Spurious watch event with no update? Keep trying.
274 if len(resp.Events) == 0 {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200275 continue
276 }
277
Serge Bazanski8d45a052021-10-18 17:24:24 +0200278 // Process updates into compacted list, transforming deletions into value: nil
279 // keyValues. This maps an etcd key into a pointer in the already existing
280 // backlog list. It will then be used to compact all updates into the smallest
281 // backlog possible (by overriding previously backlogged items for a key if this
282 // key is encountered again).
283 //
284 // TODO(q3k): this could be stored in the watcher state to not waste time on
285 // each update, but it's good enough for now.
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200286
287 // Prepare a set of keys that already exist in the backlog. This will be used
288 // to make sure we don't duplicate backlog entries while maintaining a stable
289 // backlog order.
290 seen := make(map[string]bool)
291 for _, k := range w.backlogged {
292 seen[string(k)] = true
293 }
294
Serge Bazanski8d45a052021-10-18 17:24:24 +0200295 for _, ev := range resp.Events {
296 var value []byte
297 switch ev.Type {
298 case clientv3.EventTypeDelete:
299 case clientv3.EventTypePut:
300 value = ev.Kv.Value
301 default:
302 return fmt.Errorf("invalid event type %v", ev.Type)
303 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200304
Serge Bazanski8d45a052021-10-18 17:24:24 +0200305 keyS := string(ev.Kv.Key)
Serge Bazanski832bc772022-04-07 12:33:01 +0200306 prev := w.current[keyS]
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200307 // Short-circuit and skip updates with the same content as already present.
308 // These are sometimes emitted by etcd.
309 if bytes.Equal(prev, value) {
310 continue
Serge Bazanski8d45a052021-10-18 17:24:24 +0200311 }
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200312
313 // Only insert to backlog if not yet present, but maintain order.
314 if !seen[string(ev.Kv.Key)] {
315 w.backlogged = append(w.backlogged, ev.Kv.Key)
316 seen[string(ev.Kv.Key)] = true
317 }
318 // Regardless of backlog list, always update the key to its newest value.
319 w.current[keyS] = value
Serge Bazanski8d45a052021-10-18 17:24:24 +0200320 }
321
322 // Still nothing in backlog? Keep trying.
323 if len(w.backlogged) == 0 {
324 continue
325 }
326
327 return nil
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200328 }
329}
330
Serge Bazanski8d45a052021-10-18 17:24:24 +0200331type GetOption struct {
332 backlogOnly bool
333}
334
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200335// Get implements the Get method of the Watcher interface.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200336// It can return an error in three cases:
Serge Bazanski37110c32023-03-01 13:57:27 +0000337// - the given context is canceled (in which case, the given error will wrap
338// the context error)
339// - the watcher's BytesDecoder returned an error (in which case the error
340// returned by the BytesDecoder will be returned verbatim)
341// - it has been called with BacklogOnly and the Watcher has no more local
342// event data to return (see BacklogOnly for more information on the
343// semantics of this mode of operation)
344//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200345// Note that transient and permanent etcd errors are never returned, and the
346// Get call will attempt to recover from these errors as much as possible. This
347// also means that the user of the Watcher will not be notified if the
348// underlying etcd client disconnects from the cluster, or if the cluster loses
349// quorum.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200350//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200351// TODO(q3k): implement leases to allow clients to be notified when there are
352// transient cluster/quorum/partition errors, if needed.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200353//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200354// TODO(q3k): implement internal, limited buffering for backlogged data not yet
355// consumed by client, as etcd client library seems to use an unbound buffer in
356// case this happens ( see: watcherStream.buf in clientv3).
Serge Bazanski37110c32023-03-01 13:57:27 +0000357func (w *watcher[T]) Get(ctx context.Context, opts ...event.GetOption[T]) (T, error) {
358 var empty T
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200359 select {
360 case w.getSem <- struct{}{}:
361 default:
Serge Bazanski37110c32023-03-01 13:57:27 +0000362 return empty, fmt.Errorf("cannot Get() concurrently on a single waiter")
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200363 }
364 defer func() {
365 <-w.getSem
366 }()
367
Serge Bazanski8d45a052021-10-18 17:24:24 +0200368 backlogOnly := false
Serge Bazanski37110c32023-03-01 13:57:27 +0000369 var predicate func(t T) bool
370 for _, opt := range opts {
371 if opt.Predicate != nil {
372 predicate = opt.Predicate
Serge Bazanski8d45a052021-10-18 17:24:24 +0200373 }
Serge Bazanski37110c32023-03-01 13:57:27 +0000374 if opt.BacklogOnly {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200375 backlogOnly = true
376 }
377 }
378
Serge Bazanski37110c32023-03-01 13:57:27 +0000379 ranged := w.key != w.keyEnd
380 if ranged && predicate != nil {
381 return empty, errors.New("filtering unimplemented for ranged etcd values")
382 }
383 if backlogOnly && predicate != nil {
384 return empty, errors.New("filtering unimplemented for backlog-only requests")
385 }
386
387 for {
388 v, err := w.getUnlocked(ctx, ranged, backlogOnly)
389 if err != nil {
390 return empty, err
391 }
392 if predicate == nil || predicate(v) {
393 return v, nil
394 }
395 }
396}
397
398func (w *watcher[T]) getUnlocked(ctx context.Context, ranged, backlogOnly bool) (T, error) {
399 var empty T
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200400 // Early check for context cancelations, preventing spurious contact with etcd
401 // if there's no need to.
402 if w.ctx.Err() != nil {
Serge Bazanski37110c32023-03-01 13:57:27 +0000403 return empty, w.ctx.Err()
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200404 }
405
406 if err := w.setup(ctx); err != nil {
Serge Bazanski37110c32023-03-01 13:57:27 +0000407 return empty, fmt.Errorf("when setting up watcher: %w", err)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200408 }
409
Serge Bazanski8d45a052021-10-18 17:24:24 +0200410 if backlogOnly && len(w.backlogged) == 0 {
Tim Windelschmidt513df182024-04-18 23:44:50 +0200411 return empty, event.ErrBacklogDone
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200412 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200413
414 // Update backlog from etcd if needed.
415 if len(w.backlogged) < 1 {
416 err := w.backfill(ctx)
417 if err != nil {
Serge Bazanski37110c32023-03-01 13:57:27 +0000418 return empty, fmt.Errorf("when watching for new value: %w", err)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200419 }
420 }
421 // Backlog is now guaranteed to contain at least one element.
422
Serge Bazanski8d45a052021-10-18 17:24:24 +0200423 if !ranged {
424 // For non-ranged queries, drain backlog fully.
425 if len(w.backlogged) != 1 {
Serge Bazanski9d971182022-06-23 17:44:13 +0200426 panic(fmt.Sprintf("multiple keys in nonranged value: %v", w.backlogged))
Serge Bazanski8d45a052021-10-18 17:24:24 +0200427 }
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 = nil
Serge Bazanski832bc772022-04-07 12:33:01 +0200431 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200432 } else {
433 // For ranged queries, pop one ranged query off the backlog.
Serge Bazanski832bc772022-04-07 12:33:01 +0200434 k := w.backlogged[0]
435 v := w.current[string(k)]
Serge Bazanski8d45a052021-10-18 17:24:24 +0200436 w.backlogged = w.backlogged[1:]
Serge Bazanski832bc772022-04-07 12:33:01 +0200437 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200438 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200439}
440
Serge Bazanski37110c32023-03-01 13:57:27 +0000441func (w *watcher[T]) Close() error {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200442 w.ctxC()
443 return nil
444}