forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
103 lines (89 loc) · 2.42 KB
/
watch.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
package zktopo
import (
"fmt"
"sync"
zookeeper "github.com/samuel/go-zookeeper/zk"
"golang.org/x/net/context"
"github.com/youtube/vitess/go/vt/topo"
)
func newWatchData(valueType dataType, data []byte, stats *zookeeper.Stat) *topo.WatchData {
bytes, err := rawDataFromNodeValue(valueType, data)
if err != nil {
return &topo.WatchData{Err: err}
}
return &topo.WatchData{
Contents: bytes,
Version: ZKVersion(stats.Version),
}
}
// Watch is part of the topo.Backend interface
func (zkts *Server) Watch(ctx context.Context, cell, filePath string) (*topo.WatchData, <-chan *topo.WatchData, topo.CancelFunc) {
// Special paths where we need to be backward compatible.
var valueType dataType
valueType, filePath = oldTypeAndFilePath(cell, filePath)
// Get the initial value, set the initial watch
data, stats, watch, err := zkts.zconn.GetW(filePath)
if err != nil {
return &topo.WatchData{Err: convertError(err)}, nil, nil
}
if stats == nil {
// No stats --> node doesn't exist.
return &topo.WatchData{Err: topo.ErrNoNode}, nil, nil
}
wd := newWatchData(valueType, data, stats)
if wd.Err != nil {
return wd, nil, nil
}
// mu protects the stop channel. We need to make sure the 'cancel'
// func can be called multiple times, and that we don't close 'stop'
// too many times.
mu := sync.Mutex{}
stop := make(chan struct{})
cancel := func() {
mu.Lock()
defer mu.Unlock()
if stop != nil {
close(stop)
stop = nil
}
}
c := make(chan *topo.WatchData, 10)
go func(stop chan struct{}) {
defer close(c)
for {
// Act on the watch, or on 'stop' close.
select {
case event, ok := <-watch:
if !ok {
c <- &topo.WatchData{Err: fmt.Errorf("watch on %v was closed", filePath)}
return
}
if event.Err != nil {
c <- &topo.WatchData{Err: fmt.Errorf("received a non-OK event for %v: %v", filePath, event.Err)}
return
}
case <-stop:
// user is not interested any more
c <- &topo.WatchData{Err: topo.ErrInterrupted}
return
}
// Get the value again, and send it, or error.
data, stats, watch, err = zkts.zconn.GetW(filePath)
if err != nil {
c <- &topo.WatchData{Err: convertError(err)}
return
}
if stats == nil {
// No data --> node doesn't exist
c <- &topo.WatchData{Err: topo.ErrNoNode}
return
}
wd := newWatchData(valueType, data, stats)
c <- wd
if wd.Err != nil {
return
}
}
}(stop)
return wd, c, cancel
}