blob: f5ccd2728a6c157d178eee5fe2d0fe0da2518299 [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 Bazanski8d45a052021-10-18 17:24:24 +0200281 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)
Serge Bazanski832bc772022-04-07 12:33:01 +0200292 prev := w.current[keyS]
293 if !bytes.Equal(prev, value) {
294 w.backlogged = append(w.backlogged, ev.Kv.Key)
295 w.current[keyS] = value
Serge Bazanski8d45a052021-10-18 17:24:24 +0200296 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200297 }
298
299 // Still nothing in backlog? Keep trying.
300 if len(w.backlogged) == 0 {
301 continue
302 }
303
304 return nil
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200305 }
306}
307
Serge Bazanski8d45a052021-10-18 17:24:24 +0200308type GetOption struct {
309 backlogOnly bool
310}
311
312var (
313 // BacklogOnly will prevent Get from blocking on waiting for more updates from
314 // etcd, by instead returning BacklogDone whenever no more data is currently
315 // locally available. This is different however, from establishing that there
316 // are no more pending updates from the etcd cluster - the only way to ensure
317 // the local client is up to date is by performing Get calls without this option
318 // set.
319 //
320 // This mode of retrieval should only be used for the retrieval of the existing
321 // data in the etcd cluster on the initial creation of the Watcher (by
322 // repeatedly calling Get until BacklogDone isreturned), and shouldn't be set
323 // for any subsequent call. Any use of this option after that initial fetch is
324 // undefined behaviour that exposes the internals of the Get implementation, and
325 // must not be relied on. However, in the future, this behaviour might be
326 // formalized.
327 //
328 // This mode is particularly useful for ranged watchers. Non-ranged watchers can
329 // still use this option to distinguish between blocking because of the
330 // nonexistence of an object vs. blocking because of networking issues. However,
331 // non-ranged retrieval semantics generally will rarely need to make this
332 // distinction.
333 BacklogOnly = GetOption{backlogOnly: true}
334
335 // BacklogDone is returned by Get when BacklogOnly is set and there is no more
336 // event data stored in the Watcher client, ie. when the initial cluster state
337 // of the requested key has been retrieved.
338 BacklogDone = errors.New("no more backlogged data")
339)
340
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200341// Get implements the Get method of the Watcher interface.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200342// It can return an error in three cases:
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200343// - the given context is canceled (in which case, the given error will wrap
344// the context error)
345// - the watcher's BytesDecoder returned an error (in which case the error
346// returned by the BytesDecoder will be returned verbatim)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200347// - it has been called with BacklogOnly and the Watcher has no more local
348// event data to return (see BacklogOnly for more information on the
349// semantics of this mode of operation)
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200350// Note that transient and permanent etcd errors are never returned, and the
351// Get call will attempt to recover from these errors as much as possible. This
352// also means that the user of the Watcher will not be notified if the
353// underlying etcd client disconnects from the cluster, or if the cluster loses
354// quorum.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200355//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200356// TODO(q3k): implement leases to allow clients to be notified when there are
357// transient cluster/quorum/partition errors, if needed.
Serge Bazanski8d45a052021-10-18 17:24:24 +0200358//
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200359// TODO(q3k): implement internal, limited buffering for backlogged data not yet
360// consumed by client, as etcd client library seems to use an unbound buffer in
361// case this happens ( see: watcherStream.buf in clientv3).
Serge Bazanski8d45a052021-10-18 17:24:24 +0200362func (w *watcher) Get(ctx context.Context, opts ...event.GetOption) (interface{}, error) {
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200363 select {
364 case w.getSem <- struct{}{}:
365 default:
366 return nil, fmt.Errorf("cannot Get() concurrently on a single waiter")
367 }
368 defer func() {
369 <-w.getSem
370 }()
371
Serge Bazanski8d45a052021-10-18 17:24:24 +0200372 backlogOnly := false
373 for _, optI := range opts {
374 opt, ok := optI.(GetOption)
375 if !ok {
376 return nil, fmt.Errorf("get options must be of type etcd.GetOption")
377 }
378 if opt.backlogOnly {
379 backlogOnly = true
380 }
381 }
382
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200383 // Early check for context cancelations, preventing spurious contact with etcd
384 // if there's no need to.
385 if w.ctx.Err() != nil {
386 return nil, w.ctx.Err()
387 }
388
389 if err := w.setup(ctx); err != nil {
390 return nil, fmt.Errorf("when setting up watcher: %w", err)
391 }
392
Serge Bazanski8d45a052021-10-18 17:24:24 +0200393 if backlogOnly && len(w.backlogged) == 0 {
394 return nil, BacklogDone
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200395 }
Serge Bazanski8d45a052021-10-18 17:24:24 +0200396
397 // Update backlog from etcd if needed.
398 if len(w.backlogged) < 1 {
399 err := w.backfill(ctx)
400 if err != nil {
401 return nil, fmt.Errorf("when watching for new value: %w", err)
402 }
403 }
404 // Backlog is now guaranteed to contain at least one element.
405
406 ranged := w.key != w.keyEnd
407 if !ranged {
408 // For non-ranged queries, drain backlog fully.
409 if len(w.backlogged) != 1 {
410 panic("multiple keys in nonranged value")
411 }
Serge Bazanski832bc772022-04-07 12:33:01 +0200412 k := w.backlogged[0]
413 v := w.current[string(k)]
Serge Bazanski8d45a052021-10-18 17:24:24 +0200414 w.backlogged = nil
Serge Bazanski832bc772022-04-07 12:33:01 +0200415 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200416 } else {
417 // For ranged queries, pop one ranged query off the backlog.
Serge Bazanski832bc772022-04-07 12:33:01 +0200418 k := w.backlogged[0]
419 v := w.current[string(k)]
Serge Bazanski8d45a052021-10-18 17:24:24 +0200420 w.backlogged = w.backlogged[1:]
Serge Bazanski832bc772022-04-07 12:33:01 +0200421 return w.decoder(k, v)
Serge Bazanski8d45a052021-10-18 17:24:24 +0200422 }
Serge Bazanskic89df2f2021-04-27 15:51:37 +0200423}
424
425func (w *watcher) Close() error {
426 w.ctxC()
427 return nil
428}