-
Notifications
You must be signed in to change notification settings - Fork 34
/
fsnotify.go
95 lines (73 loc) · 1.62 KB
/
fsnotify.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
package config
import (
"context"
"fmt"
"log/slog"
"os"
"github.com/fsnotify/fsnotify"
"gopkg.in/yaml.v2"
)
func watchFSNotify(ctx context.Context, ch chan<- *TunnelGroups, path string, watch bool) error {
groups, err := buildTunnelGroupsAtPath(path)
if err != nil {
return err
}
// feed initial channel group
ch <- groups
if !watch {
return nil
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
go func() {
defer close(ch)
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
slog.Debug("Watcher event", "event", event)
if !(event.Has(fsnotify.Remove)) {
continue
}
groups, err := buildTunnelGroupsAtPath(path)
if err != nil {
slog.Error("reading tunnel groups: %w", err)
continue
}
ch <- groups
// remove and re-add as the file has been moved atomically
watcher.Remove(event.Name)
watcher.Add(path)
case err, ok := <-watcher.Errors:
if !ok {
return
}
slog.Error("watching tunnel groups", "error", err)
}
}
}()
if err := watcher.Add(path); err != nil {
return err
}
return nil
}
func buildTunnelGroupsAtPath(path string) (*TunnelGroups, error) {
fi, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("reading tunnel groups: %w", err)
}
defer fi.Close()
var groups TunnelGroups
if err := yaml.NewDecoder(fi).Decode(&groups); err != nil {
return nil, fmt.Errorf("decoding tunnel groups: %w", err)
}
if err := groups.Validate(); err != nil {
return nil, fmt.Errorf("validating tunnel groups: %w", err)
}
return &groups, nil
}