Files
podman/pkg/hooks/monitor.go
samc24 d6ea4b4139 Improved hooks monitoring
...to work for specific edge cases with a simpler solution.
Re-reads hooks directories after any changes are detected by the watchers.
Added monitoring test for adding a different invalid hook to primary directory.
Some issues with prior code:
- ReadDir would stop when it encounters an invalid hook, rather than registering an error but continuing to read the valid hook.
- Wouldn’t account for Rename and Chmod events.
- After doing a mv of the hooks file instead of rm, it would still think the hooks file is in the directory, but it has been moved to another location.
- If a hook file was renamed, it would register the renamed file as a separate hook and not delete the original, so it would then execute the hook twice - once for the renamed file, and once for the original name which it did not delete.

Signed-off-by: samc24 <sam.chaturvedi24@gmail.com>
2019-07-25 09:52:45 -04:00

67 lines
1.6 KiB
Go

package hooks
import (
"context"
current "github.com/containers/libpod/pkg/hooks/1.0.0"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
)
// Monitor dynamically monitors hook directories for additions,
// updates, and removals.
//
// This function writes two empty structs to the sync channel: the
// first is written after the watchers are established and the second
// when this function exits. The expected usage is:
//
// ctx, cancel := context.WithCancel(context.Background())
// sync := make(chan error, 2)
// go m.Monitor(ctx, sync)
// err := <-sync // block until writers are established
// if err != nil {
// return err // failed to establish watchers
// }
// // do stuff
// cancel()
// err = <-sync // block until monitor finishes
func (m *Manager) Monitor(ctx context.Context, sync chan<- error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
sync <- err
return
}
defer watcher.Close()
for _, dir := range m.directories {
err = watcher.Add(dir)
if err != nil {
logrus.Errorf("failed to watch %q for hooks", dir)
sync <- err
return
}
logrus.Debugf("monitoring %q for hooks", dir)
}
sync <- nil
for {
select {
case event := <-watcher.Events:
m.hooks = make(map[string]*current.Hook)
for _, dir := range m.directories {
err = ReadDir(dir, m.extensionStages, m.hooks)
if err != nil {
logrus.Errorf("failed loading hooks for %s: %v", event.Name, err)
}
}
case <-ctx.Done():
err = ctx.Err()
logrus.Debugf("hook monitoring canceled: %v", err)
sync <- err
close(sync)
return
}
}
}