-
Notifications
You must be signed in to change notification settings - Fork 53
/
client.go
364 lines (308 loc) · 7.55 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package zk
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
szk "github.com/samuel/go-zookeeper/zk"
log "github.com/sirupsen/logrus"
)
// Client exposes some common, zk operations. Unlike the underlying
// samuel zk client, it allows passing a context into most calls.
type Client interface {
// Read-only operations
Get(ctx context.Context, path string) ([]byte, *szk.Stat, error)
GetJSON(ctx context.Context, path string, obj interface{}) (*szk.Stat, error)
Children(ctx context.Context, path string) ([]string, *szk.Stat, error)
Exists(
ctx context.Context,
path string,
) (bool, *szk.Stat, error)
// Write operations
Create(ctx context.Context, path string, data []byte, sequential bool) error
CreateJSON(ctx context.Context, path string, obj interface{}, sequential bool) error
Set(
ctx context.Context,
path string,
data []byte,
version int32,
) (*szk.Stat, error)
SetJSON(
ctx context.Context,
path string,
obj interface{},
version int32,
) (*szk.Stat, error)
// Lock operations
AcquireLock(ctx context.Context, path string) (Lock, error)
Close() error
}
var _ Client = (*PooledClient)(nil)
type pooledRequest struct {
path string
method string
respChan chan pooledResp
}
type pooledResp struct {
content []byte
exists bool
children []string
stats *szk.Stat
err error
}
// PooledClient is a Client implementation that uses a pool of connections
// instead of a single one for read-only operations. It can be subtantially faster than the base
// samuel client, particularly when getting zookeeper nodes from multiple goroutines.
type PooledClient struct {
connections []*szk.Conn
requestChan chan pooledRequest
readOnly bool
}
// NewPooledClient returns a new PooledClient instance.
func NewPooledClient(
zkAddrs []string,
timeout time.Duration,
logger szk.Logger,
poolSize int,
readOnly bool,
) (*PooledClient, error) {
connections := []*szk.Conn{}
log.Debugf("Creating zk client with addresses %+v", zkAddrs)
for i := 0; i < poolSize; i++ {
conn, _, err := szk.Connect(
zkAddrs,
time.Minute,
szk.WithLogger(logger),
)
if err != nil {
return nil, fmt.Errorf("Error connecting to zkAddr %+v: %+v", zkAddrs, err)
}
connections = append(
connections,
conn,
)
}
requestChan := make(chan pooledRequest)
for i := 0; i < poolSize; i++ {
go func(index int, conn *szk.Conn) {
log.Debugf("Starting connection %d", index)
for {
request, ok := <-requestChan
if !ok {
return
}
resp := pooledResp{}
switch request.method {
case "get":
resp.content, resp.stats, resp.err = conn.Get(request.path)
case "children":
resp.children, resp.stats, resp.err = conn.Children(request.path)
case "exists":
resp.exists, resp.stats, resp.err = conn.Exists(request.path)
default:
resp.err = fmt.Errorf("Unrecognized method: %s", request.method)
}
request.respChan <- resp
}
}(i, connections[i])
}
return &PooledClient{
connections: connections,
requestChan: requestChan,
readOnly: readOnly,
}, nil
}
// Get returns the value at the argument zk path.
func (c *PooledClient) Get(
ctx context.Context,
path string,
) ([]byte, *szk.Stat, error) {
respChan := make(chan pooledResp)
log.Debugf("Getting path %s", path)
c.requestChan <- pooledRequest{
path: path,
method: "get",
respChan: respChan,
}
select {
case resp := <-respChan:
return resp.content, resp.stats, resp.err
case <-ctx.Done():
return nil, nil, ctx.Err()
}
}
// GetJSON unmarshals the JSON content at the argument zk path into an object.
func (c *PooledClient) GetJSON(
ctx context.Context,
path string,
obj interface{},
) (*szk.Stat, error) {
data, stats, err := c.Get(ctx, path)
if err != nil {
return stats, err
}
err = json.Unmarshal(data, obj)
return stats, err
}
// Children gets all children of the node at the argument zk path.
func (c *PooledClient) Children(
ctx context.Context,
path string,
) ([]string, *szk.Stat, error) {
respChan := make(chan pooledResp)
log.Debugf("Getting children at %s", path)
c.requestChan <- pooledRequest{
path: path,
method: "children",
respChan: respChan,
}
select {
case resp := <-respChan:
return resp.children, resp.stats, resp.err
case <-ctx.Done():
return nil, nil, ctx.Err()
}
}
// Exists returns whether a node exists at the argument zk path.
func (c *PooledClient) Exists(
ctx context.Context,
path string,
) (bool, *szk.Stat, error) {
respChan := make(chan pooledResp)
c.requestChan <- pooledRequest{
path: path,
method: "exists",
respChan: respChan,
}
select {
case resp := <-respChan:
return resp.exists, resp.stats, resp.err
case <-ctx.Done():
return false, nil, ctx.Err()
}
}
// Create adds a new node at the argument zk path.
func (c *PooledClient) Create(
ctx context.Context,
path string,
data []byte,
sequential bool,
) error {
if c.readOnly {
return errors.New("Cannot write in read-only mode")
}
errChan := make(chan error)
go func() {
var err error
if sequential {
_, err = c.connections[0].Create(
path,
data,
szk.FlagSequence,
szk.WorldACL(szk.PermAll),
)
} else {
_, err = c.connections[0].Create(
path,
data,
0,
szk.WorldACL(szk.PermAll),
)
}
errChan <- err
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errChan:
return err
}
}
// CreateJSON creates a new node at the argument zk path using the JSON-marshalled contents of
// the argument object.
func (c *PooledClient) CreateJSON(
ctx context.Context,
path string,
obj interface{},
sequential bool,
) error {
data, err := json.Marshal(obj)
if err != nil {
return err
}
return c.Create(ctx, path, data, sequential)
}
type setResp struct {
stats *szk.Stat
err error
}
// Set updates the contents of the node at the argument zk path.
func (c *PooledClient) Set(
ctx context.Context,
path string,
data []byte,
version int32,
) (*szk.Stat, error) {
if c.readOnly {
return nil, errors.New("Cannot write in read-only mode")
}
resultsChan := make(chan setResp)
go func() {
stats, err := c.connections[0].Set(path, data, version)
resultsChan <- setResp{stats, err}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case result := <-resultsChan:
return result.stats, result.err
}
}
// SetJSON updates the contents of the node at the argument zk path using the JSON marshalling
// of the argument object.
func (c *PooledClient) SetJSON(
ctx context.Context,
path string,
obj interface{},
version int32,
) (*szk.Stat, error) {
data, err := json.Marshal(obj)
if err != nil {
return nil, err
}
return c.Set(ctx, path, data, version)
}
// AcquireLock tries to acquire a lock using the argument zk path.
func (c *PooledClient) AcquireLock(ctx context.Context, path string) (Lock, error) {
if c.readOnly {
return nil, errors.New("Cannot create lock in read-only mode")
}
lock := szk.NewLock(c.connections[0], path, szk.WorldACL(szk.PermAll))
errChan := make(chan error)
go func() {
errChan <- lock.Lock()
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case err := <-errChan:
return lock, err
}
}
// Close closes the current client and frees the associated resources.
func (c *PooledClient) Close() error {
close(c.requestChan)
closeChan := make(chan struct{}, len(c.connections))
for index, conn := range c.connections {
log.Debugf("Closing zk connection %d/%d", index+1, len(c.connections))
go func(innerConn *szk.Conn) {
innerConn.Close()
closeChan <- struct{}{}
}(conn)
}
for i := 0; i < len(c.connections); i++ {
<-closeChan
}
return nil
}