inotify.py 14 KB

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