1
0
dwelling-upload/pkg/watcher/linux.go

83 lines
1.6 KiB
Go
Raw Normal View History

package watcher
import (
"syscall"
"unsafe"
"github.com/pkg/errors"
)
const CrDelMask uint32 = syscall.IN_CREATE | syscall.IN_DELETE
const inotifyCount = 16
2022-03-07 23:12:02 +04:00
type InotifyWatcher struct {
fd int
wds []int
closed bool
}
2022-03-07 23:12:02 +04:00
func NewInotifyWatcher() (w *InotifyWatcher, err error) {
w = &InotifyWatcher{closed: false}
2022-03-07 23:12:02 +04:00
w.fd, err = syscall.InotifyInit()
if err != nil {
return nil, errors.Wrap(err, "failed to initialise inotify watcher")
}
2022-03-07 23:12:02 +04:00
w.wds = make([]int, 0)
2022-03-07 23:12:02 +04:00
return w, nil
}
2022-03-07 23:12:02 +04:00
func (w *InotifyWatcher) AddWatch(path string, mask uint32) error {
wd, err := syscall.InotifyAddWatch(w.fd, path, mask)
if err != nil {
return errors.Wrapf(err, "failed to set %s on watch", path)
}
2022-03-07 23:12:02 +04:00
w.wds = append(w.wds, wd)
return nil
}
// WatchForMask checking for events from mask and returns inotify mask to channel.
2022-03-07 23:12:02 +04:00
func (w *InotifyWatcher) WatchForMask(fired chan uint32, mask uint32) {
go func() {
2022-03-07 23:12:02 +04:00
for !w.closed {
buffer := make([]byte, syscall.SizeofInotifyEvent*inotifyCount)
2022-03-07 23:12:02 +04:00
n, err := syscall.Read(w.fd, buffer)
if err != nil {
break
}
if n < syscall.SizeofInotifyEvent {
continue
}
for offset := 0; offset < len(buffer); offset += syscall.SizeofInotifyEvent {
event := (*syscall.InotifyEvent)(unsafe.Pointer(&buffer[offset]))
if event.Mask&mask > 0 {
fired <- event.Mask
}
}
}
}()
}
2022-03-07 23:12:02 +04:00
func (w *InotifyWatcher) Close() error {
for _, wd := range w.wds {
if _, err := syscall.InotifyRmWatch(w.fd, uint32(wd)); err != nil {
return err
}
}
2022-03-07 23:12:02 +04:00
if err := syscall.Close(w.fd); err != nil {
return err
}
2022-03-07 23:12:02 +04:00
w.closed = true
return nil
}