forked from bluenviron/mediamtx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
confwatcher.go
113 lines (91 loc) · 2.26 KB
/
confwatcher.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Package confwatcher contains a configuration watcher.
package confwatcher
import (
"os"
"path/filepath"
"time"
"github.com/fsnotify/fsnotify"
)
const (
minInterval = 1 * time.Second
additionalWait = 10 * time.Millisecond
)
// ConfWatcher is a configuration file watcher.
type ConfWatcher struct {
inner *fsnotify.Watcher
watchedPath string
// out
signal chan struct{}
done chan struct{}
}
// New allocates a ConfWatcher.
func New(confPath string) (*ConfWatcher, error) {
if _, err := os.Stat(confPath); err != nil {
return nil, err
}
inner, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
// use absolute paths to support Darwin
absolutePath, _ := filepath.Abs(confPath)
parentPath := filepath.Dir(absolutePath)
err = inner.Add(parentPath)
if err != nil {
inner.Close()
return nil, err
}
w := &ConfWatcher{
inner: inner,
watchedPath: absolutePath,
signal: make(chan struct{}),
done: make(chan struct{}),
}
go w.run()
return w, nil
}
// Close closes a ConfWatcher.
func (w *ConfWatcher) Close() {
go func() {
for range w.signal {
}
}()
w.inner.Close()
<-w.done
}
func (w *ConfWatcher) run() {
defer close(w.done)
var lastCalled time.Time
previousWatchedPath, _ := filepath.EvalSymlinks(w.watchedPath)
outer:
for {
select {
case event := <-w.inner.Events:
if time.Since(lastCalled) < minInterval {
continue
}
currentWatchedPath, _ := filepath.EvalSymlinks(w.watchedPath)
eventPath, _ := filepath.Abs(event.Name)
if currentWatchedPath == "" {
// watched file was removed; wait for write event to trigger reload
previousWatchedPath = ""
} else if currentWatchedPath != previousWatchedPath ||
(eventPath == currentWatchedPath &&
((event.Op&fsnotify.Write) == fsnotify.Write ||
(event.Op&fsnotify.Create) == fsnotify.Create)) {
// wait some additional time to allow the writer to complete its job
time.Sleep(additionalWait)
previousWatchedPath = currentWatchedPath
lastCalled = time.Now()
w.signal <- struct{}{}
}
case <-w.inner.Errors:
break outer
}
}
close(w.signal)
}
// Watch returns a channel that is called after the configuration file has changed.
func (w *ConfWatcher) Watch() chan struct{} {
return w.signal
}