forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
108 lines (92 loc) · 2.64 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
104
105
106
107
108
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreedto in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package zk2topo
import (
"fmt"
"path"
"sync"
"golang.org/x/net/context"
"vitess.io/vitess/go/vt/topo"
)
// Watch is part of the topo.Conn interface.
func (zs *Server) Watch(ctx context.Context, filePath string) (*topo.WatchData, <-chan *topo.WatchData, topo.CancelFunc) {
zkPath := path.Join(zs.root, filePath)
// Get the initial value, set the initial watch
data, stats, watch, err := zs.conn.GetW(ctx, zkPath)
if err != nil {
return &topo.WatchData{Err: convertError(err, zkPath)}, nil, nil
}
if stats == nil {
// No stats --> node doesn't exist.
return &topo.WatchData{Err: topo.NewError(topo.NoNode, zkPath)}, nil, nil
}
wd := &topo.WatchData{
Contents: data,
Version: ZKVersion(stats.Version),
}
// 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", zkPath)}
return
}
if event.Err != nil {
c <- &topo.WatchData{Err: fmt.Errorf("received a non-OK event for %v: %v", zkPath, event.Err)}
return
}
case <-stop:
// user is not interested any more
c <- &topo.WatchData{Err: topo.NewError(topo.Interrupted, "watch")}
return
}
// Get the value again, and send it, or error.
data, stats, watch, err = zs.conn.GetW(ctx, zkPath)
if err != nil {
c <- &topo.WatchData{Err: convertError(err, zkPath)}
return
}
if stats == nil {
// No data --> node doesn't exist
c <- &topo.WatchData{Err: topo.NewError(topo.NoNode, zkPath)}
return
}
wd := &topo.WatchData{
Contents: data,
Version: ZKVersion(stats.Version),
}
c <- wd
if wd.Err != nil {
return
}
}
}(stop)
return wd, c, cancel
}