-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.go
60 lines (51 loc) · 1.13 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package etcdpasswd
import (
"context"
"strconv"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/clientv3util"
)
// Client provides high-level API to edit etcd database.
type Client struct {
*clientv3.Client
}
func (c Client) list(ctx context.Context, prefix string) ([]string, error) {
resp, err := c.Get(ctx, prefix,
clientv3.WithPrefix(),
clientv3.WithKeysOnly(),
clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend))
if err != nil {
return nil, err
}
ret := make([]string, resp.Count)
for i, kv := range resp.Kvs {
ret[i] = string(kv.Key[len(prefix):])
}
return ret, nil
}
func (c Client) getLastID(ctx context.Context, key string, startID int) (_ int, rev int64, e error) {
RETRY:
resp, err := c.Get(ctx, key)
if err != nil {
e = err
return
}
if resp.Count == 0 {
v := strconv.Itoa(startID)
_, err = c.Txn(ctx).
If(clientv3util.KeyMissing(key)).
Then(clientv3.OpPut(key, v)).
Commit()
if err != nil {
e = err
return
}
goto RETRY
}
uid, err := strconv.Atoi(string(resp.Kvs[0].Value))
if err != nil {
e = err
return
}
return uid, resp.Kvs[0].ModRevision, nil
}