forked from itspage/go-platform
/
watcher.go
75 lines (63 loc) · 1.23 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
package etcd
import (
"crypto/md5"
"errors"
"fmt"
"github.com/coreos/etcd/client"
"github.com/micro/go-os/config"
"golang.org/x/net/context"
)
type watcher struct {
name string
w client.Watcher
ctx context.Context
cancel func()
exit chan bool
}
func newWatcher(key string, addrs []string, name string) (config.SourceWatcher, error) {
c, err := client.New(client.Config{
Endpoints: addrs,
})
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
w := client.NewKeysAPI(c).Watcher(key, nil)
return &watcher{
name: name,
ctx: ctx,
cancel: cancel,
exit: make(chan bool),
w: w,
}, nil
}
func (w *watcher) Next() (*config.ChangeSet, error) {
select {
case <-w.exit:
return nil, errors.New("watcher stopped")
default:
rsp, err := w.w.Next(w.ctx)
if err != nil {
return nil, err
}
// hash the etcd
h := md5.New()
h.Write([]byte(rsp.Node.Value))
checksum := fmt.Sprintf("%x", h.Sum(nil))
return &config.ChangeSet{
Source: w.name,
Data: []byte(rsp.Node.Value),
Checksum: checksum,
}, nil
}
}
func (w *watcher) Stop() error {
select {
case <-w.exit:
return nil
default:
close(w.exit)
w.cancel()
}
return nil
}