| 1 |
package etcd |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"errors" |
| 6 |
"time" |
| 7 |
|
| 8 |
clientv3 "go.etcd.io/etcd/client/v3" |
| 9 |
) |
| 10 |
|
| 11 |
type Config struct { |
| 12 |
// etcd endpoints |
| 13 |
Endpoints []string |
| 14 |
|
| 15 |
// timeout |
| 16 |
DialTimeout time.Duration |
| 17 |
|
| 18 |
// prefix request option |
| 19 |
Prefix bool |
| 20 |
|
| 21 |
// limit request option |
| 22 |
Limit bool |
| 23 |
|
| 24 |
// number of limited pairs |
| 25 |
NLimit int64 |
| 26 |
|
| 27 |
// key, key with prefix, etc. |
| 28 |
Key string |
| 29 |
} |
| 30 |
|
| 31 |
// Etcd implements the etcd config provider. |
| 32 |
type Etcd struct { |
| 33 |
client *clientv3.Client |
| 34 |
cfg Config |
| 35 |
} |
| 36 |
|
| 37 |
// Provider returns a provider that takes etcd config. |
| 38 |
func Provider(cfg Config) (*Etcd, error) { |
| 39 |
eCfg := clientv3.Config{ |
| 40 |
Endpoints: cfg.Endpoints, |
| 41 |
DialTimeout: cfg.DialTimeout, |
| 42 |
} |
| 43 |
|
| 44 |
c, err := clientv3.New(eCfg) |
| 45 |
if err != nil { |
| 46 |
return nil, err |
| 47 |
} |
| 48 |
|
| 49 |
return &Etcd{client: c, cfg: cfg}, nil |
| 50 |
} |
| 51 |
|
| 52 |
// ReadBytes is not supported by etcd provider. |
| 53 |
func (e *Etcd) ReadBytes() ([]byte, error) { |
| 54 |
return nil, errors.New("etcd provider does not support this method") |
| 55 |
} |
| 56 |
|
| 57 |
// Read returns a nested config map. |
| 58 |
func (e *Etcd) Read() (map[string]any, error) { |
| 59 |
ctx, cancel := context.WithTimeout(context.Background(), e.cfg.DialTimeout) |
| 60 |
defer cancel() |
| 61 |
|
| 62 |
var resp *clientv3.GetResponse |
| 63 |
if e.cfg.Prefix { |
| 64 |
if e.cfg.Limit { |
| 65 |
r, err := e.client.Get(ctx, e.cfg.Key, clientv3.WithPrefix(), clientv3.WithLimit(e.cfg.NLimit)) |
| 66 |
if err != nil { |
| 67 |
return nil, err |
| 68 |
} |
| 69 |
|
| 70 |
resp = r |
| 71 |
} else { |
| 72 |
r, err := e.client.Get(ctx, e.cfg.Key, clientv3.WithPrefix()) |
| 73 |
if err != nil { |
| 74 |
return nil, err |
| 75 |
} |
| 76 |
|
| 77 |
resp = r |
| 78 |
} |
| 79 |
} else { |
| 80 |
r, err := e.client.Get(ctx, e.cfg.Key) |
| 81 |
if err != nil { |
| 82 |
return nil, err |
| 83 |
} |
| 84 |
|
| 85 |
resp = r |
| 86 |
} |
| 87 |
|
| 88 |
mp := make(map[string]any, len(resp.Kvs)) |
| 89 |
for _, r := range resp.Kvs { |
| 90 |
mp[string(r.Key)] = string(r.Value) |
| 91 |
} |
| 92 |
|
| 93 |
return mp, nil |
| 94 |
} |
| 95 |
|
| 96 |
func (e *Etcd) Watch(cb func(event any, err error)) error { |
| 97 |
var w clientv3.WatchChan |
| 98 |
|
| 99 |
go func() { |
| 100 |
if e.cfg.Prefix { |
| 101 |
w = e.client.Watch(context.Background(), e.cfg.Key, clientv3.WithPrefix()) |
| 102 |
} else { |
| 103 |
w = e.client.Watch(context.Background(), e.cfg.Key) |
| 104 |
} |
| 105 |
|
| 106 |
for wresp := range w { |
| 107 |
for _, ev := range wresp.Events { |
| 108 |
cb(ev, nil) |
| 109 |
} |
| 110 |
} |
| 111 |
}() |
| 112 |
|
| 113 |
return nil |
| 114 |
} |