forked from etcd-io/etcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
90 lines (77 loc) · 2.55 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
package etcd
import (
"errors"
)
// Errors introduced by the Watch command.
var (
ErrWatchStoppedByUser = errors.New("Watch stopped by the user via stop channel")
)
// WatchAll returns the first change under the given prefix since the given index. To
// watch for the latest change, set waitIndex = 0.
//
// If the prefix points to a directory, any change under it, including all child directories,
// will be returned.
//
// If a receiver channel is given, it will be a long-term watch. Watch will block at the
// channel. And after someone receive the channel, it will go on to watch that prefix.
// If a stop channel is given, client can close long-term watch using the stop channel
func (c *Client) WatchAll(prefix string, waitIndex uint64, receiver chan *Response, stop chan bool) (*Response, error) {
return c.watch(prefix, waitIndex, true, receiver, stop)
}
// Watch returns the first change to the given key since the given index. To
// watch for the latest change, set waitIndex = 0.
//
// If a receiver channel is given, it will be a long-term watch. Watch will block at the
// channel. And after someone receive the channel, it will go on to watch that
// prefix. If a stop channel is given, client can close long-term watch using
// the stop channel
func (c *Client) Watch(key string, waitIndex uint64, receiver chan *Response, stop chan bool) (*Response, error) {
return c.watch(key, waitIndex, false, receiver, stop)
}
func (c *Client) watch(prefix string, waitIndex uint64, recursive bool, receiver chan *Response, stop chan bool) (*Response, error) {
logger.Debugf("watch %s [%s]", prefix, c.cluster.Leader)
if receiver == nil {
return c.watchOnce(prefix, waitIndex, recursive, stop)
} else {
for {
resp, err := c.watchOnce(prefix, waitIndex, recursive, stop)
if resp != nil {
waitIndex = resp.ModifiedIndex + 1
receiver <- resp
} else {
return nil, err
}
}
}
return nil, nil
}
// helper func
// return when there is change under the given prefix
func (c *Client) watchOnce(key string, waitIndex uint64, recursive bool, stop chan bool) (*Response, error) {
respChan := make(chan *Response)
errChan := make(chan error)
go func() {
options := options{
"wait": true,
}
if waitIndex > 0 {
options["waitIndex"] = waitIndex
}
if recursive {
options["recursive"] = true
}
resp, err := c.get(key, options)
if err != nil {
errChan <- err
}
respChan <- resp
}()
select {
case resp := <-respChan:
return resp, nil
case err := <-errChan:
return nil, err
case <-stop:
return nil, ErrWatchStoppedByUser
}
}