github.com/Azure/aad-pod-identity@v1.8.17/pkg/filewatcher/filewatcher.go (about) 1 package filewatcher 2 3 import ( 4 "github.com/fsnotify/fsnotify" 5 "k8s.io/klog/v2" 6 ) 7 8 // EventHandler is called when a fsnotify event occurs. 9 type EventHandler func(fsnotify.Event) 10 11 // ErrorHandler is called when a fsnotify error occurs. 12 type ErrorHandler func(error) 13 14 // ClientInt is a file watcher abstraction based on fsnotify. 15 type ClientInt interface { 16 Add(path string) error 17 Start(exit <-chan struct{}) 18 } 19 20 // client is an implementation of ClientInt. 21 type client struct { 22 watcher *fsnotify.Watcher 23 eventHandler EventHandler 24 errorHandler ErrorHandler 25 } 26 27 var _ ClientInt = &client{} 28 29 // NewFileWatcher returns an implementation of ClientInt that continuously listens 30 // for fsnotify events and calls the event handler as soon as an event is received. 31 func NewFileWatcher(eventHandler EventHandler, errorHandler ErrorHandler) (ClientInt, error) { 32 watcher, err := fsnotify.NewWatcher() 33 if err != nil { 34 return nil, err 35 } 36 37 return &client{ 38 watcher: watcher, 39 eventHandler: eventHandler, 40 errorHandler: errorHandler, 41 }, nil 42 } 43 44 // Add adds a file path to watch. 45 func (c *client) Add(path string) error { 46 return c.watcher.Add(path) 47 } 48 49 // Start starts watching all registered files for events. 50 func (c *client) Start(exit <-chan struct{}) { 51 go func() { 52 defer c.watcher.Close() 53 for { 54 select { 55 case <-exit: 56 return 57 case event := <-c.watcher.Events: 58 klog.Infof("detected file modification: %s", event.String()) 59 if c.eventHandler != nil { 60 c.eventHandler(event) 61 } 62 case err := <-c.watcher.Errors: 63 if c.errorHandler != nil { 64 c.errorHandler(err) 65 } 66 } 67 } 68 }() 69 }