/
docker_compose_event_watcher.go
77 lines (64 loc) · 1.78 KB
/
docker_compose_event_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
76
77
package engine
import (
"context"
"github.com/pkg/errors"
"github.com/windmilleng/tilt/internal/dockercompose"
"github.com/windmilleng/tilt/internal/logger"
"github.com/windmilleng/tilt/internal/store"
)
type DockerComposeEventWatcher struct {
watching bool
dcc dockercompose.DockerComposeClient
}
func NewDockerComposeEventWatcher(dcc dockercompose.DockerComposeClient) *DockerComposeEventWatcher {
return &DockerComposeEventWatcher{
dcc: dcc,
}
}
func (w *DockerComposeEventWatcher) needsWatch(st store.RStore) bool {
state := st.RLockState()
defer st.RUnlockState()
return state.WatchFiles && !w.watching
}
func (w *DockerComposeEventWatcher) OnChange(ctx context.Context, st store.RStore) {
if !w.needsWatch(st) {
return
}
state := st.RLockState()
configPath := state.DockerComposeConfigPath()
st.RUnlockState()
if configPath == "" {
// No DC manifests to watch
return
}
w.watching = true
ch, err := w.startWatch(ctx, configPath)
if err != nil {
err = errors.Wrap(err, "Subscribing to docker-compose events")
st.Dispatch(NewErrorAction(err))
return
}
go dispatchDockerComposeEventLoop(ctx, ch, st)
}
func (w *DockerComposeEventWatcher) startWatch(ctx context.Context, configPath string) (<-chan string, error) {
return w.dcc.StreamEvents(ctx, configPath)
}
func dispatchDockerComposeEventLoop(ctx context.Context, ch <-chan string, st store.RStore) {
for {
select {
case evtJson, ok := <-ch:
if !ok {
return
}
evt, err := dockercompose.EventFromJsonStr(evtJson)
if err != nil {
// TODO(maia): handle this error better?
logger.Get(ctx).Infof("[DOCKER-COMPOSE WATCHER] failed to unmarshal dc event '%s' with err: %v", evtJson, err)
continue
}
st.Dispatch(DockerComposeEventAction{evt})
case <-ctx.Done():
return
}
}
}