| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package etcdvar provides a runtimevar implementation with variables |
| 16 |
// backed by etcd. Use OpenVariable to construct a *runtimevar.Variable. |
| 17 |
// |
| 18 |
// # URLs |
| 19 |
// |
| 20 |
// For runtimevar.OpenVariable, etcdvar registers for the scheme "etcd". |
| 21 |
// The default URL opener will dial an etcd server based on the environment |
| 22 |
// variable "ETCD_SERVER_URL". |
| 23 |
// To customize the URL opener, or for more details on the URL format, |
| 24 |
// see URLOpener. |
| 25 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 26 |
// |
| 27 |
// # As |
| 28 |
// |
| 29 |
// etcdvar exposes the following types for As: |
| 30 |
// - Snapshot: *clientv3.GetResponse |
| 31 |
// - Error: rpctypes.EtcdError |
| 32 |
package etcdvar // import "gocloud.dev/runtimevar/etcdvar" |
| 33 |
|
| 34 |
import ( |
| 35 |
"context" |
| 36 |
"errors" |
| 37 |
"fmt" |
| 38 |
"net/url" |
| 39 |
"os" |
| 40 |
"path" |
| 41 |
"sync" |
| 42 |
"time" |
| 43 |
|
| 44 |
"go.etcd.io/etcd/client/v3" |
| 45 |
"go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes" |
| 46 |
"gocloud.dev/gcerrors" |
| 47 |
"gocloud.dev/runtimevar" |
| 48 |
"gocloud.dev/runtimevar/driver" |
| 49 |
"google.golang.org/grpc/codes" |
| 50 |
) |
| 51 |
|
| 52 |
func init() { |
| 53 |
runtimevar.DefaultURLMux().RegisterVariable(Scheme, &defaultDialer{}) |
| 54 |
} |
| 55 |
|
| 56 |
// Scheme is the URL scheme etcdvar registers its URLOpener under on runtimevar.DefaultMux. |
| 57 |
const Scheme = "etcd" |
| 58 |
|
| 59 |
type defaultDialer struct { |
| 60 |
init sync.Once |
| 61 |
opener *URLOpener |
| 62 |
err error |
| 63 |
} |
| 64 |
|
| 65 |
func (o *defaultDialer) OpenVariableURL(ctx context.Context, u *url.URL) (*runtimevar.Variable, error) { |
| 66 |
o.init.Do(func() { |
| 67 |
serverURL := os.Getenv("ETCD_SERVER_URL") |
| 68 |
if serverURL == "" { |
| 69 |
o.err = errors.New("ETCD_SERVER_URL environment variable is not set") |
| 70 |
return |
| 71 |
} |
| 72 |
client, err := clientv3.NewFromURL(serverURL) |
| 73 |
if err != nil { |
| 74 |
o.err = fmt.Errorf("failed to connect to default client %q: %v", serverURL, err) |
| 75 |
return |
| 76 |
} |
| 77 |
o.opener = &URLOpener{Client: client} |
| 78 |
}) |
| 79 |
if o.err != nil { |
| 80 |
return nil, fmt.Errorf("open variable %v: %v", u, o.err) |
| 81 |
} |
| 82 |
return o.opener.OpenVariableURL(ctx, u) |
| 83 |
} |
| 84 |
|
| 85 |
// URLOpener opens etcd URLs like "etcd://mykey?decoder=string". |
| 86 |
// |
| 87 |
// The host+path is used as the variable name. |
| 88 |
// |
| 89 |
// The following URL parameters are supported: |
| 90 |
// - decoder: The decoder to use. Defaults to runtimevar.BytesDecoder. |
| 91 |
// See runtimevar.DecoderByName for supported values. |
| 92 |
type URLOpener struct { |
| 93 |
// The Client to use; required. |
| 94 |
Client *clientv3.Client |
| 95 |
|
| 96 |
// Decoder specifies the decoder to use if one is not specified in the URL. |
| 97 |
// Defaults to runtimevar.BytesDecoder. |
| 98 |
Decoder *runtimevar.Decoder |
| 99 |
|
| 100 |
// Options specifies the options to pass to OpenVariable. |
| 101 |
Options Options |
| 102 |
} |
| 103 |
|
| 104 |
// OpenVariableURL opens a etcdvar Variable for u. |
| 105 |
func (o *URLOpener) OpenVariableURL(ctx context.Context, u *url.URL) (*runtimevar.Variable, error) { |
| 106 |
q := u.Query() |
| 107 |
|
| 108 |
decoderName := q.Get("decoder") |
| 109 |
q.Del("decoder") |
| 110 |
decoder, err := runtimevar.DecoderByName(ctx, decoderName, o.Decoder) |
| 111 |
if err != nil { |
| 112 |
return nil, fmt.Errorf("open variable %v: invalid decoder: %v", u, err) |
| 113 |
} |
| 114 |
|
| 115 |
for param := range q { |
| 116 |
return nil, fmt.Errorf("open variable %v: invalid query parameter %q", u, param) |
| 117 |
} |
| 118 |
return OpenVariable(o.Client, path.Join(u.Host, u.Path), decoder, &o.Options) |
| 119 |
} |
| 120 |
|
| 121 |
// Options sets options. |
| 122 |
type Options struct { |
| 123 |
// Timeout controls the timeout on RPCs to etcd; timeouts will result in |
| 124 |
// errors being returned from Watch. Defaults to 30 seconds. |
| 125 |
Timeout time.Duration |
| 126 |
} |
| 127 |
|
| 128 |
// OpenVariable constructs a *runtimevar.Variable that uses client to watch the variable |
| 129 |
// name on an etcd server. |
| 130 |
// etcd returns raw bytes; provide a decoder to decode the raw bytes into the |
| 131 |
// appropriate type for runtimevar.Snapshot.Value. |
| 132 |
// See the runtimevar package documentation for examples of decoders. |
| 133 |
func OpenVariable(cli *clientv3.Client, name string, decoder *runtimevar.Decoder, opts *Options) (*runtimevar.Variable, error) { |
| 134 |
return runtimevar.New(newWatcher(cli, name, decoder, opts)), nil |
| 135 |
} |
| 136 |
|
| 137 |
func newWatcher(cli *clientv3.Client, name string, decoder *runtimevar.Decoder, opts *Options) *watcher { |
| 138 |
if opts == nil { |
| 139 |
opts = &Options{} |
| 140 |
} |
| 141 |
// Create a ctx for the background goroutine that does all of the reading. |
| 142 |
// The cancel function will be used to shut it down during Close. |
| 143 |
ctx, cancel := context.WithCancel(context.Background()) |
| 144 |
w := &watcher{ |
| 145 |
// See struct comments for why it's buffered. |
| 146 |
ch: make(chan *state, 1), |
| 147 |
shutdown: cancel, |
| 148 |
} |
| 149 |
go w.watch(ctx, cli, name, decoder, driver.WaitDuration(opts.Timeout)) |
| 150 |
return w |
| 151 |
} |
| 152 |
|
| 153 |
// errNotExist is a sentinel error for nonexistent variables. |
| 154 |
var errNotExist = errors.New("variable does not exist") |
| 155 |
|
| 156 |
// state implements driver.State. |
| 157 |
type state struct { |
| 158 |
val any |
| 159 |
raw *clientv3.GetResponse |
| 160 |
updateTime time.Time |
| 161 |
version int64 |
| 162 |
err error |
| 163 |
} |
| 164 |
|
| 165 |
// Value implements driver.State.Value. |
| 166 |
func (s *state) Value() (any, error) { |
| 167 |
return s.val, s.err |
| 168 |
} |
| 169 |
|
| 170 |
// UpdateTime implements driver.State.UpdateTime. |
| 171 |
func (s *state) UpdateTime() time.Time { |
| 172 |
return s.updateTime |
| 173 |
} |
| 174 |
|
| 175 |
// As implements driver.State.As. |
| 176 |
func (s *state) As(i any) bool { |
| 177 |
if s.raw == nil { |
| 178 |
return false |
| 179 |
} |
| 180 |
p, ok := i.(**clientv3.GetResponse) |
| 181 |
if !ok { |
| 182 |
return false |
| 183 |
} |
| 184 |
*p = s.raw |
| 185 |
return true |
| 186 |
} |
| 187 |
|
| 188 |
// watcher implements driver.Watcher. |
| 189 |
type watcher struct { |
| 190 |
// The background goroutine writes new *state values to ch. |
| 191 |
// It is buffered so that the background goroutine can write without |
| 192 |
// blocking; it always drains the buffer before writing so that the latest |
| 193 |
// write is buffered. If writes could block, the background goroutine could be |
| 194 |
// blocked indefinitely from reading etcd's Watch events. |
| 195 |
// The background goroutine closes ch during shutdown. |
| 196 |
ch chan *state |
| 197 |
// shutdown tells the background goroutine to exit. |
| 198 |
shutdown func() |
| 199 |
} |
| 200 |
|
| 201 |
// WatchVariable implements driver.WatchVariable. |
| 202 |
func (w *watcher) WatchVariable(ctx context.Context, _ driver.State) (driver.State, time.Duration) { |
| 203 |
select { |
| 204 |
case <-ctx.Done(): |
| 205 |
return &state{err: ctx.Err()}, 0 |
| 206 |
case cur := <-w.ch: |
| 207 |
return cur, 0 |
| 208 |
} |
| 209 |
} |
| 210 |
|
| 211 |
// updateState checks to see if s and prev both represent the same error. |
| 212 |
// If not, it drains any previous state buffered in w.ch, then writes s to it. |
| 213 |
// It always return s. |
| 214 |
func (w *watcher) updateState(s, prev *state) *state { |
| 215 |
if s.err != nil && prev != nil && prev.err != nil { |
| 216 |
if equivalentError(s.err, prev.err) { |
| 217 |
// s represents the same error as prev. |
| 218 |
return s |
| 219 |
} |
| 220 |
} |
| 221 |
// Drain any buffered value on ch; it is now stale. |
| 222 |
select { |
| 223 |
case <-w.ch: |
| 224 |
default: |
| 225 |
} |
| 226 |
// This write can't block, since we're the only writer, ch has a buffer |
| 227 |
// size of 1, and we just read anything that was buffered. |
| 228 |
w.ch <- s |
| 229 |
return s |
| 230 |
} |
| 231 |
|
| 232 |
// equivalentError returns true iff err1 and err2 represent an equivalent error; |
| 233 |
// i.e., we don't want to return it to the user as a different error. |
| 234 |
func equivalentError(err1, err2 error) bool { |
| 235 |
if err1 == err2 || err1.Error() == err2.Error() { |
| 236 |
return true |
| 237 |
} |
| 238 |
var code1, code2 codes.Code |
| 239 |
if etcdErr, ok := err1.(rpctypes.EtcdError); ok { |
| 240 |
code1 = etcdErr.Code() |
| 241 |
} |
| 242 |
if etcdErr, ok := err2.(rpctypes.EtcdError); ok { |
| 243 |
code2 = etcdErr.Code() |
| 244 |
} |
| 245 |
return code1 != codes.OK && code1 == code2 |
| 246 |
} |
| 247 |
|
| 248 |
// watch is run by a background goroutine. |
| 249 |
// It watches file using cli.Watch, and writes new states to w.ch. |
| 250 |
// It exits when ctx is canceled, and closes w.ch. |
| 251 |
func (w *watcher) watch(ctx context.Context, cli *clientv3.Client, name string, decoder *runtimevar.Decoder, timeout time.Duration) { |
| 252 |
var cur *state |
| 253 |
defer close(w.ch) |
| 254 |
|
| 255 |
var watchCh clientv3.WatchChan |
| 256 |
for { |
| 257 |
if watchCh == nil { |
| 258 |
ctxWithTimeout, cancel := context.WithTimeout(ctx, timeout) |
| 259 |
watchCh = cli.Watch(ctxWithTimeout, name) |
| 260 |
cancel() |
| 261 |
} |
| 262 |
|
| 263 |
ctxWithTimeout, cancel := context.WithTimeout(ctx, timeout) |
| 264 |
resp, err := cli.Get(ctxWithTimeout, name) |
| 265 |
cancel() |
| 266 |
if err != nil { |
| 267 |
cur = w.updateState(&state{err: err}, cur) |
| 268 |
} else if len(resp.Kvs) == 0 { |
| 269 |
cur = w.updateState(&state{err: errNotExist}, cur) |
| 270 |
} else if len(resp.Kvs) > 1 { |
| 271 |
cur = w.updateState(&state{err: fmt.Errorf("%q has multiple values", name)}, cur) |
| 272 |
} else { |
| 273 |
kv := resp.Kvs[0] |
| 274 |
if cur == nil || cur.err != nil || kv.Version != cur.version { |
| 275 |
val, err := decoder.Decode(ctx, kv.Value) |
| 276 |
if err != nil { |
| 277 |
cur = w.updateState(&state{err: err}, cur) |
| 278 |
} else { |
| 279 |
cur = w.updateState(&state{val: val, raw: resp, updateTime: time.Now(), version: kv.Version}, cur) |
| 280 |
} |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
// Value hasn't changed. Wait for change events. |
| 285 |
select { |
| 286 |
case <-ctx.Done(): |
| 287 |
return |
| 288 |
case _, ok := <-watchCh: |
| 289 |
if !ok { |
| 290 |
// watchCh has closed; retry in next loop iteration. |
| 291 |
watchCh = nil |
| 292 |
} |
| 293 |
} |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
// Close implements driver.Close. |
| 298 |
func (w *watcher) Close() error { |
| 299 |
// Tell the background goroutine to shut down by canceling its ctx. |
| 300 |
w.shutdown() |
| 301 |
// Wait for it to exit. |
| 302 |
for range w.ch { |
| 303 |
} |
| 304 |
return nil |
| 305 |
} |
| 306 |
|
| 307 |
// ErrorAs implements driver.ErrorAs. |
| 308 |
func (w *watcher) ErrorAs(err error, i any) bool { |
| 309 |
switch v := err.(type) { |
| 310 |
case rpctypes.EtcdError: |
| 311 |
if p, ok := i.(*rpctypes.EtcdError); ok { |
| 312 |
*p = v |
| 313 |
return true |
| 314 |
} |
| 315 |
} |
| 316 |
return false |
| 317 |
} |
| 318 |
|
| 319 |
// ErrorCode implements driver.ErrorCode. |
| 320 |
func (*watcher) ErrorCode(err error) gcerrors.ErrorCode { |
| 321 |
if err == errNotExist { |
| 322 |
return gcerrors.NotFound |
| 323 |
} |
| 324 |
return gcerrors.Unknown |
| 325 |
} |