This repository has been archived by the owner on Sep 2, 2022. It is now read-only.
forked from flier/curator.go
/
cache.go
284 lines (230 loc) · 7.9 KB
/
cache.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
package recipes
import (
"fmt"
"reflect"
"sync/atomic"
"unsafe"
"github.com/flier/curator.go"
"github.com/samuel/go-zookeeper/zk"
)
type CacheEventType int
const (
CHILD_ADDED CacheEventType = iota // A child was added to the path
CHILD_UPDATED // A child's data was changed
CHILD_REMOVED // A child was removed from the path
CONNECTION_SUSPENDED // Called when the connection has changed to SUSPENDED
CONNECTION_RECONNECTED // Called when the connection has changed to RECONNECTED
CONNECTION_LOST // Called when the connection has changed to LOST
INITIALIZED // Posted when PathChildrenCache.Start(StartMode) is called with POST_INITIALIZED_EVENT
)
type ChildData struct {
Path string
Stat *zk.Stat
Data []byte
}
type CacheEvent struct {
Type CacheEventType
Data ChildData
}
type PathChildrenCacheEvent CacheEvent
type TreeCacheEvent CacheEvent
type NodeCacheListener interface {
// Called when a change has occurred
NodeChanged() error
}
type NodeCacheListenable interface {
curator.Listenable /* [T] */
AddListener(listener NodeCacheListener)
RemoveListener(listener NodeCacheListener)
}
// Listener for PathChildrenCache changes
type PathChildrenCacheListener interface {
// Called when a change has occurred
ChildEvent(client curator.CuratorFramework, event PathChildrenCacheEvent) error
}
// Listener for TreeCache changes
type TreeCacheListener interface {
// Called when a change has occurred
ChildEvent(client curator.CuratorFramework, event TreeCacheEvent) error
}
type NodeCacheListenerContainer struct {
*curator.ListenerContainer
}
func (c *NodeCacheListenerContainer) AddListener(listener NodeCacheListener) {
c.Add(listener)
}
func (c *NodeCacheListenerContainer) RemoveListener(listener NodeCacheListener) {
c.Remove(listener)
}
// A utility that attempts to keep the data from a node locally cached.
// This class will watch the node, respond to update/create/delete events, pull down the data, etc.
// You can register a listener that will get notified when changes occur.
type NodeCache struct {
client curator.CuratorFramework
path string
dataIsCompressed bool
ensurePath curator.EnsurePath
state curator.State
isConnected curator.AtomicBool
data *ChildData
connectionStateListener curator.ConnectionStateListener
watcher curator.Watcher
backgroundCallback curator.BackgroundCallback
listeners *NodeCacheListenerContainer
}
func NewNodeCache(client curator.CuratorFramework, path string, dataIsCompressed bool) *NodeCache {
c := &NodeCache{
client: client,
path: path,
dataIsCompressed: dataIsCompressed,
ensurePath: client.NewNamespaceAwareEnsurePath(path).ExcludingLast(),
listeners: &NodeCacheListenerContainer{},
}
c.connectionStateListener = curator.NewConnectionStateListener(func(client curator.CuratorFramework, newState curator.ConnectionState) {
if newState.Connected() {
if c.isConnected.CompareAndSwap(false, true) {
if err := c.reset(); err != nil {
panic(fmt.Errorf("Trying to reset after reconnection, %s", err))
}
}
} else {
c.isConnected.Set(false)
}
})
c.watcher = curator.NewWatcher(func(event *zk.Event) {
c.reset()
})
c.backgroundCallback = func(client curator.CuratorFramework, event curator.CuratorEvent) error {
return c.processBackgroundResult(event)
}
return c
}
// Start the cache. The cache is not started automatically. You must call this method.
func (c *NodeCache) Start() error {
return c.StartAndInitalize(false)
}
// Same as Start() but gives the option of doing an initial build
func (c *NodeCache) StartAndInitalize(buildInitial bool) error {
if !c.state.Change(curator.LATENT, curator.STARTED) {
return fmt.Errorf("Cannot be started more than once")
} else if err := c.ensurePath.Ensure(c.client.ZookeeperClient()); err != nil {
return err
}
c.client.ConnectionStateListenable().AddListener(c.connectionStateListener)
if buildInitial {
if err := c.internalRebuild(); err != nil {
return err
}
}
return c.reset()
}
func (c *NodeCache) Close() error {
if c.state.Change(curator.STARTED, curator.STOPPED) {
c.listeners.Clear()
}
c.client.ConnectionStateListenable().RemoveListener(c.connectionStateListener)
return nil
}
func (c *NodeCache) NodeCacheListenable() NodeCacheListenable {
return c.listeners
}
func (c *NodeCache) internalRebuild() error {
var stat zk.Stat
builder := c.client.GetData()
if c.dataIsCompressed {
builder.Decompressed()
}
if data, err := builder.StoringStatIn(&stat).ForPath(c.path); err == nil {
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&c.data)), unsafe.Pointer(&ChildData{c.path, &stat, data}))
} else if err == zk.ErrNoNode {
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&c.data)), nil)
} else {
return err
}
return nil
}
func (c *NodeCache) reset() error {
if c.state.Value() == curator.STARTED && c.isConnected.Load() {
_, err := c.client.CheckExists().UsingWatcher(c.watcher).InBackgroundWithCallback(c.backgroundCallback).ForPath(c.path)
return err
}
return nil
}
func (c *NodeCache) processBackgroundResult(event curator.CuratorEvent) error {
switch event.Type() {
case curator.GET_DATA:
if event.Err() == nil {
c.setNewData(&ChildData{c.path, event.Stat(), event.Data()})
}
case curator.EXISTS:
if event.Err() == zk.ErrNoNode {
c.setNewData(nil)
} else if event.Err() == nil {
builder := c.client.GetData()
if c.dataIsCompressed {
builder.Decompressed()
}
builder.UsingWatcher(c.watcher).InBackgroundWithCallback(c.backgroundCallback).ForPath(c.path)
}
}
return nil
}
func (c *NodeCache) setNewData(newData *ChildData) {
previousData := (*ChildData)(atomic.SwapPointer((*unsafe.Pointer)(unsafe.Pointer(&c.data)), unsafe.Pointer(newData)))
if !reflect.DeepEqual(previousData, newData) {
c.listeners.ForEach(func(listener interface{}) {
listener.(NodeCacheListener).NodeChanged()
})
}
}
type RefreshMode int
const (
STANDARD RefreshMode = iota
FORCE_GET_DATA_AND_STAT
POST_INITIALIZED
)
// A utility that attempts to keep all data from all children of a ZK path locally cached.
// This class will watch the ZK path, respond to update/create/delete events, pull down the data, etc.
// You can register a listener that will get notified when changes occur.
type PathChildrenCache struct {
client curator.CuratorFramework
path string
cacheData bool
dataIsCompressed bool
ensurePath curator.EnsurePath
state curator.State
connectionStateListener curator.ConnectionStateListener
isConnected curator.AtomicBool
}
func NewPathChildrenCache(client curator.CuratorFramework, path string, cacheData, dataIsCompressed bool) *PathChildrenCache {
c := &PathChildrenCache{
client: client,
path: path,
cacheData: cacheData,
dataIsCompressed: dataIsCompressed,
ensurePath: client.NewNamespaceAwareEnsurePath(path),
}
c.connectionStateListener = curator.NewConnectionStateListener(func(client curator.CuratorFramework, newState curator.ConnectionState) {
if newState.Connected() {
if c.isConnected.CompareAndSwap(false, true) {
/*
if err := c.reset(); err != nil {
panic(fmt.Errorf("Trying to reset after reconnection, %s", err))
}
*/
}
} else {
c.isConnected.Set(false)
}
})
return c
}
func (c *PathChildrenCache) RefreshMode(mode RefreshMode) {
c.ensurePath.Ensure(c.client.ZookeeperClient())
/*
c.client.GetChildren().UsingWatcher(c.childrenWatcher).InBackground(func(client CuratorFramework, event CuratorEvent) error {
if c.state.Value() == STOPPED {
}
}).ForPath(c.path)
*/
}