|
| 1 | +package catalog |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "hash/crc32" |
| 6 | + "io" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "sync" |
| 10 | + "sync/atomic" |
| 11 | + |
| 12 | + "github.com/fsnotify/fsnotify" |
| 13 | + "github.com/golang/glog" |
| 14 | +) |
| 15 | + |
| 16 | +// monitor sends events when the contents of a file have changed. |
| 17 | +// |
| 18 | +// Unfortunately, simply watching the file misses events for our primary case |
| 19 | +// of k8s mounted configmaps because the files we're watching are actually |
| 20 | +// symlinks which aren't modified: |
| 21 | +// |
| 22 | +// drwxrwxrwx 1 root root 138 Jul 2 15:45 . |
| 23 | +// drwxr-xr-x 1 root root 116 Jul 2 15:52 .. |
| 24 | +// drwxr-xr-x 1 root root 62 Jul 2 15:45 ..2025_07_02_15_45_09.2837733502 |
| 25 | +// lrwxrwxrwx 1 root root 32 Jul 2 15:45 ..data -> ..2025_07_02_15_45_09.2837733502 |
| 26 | +// lrwxrwxrwx 1 root root 26 Jul 2 13:18 sample-catalog.yaml -> ..data/sample-catalog.yaml |
| 27 | +// lrwxrwxrwx 1 root root 19 Jul 2 13:18 sources.yaml -> ..data/sources.yaml |
| 28 | +// |
| 29 | +// Updates are written to a new directory and the ..data symlink is updated. No |
| 30 | +// fsnotify events will ever be triggered for the YAML files. |
| 31 | +// |
| 32 | +// The approach taken here is to watch the directory containing the file for |
| 33 | +// any change and then hash the contents of the file to avoid false-positives. |
| 34 | +type monitor struct { |
| 35 | + watcher *fsnotify.Watcher |
| 36 | + closed <-chan struct{} |
| 37 | + |
| 38 | + recordsMu sync.RWMutex |
| 39 | + records map[string]map[string]*monitorRecord |
| 40 | +} |
| 41 | + |
| 42 | +var _monitor *monitor |
| 43 | +var initMonitor sync.Once |
| 44 | + |
| 45 | +// getMonitor returns a singleton monitor instance. Panics on failure. |
| 46 | +func getMonitor() *monitor { |
| 47 | + initMonitor.Do(func() { |
| 48 | + var err error |
| 49 | + _monitor, err = newMonitor() |
| 50 | + if err != nil { |
| 51 | + panic(fmt.Sprintf("Unable to create file monitor: %v", err)) |
| 52 | + } |
| 53 | + }) |
| 54 | + if _monitor == nil { |
| 55 | + // Panic in case someone traps the panic that occurred during |
| 56 | + // initialization and tries to call this again. |
| 57 | + panic("Unable to get file monitor") |
| 58 | + } |
| 59 | + |
| 60 | + return _monitor |
| 61 | +} |
| 62 | + |
| 63 | +func newMonitor() (*monitor, error) { |
| 64 | + watcher, err := fsnotify.NewWatcher() |
| 65 | + if err != nil { |
| 66 | + return nil, err |
| 67 | + } |
| 68 | + |
| 69 | + m := &monitor{ |
| 70 | + watcher: watcher, |
| 71 | + records: map[string]map[string]*monitorRecord{}, |
| 72 | + } |
| 73 | + |
| 74 | + go m.monitor() |
| 75 | + return m, nil |
| 76 | +} |
| 77 | + |
| 78 | +// Close stops the monitor and waits for the background goroutine to exit. |
| 79 | +// |
| 80 | +// All channels returned by Path() will be closed. |
| 81 | +func (m *monitor) Close() { |
| 82 | + select { |
| 83 | + case <-m.closed: |
| 84 | + // Already closed, nothing to do. |
| 85 | + return |
| 86 | + default: |
| 87 | + // Fallthrough |
| 88 | + } |
| 89 | + |
| 90 | + m.watcher.Close() |
| 91 | + <-m.closed |
| 92 | + |
| 93 | + m.recordsMu.Lock() |
| 94 | + defer m.recordsMu.Unlock() |
| 95 | + |
| 96 | + uniqCh := make(map[chan<- struct{}]struct{}) |
| 97 | + for dir := range m.records { |
| 98 | + for file := range m.records[dir] { |
| 99 | + record, ok := m.records[dir][file] |
| 100 | + if !ok { |
| 101 | + continue |
| 102 | + } |
| 103 | + for _, ch := range record.channels { |
| 104 | + uniqCh[ch] = struct{}{} |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + for ch := range uniqCh { |
| 109 | + close(ch) |
| 110 | + } |
| 111 | + m.records = nil |
| 112 | +} |
| 113 | + |
| 114 | +// Path returns a channel that receives an event when the contents of a file |
| 115 | +// change. The file does not need to exist before calling this method, however |
| 116 | +// the provided path should only be a file or a symlink (not a directory, |
| 117 | +// device, etc.). The returned channel will be closed when the monitor is |
| 118 | +// closed. |
| 119 | +func (m *monitor) Path(p string) (<-chan struct{}, error) { |
| 120 | + absPath, err := filepath.Abs(p) |
| 121 | + if err != nil { |
| 122 | + return nil, fmt.Errorf("abs: %w", err) |
| 123 | + } |
| 124 | + |
| 125 | + m.recordsMu.Lock() |
| 126 | + defer m.recordsMu.Unlock() |
| 127 | + |
| 128 | + dir, base := filepath.Split(absPath) |
| 129 | + dir = filepath.Clean(dir) |
| 130 | + |
| 131 | + err = m.watcher.Add(dir) |
| 132 | + if err != nil { |
| 133 | + return nil, fmt.Errorf("unable to watch directory %q: %w", dir, err) |
| 134 | + } |
| 135 | + |
| 136 | + if _, exists := m.records[dir]; !exists { |
| 137 | + m.records[dir] = make(map[string]*monitorRecord, 1) |
| 138 | + } |
| 139 | + |
| 140 | + ch := make(chan struct{}, 1) |
| 141 | + |
| 142 | + if _, exists := m.records[dir][base]; !exists { |
| 143 | + m.records[dir][base] = &monitorRecord{ |
| 144 | + channels: []chan<- struct{}{ch}, |
| 145 | + } |
| 146 | + } else { |
| 147 | + r := m.records[dir][base] |
| 148 | + r.channels = append(r.channels, ch) |
| 149 | + } |
| 150 | + m.records[dir][base].updateHash(filepath.Join(dir, base)) |
| 151 | + |
| 152 | + return ch, nil |
| 153 | +} |
| 154 | + |
| 155 | +func (m *monitor) monitor() { |
| 156 | + closed := make(chan struct{}) |
| 157 | + m.closed = closed |
| 158 | + defer close(closed) |
| 159 | + |
| 160 | + for { |
| 161 | + select { |
| 162 | + case err, ok := <-m.watcher.Errors: |
| 163 | + if !ok { |
| 164 | + return |
| 165 | + } |
| 166 | + |
| 167 | + glog.Errorf("fsnotify error: %v", err) |
| 168 | + case e, ok := <-m.watcher.Events: |
| 169 | + if !ok { |
| 170 | + return |
| 171 | + } |
| 172 | + |
| 173 | + glog.V(2).Infof("fsnotify.Event: %v", e) |
| 174 | + |
| 175 | + switch e.Op { |
| 176 | + case fsnotify.Create, fsnotify.Write: |
| 177 | + // Fallthrough |
| 178 | + default: |
| 179 | + // Ignore fsnotify.Remove, fsnotify.Rename and fsnotify.Chmod |
| 180 | + continue |
| 181 | + } |
| 182 | + |
| 183 | + func() { |
| 184 | + m.recordsMu.RLock() |
| 185 | + defer m.recordsMu.RUnlock() |
| 186 | + |
| 187 | + dir := filepath.Dir(e.Name) |
| 188 | + |
| 189 | + dc := m.records[dir] |
| 190 | + if dc == nil { |
| 191 | + return |
| 192 | + } |
| 193 | + |
| 194 | + for base, record := range dc { |
| 195 | + path := filepath.Join(dir, base) |
| 196 | + if !record.updateHash(path) { |
| 197 | + continue |
| 198 | + } |
| 199 | + for _, ch := range record.channels { |
| 200 | + // Send the event, ignore any that would block. |
| 201 | + select { |
| 202 | + case ch <- struct{}{}: |
| 203 | + default: |
| 204 | + glog.Errorf("monitor: missed event for path %s", path) |
| 205 | + } |
| 206 | + } |
| 207 | + } |
| 208 | + }() |
| 209 | + } |
| 210 | + } |
| 211 | +} |
| 212 | + |
| 213 | +type monitorRecord struct { |
| 214 | + channels []chan<- struct{} |
| 215 | + hash uint32 |
| 216 | +} |
| 217 | + |
| 218 | +// updateHash recalculates the hash and returns true if it has changed. |
| 219 | +func (mr *monitorRecord) updateHash(path string) bool { |
| 220 | + newHash := mr.calculateHash(path) |
| 221 | + oldHash := atomic.SwapUint32(&mr.hash, newHash) |
| 222 | + return oldHash != newHash |
| 223 | +} |
| 224 | + |
| 225 | +func (monitorRecord) calculateHash(path string) uint32 { |
| 226 | + fh, err := os.Open(path) |
| 227 | + if err != nil { |
| 228 | + return 0 |
| 229 | + } |
| 230 | + defer fh.Close() |
| 231 | + |
| 232 | + h := crc32.NewIEEE() |
| 233 | + _, err = io.Copy(h, fh) |
| 234 | + if err != nil { |
| 235 | + return 0 |
| 236 | + } |
| 237 | + return h.Sum32() |
| 238 | +} |
0 commit comments