file_change_notify.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. package filehelper
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "sync"
  7. "time"
  8. "github.com/OliveTin/OliveTin/internal/configissues"
  9. "github.com/fsnotify/fsnotify"
  10. log "github.com/sirupsen/logrus"
  11. )
  12. var (
  13. debounceWriteLog map[string]*FsNotifyLogEntry
  14. debounceWriteLogMutex = sync.Mutex{}
  15. fileWatchMu sync.Mutex
  16. fileWatchStops = map[string]chan struct{}{}
  17. )
  18. func init() {
  19. debounceWriteLog = make(map[string]*FsNotifyLogEntry)
  20. }
  21. type FsNotifyLogEntry struct {
  22. callbackWrapper *time.Timer
  23. callbackComplete bool
  24. }
  25. const (
  26. debounceDelay = 300 * time.Millisecond
  27. )
  28. // WatchMeta attaches action context to watcher setup failures so Diagnostics
  29. // can apply the same action view ACL as other configuration issues.
  30. type WatchMeta struct {
  31. ActionID string
  32. ActionTitle string
  33. ConfigFile string
  34. }
  35. type watchContext struct {
  36. callback func(filename string)
  37. event *fsnotify.Event
  38. watcher *fsnotify.Watcher
  39. meta WatchMeta
  40. filename string
  41. filedir string
  42. // The fields below are only used by file watches, and only touched by the
  43. // watcher's own goroutine once it has started.
  44. // watchedPath is the file that was asked for, which may be a symlink.
  45. watchedPath string
  46. // resolvedPath is where watchedPath last pointed, or empty if it has not
  47. // resolved yet.
  48. resolvedPath string
  49. // resolvedDir is the extra directory watched when resolvedPath is in a
  50. // different directory to watchedPath, so in-place edits of a symlink's
  51. // target are seen.
  52. resolvedDir string
  53. interestedEvent fsnotify.Op
  54. }
  55. func WatchDirectoryCreate(fullpath string, callback func(filename string), meta WatchMeta) {
  56. watchPath(&watchContext{
  57. filedir: fullpath,
  58. filename: "",
  59. callback: callback,
  60. interestedEvent: fsnotify.Create,
  61. meta: meta,
  62. }, nil)
  63. }
  64. func WatchDirectoryWrite(fullpath string, callback func(filename string), meta WatchMeta) {
  65. watchPath(&watchContext{
  66. filedir: fullpath,
  67. filename: "",
  68. callback: callback,
  69. interestedEvent: fsnotify.Write,
  70. meta: meta,
  71. }, nil)
  72. }
  73. func WatchFileWrite(fullpath string, callback func(filename string), meta WatchMeta) error {
  74. filename := filepath.Base(fullpath)
  75. filedir := filepath.Dir(fullpath)
  76. watchKey := filepath.Join(filedir, filename)
  77. ctx := &watchContext{
  78. filedir: filedir,
  79. filename: filename,
  80. watchedPath: watchKey,
  81. callback: callback,
  82. interestedEvent: fsnotify.Write,
  83. meta: meta,
  84. }
  85. watcher, err := fsnotify.NewWatcher()
  86. if err != nil {
  87. reportWatcherFailure(ctx, err)
  88. return err
  89. }
  90. if err := watcher.Add(filedir); err != nil {
  91. reportWatcherFailure(ctx, err)
  92. closeWatcher(watcher)
  93. return err
  94. }
  95. ctx.watcher = watcher
  96. refreshResolvedPath(ctx)
  97. done := registerFileWatch(watchKey)
  98. go runWatcher(ctx, watcher, done)
  99. return nil
  100. }
  101. // StopFileWatch stops a file write watcher started by WatchFileWrite.
  102. func StopFileWatch(fullpath string) {
  103. watchKey, err := filepath.Abs(fullpath)
  104. if err != nil {
  105. watchKey = fullpath
  106. }
  107. fileWatchMu.Lock()
  108. done, ok := fileWatchStops[watchKey]
  109. if ok {
  110. delete(fileWatchStops, watchKey)
  111. }
  112. fileWatchMu.Unlock()
  113. if ok {
  114. close(done)
  115. }
  116. }
  117. func registerFileWatch(watchKey string) chan struct{} {
  118. absKey, err := filepath.Abs(watchKey)
  119. if err == nil {
  120. watchKey = absKey
  121. }
  122. done := make(chan struct{})
  123. fileWatchMu.Lock()
  124. if previous, ok := fileWatchStops[watchKey]; ok {
  125. close(previous)
  126. }
  127. fileWatchStops[watchKey] = done
  128. fileWatchMu.Unlock()
  129. return done
  130. }
  131. func watchPath(ctx *watchContext, done <-chan struct{}) {
  132. watcher, err := fsnotify.NewWatcher()
  133. if err != nil {
  134. reportWatcherFailure(ctx, err)
  135. return
  136. }
  137. if err := watcher.Add(ctx.filedir); err != nil {
  138. reportWatcherFailure(ctx, err)
  139. closeWatcher(watcher)
  140. return
  141. }
  142. runWatcher(ctx, watcher, done)
  143. }
  144. func runWatcher(ctx *watchContext, watcher *fsnotify.Watcher, done <-chan struct{}) {
  145. defer closeWatcher(watcher)
  146. for processEvent(ctx, watcher, done) {
  147. }
  148. }
  149. func closeWatcher(watcher *fsnotify.Watcher) {
  150. if err := watcher.Close(); err != nil {
  151. log.Errorf("Failed to close file watcher: %v", err)
  152. }
  153. }
  154. func watchTarget(ctx *watchContext) string {
  155. if ctx.filename == "" {
  156. return ctx.filedir
  157. }
  158. return filepath.Join(ctx.filedir, ctx.filename)
  159. }
  160. func reportWatcherFailure(ctx *watchContext, err error) {
  161. path := watchTarget(ctx)
  162. message := fmt.Sprintf("Could not create watcher for %q: %v", path, err)
  163. configissues.Report(configissues.Issue{
  164. Severity: configissues.SeverityError,
  165. Code: configissues.CodeWatcherPath,
  166. Message: message,
  167. ActionID: ctx.meta.ActionID,
  168. ActionTitle: ctx.meta.ActionTitle,
  169. Source: path,
  170. ConfigFile: ctx.meta.ConfigFile,
  171. })
  172. }
  173. // processEvent waits for one watcher event. It returns false when the watcher
  174. // channels are closed so the caller can stop looping.
  175. func processEvent(ctx *watchContext, watcher *fsnotify.Watcher, done <-chan struct{}) bool {
  176. if done == nil {
  177. return waitForWatcherEvent(ctx, watcher)
  178. }
  179. return waitForWatcherEventOrCancel(ctx, watcher, done)
  180. }
  181. func waitForWatcherEvent(ctx *watchContext, watcher *fsnotify.Watcher) bool {
  182. select {
  183. case event, ok := <-watcher.Events:
  184. return handleWatcherEvent(ctx, event, ok)
  185. case err, ok := <-watcher.Errors:
  186. return handleWatcherError(ctx, err, ok)
  187. }
  188. }
  189. func waitForWatcherEventOrCancel(ctx *watchContext, watcher *fsnotify.Watcher, done <-chan struct{}) bool {
  190. select {
  191. case <-done:
  192. return false
  193. case event, ok := <-watcher.Events:
  194. return !isStopped(done) && handleWatcherEvent(ctx, event, ok)
  195. case err, ok := <-watcher.Errors:
  196. return handleWatcherError(ctx, err, ok)
  197. }
  198. }
  199. // isStopped stops a watch that has been asked to stop even when an event was
  200. // already waiting, because select picks between ready channels at random.
  201. func isStopped(done <-chan struct{}) bool {
  202. select {
  203. case <-done:
  204. return true
  205. default:
  206. return false
  207. }
  208. }
  209. func handleWatcherEvent(ctx *watchContext, event fsnotify.Event, ok bool) bool {
  210. if !ok {
  211. return false
  212. }
  213. ctx.event = &event
  214. consumeEvent(ctx)
  215. return true
  216. }
  217. func handleWatcherError(ctx *watchContext, err error, ok bool) bool {
  218. if !ok {
  219. return false
  220. }
  221. if err != nil {
  222. log.WithFields(log.Fields{
  223. "path": watchTarget(ctx),
  224. }).Errorf("Error in fsnotify: %v", err)
  225. }
  226. return true
  227. }
  228. func consumeEvent(ctx *watchContext) {
  229. if ctx.watchedPath != "" {
  230. consumeFileEvent(ctx)
  231. return
  232. }
  233. if ctx.filename != "" && filepath.Base(ctx.event.Name) != ctx.filename {
  234. log.Tracef("fsnotify irreleventa event different file %+v", ctx.event)
  235. return
  236. }
  237. consumeRelevantEvents(ctx)
  238. }
  239. func consumeRelevantEvents(ctx *watchContext) {
  240. if ctx.event.Has(ctx.interestedEvent) {
  241. log.Debugf("fsnotify event relevant: %v", ctx.event)
  242. processDebounce(ctx)
  243. } else {
  244. log.Debugf("fsnotify event irrelevant: %v", ctx.event)
  245. }
  246. }
  247. // consumeFileEvent decides whether an event means the watched file's content
  248. // may have changed. Writing the file in place gives a Write event, but tools
  249. // that replace a file give other events: editors and mv rename a new file over
  250. // it (Create), and Kubernetes updates a mounted ConfigMap by swapping a
  251. // directory symlink, so the file itself gets no event at all and only the
  252. // target of its symlink changes.
  253. func consumeFileEvent(ctx *watchContext) {
  254. if isWatchedFileChange(ctx) {
  255. consumeWatchedFileChange(ctx)
  256. return
  257. }
  258. if isDirectoryChange(ctx.event) && refreshResolvedPath(ctx) {
  259. log.Debugf("fsnotify symlink target changed for %v: %v", ctx.watchedPath, ctx.event)
  260. processDebounce(ctx)
  261. return
  262. }
  263. log.Tracef("fsnotify event irrelevant: %v", ctx.event)
  264. }
  265. // consumeWatchedFileChange reloads after a write or create at the watched
  266. // path. A create can leave a dangling symlink, so it only reloads once the
  267. // file can be read. A write always reloads, as it always has.
  268. func consumeWatchedFileChange(ctx *watchContext) {
  269. _, resolved := resolveWatchedPath(ctx)
  270. if !resolved && !ctx.event.Has(fsnotify.Write) {
  271. log.Debugf("fsnotify event waiting for %v to resolve: %v", ctx.watchedPath, ctx.event)
  272. return
  273. }
  274. log.Debugf("fsnotify event relevant: %v", ctx.event)
  275. processDebounce(ctx)
  276. }
  277. func isWatchedFileChange(ctx *watchContext) bool {
  278. if !ctx.event.Has(fsnotify.Write) && !ctx.event.Has(fsnotify.Create) {
  279. return false
  280. }
  281. name := filepath.Clean(ctx.event.Name)
  282. return name == ctx.watchedPath || (ctx.resolvedPath != "" && name == ctx.resolvedPath)
  283. }
  284. func isDirectoryChange(event *fsnotify.Event) bool {
  285. return event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove)
  286. }
  287. // refreshResolvedPath checks where the watched file points now, and reports
  288. // whether that changed. While the file is missing or a symlink is dangling,
  289. // for example part way through a replacement, the last target is kept and no
  290. // change is reported, so the file is not reloaded until it can be read.
  291. func refreshResolvedPath(ctx *watchContext) bool {
  292. changed, _ := resolveWatchedPath(ctx)
  293. return changed
  294. }
  295. // resolveWatchedPath updates where the watched file points. It reports
  296. // whether the target changed, and separately whether the file resolved at
  297. // all.
  298. func resolveWatchedPath(ctx *watchContext) (changed bool, resolved bool) {
  299. target, err := filepath.EvalSymlinks(ctx.watchedPath)
  300. if err != nil {
  301. log.Debugf("fsnotify could not resolve %v: %v", ctx.watchedPath, err)
  302. return false, false
  303. }
  304. if target == ctx.resolvedPath {
  305. return false, true
  306. }
  307. ctx.resolvedPath = target
  308. watchResolvedDir(ctx, filepath.Dir(target))
  309. return true, true
  310. }
  311. func watchResolvedDir(ctx *watchContext, dir string) {
  312. if dir == ctx.resolvedDir {
  313. return
  314. }
  315. unwatchResolvedDir(ctx)
  316. // The directory may be the watched directory reached through a symlink.
  317. // inotify gives both paths the same watch, so adding it again would rename
  318. // that watch, and removing it later would stop the main watch.
  319. if sameDirectory(dir, ctx.filedir) {
  320. return
  321. }
  322. if err := ctx.watcher.Add(dir); err != nil {
  323. log.WithFields(log.Fields{
  324. "path": ctx.watchedPath,
  325. "dir": dir,
  326. }).Warnf("Could not watch the directory a symlink points to, so edits there will not be seen: %v", err)
  327. return
  328. }
  329. ctx.resolvedDir = dir
  330. }
  331. func unwatchResolvedDir(ctx *watchContext) {
  332. if ctx.resolvedDir == "" {
  333. return
  334. }
  335. // A ConfigMap's old directory has already been deleted by now, and the
  336. // watch went with it, so an error here is expected.
  337. if err := ctx.watcher.Remove(ctx.resolvedDir); err != nil {
  338. log.Debugf("fsnotify could not stop watching %v: %v", ctx.resolvedDir, err)
  339. }
  340. ctx.resolvedDir = ""
  341. }
  342. func sameDirectory(left, right string) bool {
  343. leftInfo, err := os.Stat(left)
  344. if err != nil {
  345. return false
  346. }
  347. rightInfo, err := os.Stat(right)
  348. if err != nil {
  349. return false
  350. }
  351. return os.SameFile(leftInfo, rightInfo)
  352. }
  353. // debounceKey keeps file watches apart by their whole path, so two files with
  354. // the same name in different directories do not suppress each other.
  355. // Directory watches keep their existing key.
  356. func debounceKey(ctx *watchContext) string {
  357. if ctx.watchedPath != "" {
  358. return ctx.watchedPath
  359. }
  360. return ctx.filename
  361. }
  362. func processDebounce(ctx *watchContext) {
  363. debounceWriteLogMutex.Lock()
  364. key := debounceKey(ctx)
  365. logEntry, found := debounceWriteLog[key]
  366. if !found {
  367. logEntry = &FsNotifyLogEntry{
  368. callbackComplete: false,
  369. callbackWrapper: nil,
  370. }
  371. debounceWriteLog[key] = logEntry
  372. }
  373. log.Debugf("fsnotify event %+v", logEntry)
  374. if logEntry.callbackComplete || logEntry.callbackWrapper == nil {
  375. log.Debugf("fsnotify event callback queued within debounce delay: %v", ctx.filename)
  376. callback := ctx.callback
  377. eventName := ctx.event.Name
  378. logEntry.callbackComplete = false
  379. logEntry.callbackWrapper = time.AfterFunc(debounceDelay, func() {
  380. log.Debugf("fsnotify event callback being fired: %v", eventName)
  381. callback(eventName)
  382. debounceWriteLogMutex.Lock()
  383. logEntry.callbackComplete = true
  384. debounceWriteLogMutex.Unlock()
  385. })
  386. } else {
  387. log.Debugf("fsnotify event suppressed because it's within the debounce delay: %v", ctx.filename)
  388. }
  389. debounceWriteLogMutex.Unlock()
  390. }