blob: d49a5929580e138081be14676f4598ff4445a263 [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.
22 _ event.ValueWatch = &Value{}
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.
28type Value struct {
29 etcd client.Namespaced
30 key string
Serge Bazanski8d45a052021-10-18 17:24:24 +020031 keyEnd string
Serge Bazanskic89df2f2021-04-27 15:51:37 +020032 decoder BytesDecoder
33}
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.
70func NewValue(etcd client.Namespaced, key string, decoder BytesDecoder, options ...*Option) *Value {
71 res := &Value{
72 etcd: etcd,
73 key: key,
74 keyEnd: key,
75 decoder: decoder,
76 }
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 Bazanskic89df2f2021-04-27 15:51:37 +020087// BytesDecoder is a function that converts bytes retrieved from etcd into an
Serge Bazanski8d45a052021-10-18 17:24:24 +020088// end-user facing value. Additionally, a key is available so that returned
89// values can be augmented with the location they were retrieved from. This is
90// especially useful when returning values resulting from an etcd range.
91//
92// If an error is returned, the Get call performed on a watcher configured with
93// this decoder will fail, swallowing that particular update, but the watcher
94// will continue to work. Any provided BytesDecoder implementations must be safe
95// to copy.
96type BytesDecoder = func(key []byte, data []byte) (interface{}, error)
Serge Bazanskic89df2f2021-04-27 15:51:37 +020097
98// NoDecoder is a no-op decoder which passes through the retrieved bytes as a
99// []byte type to the user.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200100func NoDecoder(key []byte, data []byte) (interface{}, error) {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200101 return data, nil
102}
103
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200104func (e *Value) Watch() event.Watcher {
105 ctx, ctxC := context.WithCancel(context.Background())
106 return &watcher{
107 Value: *e,
108
109 ctx: ctx,
110 ctxC: ctxC,
111
Serge Bazanski832bc772022-04-07 12:33:01 +0200112 current: make(map[string][]byte),
113
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200114 getSem: make(chan struct{}, 1),
115 }
116}
117
118type watcher struct {
119 // Value copy, used to configure the behaviour of this watcher.
120 Value
121
122 // ctx is the context that expresses the liveness of this watcher. It is
123 // canceled when the watcher is closed, and the etcd Watch hangs off of it.
124 ctx context.Context
125 ctxC context.CancelFunc
126
127 // getSem is a semaphore used to limit concurrent Get calls and throw an
128 // error if concurrent access is attempted.
129 getSem chan struct{}
130
Serge Bazanski832bc772022-04-07 12:33:01 +0200131 // backlogged is a list of keys retrieved from etcd but not yet returned via
132 // Get. These items are not a replay of all the updates from etcd, but are
133 // already compacted to deduplicate updates to the same object (ie., if the
134 // update stream from etcd is for keys A, B, and A, the backlogged list will
Serge Bazanski8d45a052021-10-18 17:24:24 +0200135 // only contain one update for A and B each, with the first update for A being
136 // discarded upon arrival of the second update).
Serge Bazanski832bc772022-04-07 12:33:01 +0200137 //
138 // The keys are an index into the current map, which contains the values
139 // retrieved, including ones that have already been returned via Get. This
140 // persistence allows us to deduplicate spurious updates to the user, in which
141 // etcd returned a new revision of a key, but the data stayed the same.
142 backlogged [][]byte
143 // current map, keyed from etcd key into etcd value at said key. This map
144 // persists alongside an etcd connection, permitting deduplication of spurious
145 // etcd updates even across multiple Get calls.
146 current map[string][]byte
147
Serge Bazanski8d45a052021-10-18 17:24:24 +0200148 // prev is the etcd store revision of a previously completed etcd Get/Watch
149 // call, used to resume a Watch call in case of failures.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200150 prev *int64
151 // wc is the etcd watch channel, or nil if no channel is yet open.
152 wc clientv3.WatchChan
153
154 // testRaceWG is an optional WaitGroup that, if set, will be waited upon
155 // after the initial KV value retrieval, but before the watch is created.
156 // This is only used for testing.
157 testRaceWG *sync.WaitGroup
158 // testSetupWG is an optional WaitGroup that, if set, will be waited upon
159 // after the etcd watch is created.
160 // This is only used for testing.
161 testSetupWG *sync.WaitGroup
162}
163
Serge Bazanski8d45a052021-10-18 17:24:24 +0200164// setup initiates wc (the watch channel from etcd) after retrieving the initial
165// value(s) with a get operation.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200166func (w *watcher) setup(ctx context.Context) error {
167 if w.wc != nil {
168 return nil
169 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200170 ranged := w.key != w.keyEnd
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200171
Serge Bazanski8d45a052021-10-18 17:24:24 +0200172 // First, check if some data under this key/range already exists.
173
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200174 // We use an exponential backoff and retry here as the initial Get can fail
175 // if the cluster is unstable (eg. failing over). We only fail the retry if
176 // the context expires.
177 bo := backoff.NewExponentialBackOff()
178 bo.MaxElapsedTime = 0
Serge Bazanski8d45a052021-10-18 17:24:24 +0200179
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200180 err := backoff.Retry(func() error {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200181
182 var getOpts []clientv3.OpOption
183 if ranged {
184 getOpts = append(getOpts, clientv3.WithRange(w.keyEnd))
185 }
186 get, err := w.etcd.Get(ctx, w.key, getOpts...)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200187 if err != nil {
188 return fmt.Errorf("when retrieving initial value: %w", err)
189 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200190
191 // Assert that the etcd API is behaving as expected.
192 if !ranged && len(get.Kvs) > 1 {
193 panic("More than one key returned in unary GET response")
194 }
195
196 // After a successful Get, save the revision to watch from and re-build the
197 // backlog from scratch based on what was available in the etcd store at that
198 // time.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200199 w.prev = &get.Header.Revision
Serge Bazanski8d45a052021-10-18 17:24:24 +0200200
201 w.backlogged = nil
Serge Bazanski832bc772022-04-07 12:33:01 +0200202 w.current = make(map[string][]byte)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200203 for _, kv := range get.Kvs {
Serge Bazanski832bc772022-04-07 12:33:01 +0200204 w.backlogged = append(w.backlogged, kv.Key)
205 w.current[string(kv.Key)] = kv.Value
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200206 }
207 return nil
208
209 }, backoff.WithContext(bo, ctx))
210
211 if w.testRaceWG != nil {
212 w.testRaceWG.Wait()
213 }
214 if err != nil {
215 return err
216 }
217
Serge Bazanski8d45a052021-10-18 17:24:24 +0200218 watchOpts := []clientv3.OpOption{
219 clientv3.WithRev(*w.prev + 1),
220 }
221 if ranged {
222 watchOpts = append(watchOpts, clientv3.WithRange(w.keyEnd))
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200223 }
224 w.wc = w.etcd.Watch(w.ctx, w.key, watchOpts...)
225
226 if w.testSetupWG != nil {
227 w.testSetupWG.Wait()
228 }
229 return nil
230}
231
Serge Bazanski8d45a052021-10-18 17:24:24 +0200232// backfill blocks until a backlog of items is available. An error is returned
233// if the context is canceled.
234func (w *watcher) backfill(ctx context.Context) error {
235 // Keep watching for watch events.
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200236 for {
237 var resp *clientv3.WatchResponse
238 select {
239 case r := <-w.wc:
240 resp = &r
241 case <-ctx.Done():
Serge Bazanski8d45a052021-10-18 17:24:24 +0200242 return ctx.Err()
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200243 }
244
245 if resp.Canceled {
246 // Only allow for watches to be canceled due to context
247 // cancellations. Any other error is something we need to handle,
248 // eg. a client close or compaction error.
249 if errors.Is(resp.Err(), ctx.Err()) {
Serge Bazanski8d45a052021-10-18 17:24:24 +0200250 return fmt.Errorf("watch canceled: %w", resp.Err())
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200251 }
252
253 // Attempt to reconnect.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200254 if w.wc != nil {
255 // If a wc already exists, close it. This forces a reconnection
256 // by the next setup call.
257 w.ctxC()
258 w.ctx, w.ctxC = context.WithCancel(context.Background())
259 w.wc = nil
260 }
261 if err := w.setup(ctx); err != nil {
262 return fmt.Errorf("failed to setup watcher: %w", err)
263 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200264 continue
265 }
266
Serge Bazanski8d45a052021-10-18 17:24:24 +0200267 w.prev = &resp.Header.Revision
268 // Spurious watch event with no update? Keep trying.
269 if len(resp.Events) == 0 {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200270 continue
271 }
272
Serge Bazanski8d45a052021-10-18 17:24:24 +0200273 // Process updates into compacted list, transforming deletions into value: nil
274 // keyValues. This maps an etcd key into a pointer in the already existing
275 // backlog list. It will then be used to compact all updates into the smallest
276 // backlog possible (by overriding previously backlogged items for a key if this
277 // key is encountered again).
278 //
279 // TODO(q3k): this could be stored in the watcher state to not waste time on
280 // each update, but it's good enough for now.
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200281
282 // Prepare a set of keys that already exist in the backlog. This will be used
283 // to make sure we don't duplicate backlog entries while maintaining a stable
284 // backlog order.
285 seen := make(map[string]bool)
286 for _, k := range w.backlogged {
287 seen[string(k)] = true
288 }
289
Serge Bazanski8d45a052021-10-18 17:24:24 +0200290 for _, ev := range resp.Events {
291 var value []byte
292 switch ev.Type {
293 case clientv3.EventTypeDelete:
294 case clientv3.EventTypePut:
295 value = ev.Kv.Value
296 default:
297 return fmt.Errorf("invalid event type %v", ev.Type)
298 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200299
Serge Bazanski8d45a052021-10-18 17:24:24 +0200300 keyS := string(ev.Kv.Key)
Serge Bazanski832bc772022-04-07 12:33:01 +0200301 prev := w.current[keyS]
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200302 // Short-circuit and skip updates with the same content as already present.
303 // These are sometimes emitted by etcd.
304 if bytes.Equal(prev, value) {
305 continue
Serge Bazanski8d45a052021-10-18 17:24:24 +0200306 }
Serge Bazanskibbb873d2022-06-24 14:22:39 +0200307
308 // Only insert to backlog if not yet present, but maintain order.
309 if !seen[string(ev.Kv.Key)] {
310 w.backlogged = append(w.backlogged, ev.Kv.Key)
311 seen[string(ev.Kv.Key)] = true
312 }
313 // Regardless of backlog list, always update the key to its newest value.
314 w.current[keyS] = value
Serge Bazanski8d45a052021-10-18 17:24:24 +0200315 }
316
317 // Still nothing in backlog? Keep trying.
318 if len(w.backlogged) == 0 {
319 continue
320 }
321
322 return nil
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200323 }
324}
325
Serge Bazanski8d45a052021-10-18 17:24:24 +0200326type GetOption struct {
327 backlogOnly bool
328}
329
330var (
331 // BacklogOnly will prevent Get from blocking on waiting for more updates from
332 // etcd, by instead returning BacklogDone whenever no more data is currently
333 // locally available. This is different however, from establishing that there
334 // are no more pending updates from the etcd cluster - the only way to ensure
335 // the local client is up to date is by performing Get calls without this option
336 // set.
337 //
338 // This mode of retrieval should only be used for the retrieval of the existing
339 // data in the etcd cluster on the initial creation of the Watcher (by
340 // repeatedly calling Get until BacklogDone isreturned), and shouldn't be set
341 // for any subsequent call. Any use of this option after that initial fetch is
342 // undefined behaviour that exposes the internals of the Get implementation, and
343 // must not be relied on. However, in the future, this behaviour might be
344 // formalized.
345 //
346 // This mode is particularly useful for ranged watchers. Non-ranged watchers can
347 // still use this option to distinguish between blocking because of the
348 // nonexistence of an object vs. blocking because of networking issues. However,
349 // non-ranged retrieval semantics generally will rarely need to make this
350 // distinction.
351 BacklogOnly = GetOption{backlogOnly: true}
352
353 // BacklogDone is returned by Get when BacklogOnly is set and there is no more
354 // event data stored in the Watcher client, ie. when the initial cluster state
355 // of the requested key has been retrieved.
356 BacklogDone = errors.New("no more backlogged data")
357)
358
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200359// Get implements the Get method of the Watcher interface.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200360// It can return an error in three cases:
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200361// - the given context is canceled (in which case, the given error will wrap
362// the context error)
363// - the watcher's BytesDecoder returned an error (in which case the error
364// returned by the BytesDecoder will be returned verbatim)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200365// - it has been called with BacklogOnly and the Watcher has no more local
366// event data to return (see BacklogOnly for more information on the
367// semantics of this mode of operation)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200368// Note that transient and permanent etcd errors are never returned, and the
369// Get call will attempt to recover from these errors as much as possible. This
370// also means that the user of the Watcher will not be notified if the
371// underlying etcd client disconnects from the cluster, or if the cluster loses
372// quorum.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200373//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200374// TODO(q3k): implement leases to allow clients to be notified when there are
375// transient cluster/quorum/partition errors, if needed.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200376//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200377// TODO(q3k): implement internal, limited buffering for backlogged data not yet
378// consumed by client, as etcd client library seems to use an unbound buffer in
379// case this happens ( see: watcherStream.buf in clientv3).
Serge Bazanski8d45a052021-10-18 17:24:24 +0200380func (w *watcher) Get(ctx context.Context, opts ...event.GetOption) (interface{}, error) {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200381 select {
382 case w.getSem <- struct{}{}:
383 default:
384 return nil, fmt.Errorf("cannot Get() concurrently on a single waiter")
385 }
386 defer func() {
387 <-w.getSem
388 }()
389
Serge Bazanski8d45a052021-10-18 17:24:24 +0200390 backlogOnly := false
391 for _, optI := range opts {
392 opt, ok := optI.(GetOption)
393 if !ok {
394 return nil, fmt.Errorf("get options must be of type etcd.GetOption")
395 }
396 if opt.backlogOnly {
397 backlogOnly = true
398 }
399 }
400
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200401 // Early check for context cancelations, preventing spurious contact with etcd
402 // if there's no need to.
403 if w.ctx.Err() != nil {
404 return nil, w.ctx.Err()
405 }
406
407 if err := w.setup(ctx); err != nil {
408 return nil, fmt.Errorf("when setting up watcher: %w", err)
409 }
410
Serge Bazanski8d45a052021-10-18 17:24:24 +0200411 if backlogOnly && len(w.backlogged) == 0 {
412 return nil, BacklogDone
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200413 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200414
415 // Update backlog from etcd if needed.
416 if len(w.backlogged) < 1 {
417 err := w.backfill(ctx)
418 if err != nil {
419 return nil, fmt.Errorf("when watching for new value: %w", err)
420 }
421 }
422 // Backlog is now guaranteed to contain at least one element.
423
424 ranged := w.key != w.keyEnd
425 if !ranged {
426 // For non-ranged queries, drain backlog fully.
427 if len(w.backlogged) != 1 {
Serge Bazanski9d971182022-06-23 17:44:13 +0200428 panic(fmt.Sprintf("multiple keys in nonranged value: %v", w.backlogged))
Serge Bazanski8d45a052021-10-18 17:24:24 +0200429 }
Serge Bazanski832bc772022-04-07 12:33:01 +0200430 k := w.backlogged[0]
431 v := w.current[string(k)]
Serge Bazanski8d45a052021-10-18 17:24:24 +0200432 w.backlogged = nil
Serge Bazanski832bc772022-04-07 12:33:01 +0200433 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200434 } else {
435 // For ranged queries, pop one ranged query off the backlog.
Serge Bazanski832bc772022-04-07 12:33:01 +0200436 k := w.backlogged[0]
437 v := w.current[string(k)]
Serge Bazanski8d45a052021-10-18 17:24:24 +0200438 w.backlogged = w.backlogged[1:]
Serge Bazanski832bc772022-04-07 12:33:01 +0200439 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200440 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200441}
442
443func (w *watcher) Close() error {
444 w.ctxC()
445 return nil
446}