-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
221 lines (176 loc) · 6 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package etcd
import (
"context"
"sync"
"time"
"github.com/pingcap/errors"
clientv3 "go.etcd.io/etcd/client/v3"
)
const (
DefaultConnectTimeOut = 10 * time.Second
DefaultMutexLeaseSeconds = 3600
MaxTTL = 3600 * 24
MinimumTTL = 1
ZeroRevision = 0
)
type Conn struct {
Endpoints []string
KeyLeaseIDMap sync.Map
clientv3.Config
clientv3.Client
clientv3.Lease
}
// NewEtcdConn returns connection to etcd, it uses client v3 library api
func NewEtcdConn(endpoints []string) (*Conn, error) {
cfg := clientv3.Config{
Endpoints: endpoints,
DialTimeout: DefaultConnectTimeOut,
}
client, err := clientv3.New(cfg)
if err != nil {
return nil, errors.Trace(err)
}
return &Conn{
Endpoints: endpoints,
Config: cfg,
Client: *client,
Lease: clientv3.NewLease(client),
}, nil
}
// NewEtcdConnWithConnectTimeout returns connection to etcd, it uses client v3 library api
func NewEtcdConnWithConnectTimeout(endpoints []string, timeout time.Duration) (*Conn, error) {
cfg := clientv3.Config{
Endpoints: endpoints,
DialTimeout: timeout,
}
client, err := clientv3.New(cfg)
if err != nil {
return nil, errors.Trace(err)
}
return &Conn{
Endpoints: endpoints,
Config: cfg,
Client: *client,
Lease: clientv3.NewLease(client),
}, nil
}
// Close closes the connection
func (conn *Conn) Close() error {
return errors.Trace(conn.Client.Close())
}
// GetLeaseIDByKey returns lease response by mutex key name which was maintained when successfully get the mutex
func (conn *Conn) GetLeaseIDByKey(key string) clientv3.LeaseID {
leaseID, ok := conn.KeyLeaseIDMap.Load(key)
if !ok {
return clientv3.NoLease
}
return leaseID.(clientv3.LeaseID)
}
// CheckLeaseGrantExists checks if given leaseID still exists
func (conn *Conn) CheckLeaseGrantExists(ctx context.Context, leaseID clientv3.LeaseID) (bool, error) {
if leaseID == clientv3.NoLease {
return false, nil
}
leaseResp, err := conn.TimeToLive(ctx, leaseID)
if err != nil {
return false, errors.Trace(err)
}
if leaseResp.TTL <= MinimumTTL {
return false, nil
}
return true, nil
}
// LockEtcdMutex tries to get a distributed mutex from etcd, if success, return true, nil
func (conn *Conn) LockEtcdMutex(ctx context.Context, mutexKey, mutexValue string, ttl int64) (bool, error) {
if ttl > MaxTTL {
return false, errors.Errorf("maximum ttl could not be larger than %d.", MaxTTL)
}
leaseResp, err := conn.Grant(ctx, ttl)
if err != nil {
return false, errors.Trace(err)
}
txn := clientv3.NewKV(&conn.Client).Txn(ctx)
txn.If(clientv3.Compare(clientv3.CreateRevision(mutexKey), "=", ZeroRevision)).
Then(clientv3.OpPut(mutexKey, mutexValue, clientv3.WithLease(leaseResp.ID))).
Else()
txnResp, err := txn.Commit()
if err != nil {
return false, errors.Trace(err)
}
// successfully get the mutex
if txnResp.Succeeded {
conn.KeyLeaseIDMap.Store(mutexKey, leaseResp.ID)
return true, nil
}
return false, nil
}
// UnlockEtcdMutex releases the distributed mutex
func (conn *Conn) UnlockEtcdMutex(ctx context.Context, mutexKey string) (*clientv3.LeaseRevokeResponse, error) {
leaseID := conn.GetLeaseIDByKey(mutexKey)
if leaseID == clientv3.NoLease {
return nil, nil
}
leaseRevokeResp, err := conn.Revoke(ctx, leaseID)
if err != nil {
return nil, errors.Trace(err)
}
conn.KeyLeaseIDMap.Delete(mutexKey)
return leaseRevokeResp, nil
}
// PutWithTTLAndKeepAliveOnce puts the key and value and refresh the lease with given ttl once.
func (conn *Conn) PutWithTTLAndKeepAliveOnce(ctx context.Context, key, value string, ttl int64) (*clientv3.PutResponse, *clientv3.LeaseKeepAliveResponse, error) {
leaseID := conn.GetLeaseIDByKey(key)
leaseGrantExists, err := conn.CheckLeaseGrantExists(ctx, leaseID)
if err != nil {
return nil, nil, err
}
if !leaseGrantExists {
leaseResp, err := conn.Grant(ctx, ttl)
if err != nil {
return nil, nil, errors.Trace(err)
}
leaseID = leaseResp.ID
conn.KeyLeaseIDMap.Store(key, leaseID)
}
putResp, err := conn.Client.Put(ctx, key, value, clientv3.WithLease(leaseID))
if err != nil {
return nil, nil, errors.Trace(err)
}
leaseKeepAliveResp, err := conn.KeepAliveOnce(ctx, leaseID)
return putResp, leaseKeepAliveResp, errors.Trace(err)
}
// PutWithTTLAndKeepAlive put the key and value and keep alive the lease with given ttl
func (conn *Conn) PutWithTTLAndKeepAlive(ctx context.Context, key, value string, ttl int64) (*clientv3.PutResponse, <-chan *clientv3.LeaseKeepAliveResponse, error) {
putResp, leaseKeepAliveResp, err := conn.PutWithTTLAndKeepAliveOnce(ctx, key, value, ttl)
if err != nil {
return nil, nil, err
}
leaseKeepAliveRespChan, err := conn.KeepAlive(ctx, leaseKeepAliveResp.ID)
return putResp, leaseKeepAliveRespChan, errors.Trace(err)
}
// Delete deletes the key, but does NOT revoke the concerned lease because the lease may be assigned to other keys.
func (conn *Conn) Delete(ctx context.Context, key string) (*clientv3.DeleteResponse, error) {
leaseID := conn.GetLeaseIDByKey(key)
if leaseID == clientv3.NoLease {
return conn.Client.Delete(ctx, key)
}
conn.KeyLeaseIDMap.Delete(key)
deleteResp, err := conn.Client.Delete(ctx, key)
return deleteResp, errors.Trace(err)
}
// DeleteWithPrefix delete the keys of which name started with the given key,
// but does NOT revoke the concerned lease because the lease may be assigned to other keys.
func (conn *Conn) DeleteWithPrefix(ctx context.Context, key string) (*clientv3.DeleteResponse, error) {
leaseID := conn.GetLeaseIDByKey(key)
if leaseID == clientv3.NoLease {
deleteResp, err := conn.Client.Delete(ctx, key)
return deleteResp, errors.Trace(err)
}
conn.KeyLeaseIDMap.Delete(key)
deleteResp, err := conn.Client.Delete(ctx, key, clientv3.WithPrefix())
return deleteResp, errors.Trace(err)
}
// PutWithTTL is an alias of PutWithTTLAndKeepAliveOnce
func (conn *Conn) PutWithTTL(ctx context.Context, key, value string, ttl int64) (*clientv3.PutResponse, *clientv3.LeaseKeepAliveResponse, error) {
return conn.PutWithTTLAndKeepAliveOnce(ctx, key, value, ttl)
}