gunk-dev/the-valley

wake_linux.go

sourcec1620ef8763amain's published tip history
5.7 KiB
1//go:build linux
2
3package main
4
5import (
6 "encoding/binary"
7 "errors"
8 "fmt"
9 "io/fs"
10 "os"
11 "path/filepath"
12 "syscall"
13)
14
15// wakeSupported says whether watch can be given --woken-by here.
16const wakeSupported = true
17
18// watchOpened, when set, runs once watchDir has opened and locked the
19// directory and before it watches it. Tests set it to replace the
20// directory there.
21var watchOpened func()
22
23// inotifyWatch watches one wake directory for a created or moved-in due.
24//
25// It holds the directory open, and everything it does goes through that
26// descriptor: the inotify watch is on the directory it holds, and due is
27// looked for and removed there. So the watch and the marks it consumes are
28// always one directory's, whatever the path comes to name. A goroutine
29// reads the inotify descriptor through the runtime's poller, so closing the
30// file ends the read.
31type inotifyWatch struct {
32 path string
33 dir *os.File // the directory, held open and locked
34 held string // the directory as /proc/self/fd names the one held
35 f *os.File // the inotify descriptor
36 dirWd int32
37 parent int32 // the watch on the parent, for the directory's own name
38 note chan struct{}
39 end chan error
40}
41
42// watchDir watches dir. It opens the directory and takes the consumer's
43// lock on it, so a second controller given the same directory does not
44// consume its marks. It watches the directory it opened, through
45// /proc/self/fd, and the parent for the directory's name, so a directory
46// removed, moved or replaced at the path ends the watch at once, even
47// though the descriptor it holds keeps the old directory alive. Then it
48// checks that the path still names the directory it holds. A directory
49// replaced before the watch was in place fails that check, and the watch
50// is not made. Every descriptor a failure leaves open is closed.
51func watchDir(path string) (watcher, error) {
52 dir, err := os.Open(path)
53 if err != nil {
54 return nil, err
55 }
56 w := &inotifyWatch{
57 path: path,
58 dir: dir,
59 held: fmt.Sprintf("/proc/self/fd/%d", dir.Fd()),
60 note: make(chan struct{}, 1),
61 end: make(chan error, 1),
62 }
63 fail := func(err error) (watcher, error) {
64 if w.f != nil {
65 w.f.Close()
66 }
67 dir.Close()
68 return nil, err
69 }
70 if err := syscall.Flock(int(dir.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
71 if errors.Is(err, syscall.EWOULDBLOCK) {
72 return fail(errors.New("another controller consumes its marks"))
73 }
74 return fail(os.NewSyscallError("flock", err))
75 }
76 if watchOpened != nil {
77 watchOpened()
78 }
79 fd, err := syscall.InotifyInit1(syscall.IN_CLOEXEC | syscall.IN_NONBLOCK)
80 if err != nil {
81 return fail(os.NewSyscallError("inotify_init1", err))
82 }
83 w.f = os.NewFile(uintptr(fd), "inotify")
84 wd, err := syscall.InotifyAddWatch(fd, w.held, syscall.IN_CREATE|syscall.IN_MOVED_TO|syscall.IN_ONLYDIR|
85 syscall.IN_DELETE_SELF|syscall.IN_MOVE_SELF)
86 if err != nil {
87 return fail(os.NewSyscallError("inotify_add_watch", err))
88 }
89 w.dirWd = int32(wd)
90 wd, err = syscall.InotifyAddWatch(fd, filepath.Dir(path), syscall.IN_CREATE|syscall.IN_DELETE|
91 syscall.IN_MOVED_FROM|syscall.IN_MOVED_TO|syscall.IN_ONLYDIR|syscall.IN_DELETE_SELF|syscall.IN_MOVE_SELF)
92 if err != nil {
93 return fail(fmt.Errorf("watching its parent: %w", os.NewSyscallError("inotify_add_watch", err)))
94 }
95 w.parent = int32(wd)
96 if !w.same() {
97 return fail(fmt.Errorf("another directory took its place while it was being watched"))
98 }
99 go w.read()
100 return w, nil
101}
102
103// same says whether the path still names the directory the watch holds.
104func (w *inotifyWatch) same() bool {
105 held, err := w.dir.Stat()
106 if err != nil {
107 return false
108 }
109 now, err := os.Stat(w.path)
110 return err == nil && os.SameFile(held, now)
111}
112
113func (w *inotifyWatch) events() <-chan struct{} { return w.note }
114func (w *inotifyWatch) failed() <-chan error { return w.end }
115
116func (w *inotifyWatch) close() {
117 w.f.Close()
118 w.dir.Close()
119}
120
121// removeDue removes due from the directory the watch holds.
122func (w *inotifyWatch) removeDue() error {
123 err := os.Remove(filepath.Join(w.held, "due"))
124 if errors.Is(err, fs.ErrNotExist) {
125 return nil
126 }
127 return err
128}
129
130// hasDue says whether due is in the directory the watch holds.
131func (w *inotifyWatch) hasDue() bool {
132 _, err := os.Lstat(filepath.Join(w.held, "due"))
133 return err == nil
134}
135
136func (w *inotifyWatch) notify() {
137 select {
138 case w.note <- struct{}{}:
139 default:
140 }
141}
142
143func (w *inotifyWatch) read() {
144 base := filepath.Base(w.path)
145 buf := make([]byte, 64*(syscall.SizeofInotifyEvent+syscall.NAME_MAX+1))
146 for {
147 n, err := w.f.Read(buf)
148 if err != nil {
149 w.end <- fmt.Errorf("reading its events: %w", err)
150 return
151 }
152 for off := 0; off+syscall.SizeofInotifyEvent <= n; {
153 wd := int32(binary.NativeEndian.Uint32(buf[off:]))
154 mask := binary.NativeEndian.Uint32(buf[off+4:])
155 size := int(binary.NativeEndian.Uint32(buf[off+12:]))
156 name := string(trimNUL(buf[off+syscall.SizeofInotifyEvent : min(n, off+syscall.SizeofInotifyEvent+size)]))
157 off += syscall.SizeofInotifyEvent + size
158 self := uint32(syscall.IN_IGNORED | syscall.IN_DELETE_SELF | syscall.IN_MOVE_SELF | syscall.IN_UNMOUNT)
159 switch {
160 case mask&syscall.IN_Q_OVERFLOW != 0:
161 // Events were dropped, and one may have been the
162 // directory's replacement, so the path is checked. due is
163 // on disk, so a look at it is all any other was worth.
164 if !w.same() {
165 w.end <- errGone
166 return
167 }
168 w.notify()
169 case mask&self != 0:
170 w.end <- errGone
171 return
172 case wd == w.parent:
173 if name == base {
174 w.end <- errGone
175 return
176 }
177 case wd == w.dirWd && name == "due" && mask&(syscall.IN_CREATE|syscall.IN_MOVED_TO) != 0:
178 w.notify()
179 }
180 }
181 }
182}
183
184func trimNUL(b []byte) []byte {
185 for len(b) > 0 && b[len(b)-1] == 0 {
186 b = b[:len(b)-1]
187 }
188 return b
189}