inotify_c.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
  4. # Copyright 2012 Google, Inc.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. from __future__ import with_statement
  18. import os
  19. import errno
  20. import struct
  21. import threading
  22. import ctypes
  23. import ctypes.util
  24. from functools import reduce
  25. from ctypes import c_int, c_char_p, c_uint32
  26. from watchdog.utils import has_attribute
  27. from watchdog.utils import UnsupportedLibc
  28. from watchdog.utils.unicode_paths import decode
  29. def _load_libc():
  30. libc_path = None
  31. try:
  32. libc_path = ctypes.util.find_library('c')
  33. except (OSError, IOError, RuntimeError):
  34. # Note: find_library will on some platforms raise these undocumented
  35. # errors, e.g.on android IOError "No usable temporary directory found"
  36. # will be raised.
  37. pass
  38. if libc_path is not None:
  39. return ctypes.CDLL(libc_path)
  40. # Fallbacks
  41. try:
  42. return ctypes.CDLL('libc.so')
  43. except (OSError, IOError):
  44. pass
  45. try:
  46. return ctypes.CDLL('libc.so.6')
  47. except (OSError, IOError):
  48. pass
  49. # uClibc
  50. try:
  51. return ctypes.CDLL('libc.so.0')
  52. except (OSError, IOError) as err:
  53. raise err
  54. libc = _load_libc()
  55. if not has_attribute(libc, 'inotify_init') or \
  56. not has_attribute(libc, 'inotify_add_watch') or \
  57. not has_attribute(libc, 'inotify_rm_watch'):
  58. raise UnsupportedLibc("Unsupported libc version found: %s" % libc._name)
  59. inotify_add_watch = ctypes.CFUNCTYPE(c_int, c_int, c_char_p, c_uint32, use_errno=True)(
  60. ("inotify_add_watch", libc))
  61. inotify_rm_watch = ctypes.CFUNCTYPE(c_int, c_int, c_uint32, use_errno=True)(
  62. ("inotify_rm_watch", libc))
  63. inotify_init = ctypes.CFUNCTYPE(c_int, use_errno=True)(
  64. ("inotify_init", libc))
  65. class InotifyConstants(object):
  66. # User-space events
  67. IN_ACCESS = 0x00000001 # File was accessed.
  68. IN_MODIFY = 0x00000002 # File was modified.
  69. IN_ATTRIB = 0x00000004 # Meta-data changed.
  70. IN_CLOSE_WRITE = 0x00000008 # Writable file was closed.
  71. IN_CLOSE_NOWRITE = 0x00000010 # Unwritable file closed.
  72. IN_OPEN = 0x00000020 # File was opened.
  73. IN_MOVED_FROM = 0x00000040 # File was moved from X.
  74. IN_MOVED_TO = 0x00000080 # File was moved to Y.
  75. IN_CREATE = 0x00000100 # Subfile was created.
  76. IN_DELETE = 0x00000200 # Subfile was deleted.
  77. IN_DELETE_SELF = 0x00000400 # Self was deleted.
  78. IN_MOVE_SELF = 0x00000800 # Self was moved.
  79. # Helper user-space events.
  80. IN_CLOSE = IN_CLOSE_WRITE | IN_CLOSE_NOWRITE # Close.
  81. IN_MOVE = IN_MOVED_FROM | IN_MOVED_TO # Moves.
  82. # Events sent by the kernel to a watch.
  83. IN_UNMOUNT = 0x00002000 # Backing file system was unmounted.
  84. IN_Q_OVERFLOW = 0x00004000 # Event queued overflowed.
  85. IN_IGNORED = 0x00008000 # File was ignored.
  86. # Special flags.
  87. IN_ONLYDIR = 0x01000000 # Only watch the path if it's a directory.
  88. IN_DONT_FOLLOW = 0x02000000 # Do not follow a symbolic link.
  89. IN_EXCL_UNLINK = 0x04000000 # Exclude events on unlinked objects
  90. IN_MASK_ADD = 0x20000000 # Add to the mask of an existing watch.
  91. IN_ISDIR = 0x40000000 # Event occurred against directory.
  92. IN_ONESHOT = 0x80000000 # Only send event once.
  93. # All user-space events.
  94. IN_ALL_EVENTS = reduce(
  95. lambda x, y: x | y, [
  96. IN_ACCESS,
  97. IN_MODIFY,
  98. IN_ATTRIB,
  99. IN_CLOSE_WRITE,
  100. IN_CLOSE_NOWRITE,
  101. IN_OPEN,
  102. IN_MOVED_FROM,
  103. IN_MOVED_TO,
  104. IN_DELETE,
  105. IN_CREATE,
  106. IN_DELETE_SELF,
  107. IN_MOVE_SELF,
  108. ])
  109. # Flags for ``inotify_init1``
  110. IN_CLOEXEC = 0x02000000
  111. IN_NONBLOCK = 0x00004000
  112. # Watchdog's API cares only about these events.
  113. WATCHDOG_ALL_EVENTS = reduce(
  114. lambda x, y: x | y, [
  115. InotifyConstants.IN_MODIFY,
  116. InotifyConstants.IN_ATTRIB,
  117. InotifyConstants.IN_MOVED_FROM,
  118. InotifyConstants.IN_MOVED_TO,
  119. InotifyConstants.IN_CREATE,
  120. InotifyConstants.IN_DELETE,
  121. InotifyConstants.IN_DELETE_SELF,
  122. InotifyConstants.IN_DONT_FOLLOW,
  123. ])
  124. class inotify_event_struct(ctypes.Structure):
  125. """
  126. Structure representation of the inotify_event structure
  127. (used in buffer size calculations)::
  128. struct inotify_event {
  129. __s32 wd; /* watch descriptor */
  130. __u32 mask; /* watch mask */
  131. __u32 cookie; /* cookie to synchronize two events */
  132. __u32 len; /* length (including nulls) of name */
  133. char name[0]; /* stub for possible name */
  134. };
  135. """
  136. _fields_ = [('wd', c_int),
  137. ('mask', c_uint32),
  138. ('cookie', c_uint32),
  139. ('len', c_uint32),
  140. ('name', c_char_p)]
  141. EVENT_SIZE = ctypes.sizeof(inotify_event_struct)
  142. DEFAULT_NUM_EVENTS = 2048
  143. DEFAULT_EVENT_BUFFER_SIZE = DEFAULT_NUM_EVENTS * (EVENT_SIZE + 16)
  144. class Inotify(object):
  145. """
  146. Linux inotify(7) API wrapper class.
  147. :param path:
  148. The directory path for which we want an inotify object.
  149. :type path:
  150. :class:`bytes`
  151. :param recursive:
  152. ``True`` if subdirectories should be monitored; ``False`` otherwise.
  153. """
  154. def __init__(self, path, recursive=False, event_mask=WATCHDOG_ALL_EVENTS):
  155. # The file descriptor associated with the inotify instance.
  156. inotify_fd = inotify_init()
  157. if inotify_fd == -1:
  158. Inotify._raise_error()
  159. self._inotify_fd = inotify_fd
  160. self._lock = threading.Lock()
  161. # Stores the watch descriptor for a given path.
  162. self._wd_for_path = dict()
  163. self._path_for_wd = dict()
  164. self._path = path
  165. self._event_mask = event_mask
  166. self._is_recursive = recursive
  167. self._add_dir_watch(path, recursive, event_mask)
  168. self._moved_from_events = dict()
  169. @property
  170. def event_mask(self):
  171. """The event mask for this inotify instance."""
  172. return self._event_mask
  173. @property
  174. def path(self):
  175. """The path associated with the inotify instance."""
  176. return self._path
  177. @property
  178. def is_recursive(self):
  179. """Whether we are watching directories recursively."""
  180. return self._is_recursive
  181. @property
  182. def fd(self):
  183. """The file descriptor associated with the inotify instance."""
  184. return self._inotify_fd
  185. def clear_move_records(self):
  186. """Clear cached records of MOVED_FROM events"""
  187. self._moved_from_events = dict()
  188. def source_for_move(self, destination_event):
  189. """
  190. The source path corresponding to the given MOVED_TO event.
  191. If the source path is outside the monitored directories, None
  192. is returned instead.
  193. """
  194. if destination_event.cookie in self._moved_from_events:
  195. return self._moved_from_events[destination_event.cookie].src_path
  196. else:
  197. return None
  198. def remember_move_from_event(self, event):
  199. """
  200. Save this event as the source event for future MOVED_TO events to
  201. reference.
  202. """
  203. self._moved_from_events[event.cookie] = event
  204. def add_watch(self, path):
  205. """
  206. Adds a watch for the given path.
  207. :param path:
  208. Path to begin monitoring.
  209. """
  210. with self._lock:
  211. self._add_watch(path, self._event_mask)
  212. def remove_watch(self, path):
  213. """
  214. Removes a watch for the given path.
  215. :param path:
  216. Path string for which the watch will be removed.
  217. """
  218. with self._lock:
  219. wd = self._wd_for_path.pop(path)
  220. del self._path_for_wd[wd]
  221. if inotify_rm_watch(self._inotify_fd, wd) == -1:
  222. Inotify._raise_error()
  223. def close(self):
  224. """
  225. Closes the inotify instance and removes all associated watches.
  226. """
  227. with self._lock:
  228. if self._path in self._wd_for_path:
  229. wd = self._wd_for_path[self._path]
  230. inotify_rm_watch(self._inotify_fd, wd)
  231. os.close(self._inotify_fd)
  232. def read_events(self, event_buffer_size=DEFAULT_EVENT_BUFFER_SIZE):
  233. """
  234. Reads events from inotify and yields them.
  235. """
  236. # HACK: We need to traverse the directory path
  237. # recursively and simulate events for newly
  238. # created subdirectories/files. This will handle
  239. # mkdir -p foobar/blah/bar; touch foobar/afile
  240. def _recursive_simulate(src_path):
  241. events = []
  242. for root, dirnames, filenames in os.walk(src_path):
  243. for dirname in dirnames:
  244. try:
  245. full_path = os.path.join(root, dirname)
  246. wd_dir = self._add_watch(full_path, self._event_mask)
  247. e = InotifyEvent(
  248. wd_dir, InotifyConstants.IN_CREATE | InotifyConstants.IN_ISDIR, 0, dirname, full_path)
  249. events.append(e)
  250. except OSError:
  251. pass
  252. for filename in filenames:
  253. full_path = os.path.join(root, filename)
  254. wd_parent_dir = self._wd_for_path[os.path.dirname(full_path)]
  255. e = InotifyEvent(
  256. wd_parent_dir, InotifyConstants.IN_CREATE, 0, filename, full_path)
  257. events.append(e)
  258. return events
  259. event_buffer = None
  260. while True:
  261. try:
  262. event_buffer = os.read(self._inotify_fd, event_buffer_size)
  263. except OSError as e:
  264. if e.errno == errno.EINTR:
  265. continue
  266. break
  267. with self._lock:
  268. event_list = []
  269. for wd, mask, cookie, name in Inotify._parse_event_buffer(event_buffer):
  270. if wd == -1:
  271. continue
  272. wd_path = self._path_for_wd[wd]
  273. src_path = os.path.join(wd_path, name) if name else wd_path # avoid trailing slash
  274. inotify_event = InotifyEvent(wd, mask, cookie, name, src_path)
  275. if inotify_event.is_moved_from:
  276. self.remember_move_from_event(inotify_event)
  277. elif inotify_event.is_moved_to:
  278. move_src_path = self.source_for_move(inotify_event)
  279. if move_src_path in self._wd_for_path:
  280. moved_wd = self._wd_for_path[move_src_path]
  281. del self._wd_for_path[move_src_path]
  282. self._wd_for_path[inotify_event.src_path] = moved_wd
  283. self._path_for_wd[moved_wd] = inotify_event.src_path
  284. if self.is_recursive:
  285. for _path, _wd in self._wd_for_path.copy().items():
  286. if _path.startswith(move_src_path + os.path.sep.encode()):
  287. moved_wd = self._wd_for_path.pop(_path)
  288. _move_to_path = _path.replace(move_src_path, inotify_event.src_path)
  289. self._wd_for_path[_move_to_path] = moved_wd
  290. self._path_for_wd[moved_wd] = _move_to_path
  291. src_path = os.path.join(wd_path, name)
  292. inotify_event = InotifyEvent(wd, mask, cookie, name, src_path)
  293. if inotify_event.is_ignored:
  294. # Clean up book-keeping for deleted watches.
  295. path = self._path_for_wd.pop(wd)
  296. if self._wd_for_path[path] == wd:
  297. del self._wd_for_path[path]
  298. continue
  299. event_list.append(inotify_event)
  300. if (self.is_recursive and inotify_event.is_directory
  301. and inotify_event.is_create):
  302. # TODO: When a directory from another part of the
  303. # filesystem is moved into a watched directory, this
  304. # will not generate events for the directory tree.
  305. # We need to coalesce IN_MOVED_TO events and those
  306. # IN_MOVED_TO events which don't pair up with
  307. # IN_MOVED_FROM events should be marked IN_CREATE
  308. # instead relative to this directory.
  309. try:
  310. self._add_watch(src_path, self._event_mask)
  311. except OSError:
  312. continue
  313. event_list.extend(_recursive_simulate(src_path))
  314. return event_list
  315. # Non-synchronized methods.
  316. def _add_dir_watch(self, path, recursive, mask):
  317. """
  318. Adds a watch (optionally recursively) for the given directory path
  319. to monitor events specified by the mask.
  320. :param path:
  321. Path to monitor
  322. :param recursive:
  323. ``True`` to monitor recursively.
  324. :param mask:
  325. Event bit mask.
  326. """
  327. if not os.path.isdir(path):
  328. raise OSError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), path)
  329. self._add_watch(path, mask)
  330. if recursive:
  331. for root, dirnames, _ in os.walk(path):
  332. for dirname in dirnames:
  333. full_path = os.path.join(root, dirname)
  334. if os.path.islink(full_path):
  335. continue
  336. self._add_watch(full_path, mask)
  337. def _add_watch(self, path, mask):
  338. """
  339. Adds a watch for the given path to monitor events specified by the
  340. mask.
  341. :param path:
  342. Path to monitor
  343. :param mask:
  344. Event bit mask.
  345. """
  346. wd = inotify_add_watch(self._inotify_fd, path, mask)
  347. if wd == -1:
  348. Inotify._raise_error()
  349. self._wd_for_path[path] = wd
  350. self._path_for_wd[wd] = path
  351. return wd
  352. @staticmethod
  353. def _raise_error():
  354. """
  355. Raises errors for inotify failures.
  356. """
  357. err = ctypes.get_errno()
  358. if err == errno.ENOSPC:
  359. raise OSError(errno.ENOSPC, "inotify watch limit reached")
  360. elif err == errno.EMFILE:
  361. raise OSError(errno.EMFILE, "inotify instance limit reached")
  362. else:
  363. raise OSError(err, os.strerror(err))
  364. @staticmethod
  365. def _parse_event_buffer(event_buffer):
  366. """
  367. Parses an event buffer of ``inotify_event`` structs returned by
  368. inotify::
  369. struct inotify_event {
  370. __s32 wd; /* watch descriptor */
  371. __u32 mask; /* watch mask */
  372. __u32 cookie; /* cookie to synchronize two events */
  373. __u32 len; /* length (including nulls) of name */
  374. char name[0]; /* stub for possible name */
  375. };
  376. The ``cookie`` member of this struct is used to pair two related
  377. events, for example, it pairs an IN_MOVED_FROM event with an
  378. IN_MOVED_TO event.
  379. """
  380. i = 0
  381. while i + 16 <= len(event_buffer):
  382. wd, mask, cookie, length = struct.unpack_from('iIII', event_buffer, i)
  383. name = event_buffer[i + 16:i + 16 + length].rstrip(b'\0')
  384. i += 16 + length
  385. yield wd, mask, cookie, name
  386. class InotifyEvent(object):
  387. """
  388. Inotify event struct wrapper.
  389. :param wd:
  390. Watch descriptor
  391. :param mask:
  392. Event mask
  393. :param cookie:
  394. Event cookie
  395. :param name:
  396. Base name of the event source path.
  397. :param src_path:
  398. Full event source path.
  399. """
  400. def __init__(self, wd, mask, cookie, name, src_path):
  401. self._wd = wd
  402. self._mask = mask
  403. self._cookie = cookie
  404. self._name = name
  405. self._src_path = src_path
  406. @property
  407. def src_path(self):
  408. return self._src_path
  409. @property
  410. def wd(self):
  411. return self._wd
  412. @property
  413. def mask(self):
  414. return self._mask
  415. @property
  416. def cookie(self):
  417. return self._cookie
  418. @property
  419. def name(self):
  420. return self._name
  421. @property
  422. def is_modify(self):
  423. return self._mask & InotifyConstants.IN_MODIFY > 0
  424. @property
  425. def is_close_write(self):
  426. return self._mask & InotifyConstants.IN_CLOSE_WRITE > 0
  427. @property
  428. def is_close_nowrite(self):
  429. return self._mask & InotifyConstants.IN_CLOSE_NOWRITE > 0
  430. @property
  431. def is_access(self):
  432. return self._mask & InotifyConstants.IN_ACCESS > 0
  433. @property
  434. def is_delete(self):
  435. return self._mask & InotifyConstants.IN_DELETE > 0
  436. @property
  437. def is_delete_self(self):
  438. return self._mask & InotifyConstants.IN_DELETE_SELF > 0
  439. @property
  440. def is_create(self):
  441. return self._mask & InotifyConstants.IN_CREATE > 0
  442. @property
  443. def is_moved_from(self):
  444. return self._mask & InotifyConstants.IN_MOVED_FROM > 0
  445. @property
  446. def is_moved_to(self):
  447. return self._mask & InotifyConstants.IN_MOVED_TO > 0
  448. @property
  449. def is_move(self):
  450. return self._mask & InotifyConstants.IN_MOVE > 0
  451. @property
  452. def is_move_self(self):
  453. return self._mask & InotifyConstants.IN_MOVE_SELF > 0
  454. @property
  455. def is_attrib(self):
  456. return self._mask & InotifyConstants.IN_ATTRIB > 0
  457. @property
  458. def is_ignored(self):
  459. return self._mask & InotifyConstants.IN_IGNORED > 0
  460. @property
  461. def is_directory(self):
  462. # It looks like the kernel does not provide this information for
  463. # IN_DELETE_SELF and IN_MOVE_SELF. In this case, assume it's a dir.
  464. # See also: https://github.com/seb-m/pyinotify/blob/2c7e8f8/python2/pyinotify.py#L897
  465. return (self.is_delete_self or self.is_move_self
  466. or self._mask & InotifyConstants.IN_ISDIR > 0)
  467. @property
  468. def key(self):
  469. return self._src_path, self._wd, self._mask, self._cookie, self._name
  470. def __eq__(self, inotify_event):
  471. return self.key == inotify_event.key
  472. def __ne__(self, inotify_event):
  473. return self.key == inotify_event.key
  474. def __hash__(self):
  475. return hash(self.key)
  476. @staticmethod
  477. def _get_mask_string(mask):
  478. masks = []
  479. for c in dir(InotifyConstants):
  480. if c.startswith('IN_') and c not in ['IN_ALL_EVENTS', 'IN_CLOSE', 'IN_MOVE']:
  481. c_val = getattr(InotifyConstants, c)
  482. if mask & c_val:
  483. masks.append(c)
  484. mask_string = '|'.join(masks)
  485. return mask_string
  486. def __repr__(self):
  487. mask_string = self._get_mask_string(self.mask)
  488. s = '<%s: src_path=%r, wd=%d, mask=%s, cookie=%d, name=%s>'
  489. return s % (type(self).__name__, self.src_path, self.wd, mask_string,
  490. self.cookie, decode(self.name))