-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmock_zookeeper_client.go
112 lines (84 loc) · 1.77 KB
/
mock_zookeeper_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
package epee
import (
"encoding/json"
"log"
"path"
"sync"
)
type mockZookeeperClient struct {
sync.Mutex
paths map[string][]byte
locks map[string]bool
}
func (zk *mockZookeeperClient) List(prefix string) ([]string, error) {
if prefix == "" {
return []string{}, nil
}
// If the prefix ends with a / we'll remove it.
if prefix[len(prefix)-1] == '/' {
prefix = prefix[0 : len(prefix)-1]
}
paths := make([]string, 0)
for k := range zk.paths {
dir := path.Dir(k)
if prefix == dir {
paths = append(paths, k)
}
}
return paths, nil
}
func (zk *mockZookeeperClient) Get(path string, i interface{}) error {
bytes, ok := zk.paths[path]
if !ok {
return ErrNotFound
}
if ok {
return json.Unmarshal(bytes, i)
}
// Not found.
return nil
}
func (zk *mockZookeeperClient) Create(path string, i interface{}) error {
zk.Lock()
defer zk.Unlock()
_, ok := zk.paths[path]
if ok {
return ErrZookeeperNodeExists
}
log.Printf("ZK: Setting %s to %v", path, i)
bytes, err := json.Marshal(i)
if err == nil {
zk.paths[path] = bytes
}
return nil
}
func (zk *mockZookeeperClient) Set(path string, i interface{}) error {
zk.Lock()
defer zk.Unlock()
log.Printf("ZK: Setting %s to %v", path, i)
bytes, err := json.Marshal(i)
if err == nil {
zk.paths[path] = bytes
}
return err
}
func (zk *mockZookeeperClient) TryLock(name string) (acquired bool, err error) {
_, ok := zk.locks[name]
// If it's already locked, we can't acquire it.
if ok {
acquired = false
} else {
acquired = true
zk.locks[name] = true
}
return
}
func (zk *mockZookeeperClient) Close() error {
return nil
}
func newMockZookeeperClient() ZookeeperClient {
zk := new(mockZookeeperClient)
zk.paths = make(map[string][]byte)
zk.locks = make(map[string]bool)
return zk
}