forked from signalfx/golib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zktest.go
544 lines (492 loc) · 12.7 KB
/
zktest.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
package zktest
import (
"strings"
"time"
"errors"
"sync"
"github.com/samuel/go-zookeeper/zk"
"github.com/signalfx/golib/log"
"github.com/signalfx/golib/sfxtest"
"sync/atomic"
)
// DefaultLogger is used by zktest if no logger is set
var DefaultLogger = log.Logger(log.DefaultLogger.CreateChild())
type event struct {
}
// ErrDeleteOnRoot is returned when EnsureDelete is called with a root path
var ErrDeleteOnRoot = errors.New("cannot delete on root path")
// ErrDeleteFailed is retured when EnsureDelete() is unable to ensure the delete
var ErrDeleteFailed = errors.New("delete eventually failed")
// EnsureDelete will ensure that path is deleted from zk, trying up to three times before eventually
// failing with an error
func EnsureDelete(z ZkConnSupported, path string) error {
if path == "/" {
return ErrDeleteOnRoot
}
c, _, err := z.Children(path)
if err == nil {
wg := sync.WaitGroup{}
var err error
for _, chil := range c {
wg.Add(1)
go func(chil string) {
defer wg.Done()
err = EnsureDelete(z, path+"/"+chil)
if err != nil {
return
}
}(chil)
}
wg.Wait()
if err != nil {
return err
}
}
for i := 0; i < 3; i++ {
err = z.Delete(path, -1)
if err == nil || err == zk.ErrNoNode {
return nil
}
}
return ErrDeleteFailed
}
// MemoryZkServer can be used in the place of a zk.Conn() to unit test zk connections
type MemoryZkServer struct {
sfxtest.ErrChecker
root *zkNode
rootLock sync.Mutex
GlobalChan chan zk.Event
Logger log.Logger
events chan event
nextID int64
childrenConnectionsLock sync.Mutex
childrenConnections map[*ZkConn]struct{}
ChanTimeout time.Duration
}
// ZkConn is the connection type returned from a MemoryZkConn that simulates a zk connection
type ZkConn struct {
connectedTo *MemoryZkServer
events chan zk.Event
pathWatch map[string]chan zk.Event
pathWatchLock sync.Mutex
Logger log.Logger
chanTimeout time.Duration
methodCallLock sync.Mutex
sfxtest.ErrChecker
}
// Pretty returns a pretty print of the zk structure
func (z *MemoryZkServer) Pretty() string {
return z.root.pretty(0)
}
func (z *zkNode) pretty(tabsize int) string {
t := strings.Repeat("\t", tabsize)
s := []string{(t + z.name + "->" + string(z.data))}
for _, c := range z.children {
s = append(s, c.pretty(tabsize+1))
}
return strings.Join(s, "\n")
}
type zkNode struct {
data []byte
children map[string]*zkNode
name string
parent *zkNode
stat *zk.Stat
}
// New returns a new testing zk connection
func New() *MemoryZkServer {
GlobalChan := make(chan zk.Event, 5)
z := &MemoryZkServer{
root: &zkNode{
data: []byte(""),
children: make(map[string]*zkNode),
name: "",
parent: nil,
stat: &zk.Stat{},
},
GlobalChan: GlobalChan,
Logger: DefaultLogger,
events: make(chan event),
childrenConnections: make(map[*ZkConn]struct{}),
ChanTimeout: time.Second,
}
return z
}
// Conn satisfies the ZkConnector interface for zkplus so we can easily pass the memory zk server
// into a builder
func (z *MemoryZkServer) Conn() (ZkConnSupported, <-chan zk.Event, error) {
return z.Connect()
}
// Connect to this server
func (z *MemoryZkServer) Connect() (*ZkConn, <-chan zk.Event, error) {
r := &ZkConn{
connectedTo: z,
Logger: log.NewContext(z.Logger).With("id", atomic.AddInt64(&z.nextID, 1)),
events: make(chan zk.Event, 1000),
pathWatch: make(map[string]chan zk.Event),
chanTimeout: z.ChanTimeout,
}
z.childrenConnectionsLock.Lock()
defer z.childrenConnectionsLock.Unlock()
z.childrenConnections[r] = struct{}{}
r.events <- zk.Event{
Type: zk.EventSession,
State: zk.StateConnecting,
Server: "localhost",
}
r.events <- zk.Event{
Type: zk.EventSession,
State: zk.StateHasSession,
Server: "localhost",
}
return r, r.events, nil
}
func (z *MemoryZkServer) addEvent(e zk.Event) {
z.childrenConnectionsLock.Lock()
defer z.childrenConnectionsLock.Unlock()
for conn := range z.childrenConnections {
conn.offerEvent(e)
}
}
func (z *MemoryZkServer) removeConnection(c *ZkConn) {
z.childrenConnectionsLock.Lock()
defer z.childrenConnectionsLock.Unlock()
delete(z.childrenConnections, c)
}
func (z *ZkConn) offerEvent(e zk.Event) {
eventLog := log.NewContext(z.Logger).With("event", e.Path)
z.pathWatchLock.Lock()
defer z.pathWatchLock.Unlock()
if z.pathWatch == nil {
return
}
w, exists := z.pathWatch[e.Path]
eventLog.Log("exists", exists, "Event on path")
if exists {
eventLog.Log("Firing event!")
delete(z.pathWatch, e.Path)
go func() {
select {
case w <- e:
eventLog.Log("Event sent!")
case <-time.After(z.chanTimeout):
}
close(w)
}()
go func() {
select {
case z.events <- e:
eventLog.Log("Event sent again!")
case <-time.After(z.chanTimeout):
}
}()
}
}
func (z *zkNode) path() string {
if z.parent == nil {
return z.name
}
return z.parent.path() + "/" + z.name
}
func (z *MemoryZkServer) node(path string) (*zkNode, *zkNode) {
parts := strings.Split(path, "/")
parent := (*zkNode)(nil)
at := z.root
for _, part := range parts {
if part == "" {
continue
}
if at == nil {
return nil, nil
}
nextDir := at.children[part]
parent = at
at = nextDir
}
return at, parent
}
// ZkConnSupported is the interface of zk.Conn we currently support
type ZkConnSupported interface {
// Exists returns true if the path exists
Exists(path string) (bool, *zk.Stat, error)
ExistsW(path string) (bool, *zk.Stat, <-chan zk.Event, error)
Get(path string) ([]byte, *zk.Stat, error)
GetW(path string) ([]byte, *zk.Stat, <-chan zk.Event, error)
Children(path string) ([]string, *zk.Stat, error)
ChildrenW(path string) ([]string, *zk.Stat, <-chan zk.Event, error)
Delete(path string, version int32) error
Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error)
Set(path string, data []byte, version int32) (*zk.Stat, error)
Close()
}
var _ ZkConnSupported = &zk.Conn{}
var _ ZkConnSupported = &ZkConn{}
// Close sends disconnected to all waiting events and deregisteres this
// conn with the parent server
func (z *ZkConn) Close() {
z.pathWatchLock.Lock()
var wg sync.WaitGroup
for _, e := range z.pathWatch {
wg.Add(1)
go func(e chan zk.Event) {
defer wg.Done()
select {
case e <- zk.Event{
State: zk.StateDisconnected,
}:
case <-time.After(z.chanTimeout):
}
}(e)
}
wg.Add(1)
go func() {
defer wg.Done()
select {
case z.events <- zk.Event{
State: zk.StateDisconnected,
}:
case <-time.After(z.chanTimeout):
}
}()
z.pathWatch = nil
z.pathWatchLock.Unlock()
wg.Wait()
z.connectedTo.removeConnection(z)
}
func (z *MemoryZkServer) exists(path string) (bool, *zk.Stat, error) {
path = fixPath(path)
z.rootLock.Lock()
defer z.rootLock.Unlock()
if err := z.CheckForError("exists"); err != nil {
return false, nil, err
}
at, _ := z.node(path)
if at == nil {
return false, nil, nil
}
return true, at.stat, nil
}
// Exists returns true if the path exists
func (z *ZkConn) Exists(path string) (bool, *zk.Stat, error) {
z.methodCallLock.Lock()
defer z.methodCallLock.Unlock()
if err := z.CheckForError("exists"); err != nil {
return false, nil, err
}
return z.connectedTo.exists(path)
}
func fixPath(path string) string {
if len(path) > 0 && path[0] != '/' {
return "/" + path
}
return path
}
// ExistsW is like Exists but also sets a watch.
func (z *ZkConn) ExistsW(path string) (bool, *zk.Stat, <-chan zk.Event, error) {
z.methodCallLock.Lock()
defer z.methodCallLock.Unlock()
if err := z.CheckForError("exists"); err != nil {
return false, nil, nil, err
}
e, s, err := z.connectedTo.exists(path)
return e, s, z.patchWatch(path), err
}
func (z *MemoryZkServer) get(path string) ([]byte, *zk.Stat, error) {
z.rootLock.Lock()
defer z.rootLock.Unlock()
if err := z.CheckForError("get"); err != nil {
return nil, nil, err
}
at, _ := z.node(path)
if at == nil {
return nil, nil, zk.ErrNoNode
}
return at.data, at.stat, nil
}
// Get the bytes of a zk path
func (z *ZkConn) Get(path string) ([]byte, *zk.Stat, error) {
if err := z.CheckForError("get"); err != nil {
return nil, nil, err
}
return z.connectedTo.get(path)
}
// GetW is like Get, but also sets a watch
func (z *ZkConn) GetW(path string) ([]byte, *zk.Stat, <-chan zk.Event, error) {
z.methodCallLock.Lock()
defer z.methodCallLock.Unlock()
if err := z.CheckForError("getw"); err != nil {
return nil, nil, nil, err
}
e, s, err := z.Get(path)
if err != nil {
return e, s, nil, err
}
return e, s, z.patchWatch(path), err
}
func (z *ZkConn) patchWatch(path string) chan zk.Event {
path = fixPath(path)
pathWatchLogger := log.NewContext(z.Logger).With("path", path)
pathWatchLogger.Log("Should I set a path watch?")
z.pathWatchLock.Lock()
defer z.pathWatchLock.Unlock()
if z.pathWatch == nil {
return nil
}
ch, exists := z.pathWatch[path]
if !exists {
pathWatchLogger.Log("Setting patch watch")
ch = make(chan zk.Event)
z.pathWatch[path] = ch
}
return ch
}
func (z *MemoryZkServer) children(path string) ([]string, *zk.Stat, error) {
if err := z.CheckForError("children"); err != nil {
return nil, nil, err
}
z.rootLock.Lock()
defer z.rootLock.Unlock()
at, _ := z.node(path)
if at == nil {
return nil, nil, zk.ErrNoNode
}
childrenNames := []string{}
for k := range at.children {
childrenNames = append(childrenNames, k)
}
return childrenNames, at.stat, nil
}
// Children gets children of a path
func (z *ZkConn) Children(path string) ([]string, *zk.Stat, error) {
if err := z.CheckForError("children"); err != nil {
return nil, nil, err
}
return z.connectedTo.children(path)
}
// ChildrenW is like children but also sets a watch
func (z *ZkConn) ChildrenW(path string) ([]string, *zk.Stat, <-chan zk.Event, error) {
z.methodCallLock.Lock()
defer z.methodCallLock.Unlock()
if err := z.CheckForError("childrenw"); err != nil {
return nil, nil, nil, err
}
e, s, err := z.Children(path)
if err != nil {
return e, s, nil, err
}
return e, s, z.patchWatch(path), err
}
func (z *MemoryZkServer) delete(path string, version int32) error {
z.rootLock.Lock()
defer z.rootLock.Unlock()
if err := z.CheckForError("delete"); err != nil {
return err
}
path = fixPath(path)
at, parent := z.node(path)
if at == nil {
return zk.ErrNoNode
}
if version != at.stat.Version && version != -1 {
return zk.ErrBadVersion
}
if len(at.children) != 0 {
return zk.ErrNotEmpty
}
delete(at.parent.children, at.name)
z.addEvent(zk.Event{
Type: zk.EventNodeDeleted,
State: zk.StateConnected,
Path: path,
Err: nil,
})
z.addEvent(zk.Event{
Type: zk.EventNodeChildrenChanged,
State: zk.StateConnected,
Path: parent.path(),
Err: nil,
})
return nil
}
// Delete a Zk node
func (z *ZkConn) Delete(path string, version int32) error {
z.methodCallLock.Lock()
defer z.methodCallLock.Unlock()
if err := z.CheckForError("delete"); err != nil {
return err
}
return z.connectedTo.delete(path, version)
}
func (z *MemoryZkServer) create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {
z.rootLock.Lock()
defer z.rootLock.Unlock()
path = fixPath(path)
if err := z.CheckForError("create"); err != nil {
return "", err
}
at, parent := z.node(path)
if at != nil {
return "", zk.ErrNodeExists
}
if parent == nil {
return "", zk.ErrNoNode
}
name := path[len(parent.path())+1:]
n := &zkNode{
data: data,
children: make(map[string]*zkNode),
name: name,
parent: parent,
stat: &zk.Stat{},
}
parent.children[n.name] = n
z.addEvent(zk.Event{
Type: zk.EventNodeCreated,
State: zk.StateConnected,
Path: path,
Err: nil,
})
z.addEvent(zk.Event{
Type: zk.EventNodeChildrenChanged,
State: zk.StateConnected,
Path: parent.path(),
Err: nil,
})
return n.path(), nil
}
// Create a Zk node
func (z *ZkConn) Create(path string, data []byte, flags int32, acl []zk.ACL) (string, error) {
z.methodCallLock.Lock()
defer z.methodCallLock.Unlock()
if err := z.CheckForError("create"); err != nil {
return "", err
}
return z.connectedTo.create(path, data, flags, acl)
}
func (z *MemoryZkServer) set(path string, data []byte, version int32) (*zk.Stat, error) {
z.rootLock.Lock()
defer z.rootLock.Unlock()
path = fixPath(path)
at, _ := z.node(path)
if at == nil {
return nil, zk.ErrNoNode
}
if version != at.stat.Version {
return nil, zk.ErrBadVersion
}
at.data = data
at.stat.Version++
z.addEvent(zk.Event{
Type: zk.EventNodeDataChanged,
State: zk.StateConnected,
Path: path,
Err: nil,
})
return at.stat, nil
}
// Set the data of a zk node
func (z *ZkConn) Set(path string, data []byte, version int32) (*zk.Stat, error) {
z.methodCallLock.Lock()
defer z.methodCallLock.Unlock()
return z.connectedTo.set(path, data, version)
}