-
Notifications
You must be signed in to change notification settings - Fork 10
/
watch.go
98 lines (84 loc) · 2.1 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
package store
import (
"golang.org/x/net/context"
"github.com/weaveworks/flux/common/daemon"
)
type ServiceUpdate struct {
Services map[string]*ServiceInfo
Reset bool
}
type watchServices struct {
store Store
opts QueryServiceOptions
callback func(update ServiceUpdate, stop <-chan struct{})
errorSink daemon.ErrorSink
context context.Context
cancel context.CancelFunc
finished chan struct{}
}
func WatchServicesIndirectStartFunc(store Store, opts QueryServiceOptions, cb func(update ServiceUpdate, stop <-chan struct{})) daemon.StartFunc {
return func(es daemon.ErrorSink) daemon.Component {
ctx, cancel := context.WithCancel(context.Background())
ws := &watchServices{
store: store,
opts: opts,
callback: cb,
errorSink: es,
context: ctx,
cancel: cancel,
finished: make(chan struct{}),
}
go func() {
es.Post(ws.run())
}()
return ws
}
}
func WatchServicesStartFunc(store Store, opts QueryServiceOptions, updates chan<- ServiceUpdate) daemon.StartFunc {
return WatchServicesIndirectStartFunc(store, opts, func(su ServiceUpdate, stop <-chan struct{}) {
select {
case updates <- su:
case <-stop:
}
})
}
func (ws *watchServices) run() error {
defer close(ws.finished)
changes := make(chan ServiceChange)
ws.store.WatchServices(ws.context, changes, ws.errorSink, ws.opts)
err := ws.doInitialQuery()
if err != nil {
return err
}
for {
var change ServiceChange
select {
case change = <-changes:
case <-ws.context.Done():
return nil
}
var svc *ServiceInfo
if !change.ServiceDeleted {
if svc, err = ws.store.GetService(change.Name, ws.opts); err != nil {
return err
}
}
ws.callback(ServiceUpdate{
Services: map[string]*ServiceInfo{change.Name: svc},
}, ws.context.Done())
}
}
func (ws *watchServices) doInitialQuery() error {
// Send initial state of each service
svcs, err := ws.store.GetAllServices(ws.opts)
if err != nil {
return err
}
ws.callback(ServiceUpdate{Services: svcs, Reset: true},
ws.context.Done())
return nil
}
func (ws *watchServices) Stop() {
ws.cancel()
<-ws.finished
}