-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
71 lines (60 loc) · 1.62 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
package configmap
import (
"github.com/fsnotify/fsnotify"
)
// Watcher holds details required to watch for ConfigMap updates
type Watcher struct {
// Holds the location in which the config file lives
FilePath string
// The function to run when an update on the ConfigMap is applied
OnUpdate func()
// The function to run when an error occurs
OnError func(error)
// The function to run when a fatal error occurs
// When fatal errors occur, the Watcher is NOT running. Therefore, any ConfigMap updates
// will be missed.
OnFatal func(error)
}
// New generates and returns a new Watcher
func New(filePath string, onUpdate func(), onError, onFatal func(error)) *Watcher {
return &Watcher{
FilePath: filePath,
OnUpdate: onUpdate,
OnError: onError,
OnFatal: onFatal,
}
}
// Run starts watching for updates to a ConfigMap file
//
// You'll want to call this method in a goroutine or it will block your main thread.
// RunInBackground is also available for just this purpose.
func (w *Watcher) Run() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
w.OnFatal(err)
return
}
defer watcher.Close()
if err := watcher.Add(w.FilePath); err != nil {
w.OnFatal(err)
return
}
for {
select {
case event := <-watcher.Events:
// If the ConfigMap is removed during the update, we need to reapply the watcher to
// refresh the symlink
if event.Op == fsnotify.Remove {
watcher.Remove(event.Name)
watcher.Add(w.FilePath)
}
w.OnUpdate()
case err := <-watcher.Errors:
w.OnError(err)
}
}
}
// RunInBackground starts the Watcher in a new thread
func (w *Watcher) RunInBackground() {
go w.Run()
}