blob: ff40bcd159f1df467601dbe6b8ea8e8087efc694 [file] [log] [blame]
Serge Bazanskic89df2f2021-04-27 15:51:37 +02001package etcd
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "sync"
8
9 "github.com/cenkalti/backoff/v4"
10 "go.etcd.io/etcd/clientv3"
11
12 "source.monogon.dev/metropolis/node/core/consensus/client"
13 "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.
21 _ event.ValueWatch = &Value{}
Serge Bazanskic89df2f2021-04-27 15:51:37 +020022)
23
24// Value is an 'Event Value' backed in an etcd cluster, accessed over an
25// etcd client. This is a stateless handle and can be copied and shared across
26// goroutines.
27type Value struct {
28 etcd client.Namespaced
29 key string
30 decoder BytesDecoder
31}
32
33// NewValue creates a new Value for a given key in an etcd client. The
34// given decoder will be used to convert bytes retrieved from etcd into the
35// interface{} value retrieved by Get by this value's watcher.
36func NewValue(etcd client.Namespaced, key string, decoder BytesDecoder) *Value {
37 return &Value{
38 etcd: etcd,
39 key: key,
40 decoder: decoder,
41 }
42}
43
44// BytesDecoder is a function that converts bytes retrieved from etcd into an
45// end-user facing value. If an error is returned, the Get call performed on a
46// watcher configured with this decoder will fail, swallowing that particular
47// update, but the watcher will continue to work.
48// Any provided BytesDecoder implementations must be safe to copy.
49type BytesDecoder = func(data []byte) (interface{}, error)
50
51// NoDecoder is a no-op decoder which passes through the retrieved bytes as a
52// []byte type to the user.
53func NoDecoder(data []byte) (interface{}, error) {
54 return data, nil
55}
56
Serge Bazanskic89df2f2021-04-27 15:51:37 +020057func (e *Value) Watch() event.Watcher {
58 ctx, ctxC := context.WithCancel(context.Background())
59 return &watcher{
60 Value: *e,
61
62 ctx: ctx,
63 ctxC: ctxC,
64
65 getSem: make(chan struct{}, 1),
66 }
67}
68
69type watcher struct {
70 // Value copy, used to configure the behaviour of this watcher.
71 Value
72
73 // ctx is the context that expresses the liveness of this watcher. It is
74 // canceled when the watcher is closed, and the etcd Watch hangs off of it.
75 ctx context.Context
76 ctxC context.CancelFunc
77
78 // getSem is a semaphore used to limit concurrent Get calls and throw an
79 // error if concurrent access is attempted.
80 getSem chan struct{}
81
82 // backlogged is the value retrieved by an initial KV Get from etcd that
83 // should be returned at the next opportunity, or nil if there isn't any.
84 backlogged *[]byte
85 // prev is the revision of a previously retrieved value within this
86 // watcher, or nil if there hasn't been any.
87 prev *int64
88 // wc is the etcd watch channel, or nil if no channel is yet open.
89 wc clientv3.WatchChan
90
91 // testRaceWG is an optional WaitGroup that, if set, will be waited upon
92 // after the initial KV value retrieval, but before the watch is created.
93 // This is only used for testing.
94 testRaceWG *sync.WaitGroup
95 // testSetupWG is an optional WaitGroup that, if set, will be waited upon
96 // after the etcd watch is created.
97 // This is only used for testing.
98 testSetupWG *sync.WaitGroup
99}
100
101func (w *watcher) setup(ctx context.Context) error {
102 if w.wc != nil {
103 return nil
104 }
105
106 // First, check if some data under this key already exists.
107 // We use an exponential backoff and retry here as the initial Get can fail
108 // if the cluster is unstable (eg. failing over). We only fail the retry if
109 // the context expires.
110 bo := backoff.NewExponentialBackOff()
111 bo.MaxElapsedTime = 0
112 err := backoff.Retry(func() error {
113 get, err := w.etcd.Get(ctx, w.key)
114 if err != nil {
115 return fmt.Errorf("when retrieving initial value: %w", err)
116 }
117 w.prev = &get.Header.Revision
118 if len(get.Kvs) != 0 {
119 // Assert that the etcd API is behaving as expected.
120 if len(get.Kvs) > 1 {
121 panic("More than one key returned in unary GET response")
122 }
123 // If an existing value is present, backlog it and set the prev value
124 // accordingly.
125 kv := get.Kvs[0]
126 w.backlogged = &kv.Value
127 } else {
128 w.backlogged = nil
129 }
130 return nil
131
132 }, backoff.WithContext(bo, ctx))
133
134 if w.testRaceWG != nil {
135 w.testRaceWG.Wait()
136 }
137 if err != nil {
138 return err
139 }
140
141 var watchOpts []clientv3.OpOption
142 if w.prev != nil {
143 watchOpts = append(watchOpts, clientv3.WithRev(*w.prev+1))
144 } else {
145 }
146 w.wc = w.etcd.Watch(w.ctx, w.key, watchOpts...)
147
148 if w.testSetupWG != nil {
149 w.testSetupWG.Wait()
150 }
151 return nil
152}
153
154func (w *watcher) get(ctx context.Context) ([]byte, error) {
155 // Return backlogged value, if present.
156 if w.backlogged != nil {
157 value := *w.backlogged
158 w.backlogged = nil
159 return value, nil
160 }
161
162 // Keep watching for a watch event.
163 var event *clientv3.Event
164 for {
165 var resp *clientv3.WatchResponse
166 select {
167 case r := <-w.wc:
168 resp = &r
169 case <-ctx.Done():
170 return nil, ctx.Err()
171 }
172
173 if resp.Canceled {
174 // Only allow for watches to be canceled due to context
175 // cancellations. Any other error is something we need to handle,
176 // eg. a client close or compaction error.
177 if errors.Is(resp.Err(), ctx.Err()) {
178 return nil, fmt.Errorf("watch canceled: %w", resp.Err())
179 }
180
181 // Attempt to reconnect.
182 w.wc = nil
183 w.setup(ctx)
184 continue
185 }
186
187 if len(resp.Events) < 1 {
188 continue
189 }
190
191 event = resp.Events[len(resp.Events)-1]
192 break
193 }
194
195 w.prev = &event.Kv.ModRevision
196 // Return deletions as nil, and new values as their content.
197 switch event.Type {
198 case clientv3.EventTypeDelete:
199 return nil, nil
200 case clientv3.EventTypePut:
201 return event.Kv.Value, nil
202 default:
203 return nil, fmt.Errorf("invalid event type %v", event.Type)
204 }
205}
206
207// Get implements the Get method of the Watcher interface.
208// It can return an error in two cases:
209// - the given context is canceled (in which case, the given error will wrap
210// the context error)
211// - the watcher's BytesDecoder returned an error (in which case the error
212// returned by the BytesDecoder will be returned verbatim)
213// Note that transient and permanent etcd errors are never returned, and the
214// Get call will attempt to recover from these errors as much as possible. This
215// also means that the user of the Watcher will not be notified if the
216// underlying etcd client disconnects from the cluster, or if the cluster loses
217// quorum.
218// TODO(q3k): implement leases to allow clients to be notified when there are
219// transient cluster/quorum/partition errors, if needed.
220// TODO(q3k): implement internal, limited buffering for backlogged data not yet
221// consumed by client, as etcd client library seems to use an unbound buffer in
222// case this happens ( see: watcherStream.buf in clientv3).
223func (w *watcher) Get(ctx context.Context) (interface{}, error) {
224 select {
225 case w.getSem <- struct{}{}:
226 default:
227 return nil, fmt.Errorf("cannot Get() concurrently on a single waiter")
228 }
229 defer func() {
230 <-w.getSem
231 }()
232
233 // Early check for context cancelations, preventing spurious contact with etcd
234 // if there's no need to.
235 if w.ctx.Err() != nil {
236 return nil, w.ctx.Err()
237 }
238
239 if err := w.setup(ctx); err != nil {
240 return nil, fmt.Errorf("when setting up watcher: %w", err)
241 }
242
243 value, err := w.get(ctx)
244 if err != nil {
245 return nil, fmt.Errorf("when watching for new value: %w", err)
246 }
247 return w.decoder(value)
248}
249
250func (w *watcher) Close() error {
251 w.ctxC()
252 return nil
253}