-
Notifications
You must be signed in to change notification settings - Fork 1
/
watcher.go
338 lines (286 loc) · 6.61 KB
/
watcher.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
package prophet
import (
"sync"
"sync/atomic"
"github.com/fagongzi/goetty"
)
var (
// EventInit event init
EventInit = 1 << 1
// EventResourceCreated event resource created
EventResourceCreated = 1 << 2
// EventResourceLeaderChanged event resource leader changed
EventResourceLeaderChanged = 1 << 3
// EventResourceChaned event resource changed
EventResourceChaned = 1 << 4
// EventContainerCreated event container create
EventContainerCreated = 1 << 5
// EventContainerChanged event container create
EventContainerChanged = 1 << 6
// EventFlagResource all resource event
EventFlagResource = EventResourceCreated | EventResourceLeaderChanged | EventResourceChaned
// EventFlagContainer all container event
EventFlagContainer = EventContainerCreated | EventContainerChanged
// EventFlagAll all event
EventFlagAll = 0xffffffff
)
// MatchEvent returns the flag has the target event
func MatchEvent(event, flag int) bool {
return event == 0 || event&flag != 0
}
func (p *defaultProphet) notifyEvent(event *EventNotify) {
if event == nil {
return
}
if p.isLeader() {
p.wn.onEvent(event)
}
}
// InitWatcher init watcher
type InitWatcher struct {
Flag int `json:"flag"`
}
// EventNotify event notify
type EventNotify struct {
Seq uint64 `json:"seq"`
Event int `json:"event"`
Value []byte `json:"value"`
}
func newInitEvent(snap *snap) (*EventNotify, error) {
value := goetty.NewByteBuf(512)
value.WriteInt(len(snap.containers))
value.WriteInt(len(snap.resources))
for _, v := range snap.containers {
data, err := v.Marshal()
if err != nil {
return nil, err
}
value.WriteInt(len(data))
value.Write(data)
}
for _, v := range snap.resources {
data, err := v.Marshal()
if err != nil {
return nil, err
}
value.WriteInt(len(data) + 8)
value.Write(data)
if id, ok := snap.leaders[v.ID()]; ok {
value.WriteUint64(id)
} else {
value.WriteUint64(0)
}
}
_, data, _ := value.ReadAll()
nt := &EventNotify{
Event: EventInit,
Value: data,
}
value.Release()
return nt, nil
}
func newResourceEvent(event int, target Resource) *EventNotify {
value, err := target.Marshal()
if err != nil {
return nil
}
return &EventNotify{
Event: event,
Value: value,
}
}
func newContainerEvent(event int, target Container) *EventNotify {
value, err := target.Marshal()
if err != nil {
return nil
}
return &EventNotify{
Event: event,
Value: value,
}
}
func newLeaderChangerEvent(target, leader uint64) *EventNotify {
value := goetty.NewByteBuf(16)
value.WriteUint64(target)
value.WriteUint64(leader)
_, data, _ := value.ReadAll()
nt := &EventNotify{
Event: EventResourceLeaderChanged,
Value: data,
}
value.Release()
return nt
}
// ReadInitEventValues read all resource info
func (evt *EventNotify) ReadInitEventValues(resourceF func([]byte, uint64), containerF func([]byte)) {
if len(evt.Value) == 0 {
return
}
buf := goetty.NewByteBuf(len(evt.Value))
buf.Write(evt.Value)
cn, _ := buf.ReadInt()
rn, _ := buf.ReadInt()
for i := 0; i < cn; i++ {
size, _ := buf.ReadInt()
_, data, _ := buf.ReadBytes(size)
containerF(data)
}
for i := 0; i < rn; i++ {
size, _ := buf.ReadInt()
_, data, _ := buf.ReadBytes(size - 8)
leader, _ := buf.ReadUInt64()
resourceF(data, leader)
}
buf.Release()
return
}
// ReadLeaderChangerValue returns the target resource and the new leader
// returns resourceid, newleaderid
func (evt *EventNotify) ReadLeaderChangerValue() (uint64, uint64) {
if len(evt.Value) == 0 {
return 0, 0
}
buf := goetty.NewByteBuf(len(evt.Value))
buf.Write(evt.Value)
resourceID, _ := buf.ReadUInt64()
newLeaderID, _ := buf.ReadUInt64()
buf.Release()
return resourceID, newLeaderID
}
type watcher struct {
seq uint64
info *InitWatcher
conn goetty.IOSession
}
func (wt *watcher) notify(evt *EventNotify) {
if MatchEvent(evt.Event, wt.info.Flag) {
evt.Seq = atomic.AddUint64(&wt.seq, 1)
err := wt.conn.WriteAndFlush(evt)
if err != nil {
wt.conn.Close()
}
}
}
type watcherNotifier struct {
sync.RWMutex
watchers *sync.Map
eventC chan *EventNotify
rt *Runtime
}
func newWatcherNotifier(rt *Runtime) *watcherNotifier {
return &watcherNotifier{
watchers: &sync.Map{},
eventC: make(chan *EventNotify, 256),
rt: rt,
}
}
func (wn *watcherNotifier) onEvent(evt *EventNotify) {
wn.RLock()
if wn.eventC != nil {
wn.eventC <- evt
}
wn.RUnlock()
}
func (wn *watcherNotifier) onInitWatcher(msg *InitWatcher, conn goetty.IOSession) {
log.Infof("new watcher %s added", conn.RemoteIP())
snap := wn.rt.snap()
wn.Lock()
defer wn.Unlock()
if wn.eventC != nil {
if MatchEvent(EventInit, msg.Flag) {
nt, err := newInitEvent(snap)
if err != nil {
log.Errorf("marshal init notify failed, errors:%+v", err)
conn.Close()
return
}
err = conn.WriteAndFlush(nt)
if err != nil {
log.Errorf("notify to %s failed, errors:%+v",
conn.RemoteIP(),
err)
conn.Close()
return
}
}
wn.watchers.Store(conn.ID(), &watcher{
info: msg,
conn: conn,
})
}
}
func (wn *watcherNotifier) clearWatcher(conn goetty.IOSession) {
wn.Lock()
log.Infof("clear watcher %s", conn.RemoteIP())
wn.watchers.Delete(conn.ID())
wn.Unlock()
}
func (wn *watcherNotifier) stop() {
wn.Lock()
defer wn.Unlock()
if wn.eventC != nil {
close(wn.eventC)
wn.eventC = nil
}
if wn.watchers != nil {
wn.watchers.Range(func(key, value interface{}) bool {
wn.watchers.Delete(key)
value.(*watcher).conn.Close()
return true
})
}
log.Infof("watcher notifyer stopped")
}
func (wn *watcherNotifier) start() {
go func() {
defer func() {
if err := recover(); err == nil {
log.Errorf("watcher notify failed with %+v, restart later", err)
wn.start()
}
}()
for {
evt, ok := <-wn.eventC
if !ok {
log.Infof("watcher notifer exited")
return
}
log.Debugf("new event: %+v", evt)
wn.RLock()
wn.watchers.Range(func(key, value interface{}) bool {
wt := value.(*watcher)
wt.notify(evt)
return true
})
wn.RUnlock()
}
}()
}
type snap struct {
resources []Resource
containers []Container
leaders map[uint64]uint64
}
func (rc *Runtime) snap() *snap {
rc.RLock()
defer rc.RUnlock()
value := &snap{
resources: make([]Resource, len(rc.resources), len(rc.resources)),
containers: make([]Container, len(rc.containers), len(rc.containers)),
leaders: make(map[uint64]uint64),
}
idx := 0
for _, c := range rc.containers {
value.containers[idx] = c.meta.Clone()
idx++
}
idx = 0
for _, r := range rc.resources {
value.resources[idx] = r.meta.Clone()
if r.leaderPeer != nil {
value.leaders[r.meta.ID()] = r.leaderPeer.ID
}
idx++
}
return value
}