watcher.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package filesystem
  14. import (
  15. "github.com/fsnotify/fsnotify"
  16. )
  17. // FSWatcher is a callback-based filesystem watcher abstraction for fsnotify.
  18. type FSWatcher interface {
  19. // Initializes the watcher with the given watch handlers.
  20. // Called before all other methods.
  21. Init(FSEventHandler, FSErrorHandler) error
  22. // Starts listening for events and errors.
  23. // When an event or error occurs, the corresponding handler is called.
  24. Run()
  25. // Add a filesystem path to watch
  26. AddWatch(path string) error
  27. }
  28. // FSEventHandler is called when a fsnotify event occurs.
  29. type FSEventHandler func(event fsnotify.Event)
  30. // FSErrorHandler is called when a fsnotify error occurs.
  31. type FSErrorHandler func(err error)
  32. type fsnotifyWatcher struct {
  33. watcher *fsnotify.Watcher
  34. eventHandler FSEventHandler
  35. errorHandler FSErrorHandler
  36. }
  37. var _ FSWatcher = &fsnotifyWatcher{}
  38. // NewFsnotifyWatcher returns an implementation of FSWatcher that continuously listens for
  39. // fsnotify events and calls the event handler as soon as an event is received.
  40. func NewFsnotifyWatcher() FSWatcher {
  41. return &fsnotifyWatcher{}
  42. }
  43. func (w *fsnotifyWatcher) AddWatch(path string) error {
  44. return w.watcher.Add(path)
  45. }
  46. func (w *fsnotifyWatcher) Init(eventHandler FSEventHandler, errorHandler FSErrorHandler) error {
  47. var err error
  48. w.watcher, err = fsnotify.NewWatcher()
  49. if err != nil {
  50. return err
  51. }
  52. w.eventHandler = eventHandler
  53. w.errorHandler = errorHandler
  54. return nil
  55. }
  56. func (w *fsnotifyWatcher) Run() {
  57. go func() {
  58. defer w.watcher.Close()
  59. for {
  60. select {
  61. case event := <-w.watcher.Events:
  62. if w.eventHandler != nil {
  63. w.eventHandler(event)
  64. }
  65. case err := <-w.watcher.Errors:
  66. if w.errorHandler != nil {
  67. w.errorHandler(err)
  68. }
  69. }
  70. }
  71. }()
  72. }