inotify.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. # -*- test-case-name: twisted.internet.test.test_inotify -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. This module provides support for Twisted to linux inotify API.
  6. In order to use this support, simply do the following (and start a reactor
  7. at some point)::
  8. from twisted.internet import inotify
  9. from twisted.python import filepath
  10. def notify(ignored, filepath, mask):
  11. \"""
  12. For historical reasons, an opaque handle is passed as first
  13. parameter. This object should never be used.
  14. @param filepath: FilePath on which the event happened.
  15. @param mask: inotify event as hexadecimal masks
  16. \"""
  17. print("event %s on %s" % (
  18. ', '.join(inotify.humanReadableMask(mask)), filepath))
  19. notifier = inotify.INotify()
  20. notifier.startReading()
  21. notifier.watch(filepath.FilePath("/some/directory"), callbacks=[notify])
  22. notifier.watch(filepath.FilePath(b"/some/directory2"), callbacks=[notify])
  23. Note that in the above example, a L{FilePath} which is a L{bytes} path name
  24. or L{str} path name may be used. However, no matter what type of
  25. L{FilePath} is passed to this module, internally the L{FilePath} is
  26. converted to L{bytes} according to L{sys.getfilesystemencoding}.
  27. For any L{FilePath} returned by this module, the caller is responsible for
  28. converting from a L{bytes} path name to a L{str} path name.
  29. @since: 10.1
  30. """
  31. import os
  32. import struct
  33. from twisted.internet import fdesc
  34. from twisted.internet.abstract import FileDescriptor
  35. from twisted.python import _inotify, log
  36. # from /usr/src/linux/include/linux/inotify.h
  37. IN_ACCESS = 0x00000001 # File was accessed
  38. IN_MODIFY = 0x00000002 # File was modified
  39. IN_ATTRIB = 0x00000004 # Metadata changed
  40. IN_CLOSE_WRITE = 0x00000008 # Writeable file was closed
  41. IN_CLOSE_NOWRITE = 0x00000010 # Unwriteable file closed
  42. IN_OPEN = 0x00000020 # File was opened
  43. IN_MOVED_FROM = 0x00000040 # File was moved from X
  44. IN_MOVED_TO = 0x00000080 # File was moved to Y
  45. IN_CREATE = 0x00000100 # Subfile was created
  46. IN_DELETE = 0x00000200 # Subfile was delete
  47. IN_DELETE_SELF = 0x00000400 # Self was deleted
  48. IN_MOVE_SELF = 0x00000800 # Self was moved
  49. IN_UNMOUNT = 0x00002000 # Backing fs was unmounted
  50. IN_Q_OVERFLOW = 0x00004000 # Event queued overflowed
  51. IN_IGNORED = 0x00008000 # File was ignored
  52. IN_ONLYDIR = 0x01000000 # only watch the path if it is a directory
  53. IN_DONT_FOLLOW = 0x02000000 # don't follow a sym link
  54. IN_MASK_ADD = 0x20000000 # add to the mask of an already existing watch
  55. IN_ISDIR = 0x40000000 # event occurred against dir
  56. IN_ONESHOT = 0x80000000 # only send event once
  57. IN_CLOSE = IN_CLOSE_WRITE | IN_CLOSE_NOWRITE # closes
  58. IN_MOVED = IN_MOVED_FROM | IN_MOVED_TO # moves
  59. IN_CHANGED = IN_MODIFY | IN_ATTRIB # changes
  60. IN_WATCH_MASK = (
  61. IN_MODIFY
  62. | IN_ATTRIB
  63. | IN_CREATE
  64. | IN_DELETE
  65. | IN_DELETE_SELF
  66. | IN_MOVE_SELF
  67. | IN_UNMOUNT
  68. | IN_MOVED_FROM
  69. | IN_MOVED_TO
  70. )
  71. _FLAG_TO_HUMAN = [
  72. (IN_ACCESS, "access"),
  73. (IN_MODIFY, "modify"),
  74. (IN_ATTRIB, "attrib"),
  75. (IN_CLOSE_WRITE, "close_write"),
  76. (IN_CLOSE_NOWRITE, "close_nowrite"),
  77. (IN_OPEN, "open"),
  78. (IN_MOVED_FROM, "moved_from"),
  79. (IN_MOVED_TO, "moved_to"),
  80. (IN_CREATE, "create"),
  81. (IN_DELETE, "delete"),
  82. (IN_DELETE_SELF, "delete_self"),
  83. (IN_MOVE_SELF, "move_self"),
  84. (IN_UNMOUNT, "unmount"),
  85. (IN_Q_OVERFLOW, "queue_overflow"),
  86. (IN_IGNORED, "ignored"),
  87. (IN_ONLYDIR, "only_dir"),
  88. (IN_DONT_FOLLOW, "dont_follow"),
  89. (IN_MASK_ADD, "mask_add"),
  90. (IN_ISDIR, "is_dir"),
  91. (IN_ONESHOT, "one_shot"),
  92. ]
  93. def humanReadableMask(mask):
  94. """
  95. Auxiliary function that converts a hexadecimal mask into a series
  96. of human readable flags.
  97. """
  98. s = []
  99. for k, v in _FLAG_TO_HUMAN:
  100. if k & mask:
  101. s.append(v)
  102. return s
  103. class _Watch:
  104. """
  105. Watch object that represents a Watch point in the filesystem. The
  106. user should let INotify to create these objects
  107. @ivar path: The path over which this watch point is monitoring
  108. @ivar mask: The events monitored by this watchpoint
  109. @ivar autoAdd: Flag that determines whether this watch point
  110. should automatically add created subdirectories
  111. @ivar callbacks: L{list} of callback functions that will be called
  112. when an event occurs on this watch.
  113. """
  114. def __init__(self, path, mask=IN_WATCH_MASK, autoAdd=False, callbacks=None):
  115. self.path = path.asBytesMode()
  116. self.mask = mask
  117. self.autoAdd = autoAdd
  118. if callbacks is None:
  119. callbacks = []
  120. self.callbacks = callbacks
  121. def _notify(self, filepath, events):
  122. """
  123. Callback function used by L{INotify} to dispatch an event.
  124. """
  125. filepath = filepath.asBytesMode()
  126. for callback in self.callbacks:
  127. callback(self, filepath, events)
  128. class INotify(FileDescriptor):
  129. """
  130. The INotify file descriptor, it basically does everything related
  131. to INotify, from reading to notifying watch points.
  132. @ivar _buffer: a L{bytes} containing the data read from the inotify fd.
  133. @ivar _watchpoints: a L{dict} that maps from inotify watch ids to
  134. watchpoints objects
  135. @ivar _watchpaths: a L{dict} that maps from watched paths to the
  136. inotify watch ids
  137. """
  138. _inotify = _inotify
  139. def __init__(self, reactor=None):
  140. FileDescriptor.__init__(self, reactor=reactor)
  141. # Smart way to allow parametrization of libc so I can override
  142. # it and test for the system errors.
  143. self._fd = self._inotify.init()
  144. fdesc.setNonBlocking(self._fd)
  145. fdesc._setCloseOnExec(self._fd)
  146. # The next 2 lines are needed to have self.loseConnection()
  147. # to call connectionLost() on us. Since we already created the
  148. # fd that talks to inotify we want to be notified even if we
  149. # haven't yet started reading.
  150. self.connected = 1
  151. self._writeDisconnected = True
  152. self._buffer = b""
  153. self._watchpoints = {}
  154. self._watchpaths = {}
  155. def _addWatch(self, path, mask, autoAdd, callbacks):
  156. """
  157. Private helper that abstracts the use of ctypes.
  158. Calls the internal inotify API and checks for any errors after the
  159. call. If there's an error L{INotify._addWatch} can raise an
  160. INotifyError. If there's no error it proceeds creating a watchpoint and
  161. adding a watchpath for inverse lookup of the file descriptor from the
  162. path.
  163. """
  164. path = path.asBytesMode()
  165. wd = self._inotify.add(self._fd, path, mask)
  166. iwp = _Watch(path, mask, autoAdd, callbacks)
  167. self._watchpoints[wd] = iwp
  168. self._watchpaths[path] = wd
  169. return wd
  170. def _rmWatch(self, wd):
  171. """
  172. Private helper that abstracts the use of ctypes.
  173. Calls the internal inotify API to remove an fd from inotify then
  174. removes the corresponding watchpoint from the internal mapping together
  175. with the file descriptor from the watchpath.
  176. """
  177. self._inotify.remove(self._fd, wd)
  178. iwp = self._watchpoints.pop(wd)
  179. self._watchpaths.pop(iwp.path)
  180. def connectionLost(self, reason):
  181. """
  182. Release the inotify file descriptor and do the necessary cleanup
  183. """
  184. FileDescriptor.connectionLost(self, reason)
  185. if self._fd >= 0:
  186. try:
  187. os.close(self._fd)
  188. except OSError as e:
  189. log.err(e, "Couldn't close INotify file descriptor.")
  190. def fileno(self):
  191. """
  192. Get the underlying file descriptor from this inotify observer.
  193. Required by L{abstract.FileDescriptor} subclasses.
  194. """
  195. return self._fd
  196. def doRead(self):
  197. """
  198. Read some data from the observed file descriptors
  199. """
  200. fdesc.readFromFD(self._fd, self._doRead)
  201. def _doRead(self, in_):
  202. """
  203. Work on the data just read from the file descriptor.
  204. """
  205. self._buffer += in_
  206. while len(self._buffer) >= 16:
  207. wd, mask, cookie, size = struct.unpack("=LLLL", self._buffer[0:16])
  208. if size:
  209. name = self._buffer[16 : 16 + size].rstrip(b"\0")
  210. else:
  211. name = None
  212. self._buffer = self._buffer[16 + size :]
  213. try:
  214. iwp = self._watchpoints[wd]
  215. except KeyError:
  216. continue
  217. path = iwp.path.asBytesMode()
  218. if name:
  219. path = path.child(name)
  220. iwp._notify(path, mask)
  221. if iwp.autoAdd and mask & IN_ISDIR and mask & IN_CREATE:
  222. # mask & IN_ISDIR already guarantees that the path is a
  223. # directory. There's no way you can get here without a
  224. # directory anyway, so no point in checking for that again.
  225. new_wd = self.watch(
  226. path, mask=iwp.mask, autoAdd=True, callbacks=iwp.callbacks
  227. )
  228. # This is very very very hacky and I'd rather not do this but
  229. # we have no other alternative that is less hacky other than
  230. # surrender. We use callLater because we don't want to have
  231. # too many events waiting while we process these subdirs, we
  232. # must always answer events as fast as possible or the overflow
  233. # might come.
  234. self.reactor.callLater(0, self._addChildren, self._watchpoints[new_wd])
  235. if mask & IN_DELETE_SELF:
  236. self._rmWatch(wd)
  237. self.loseConnection()
  238. def _addChildren(self, iwp):
  239. """
  240. This is a very private method, please don't even think about using it.
  241. Note that this is a fricking hack... it's because we cannot be fast
  242. enough in adding a watch to a directory and so we basically end up
  243. getting here too late if some operations have already been going on in
  244. the subdir, we basically need to catchup. This eventually ends up
  245. meaning that we generate double events, your app must be resistant.
  246. """
  247. try:
  248. listdir = iwp.path.children()
  249. except OSError:
  250. # Somebody or something (like a test) removed this directory while
  251. # we were in the callLater(0...) waiting. It doesn't make sense to
  252. # process it anymore
  253. return
  254. # note that it's true that listdir will only see the subdirs inside
  255. # path at the moment of the call but path is monitored already so if
  256. # something is created we will receive an event.
  257. for f in listdir:
  258. # It's a directory, watch it and then add its children
  259. if f.isdir():
  260. wd = self.watch(f, mask=iwp.mask, autoAdd=True, callbacks=iwp.callbacks)
  261. iwp._notify(f, IN_ISDIR | IN_CREATE)
  262. # now f is watched, we can add its children the callLater is to
  263. # avoid recursion
  264. self.reactor.callLater(0, self._addChildren, self._watchpoints[wd])
  265. # It's a file and we notify it.
  266. if f.isfile():
  267. iwp._notify(f, IN_CREATE | IN_CLOSE_WRITE)
  268. def watch(
  269. self, path, mask=IN_WATCH_MASK, autoAdd=False, callbacks=None, recursive=False
  270. ):
  271. """
  272. Watch the 'mask' events in given path. Can raise C{INotifyError} when
  273. there's a problem while adding a directory.
  274. @param path: The path needing monitoring
  275. @type path: L{FilePath}
  276. @param mask: The events that should be watched
  277. @type mask: L{int}
  278. @param autoAdd: if True automatically add newly created
  279. subdirectories
  280. @type autoAdd: L{bool}
  281. @param callbacks: A list of callbacks that should be called
  282. when an event happens in the given path.
  283. The callback should accept 3 arguments:
  284. (ignored, filepath, mask)
  285. @type callbacks: L{list} of callables
  286. @param recursive: Also add all the subdirectories in this path
  287. @type recursive: L{bool}
  288. """
  289. if recursive:
  290. # This behavior is needed to be compatible with the windows
  291. # interface for filesystem changes:
  292. # http://msdn.microsoft.com/en-us/library/aa365465(VS.85).aspx
  293. # ReadDirectoryChangesW can do bWatchSubtree so it doesn't
  294. # make sense to implement this at a higher abstraction
  295. # level when other platforms support it already
  296. for child in path.walk():
  297. if child.isdir():
  298. self.watch(child, mask, autoAdd, callbacks, recursive=False)
  299. else:
  300. wd = self._isWatched(path)
  301. if wd:
  302. return wd
  303. mask = mask | IN_DELETE_SELF # need this to remove the watch
  304. return self._addWatch(path, mask, autoAdd, callbacks)
  305. def ignore(self, path):
  306. """
  307. Remove the watch point monitoring the given path
  308. @param path: The path that should be ignored
  309. @type path: L{FilePath}
  310. """
  311. path = path.asBytesMode()
  312. wd = self._isWatched(path)
  313. if wd is None:
  314. raise KeyError(f"{path!r} is not watched")
  315. else:
  316. self._rmWatch(wd)
  317. def _isWatched(self, path):
  318. """
  319. Helper function that checks if the path is already monitored
  320. and returns its watchdescriptor if so or None otherwise.
  321. @param path: The path that should be checked
  322. @type path: L{FilePath}
  323. """
  324. path = path.asBytesMode()
  325. return self._watchpaths.get(path, None)
  326. INotifyError = _inotify.INotifyError
  327. __all__ = [
  328. "INotify",
  329. "humanReadableMask",
  330. "IN_WATCH_MASK",
  331. "IN_ACCESS",
  332. "IN_MODIFY",
  333. "IN_ATTRIB",
  334. "IN_CLOSE_NOWRITE",
  335. "IN_CLOSE_WRITE",
  336. "IN_OPEN",
  337. "IN_MOVED_FROM",
  338. "IN_MOVED_TO",
  339. "IN_CREATE",
  340. "IN_DELETE",
  341. "IN_DELETE_SELF",
  342. "IN_MOVE_SELF",
  343. "IN_UNMOUNT",
  344. "IN_Q_OVERFLOW",
  345. "IN_IGNORED",
  346. "IN_ONLYDIR",
  347. "IN_DONT_FOLLOW",
  348. "IN_MASK_ADD",
  349. "IN_ISDIR",
  350. "IN_ONESHOT",
  351. "IN_CLOSE",
  352. "IN_MOVED",
  353. "IN_CHANGED",
  354. ]