pyinotify.py 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326
  1. #
  2. # pyinotify.py - python interface to inotify
  3. # Copyright (c) 2005-2015 Sebastien Martini <seb@dbzteam.org>
  4. #
  5. # SPDX-License-Identifier: MIT
  6. #
  7. """
  8. pyinotify
  9. @author: Sebastien Martini
  10. @license: MIT License
  11. @contact: seb@dbzteam.org
  12. """
  13. class PyinotifyError(Exception):
  14. """Indicates exceptions raised by a Pyinotify class."""
  15. pass
  16. class UnsupportedPythonVersionError(PyinotifyError):
  17. """
  18. Raised on unsupported Python versions.
  19. """
  20. def __init__(self, version):
  21. """
  22. @param version: Current Python version
  23. @type version: string
  24. """
  25. PyinotifyError.__init__(self,
  26. ('Python %s is unsupported, requires '
  27. 'at least Python 3.0') % version)
  28. # Check Python version
  29. import sys
  30. if sys.version_info < (3, 0):
  31. raise UnsupportedPythonVersionError(sys.version)
  32. # Import directives
  33. import threading
  34. import os
  35. import select
  36. import struct
  37. import fcntl
  38. import errno
  39. import termios
  40. import array
  41. import logging
  42. import atexit
  43. from collections import deque
  44. from datetime import datetime, timedelta
  45. import time
  46. import re
  47. import glob
  48. import locale
  49. import subprocess
  50. try:
  51. from functools import reduce
  52. except ImportError:
  53. pass # Will fail on Python 2.4 which has reduce() builtin anyway.
  54. try:
  55. import ctypes
  56. import ctypes.util
  57. except ImportError:
  58. ctypes = None
  59. try:
  60. import inotify_syscalls
  61. except ImportError:
  62. inotify_syscalls = None
  63. __author__ = "seb@dbzteam.org (Sebastien Martini)"
  64. __version__ = "0.9.6"
  65. # Compatibity mode: set to True to improve compatibility with
  66. # Pyinotify 0.7.1. Do not set this variable yourself, call the
  67. # function compatibility_mode() instead.
  68. COMPATIBILITY_MODE = False
  69. class InotifyBindingNotFoundError(PyinotifyError):
  70. """
  71. Raised when no inotify support couldn't be found.
  72. """
  73. def __init__(self):
  74. err = "Couldn't find any inotify binding"
  75. PyinotifyError.__init__(self, err)
  76. class INotifyWrapper:
  77. """
  78. Abstract class wrapping access to inotify's functions. This is an
  79. internal class.
  80. """
  81. @staticmethod
  82. def create():
  83. """
  84. Factory method instanciating and returning the right wrapper.
  85. """
  86. # First, try to use ctypes.
  87. if ctypes:
  88. inotify = _CtypesLibcINotifyWrapper()
  89. if inotify.init():
  90. return inotify
  91. # Second, see if C extension is compiled.
  92. if inotify_syscalls:
  93. inotify = _INotifySyscallsWrapper()
  94. if inotify.init():
  95. return inotify
  96. def get_errno(self):
  97. """
  98. Return None is no errno code is available.
  99. """
  100. return self._get_errno()
  101. def str_errno(self):
  102. code = self.get_errno()
  103. if code is None:
  104. return 'Errno: no errno support'
  105. return 'Errno=%s (%s)' % (os.strerror(code), errno.errorcode[code])
  106. def inotify_init(self):
  107. return self._inotify_init()
  108. def inotify_add_watch(self, fd, pathname, mask):
  109. # Unicode strings must be encoded to string prior to calling this
  110. # method.
  111. assert isinstance(pathname, str)
  112. return self._inotify_add_watch(fd, pathname, mask)
  113. def inotify_rm_watch(self, fd, wd):
  114. return self._inotify_rm_watch(fd, wd)
  115. class _INotifySyscallsWrapper(INotifyWrapper):
  116. def __init__(self):
  117. # Stores the last errno value.
  118. self._last_errno = None
  119. def init(self):
  120. assert inotify_syscalls
  121. return True
  122. def _get_errno(self):
  123. return self._last_errno
  124. def _inotify_init(self):
  125. try:
  126. fd = inotify_syscalls.inotify_init()
  127. except IOError as err:
  128. self._last_errno = err.errno
  129. return -1
  130. return fd
  131. def _inotify_add_watch(self, fd, pathname, mask):
  132. try:
  133. wd = inotify_syscalls.inotify_add_watch(fd, pathname, mask)
  134. except IOError as err:
  135. self._last_errno = err.errno
  136. return -1
  137. return wd
  138. def _inotify_rm_watch(self, fd, wd):
  139. try:
  140. ret = inotify_syscalls.inotify_rm_watch(fd, wd)
  141. except IOError as err:
  142. self._last_errno = err.errno
  143. return -1
  144. return ret
  145. class _CtypesLibcINotifyWrapper(INotifyWrapper):
  146. def __init__(self):
  147. self._libc = None
  148. self._get_errno_func = None
  149. def init(self):
  150. assert ctypes
  151. try_libc_name = 'c'
  152. if sys.platform.startswith('freebsd'):
  153. try_libc_name = 'inotify'
  154. libc_name = None
  155. try:
  156. libc_name = ctypes.util.find_library(try_libc_name)
  157. except (OSError, IOError):
  158. pass # Will attemp to load it with None anyway.
  159. self._libc = ctypes.CDLL(libc_name, use_errno=True)
  160. self._get_errno_func = ctypes.get_errno
  161. # Eventually check that libc has needed inotify bindings.
  162. if (not hasattr(self._libc, 'inotify_init') or
  163. not hasattr(self._libc, 'inotify_add_watch') or
  164. not hasattr(self._libc, 'inotify_rm_watch')):
  165. return False
  166. self._libc.inotify_init.argtypes = []
  167. self._libc.inotify_init.restype = ctypes.c_int
  168. self._libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p,
  169. ctypes.c_uint32]
  170. self._libc.inotify_add_watch.restype = ctypes.c_int
  171. self._libc.inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int]
  172. self._libc.inotify_rm_watch.restype = ctypes.c_int
  173. return True
  174. def _get_errno(self):
  175. assert self._get_errno_func
  176. return self._get_errno_func()
  177. def _inotify_init(self):
  178. assert self._libc is not None
  179. return self._libc.inotify_init()
  180. def _inotify_add_watch(self, fd, pathname, mask):
  181. assert self._libc is not None
  182. # Encodes path to a bytes string. This conversion seems required because
  183. # ctypes.create_string_buffer seems to manipulate bytes internally.
  184. # Moreover it seems that inotify_add_watch does not work very well when
  185. # it receives an ctypes.create_unicode_buffer instance as argument.
  186. pathname = pathname.encode(sys.getfilesystemencoding())
  187. pathname = ctypes.create_string_buffer(pathname)
  188. return self._libc.inotify_add_watch(fd, pathname, mask)
  189. def _inotify_rm_watch(self, fd, wd):
  190. assert self._libc is not None
  191. return self._libc.inotify_rm_watch(fd, wd)
  192. # Logging
  193. def logger_init():
  194. """Initialize logger instance."""
  195. log = logging.getLogger("pyinotify")
  196. console_handler = logging.StreamHandler()
  197. console_handler.setFormatter(
  198. logging.Formatter("[%(asctime)s %(name)s %(levelname)s] %(message)s"))
  199. log.addHandler(console_handler)
  200. log.setLevel(20)
  201. return log
  202. log = logger_init()
  203. # inotify's variables
  204. class ProcINotify:
  205. """
  206. Access (read, write) inotify's variables through /proc/sys/. Note that
  207. usually it requires administrator rights to update them.
  208. Examples:
  209. - Read max_queued_events attribute: myvar = max_queued_events.value
  210. - Update max_queued_events attribute: max_queued_events.value = 42
  211. """
  212. def __init__(self, attr):
  213. self._base = "/proc/sys/fs/inotify"
  214. self._attr = attr
  215. def get_val(self):
  216. """
  217. Gets attribute's value.
  218. @return: stored value.
  219. @rtype: int
  220. @raise IOError: if corresponding file in /proc/sys cannot be read.
  221. """
  222. with open(os.path.join(self._base, self._attr), 'r') as file_obj:
  223. return int(file_obj.readline())
  224. def set_val(self, nval):
  225. """
  226. Sets new attribute's value.
  227. @param nval: replaces current value by nval.
  228. @type nval: int
  229. @raise IOError: if corresponding file in /proc/sys cannot be written.
  230. """
  231. with open(os.path.join(self._base, self._attr), 'w') as file_obj:
  232. file_obj.write(str(nval) + '\n')
  233. value = property(get_val, set_val)
  234. def __repr__(self):
  235. return '<%s=%d>' % (self._attr, self.get_val())
  236. # Inotify's variables
  237. #
  238. # Note: may raise IOError if the corresponding value in /proc/sys
  239. # cannot be accessed.
  240. #
  241. # Examples:
  242. # - read: myvar = max_queued_events.value
  243. # - update: max_queued_events.value = 42
  244. #
  245. for attrname in ('max_queued_events', 'max_user_instances', 'max_user_watches'):
  246. globals()[attrname] = ProcINotify(attrname)
  247. class EventsCodes:
  248. """
  249. Set of codes corresponding to each kind of events.
  250. Some of these flags are used to communicate with inotify, whereas
  251. the others are sent to userspace by inotify notifying some events.
  252. @cvar IN_ACCESS: File was accessed.
  253. @type IN_ACCESS: int
  254. @cvar IN_MODIFY: File was modified.
  255. @type IN_MODIFY: int
  256. @cvar IN_ATTRIB: Metadata changed.
  257. @type IN_ATTRIB: int
  258. @cvar IN_CLOSE_WRITE: Writtable file was closed.
  259. @type IN_CLOSE_WRITE: int
  260. @cvar IN_CLOSE_NOWRITE: Unwrittable file closed.
  261. @type IN_CLOSE_NOWRITE: int
  262. @cvar IN_OPEN: File was opened.
  263. @type IN_OPEN: int
  264. @cvar IN_MOVED_FROM: File was moved from X.
  265. @type IN_MOVED_FROM: int
  266. @cvar IN_MOVED_TO: File was moved to Y.
  267. @type IN_MOVED_TO: int
  268. @cvar IN_CREATE: Subfile was created.
  269. @type IN_CREATE: int
  270. @cvar IN_DELETE: Subfile was deleted.
  271. @type IN_DELETE: int
  272. @cvar IN_DELETE_SELF: Self (watched item itself) was deleted.
  273. @type IN_DELETE_SELF: int
  274. @cvar IN_MOVE_SELF: Self (watched item itself) was moved.
  275. @type IN_MOVE_SELF: int
  276. @cvar IN_UNMOUNT: Backing fs was unmounted.
  277. @type IN_UNMOUNT: int
  278. @cvar IN_Q_OVERFLOW: Event queued overflowed.
  279. @type IN_Q_OVERFLOW: int
  280. @cvar IN_IGNORED: File was ignored.
  281. @type IN_IGNORED: int
  282. @cvar IN_ONLYDIR: only watch the path if it is a directory (new
  283. in kernel 2.6.15).
  284. @type IN_ONLYDIR: int
  285. @cvar IN_DONT_FOLLOW: don't follow a symlink (new in kernel 2.6.15).
  286. IN_ONLYDIR we can make sure that we don't watch
  287. the target of symlinks.
  288. @type IN_DONT_FOLLOW: int
  289. @cvar IN_EXCL_UNLINK: Events are not generated for children after they
  290. have been unlinked from the watched directory.
  291. (new in kernel 2.6.36).
  292. @type IN_EXCL_UNLINK: int
  293. @cvar IN_MASK_ADD: add to the mask of an already existing watch (new
  294. in kernel 2.6.14).
  295. @type IN_MASK_ADD: int
  296. @cvar IN_ISDIR: Event occurred against dir.
  297. @type IN_ISDIR: int
  298. @cvar IN_ONESHOT: Only send event once.
  299. @type IN_ONESHOT: int
  300. @cvar ALL_EVENTS: Alias for considering all of the events.
  301. @type ALL_EVENTS: int
  302. """
  303. # The idea here is 'configuration-as-code' - this way, we get our nice class
  304. # constants, but we also get nice human-friendly text mappings to do lookups
  305. # against as well, for free:
  306. FLAG_COLLECTIONS = {'OP_FLAGS': {
  307. 'IN_ACCESS' : 0x00000001, # File was accessed
  308. 'IN_MODIFY' : 0x00000002, # File was modified
  309. 'IN_ATTRIB' : 0x00000004, # Metadata changed
  310. 'IN_CLOSE_WRITE' : 0x00000008, # Writable file was closed
  311. 'IN_CLOSE_NOWRITE' : 0x00000010, # Unwritable file closed
  312. 'IN_OPEN' : 0x00000020, # File was opened
  313. 'IN_MOVED_FROM' : 0x00000040, # File was moved from X
  314. 'IN_MOVED_TO' : 0x00000080, # File was moved to Y
  315. 'IN_CREATE' : 0x00000100, # Subfile was created
  316. 'IN_DELETE' : 0x00000200, # Subfile was deleted
  317. 'IN_DELETE_SELF' : 0x00000400, # Self (watched item itself)
  318. # was deleted
  319. 'IN_MOVE_SELF' : 0x00000800, # Self (watched item itself) was moved
  320. },
  321. 'EVENT_FLAGS': {
  322. 'IN_UNMOUNT' : 0x00002000, # Backing fs was unmounted
  323. 'IN_Q_OVERFLOW' : 0x00004000, # Event queued overflowed
  324. 'IN_IGNORED' : 0x00008000, # File was ignored
  325. },
  326. 'SPECIAL_FLAGS': {
  327. 'IN_ONLYDIR' : 0x01000000, # only watch the path if it is a
  328. # directory
  329. 'IN_DONT_FOLLOW' : 0x02000000, # don't follow a symlink
  330. 'IN_EXCL_UNLINK' : 0x04000000, # exclude events on unlinked objects
  331. 'IN_MASK_ADD' : 0x20000000, # add to the mask of an already
  332. # existing watch
  333. 'IN_ISDIR' : 0x40000000, # event occurred against dir
  334. 'IN_ONESHOT' : 0x80000000, # only send event once
  335. },
  336. }
  337. def maskname(mask):
  338. """
  339. Returns the event name associated to mask. IN_ISDIR is appended to
  340. the result when appropriate. Note: only one event is returned, because
  341. only one event can be raised at a given time.
  342. @param mask: mask.
  343. @type mask: int
  344. @return: event name.
  345. @rtype: str
  346. """
  347. ms = mask
  348. name = '%s'
  349. if mask & IN_ISDIR:
  350. ms = mask - IN_ISDIR
  351. name = '%s|IN_ISDIR'
  352. return name % EventsCodes.ALL_VALUES[ms]
  353. maskname = staticmethod(maskname)
  354. # So let's now turn the configuration into code
  355. EventsCodes.ALL_FLAGS = {}
  356. EventsCodes.ALL_VALUES = {}
  357. for flagc, valc in EventsCodes.FLAG_COLLECTIONS.items():
  358. # Make the collections' members directly accessible through the
  359. # class dictionary
  360. setattr(EventsCodes, flagc, valc)
  361. # Collect all the flags under a common umbrella
  362. EventsCodes.ALL_FLAGS.update(valc)
  363. # Make the individual masks accessible as 'constants' at globals() scope
  364. # and masknames accessible by values.
  365. for name, val in valc.items():
  366. globals()[name] = val
  367. EventsCodes.ALL_VALUES[val] = name
  368. # all 'normal' events
  369. ALL_EVENTS = reduce(lambda x, y: x | y, EventsCodes.OP_FLAGS.values())
  370. EventsCodes.ALL_FLAGS['ALL_EVENTS'] = ALL_EVENTS
  371. EventsCodes.ALL_VALUES[ALL_EVENTS] = 'ALL_EVENTS'
  372. class _Event:
  373. """
  374. Event structure, represent events raised by the system. This
  375. is the base class and should be subclassed.
  376. """
  377. def __init__(self, dict_):
  378. """
  379. Attach attributes (contained in dict_) to self.
  380. @param dict_: Set of attributes.
  381. @type dict_: dictionary
  382. """
  383. for tpl in dict_.items():
  384. setattr(self, *tpl)
  385. def __repr__(self):
  386. """
  387. @return: Generic event string representation.
  388. @rtype: str
  389. """
  390. s = ''
  391. for attr, value in sorted(self.__dict__.items(), key=lambda x: x[0]):
  392. if attr.startswith('_'):
  393. continue
  394. if attr == 'mask':
  395. value = hex(getattr(self, attr))
  396. elif isinstance(value, str) and not value:
  397. value = "''"
  398. s += ' %s%s%s' % (output_format.field_name(attr),
  399. output_format.punctuation('='),
  400. output_format.field_value(value))
  401. s = '%s%s%s %s' % (output_format.punctuation('<'),
  402. output_format.class_name(self.__class__.__name__),
  403. s,
  404. output_format.punctuation('>'))
  405. return s
  406. def __str__(self):
  407. return repr(self)
  408. class _RawEvent(_Event):
  409. """
  410. Raw event, it contains only the informations provided by the system.
  411. It doesn't infer anything.
  412. """
  413. def __init__(self, wd, mask, cookie, name):
  414. """
  415. @param wd: Watch Descriptor.
  416. @type wd: int
  417. @param mask: Bitmask of events.
  418. @type mask: int
  419. @param cookie: Cookie.
  420. @type cookie: int
  421. @param name: Basename of the file or directory against which the
  422. event was raised in case where the watched directory
  423. is the parent directory. None if the event was raised
  424. on the watched item itself.
  425. @type name: string or None
  426. """
  427. # Use this variable to cache the result of str(self), this object
  428. # is immutable.
  429. self._str = None
  430. # name: remove trailing '\0'
  431. d = {'wd': wd,
  432. 'mask': mask,
  433. 'cookie': cookie,
  434. 'name': name.rstrip('\0')}
  435. _Event.__init__(self, d)
  436. log.debug(str(self))
  437. def __str__(self):
  438. if self._str is None:
  439. self._str = _Event.__str__(self)
  440. return self._str
  441. class Event(_Event):
  442. """
  443. This class contains all the useful informations about the observed
  444. event. However, the presence of each field is not guaranteed and
  445. depends on the type of event. In effect, some fields are irrelevant
  446. for some kind of event (for example 'cookie' is meaningless for
  447. IN_CREATE whereas it is mandatory for IN_MOVE_TO).
  448. The possible fields are:
  449. - wd (int): Watch Descriptor.
  450. - mask (int): Mask.
  451. - maskname (str): Readable event name.
  452. - path (str): path of the file or directory being watched.
  453. - name (str): Basename of the file or directory against which the
  454. event was raised in case where the watched directory
  455. is the parent directory. None if the event was raised
  456. on the watched item itself. This field is always provided
  457. even if the string is ''.
  458. - pathname (str): Concatenation of 'path' and 'name'.
  459. - src_pathname (str): Only present for IN_MOVED_TO events and only in
  460. the case where IN_MOVED_FROM events are watched too. Holds the
  461. source pathname from where pathname was moved from.
  462. - cookie (int): Cookie.
  463. - dir (bool): True if the event was raised against a directory.
  464. """
  465. def __init__(self, raw):
  466. """
  467. Concretely, this is the raw event plus inferred infos.
  468. """
  469. _Event.__init__(self, raw)
  470. self.maskname = EventsCodes.maskname(self.mask)
  471. if COMPATIBILITY_MODE:
  472. self.event_name = self.maskname
  473. try:
  474. if self.name:
  475. self.pathname = os.path.abspath(os.path.join(self.path,
  476. self.name))
  477. else:
  478. self.pathname = os.path.abspath(self.path)
  479. except AttributeError as err:
  480. # Usually it is not an error some events are perfectly valids
  481. # despite the lack of these attributes.
  482. log.debug(err)
  483. class ProcessEventError(PyinotifyError):
  484. """
  485. ProcessEventError Exception. Raised on ProcessEvent error.
  486. """
  487. def __init__(self, err):
  488. """
  489. @param err: Exception error description.
  490. @type err: string
  491. """
  492. PyinotifyError.__init__(self, err)
  493. class _ProcessEvent:
  494. """
  495. Abstract processing event class.
  496. """
  497. def __call__(self, event):
  498. """
  499. To behave like a functor the object must be callable.
  500. This method is a dispatch method. Its lookup order is:
  501. 1. process_MASKNAME method
  502. 2. process_FAMILY_NAME method
  503. 3. otherwise calls process_default
  504. @param event: Event to be processed.
  505. @type event: Event object
  506. @return: By convention when used from the ProcessEvent class:
  507. - Returning False or None (default value) means keep on
  508. executing next chained functors (see chain.py example).
  509. - Returning True instead means do not execute next
  510. processing functions.
  511. @rtype: bool
  512. @raise ProcessEventError: Event object undispatchable,
  513. unknown event.
  514. """
  515. stripped_mask = event.mask & ~IN_ISDIR
  516. # Bitbake hack - we see event masks of 0x6, i.e., IN_MODIFY & IN_ATTRIB.
  517. # The kernel inotify code can set more than one of the bits in the mask,
  518. # fsnotify_change() in linux/fsnotify.h is quite clear that IN_ATTRIB,
  519. # IN_MODIFY and IN_ACCESS can arrive together.
  520. # This breaks the code below which assume only one mask bit is ever
  521. # set in an event. We don't care about attrib or access in bitbake so
  522. # drop those.
  523. if stripped_mask & IN_MODIFY:
  524. stripped_mask &= ~(IN_ATTRIB | IN_ACCESS)
  525. maskname = EventsCodes.ALL_VALUES.get(stripped_mask)
  526. if maskname is None:
  527. raise ProcessEventError("Unknown mask 0x%08x" % stripped_mask)
  528. # 1- look for process_MASKNAME
  529. meth = getattr(self, 'process_' + maskname, None)
  530. if meth is not None:
  531. return meth(event)
  532. # 2- look for process_FAMILY_NAME
  533. meth = getattr(self, 'process_IN_' + maskname.split('_')[1], None)
  534. if meth is not None:
  535. return meth(event)
  536. # 3- default call method process_default
  537. return self.process_default(event)
  538. def __repr__(self):
  539. return '<%s>' % self.__class__.__name__
  540. class _SysProcessEvent(_ProcessEvent):
  541. """
  542. There is three kind of processing according to each event:
  543. 1. special handling (deletion from internal container, bug, ...).
  544. 2. default treatment: which is applied to the majority of events.
  545. 3. IN_ISDIR is never sent alone, he is piggybacked with a standard
  546. event, he is not processed as the others events, instead, its
  547. value is captured and appropriately aggregated to dst event.
  548. """
  549. def __init__(self, wm, notifier):
  550. """
  551. @param wm: Watch Manager.
  552. @type wm: WatchManager instance
  553. @param notifier: Notifier.
  554. @type notifier: Notifier instance
  555. """
  556. self._watch_manager = wm # watch manager
  557. self._notifier = notifier # notifier
  558. self._mv_cookie = {} # {cookie(int): (src_path(str), date), ...}
  559. self._mv = {} # {src_path(str): (dst_path(str), date), ...}
  560. def cleanup(self):
  561. """
  562. Cleanup (delete) old (>1mn) records contained in self._mv_cookie
  563. and self._mv.
  564. """
  565. date_cur_ = datetime.now()
  566. for seq in (self._mv_cookie, self._mv):
  567. for k in list(seq.keys()):
  568. if (date_cur_ - seq[k][1]) > timedelta(minutes=1):
  569. log.debug('Cleanup: deleting entry %s', seq[k][0])
  570. del seq[k]
  571. def process_IN_CREATE(self, raw_event):
  572. """
  573. If the event affects a directory and the auto_add flag of the
  574. targetted watch is set to True, a new watch is added on this
  575. new directory, with the same attribute values than those of
  576. this watch.
  577. """
  578. if raw_event.mask & IN_ISDIR:
  579. watch_ = self._watch_manager.get_watch(raw_event.wd)
  580. created_dir = os.path.join(watch_.path, raw_event.name)
  581. if watch_.auto_add and not watch_.exclude_filter(created_dir):
  582. addw = self._watch_manager.add_watch
  583. # The newly monitored directory inherits attributes from its
  584. # parent directory.
  585. addw_ret = addw(created_dir, watch_.mask,
  586. proc_fun=watch_.proc_fun,
  587. rec=False, auto_add=watch_.auto_add,
  588. exclude_filter=watch_.exclude_filter)
  589. # Trick to handle mkdir -p /d1/d2/t3 where d1 is watched and
  590. # d2 and t3 (directory or file) are created.
  591. # Since the directory d2 is new, then everything inside it must
  592. # also be new.
  593. created_dir_wd = addw_ret.get(created_dir)
  594. if ((created_dir_wd is not None) and (created_dir_wd > 0) and
  595. os.path.isdir(created_dir)):
  596. try:
  597. for name in os.listdir(created_dir):
  598. inner = os.path.join(created_dir, name)
  599. if self._watch_manager.get_wd(inner) is not None:
  600. continue
  601. # Generate (simulate) creation events for sub-
  602. # directories and files.
  603. if os.path.isfile(inner):
  604. # symlinks are handled as files.
  605. flags = IN_CREATE
  606. elif os.path.isdir(inner):
  607. flags = IN_CREATE | IN_ISDIR
  608. else:
  609. # This path should not be taken.
  610. continue
  611. rawevent = _RawEvent(created_dir_wd, flags, 0, name)
  612. self._notifier.append_event(rawevent)
  613. except OSError as err:
  614. msg = "process_IN_CREATE, invalid directory: %s"
  615. log.debug(msg % str(err))
  616. return self.process_default(raw_event)
  617. def process_IN_MOVED_FROM(self, raw_event):
  618. """
  619. Map the cookie with the source path (+ date for cleaning).
  620. """
  621. watch_ = self._watch_manager.get_watch(raw_event.wd)
  622. path_ = watch_.path
  623. src_path = os.path.normpath(os.path.join(path_, raw_event.name))
  624. self._mv_cookie[raw_event.cookie] = (src_path, datetime.now())
  625. return self.process_default(raw_event, {'cookie': raw_event.cookie})
  626. def process_IN_MOVED_TO(self, raw_event):
  627. """
  628. Map the source path with the destination path (+ date for
  629. cleaning).
  630. """
  631. watch_ = self._watch_manager.get_watch(raw_event.wd)
  632. path_ = watch_.path
  633. dst_path = os.path.normpath(os.path.join(path_, raw_event.name))
  634. mv_ = self._mv_cookie.get(raw_event.cookie)
  635. to_append = {'cookie': raw_event.cookie}
  636. if mv_ is not None:
  637. self._mv[mv_[0]] = (dst_path, datetime.now())
  638. # Let's assume that IN_MOVED_FROM event is always queued before
  639. # that its associated (they share a common cookie) IN_MOVED_TO
  640. # event is queued itself. It is then possible in that scenario
  641. # to provide as additional information to the IN_MOVED_TO event
  642. # the original pathname of the moved file/directory.
  643. to_append['src_pathname'] = mv_[0]
  644. elif (raw_event.mask & IN_ISDIR and watch_.auto_add and
  645. not watch_.exclude_filter(dst_path)):
  646. # We got a diretory that's "moved in" from an unknown source and
  647. # auto_add is enabled. Manually add watches to the inner subtrees.
  648. # The newly monitored directory inherits attributes from its
  649. # parent directory.
  650. self._watch_manager.add_watch(dst_path, watch_.mask,
  651. proc_fun=watch_.proc_fun,
  652. rec=True, auto_add=True,
  653. exclude_filter=watch_.exclude_filter)
  654. return self.process_default(raw_event, to_append)
  655. def process_IN_MOVE_SELF(self, raw_event):
  656. """
  657. STATUS: the following bug has been fixed in recent kernels (FIXME:
  658. which version ?). Now it raises IN_DELETE_SELF instead.
  659. Old kernels were bugged, this event raised when the watched item
  660. were moved, so we had to update its path, but under some circumstances
  661. it was impossible: if its parent directory and its destination
  662. directory wasn't watched. The kernel (see include/linux/fsnotify.h)
  663. doesn't bring us enough informations like the destination path of
  664. moved items.
  665. """
  666. watch_ = self._watch_manager.get_watch(raw_event.wd)
  667. src_path = watch_.path
  668. mv_ = self._mv.get(src_path)
  669. if mv_:
  670. dest_path = mv_[0]
  671. watch_.path = dest_path
  672. # add the separator to the source path to avoid overlapping
  673. # path issue when testing with startswith()
  674. src_path += os.path.sep
  675. src_path_len = len(src_path)
  676. # The next loop renames all watches with src_path as base path.
  677. # It seems that IN_MOVE_SELF does not provide IN_ISDIR information
  678. # therefore the next loop is iterated even if raw_event is a file.
  679. for w in self._watch_manager.watches.values():
  680. if w.path.startswith(src_path):
  681. # Note that dest_path is a normalized path.
  682. w.path = os.path.join(dest_path, w.path[src_path_len:])
  683. else:
  684. log.error("The pathname '%s' of this watch %s has probably changed "
  685. "and couldn't be updated, so it cannot be trusted "
  686. "anymore. To fix this error move directories/files only "
  687. "between watched parents directories, in this case e.g. "
  688. "put a watch on '%s'.",
  689. watch_.path, watch_,
  690. os.path.normpath(os.path.join(watch_.path,
  691. os.path.pardir)))
  692. if not watch_.path.endswith('-unknown-path'):
  693. watch_.path += '-unknown-path'
  694. return self.process_default(raw_event)
  695. def process_IN_Q_OVERFLOW(self, raw_event):
  696. """
  697. Only signal an overflow, most of the common flags are irrelevant
  698. for this event (path, wd, name).
  699. """
  700. return Event({'mask': raw_event.mask})
  701. def process_IN_IGNORED(self, raw_event):
  702. """
  703. The watch descriptor raised by this event is now ignored (forever),
  704. it can be safely deleted from the watch manager dictionary.
  705. After this event we can be sure that neither the event queue nor
  706. the system will raise an event associated to this wd again.
  707. """
  708. event_ = self.process_default(raw_event)
  709. self._watch_manager.del_watch(raw_event.wd)
  710. return event_
  711. def process_default(self, raw_event, to_append=None):
  712. """
  713. Commons handling for the followings events:
  714. IN_ACCESS, IN_MODIFY, IN_ATTRIB, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE,
  715. IN_OPEN, IN_DELETE, IN_DELETE_SELF, IN_UNMOUNT.
  716. """
  717. watch_ = self._watch_manager.get_watch(raw_event.wd)
  718. if raw_event.mask & (IN_DELETE_SELF | IN_MOVE_SELF):
  719. # Unfornulately this information is not provided by the kernel
  720. dir_ = watch_.dir
  721. else:
  722. dir_ = bool(raw_event.mask & IN_ISDIR)
  723. dict_ = {'wd': raw_event.wd,
  724. 'mask': raw_event.mask,
  725. 'path': watch_.path,
  726. 'name': raw_event.name,
  727. 'dir': dir_}
  728. if COMPATIBILITY_MODE:
  729. dict_['is_dir'] = dir_
  730. if to_append is not None:
  731. dict_.update(to_append)
  732. return Event(dict_)
  733. class ProcessEvent(_ProcessEvent):
  734. """
  735. Process events objects, can be specialized via subclassing, thus its
  736. behavior can be overriden:
  737. Note: you should not override __init__ in your subclass instead define
  738. a my_init() method, this method will be called automatically from the
  739. constructor of this class with its optionals parameters.
  740. 1. Provide specialized individual methods, e.g. process_IN_DELETE for
  741. processing a precise type of event (e.g. IN_DELETE in this case).
  742. 2. Or/and provide methods for processing events by 'family', e.g.
  743. process_IN_CLOSE method will process both IN_CLOSE_WRITE and
  744. IN_CLOSE_NOWRITE events (if process_IN_CLOSE_WRITE and
  745. process_IN_CLOSE_NOWRITE aren't defined though).
  746. 3. Or/and override process_default for catching and processing all
  747. the remaining types of events.
  748. """
  749. pevent = None
  750. def __init__(self, pevent=None, **kargs):
  751. """
  752. Enable chaining of ProcessEvent instances.
  753. @param pevent: Optional callable object, will be called on event
  754. processing (before self).
  755. @type pevent: callable
  756. @param kargs: This constructor is implemented as a template method
  757. delegating its optionals keyworded arguments to the
  758. method my_init().
  759. @type kargs: dict
  760. """
  761. self.pevent = pevent
  762. self.my_init(**kargs)
  763. def my_init(self, **kargs):
  764. """
  765. This method is called from ProcessEvent.__init__(). This method is
  766. empty here and must be redefined to be useful. In effect, if you
  767. need to specifically initialize your subclass' instance then you
  768. just have to override this method in your subclass. Then all the
  769. keyworded arguments passed to ProcessEvent.__init__() will be
  770. transmitted as parameters to this method. Beware you MUST pass
  771. keyword arguments though.
  772. @param kargs: optional delegated arguments from __init__().
  773. @type kargs: dict
  774. """
  775. pass
  776. def __call__(self, event):
  777. stop_chaining = False
  778. if self.pevent is not None:
  779. # By default methods return None so we set as guideline
  780. # that methods asking for stop chaining must explicitely
  781. # return non None or non False values, otherwise the default
  782. # behavior will be to accept chain call to the corresponding
  783. # local method.
  784. stop_chaining = self.pevent(event)
  785. if not stop_chaining:
  786. return _ProcessEvent.__call__(self, event)
  787. def nested_pevent(self):
  788. return self.pevent
  789. def process_IN_Q_OVERFLOW(self, event):
  790. """
  791. By default this method only reports warning messages, you can overredide
  792. it by subclassing ProcessEvent and implement your own
  793. process_IN_Q_OVERFLOW method. The actions you can take on receiving this
  794. event is either to update the variable max_queued_events in order to
  795. handle more simultaneous events or to modify your code in order to
  796. accomplish a better filtering diminishing the number of raised events.
  797. Because this method is defined, IN_Q_OVERFLOW will never get
  798. transmitted as arguments to process_default calls.
  799. @param event: IN_Q_OVERFLOW event.
  800. @type event: dict
  801. """
  802. log.warning('Event queue overflowed.')
  803. def process_default(self, event):
  804. """
  805. Default processing event method. By default does nothing. Subclass
  806. ProcessEvent and redefine this method in order to modify its behavior.
  807. @param event: Event to be processed. Can be of any type of events but
  808. IN_Q_OVERFLOW events (see method process_IN_Q_OVERFLOW).
  809. @type event: Event instance
  810. """
  811. pass
  812. class PrintAllEvents(ProcessEvent):
  813. """
  814. Dummy class used to print events strings representations. For instance this
  815. class is used from command line to print all received events to stdout.
  816. """
  817. def my_init(self, out=None):
  818. """
  819. @param out: Where events will be written.
  820. @type out: Object providing a valid file object interface.
  821. """
  822. if out is None:
  823. out = sys.stdout
  824. self._out = out
  825. def process_default(self, event):
  826. """
  827. Writes event string representation to file object provided to
  828. my_init().
  829. @param event: Event to be processed. Can be of any type of events but
  830. IN_Q_OVERFLOW events (see method process_IN_Q_OVERFLOW).
  831. @type event: Event instance
  832. """
  833. self._out.write(str(event))
  834. self._out.write('\n')
  835. self._out.flush()
  836. class ChainIfTrue(ProcessEvent):
  837. """
  838. Makes conditional chaining depending on the result of the nested
  839. processing instance.
  840. """
  841. def my_init(self, func):
  842. """
  843. Method automatically called from base class constructor.
  844. """
  845. self._func = func
  846. def process_default(self, event):
  847. return not self._func(event)
  848. class Stats(ProcessEvent):
  849. """
  850. Compute and display trivial statistics about processed events.
  851. """
  852. def my_init(self):
  853. """
  854. Method automatically called from base class constructor.
  855. """
  856. self._start_time = time.time()
  857. self._stats = {}
  858. self._stats_lock = threading.Lock()
  859. def process_default(self, event):
  860. """
  861. Processes |event|.
  862. """
  863. self._stats_lock.acquire()
  864. try:
  865. events = event.maskname.split('|')
  866. for event_name in events:
  867. count = self._stats.get(event_name, 0)
  868. self._stats[event_name] = count + 1
  869. finally:
  870. self._stats_lock.release()
  871. def _stats_copy(self):
  872. self._stats_lock.acquire()
  873. try:
  874. return self._stats.copy()
  875. finally:
  876. self._stats_lock.release()
  877. def __repr__(self):
  878. stats = self._stats_copy()
  879. elapsed = int(time.time() - self._start_time)
  880. elapsed_str = ''
  881. if elapsed < 60:
  882. elapsed_str = str(elapsed) + 'sec'
  883. elif 60 <= elapsed < 3600:
  884. elapsed_str = '%dmn%dsec' % (elapsed / 60, elapsed % 60)
  885. elif 3600 <= elapsed < 86400:
  886. elapsed_str = '%dh%dmn' % (elapsed / 3600, (elapsed % 3600) / 60)
  887. elif elapsed >= 86400:
  888. elapsed_str = '%dd%dh' % (elapsed / 86400, (elapsed % 86400) / 3600)
  889. stats['ElapsedTime'] = elapsed_str
  890. l = []
  891. for ev, value in sorted(stats.items(), key=lambda x: x[0]):
  892. l.append(' %s=%s' % (output_format.field_name(ev),
  893. output_format.field_value(value)))
  894. s = '<%s%s >' % (output_format.class_name(self.__class__.__name__),
  895. ''.join(l))
  896. return s
  897. def dump(self, filename):
  898. """
  899. Dumps statistics.
  900. @param filename: filename where stats will be dumped, filename is
  901. created and must not exist prior to this call.
  902. @type filename: string
  903. """
  904. flags = os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW|os.O_EXCL
  905. fd = os.open(filename, flags, 0o0600)
  906. os.write(fd, bytes(self.__str__(), locale.getpreferredencoding()))
  907. os.close(fd)
  908. def __str__(self, scale=45):
  909. stats = self._stats_copy()
  910. if not stats:
  911. return ''
  912. m = max(stats.values())
  913. unity = scale / m
  914. fmt = '%%-26s%%-%ds%%s' % (len(output_format.field_value('@' * scale))
  915. + 1)
  916. def func(x):
  917. return fmt % (output_format.field_name(x[0]),
  918. output_format.field_value('@' * int(x[1] * unity)),
  919. output_format.simple('%d' % x[1], 'yellow'))
  920. s = '\n'.join(map(func, sorted(stats.items(), key=lambda x: x[0])))
  921. return s
  922. class NotifierError(PyinotifyError):
  923. """
  924. Notifier Exception. Raised on Notifier error.
  925. """
  926. def __init__(self, err):
  927. """
  928. @param err: Exception string's description.
  929. @type err: string
  930. """
  931. PyinotifyError.__init__(self, err)
  932. class Notifier:
  933. """
  934. Read notifications, process events.
  935. """
  936. def __init__(self, watch_manager, default_proc_fun=None, read_freq=0,
  937. threshold=0, timeout=None):
  938. """
  939. Initialization. read_freq, threshold and timeout parameters are used
  940. when looping.
  941. @param watch_manager: Watch Manager.
  942. @type watch_manager: WatchManager instance
  943. @param default_proc_fun: Default processing method. If None, a new
  944. instance of PrintAllEvents will be assigned.
  945. @type default_proc_fun: instance of ProcessEvent
  946. @param read_freq: if read_freq == 0, events are read asap,
  947. if read_freq is > 0, this thread sleeps
  948. max(0, read_freq - (timeout / 1000)) seconds. But if
  949. timeout is None it may be different because
  950. poll is blocking waiting for something to read.
  951. @type read_freq: int
  952. @param threshold: File descriptor will be read only if the accumulated
  953. size to read becomes >= threshold. If != 0, you likely
  954. want to use it in combination with an appropriate
  955. value for read_freq because without that you would
  956. keep looping without really reading anything and that
  957. until the amount of events to read is >= threshold.
  958. At least with read_freq set you might sleep.
  959. @type threshold: int
  960. @param timeout: see read_freq above. If provided, it must be set in
  961. milliseconds. See
  962. https://docs.python.org/3/library/select.html#select.poll.poll
  963. @type timeout: int
  964. """
  965. # Watch Manager instance
  966. self._watch_manager = watch_manager
  967. # File descriptor
  968. self._fd = self._watch_manager.get_fd()
  969. # Poll object and registration
  970. self._pollobj = select.poll()
  971. self._pollobj.register(self._fd, select.POLLIN)
  972. # This pipe is correctely initialized and used by ThreadedNotifier
  973. self._pipe = (-1, -1)
  974. # Event queue
  975. self._eventq = deque()
  976. # System processing functor, common to all events
  977. self._sys_proc_fun = _SysProcessEvent(self._watch_manager, self)
  978. # Default processing method
  979. self._default_proc_fun = default_proc_fun
  980. if default_proc_fun is None:
  981. self._default_proc_fun = PrintAllEvents()
  982. # Loop parameters
  983. self._read_freq = read_freq
  984. self._threshold = threshold
  985. self._timeout = timeout
  986. # Coalesce events option
  987. self._coalesce = False
  988. # set of str(raw_event), only used when coalesce option is True
  989. self._eventset = set()
  990. def append_event(self, event):
  991. """
  992. Append a raw event to the event queue.
  993. @param event: An event.
  994. @type event: _RawEvent instance.
  995. """
  996. self._eventq.append(event)
  997. def proc_fun(self):
  998. return self._default_proc_fun
  999. def coalesce_events(self, coalesce=True):
  1000. """
  1001. Coalescing events. Events are usually processed by batchs, their size
  1002. depend on various factors. Thus, before processing them, events received
  1003. from inotify are aggregated in a fifo queue. If this coalescing
  1004. option is enabled events are filtered based on their unicity, only
  1005. unique events are enqueued, doublons are discarded. An event is unique
  1006. when the combination of its fields (wd, mask, cookie, name) is unique
  1007. among events of a same batch. After a batch of events is processed any
  1008. events is accepted again. By default this option is disabled, you have
  1009. to explictly call this function to turn it on.
  1010. @param coalesce: Optional new coalescing value. True by default.
  1011. @type coalesce: Bool
  1012. """
  1013. self._coalesce = coalesce
  1014. if not coalesce:
  1015. self._eventset.clear()
  1016. def check_events(self, timeout=None):
  1017. """
  1018. Check for new events available to read, blocks up to timeout
  1019. milliseconds.
  1020. @param timeout: If specified it overrides the corresponding instance
  1021. attribute _timeout. timeout must be sepcified in
  1022. milliseconds.
  1023. @type timeout: int
  1024. @return: New events to read.
  1025. @rtype: bool
  1026. """
  1027. while True:
  1028. try:
  1029. # blocks up to 'timeout' milliseconds
  1030. if timeout is None:
  1031. timeout = self._timeout
  1032. ret = self._pollobj.poll(timeout)
  1033. except select.error as err:
  1034. if err.args[0] == errno.EINTR:
  1035. continue # interrupted, retry
  1036. else:
  1037. raise
  1038. else:
  1039. break
  1040. if not ret or (self._pipe[0] == ret[0][0]):
  1041. return False
  1042. # only one fd is polled
  1043. return ret[0][1] & select.POLLIN
  1044. def read_events(self):
  1045. """
  1046. Read events from device, build _RawEvents, and enqueue them.
  1047. """
  1048. buf_ = array.array('i', [0])
  1049. # get event queue size
  1050. if fcntl.ioctl(self._fd, termios.FIONREAD, buf_, 1) == -1:
  1051. return
  1052. queue_size = buf_[0]
  1053. if queue_size < self._threshold:
  1054. log.debug('(fd: %d) %d bytes available to read but threshold is '
  1055. 'fixed to %d bytes', self._fd, queue_size,
  1056. self._threshold)
  1057. return
  1058. try:
  1059. # Read content from file
  1060. r = os.read(self._fd, queue_size)
  1061. except Exception as msg:
  1062. raise NotifierError(msg)
  1063. log.debug('Event queue size: %d', queue_size)
  1064. rsum = 0 # counter
  1065. while rsum < queue_size:
  1066. s_size = 16
  1067. # Retrieve wd, mask, cookie and fname_len
  1068. wd, mask, cookie, fname_len = struct.unpack('iIII',
  1069. r[rsum:rsum+s_size])
  1070. # Retrieve name
  1071. bname, = struct.unpack('%ds' % fname_len,
  1072. r[rsum + s_size:rsum + s_size + fname_len])
  1073. # FIXME: should we explictly call sys.getdefaultencoding() here ??
  1074. uname = bname.decode()
  1075. rawevent = _RawEvent(wd, mask, cookie, uname)
  1076. if self._coalesce:
  1077. # Only enqueue new (unique) events.
  1078. raweventstr = str(rawevent)
  1079. if raweventstr not in self._eventset:
  1080. self._eventset.add(raweventstr)
  1081. self._eventq.append(rawevent)
  1082. else:
  1083. self._eventq.append(rawevent)
  1084. rsum += s_size + fname_len
  1085. def process_events(self):
  1086. """
  1087. Routine for processing events from queue by calling their
  1088. associated proccessing method (an instance of ProcessEvent).
  1089. It also does internal processings, to keep the system updated.
  1090. """
  1091. while self._eventq:
  1092. raw_event = self._eventq.popleft() # pop next event
  1093. if self._watch_manager.ignore_events:
  1094. log.debug("Event ignored: %s" % repr(raw_event))
  1095. continue
  1096. watch_ = self._watch_manager.get_watch(raw_event.wd)
  1097. if (watch_ is None) and not (raw_event.mask & IN_Q_OVERFLOW):
  1098. if not (raw_event.mask & IN_IGNORED):
  1099. # Not really sure how we ended up here, nor how we should
  1100. # handle these types of events and if it is appropriate to
  1101. # completly skip them (like we are doing here).
  1102. log.warning("Unable to retrieve Watch object associated to %s",
  1103. repr(raw_event))
  1104. continue
  1105. revent = self._sys_proc_fun(raw_event) # system processings
  1106. if watch_ and watch_.proc_fun:
  1107. watch_.proc_fun(revent) # user processings
  1108. else:
  1109. self._default_proc_fun(revent)
  1110. self._sys_proc_fun.cleanup() # remove olds MOVED_* events records
  1111. if self._coalesce:
  1112. self._eventset.clear()
  1113. def __daemonize(self, pid_file=None, stdin=os.devnull, stdout=os.devnull,
  1114. stderr=os.devnull):
  1115. """
  1116. pid_file: file where the pid will be written. If pid_file=None the pid
  1117. is written to /var/run/<sys.argv[0]|pyinotify>.pid, if
  1118. pid_file=False no pid_file is written.
  1119. stdin, stdout, stderr: files associated to common streams.
  1120. """
  1121. if pid_file is None:
  1122. dirname = '/var/run/'
  1123. basename = os.path.basename(sys.argv[0]) or 'pyinotify'
  1124. pid_file = os.path.join(dirname, basename + '.pid')
  1125. if pid_file and os.path.lexists(pid_file):
  1126. err = 'Cannot daemonize: pid file %s already exists.' % pid_file
  1127. raise NotifierError(err)
  1128. def fork_daemon():
  1129. # Adapted from Chad J. Schroeder's recipe
  1130. # @see http://code.activestate.com/recipes/278731/
  1131. pid = os.fork()
  1132. if (pid == 0):
  1133. # parent 2
  1134. os.setsid()
  1135. pid = os.fork()
  1136. if (pid == 0):
  1137. # child
  1138. os.chdir('/')
  1139. os.umask(0o022)
  1140. else:
  1141. # parent 2
  1142. os._exit(0)
  1143. else:
  1144. # parent 1
  1145. os._exit(0)
  1146. fd_inp = os.open(stdin, os.O_RDONLY)
  1147. os.dup2(fd_inp, 0)
  1148. fd_out = os.open(stdout, os.O_WRONLY|os.O_CREAT, 0o0600)
  1149. os.dup2(fd_out, 1)
  1150. fd_err = os.open(stderr, os.O_WRONLY|os.O_CREAT, 0o0600)
  1151. os.dup2(fd_err, 2)
  1152. # Detach task
  1153. fork_daemon()
  1154. # Write pid
  1155. if pid_file:
  1156. flags = os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW|os.O_EXCL
  1157. fd_pid = os.open(pid_file, flags, 0o0600)
  1158. os.write(fd_pid, bytes(str(os.getpid()) + '\n',
  1159. locale.getpreferredencoding()))
  1160. os.close(fd_pid)
  1161. # Register unlink function
  1162. atexit.register(lambda : os.unlink(pid_file))
  1163. def _sleep(self, ref_time):
  1164. # Only consider sleeping if read_freq is > 0
  1165. if self._read_freq > 0:
  1166. cur_time = time.time()
  1167. sleep_amount = self._read_freq - (cur_time - ref_time)
  1168. if sleep_amount > 0:
  1169. log.debug('Now sleeping %d seconds', sleep_amount)
  1170. time.sleep(sleep_amount)
  1171. def loop(self, callback=None, daemonize=False, **args):
  1172. """
  1173. Events are read only one time every min(read_freq, timeout)
  1174. seconds at best and only if the size to read is >= threshold.
  1175. After this method returns it must not be called again for the same
  1176. instance.
  1177. @param callback: Functor called after each event processing iteration.
  1178. Expects to receive the notifier object (self) as first
  1179. parameter. If this function returns True the loop is
  1180. immediately terminated otherwise the loop method keeps
  1181. looping.
  1182. @type callback: callable object or function
  1183. @param daemonize: This thread is daemonized if set to True.
  1184. @type daemonize: boolean
  1185. @param args: Optional and relevant only if daemonize is True. Remaining
  1186. keyworded arguments are directly passed to daemonize see
  1187. __daemonize() method. If pid_file=None or is set to a
  1188. pathname the caller must ensure the file does not exist
  1189. before this method is called otherwise an exception
  1190. pyinotify.NotifierError will be raised. If pid_file=False
  1191. it is still daemonized but the pid is not written in any
  1192. file.
  1193. @type args: various
  1194. """
  1195. if daemonize:
  1196. self.__daemonize(**args)
  1197. # Read and process events forever
  1198. while 1:
  1199. try:
  1200. self.process_events()
  1201. if (callback is not None) and (callback(self) is True):
  1202. break
  1203. ref_time = time.time()
  1204. # check_events is blocking
  1205. if self.check_events():
  1206. self._sleep(ref_time)
  1207. self.read_events()
  1208. except KeyboardInterrupt:
  1209. # Stop monitoring if sigint is caught (Control-C).
  1210. log.debug('Pyinotify stops monitoring.')
  1211. break
  1212. # Close internals
  1213. self.stop()
  1214. def stop(self):
  1215. """
  1216. Close inotify's instance (close its file descriptor).
  1217. It destroys all existing watches, pending events,...
  1218. This method is automatically called at the end of loop().
  1219. Afterward it is invalid to access this instance.
  1220. """
  1221. if self._fd is not None:
  1222. self._pollobj.unregister(self._fd)
  1223. os.close(self._fd)
  1224. self._fd = None
  1225. self._sys_proc_fun = None
  1226. class ThreadedNotifier(threading.Thread, Notifier):
  1227. """
  1228. This notifier inherits from threading.Thread for instanciating a separate
  1229. thread, and also inherits from Notifier, because it is a threaded notifier.
  1230. Note that every functionality provided by this class is also provided
  1231. through Notifier class. Moreover Notifier should be considered first because
  1232. it is not threaded and could be easily daemonized.
  1233. """
  1234. def __init__(self, watch_manager, default_proc_fun=None, read_freq=0,
  1235. threshold=0, timeout=None):
  1236. """
  1237. Initialization, initialize base classes. read_freq, threshold and
  1238. timeout parameters are used when looping.
  1239. @param watch_manager: Watch Manager.
  1240. @type watch_manager: WatchManager instance
  1241. @param default_proc_fun: Default processing method. See base class.
  1242. @type default_proc_fun: instance of ProcessEvent
  1243. @param read_freq: if read_freq == 0, events are read asap,
  1244. if read_freq is > 0, this thread sleeps
  1245. max(0, read_freq - (timeout / 1000)) seconds.
  1246. @type read_freq: int
  1247. @param threshold: File descriptor will be read only if the accumulated
  1248. size to read becomes >= threshold. If != 0, you likely
  1249. want to use it in combination with an appropriate
  1250. value set for read_freq because without that you would
  1251. keep looping without really reading anything and that
  1252. until the amount of events to read is >= threshold. At
  1253. least with read_freq you might sleep.
  1254. @type threshold: int
  1255. @param timeout: see read_freq above. If provided, it must be set in
  1256. milliseconds. See
  1257. https://docs.python.org/3/library/select.html#select.poll.poll
  1258. @type timeout: int
  1259. """
  1260. # Init threading base class
  1261. threading.Thread.__init__(self)
  1262. # Stop condition
  1263. self._stop_event = threading.Event()
  1264. # Init Notifier base class
  1265. Notifier.__init__(self, watch_manager, default_proc_fun, read_freq,
  1266. threshold, timeout)
  1267. # Create a new pipe used for thread termination
  1268. self._pipe = os.pipe()
  1269. self._pollobj.register(self._pipe[0], select.POLLIN)
  1270. def stop(self):
  1271. """
  1272. Stop notifier's loop. Stop notification. Join the thread.
  1273. """
  1274. self._stop_event.set()
  1275. os.write(self._pipe[1], b'stop')
  1276. threading.Thread.join(self)
  1277. Notifier.stop(self)
  1278. self._pollobj.unregister(self._pipe[0])
  1279. os.close(self._pipe[0])
  1280. os.close(self._pipe[1])
  1281. def loop(self):
  1282. """
  1283. Thread's main loop. Don't meant to be called by user directly.
  1284. Call inherited start() method instead.
  1285. Events are read only once time every min(read_freq, timeout)
  1286. seconds at best and only if the size of events to read is >= threshold.
  1287. """
  1288. # When the loop must be terminated .stop() is called, 'stop'
  1289. # is written to pipe fd so poll() returns and .check_events()
  1290. # returns False which make evaluate the While's stop condition
  1291. # ._stop_event.isSet() wich put an end to the thread's execution.
  1292. while not self._stop_event.isSet():
  1293. self.process_events()
  1294. ref_time = time.time()
  1295. if self.check_events():
  1296. self._sleep(ref_time)
  1297. self.read_events()
  1298. def run(self):
  1299. """
  1300. Start thread's loop: read and process events until the method
  1301. stop() is called.
  1302. Never call this method directly, instead call the start() method
  1303. inherited from threading.Thread, which then will call run() in
  1304. its turn.
  1305. """
  1306. self.loop()
  1307. class TornadoAsyncNotifier(Notifier):
  1308. """
  1309. Tornado ioloop adapter.
  1310. """
  1311. def __init__(self, watch_manager, ioloop, callback=None,
  1312. default_proc_fun=None, read_freq=0, threshold=0, timeout=None,
  1313. channel_map=None):
  1314. """
  1315. Note that if later you must call ioloop.close() be sure to let the
  1316. default parameter to all_fds=False.
  1317. See example tornado_notifier.py for an example using this notifier.
  1318. @param ioloop: Tornado's IO loop.
  1319. @type ioloop: tornado.ioloop.IOLoop instance.
  1320. @param callback: Functor called at the end of each call to handle_read
  1321. (IOLoop's read handler). Expects to receive the
  1322. notifier object (self) as single parameter.
  1323. @type callback: callable object or function
  1324. """
  1325. self.io_loop = ioloop
  1326. self.handle_read_callback = callback
  1327. Notifier.__init__(self, watch_manager, default_proc_fun, read_freq,
  1328. threshold, timeout)
  1329. ioloop.add_handler(self._fd, self.handle_read, ioloop.READ)
  1330. def stop(self):
  1331. self.io_loop.remove_handler(self._fd)
  1332. Notifier.stop(self)
  1333. def handle_read(self, *args, **kwargs):
  1334. """
  1335. See comment in AsyncNotifier.
  1336. """
  1337. self.read_events()
  1338. self.process_events()
  1339. if self.handle_read_callback is not None:
  1340. self.handle_read_callback(self)
  1341. class AsyncioNotifier(Notifier):
  1342. """
  1343. asyncio/trollius event loop adapter.
  1344. """
  1345. def __init__(self, watch_manager, loop, callback=None,
  1346. default_proc_fun=None, read_freq=0, threshold=0, timeout=None):
  1347. """
  1348. See examples/asyncio_notifier.py for an example usage.
  1349. @param loop: asyncio or trollius event loop instance.
  1350. @type loop: asyncio.BaseEventLoop or trollius.BaseEventLoop instance.
  1351. @param callback: Functor called at the end of each call to handle_read.
  1352. Expects to receive the notifier object (self) as
  1353. single parameter.
  1354. @type callback: callable object or function
  1355. """
  1356. self.loop = loop
  1357. self.handle_read_callback = callback
  1358. Notifier.__init__(self, watch_manager, default_proc_fun, read_freq,
  1359. threshold, timeout)
  1360. loop.add_reader(self._fd, self.handle_read)
  1361. def stop(self):
  1362. self.loop.remove_reader(self._fd)
  1363. Notifier.stop(self)
  1364. def handle_read(self, *args, **kwargs):
  1365. self.read_events()
  1366. self.process_events()
  1367. if self.handle_read_callback is not None:
  1368. self.handle_read_callback(self)
  1369. class Watch:
  1370. """
  1371. Represent a watch, i.e. a file or directory being watched.
  1372. """
  1373. __slots__ = ('wd', 'path', 'mask', 'proc_fun', 'auto_add',
  1374. 'exclude_filter', 'dir')
  1375. def __init__(self, wd, path, mask, proc_fun, auto_add, exclude_filter):
  1376. """
  1377. Initializations.
  1378. @param wd: Watch descriptor.
  1379. @type wd: int
  1380. @param path: Path of the file or directory being watched.
  1381. @type path: str
  1382. @param mask: Mask.
  1383. @type mask: int
  1384. @param proc_fun: Processing callable object.
  1385. @type proc_fun:
  1386. @param auto_add: Automatically add watches on new directories.
  1387. @type auto_add: bool
  1388. @param exclude_filter: Boolean function, used to exclude new
  1389. directories from being automatically watched.
  1390. See WatchManager.__init__
  1391. @type exclude_filter: callable object
  1392. """
  1393. self.wd = wd
  1394. self.path = path
  1395. self.mask = mask
  1396. self.proc_fun = proc_fun
  1397. self.auto_add = auto_add
  1398. self.exclude_filter = exclude_filter
  1399. self.dir = os.path.isdir(self.path)
  1400. def __repr__(self):
  1401. """
  1402. @return: String representation.
  1403. @rtype: str
  1404. """
  1405. s = ' '.join(['%s%s%s' % (output_format.field_name(attr),
  1406. output_format.punctuation('='),
  1407. output_format.field_value(getattr(self,
  1408. attr))) \
  1409. for attr in self.__slots__ if not attr.startswith('_')])
  1410. s = '%s%s %s %s' % (output_format.punctuation('<'),
  1411. output_format.class_name(self.__class__.__name__),
  1412. s,
  1413. output_format.punctuation('>'))
  1414. return s
  1415. class ExcludeFilter:
  1416. """
  1417. ExcludeFilter is an exclusion filter.
  1418. """
  1419. def __init__(self, arg_lst):
  1420. """
  1421. Examples:
  1422. ef1 = ExcludeFilter(["/etc/rc.*", "/etc/hostname"])
  1423. ef2 = ExcludeFilter("/my/path/exclude.lst")
  1424. Where exclude.lst contains:
  1425. /etc/rc.*
  1426. /etc/hostname
  1427. Note: it is not possible to exclude a file if its encapsulating
  1428. directory is itself watched. See this issue for more details
  1429. https://github.com/seb-m/pyinotify/issues/31
  1430. @param arg_lst: is either a list of patterns or a filename from which
  1431. patterns will be loaded.
  1432. @type arg_lst: list of str or str
  1433. """
  1434. if isinstance(arg_lst, str):
  1435. lst = self._load_patterns_from_file(arg_lst)
  1436. elif isinstance(arg_lst, list):
  1437. lst = arg_lst
  1438. else:
  1439. raise TypeError
  1440. self._lregex = []
  1441. for regex in lst:
  1442. self._lregex.append(re.compile(regex, re.UNICODE))
  1443. def _load_patterns_from_file(self, filename):
  1444. lst = []
  1445. with open(filename, 'r') as file_obj:
  1446. for line in file_obj.readlines():
  1447. # Trim leading an trailing whitespaces
  1448. pattern = line.strip()
  1449. if not pattern or pattern.startswith('#'):
  1450. continue
  1451. lst.append(pattern)
  1452. return lst
  1453. def _match(self, regex, path):
  1454. return regex.match(path) is not None
  1455. def __call__(self, path):
  1456. """
  1457. @param path: Path to match against provided regexps.
  1458. @type path: str
  1459. @return: Return True if path has been matched and should
  1460. be excluded, False otherwise.
  1461. @rtype: bool
  1462. """
  1463. for regex in self._lregex:
  1464. if self._match(regex, path):
  1465. return True
  1466. return False
  1467. class WatchManagerError(Exception):
  1468. """
  1469. WatchManager Exception. Raised on error encountered on watches
  1470. operations.
  1471. """
  1472. def __init__(self, msg, wmd):
  1473. """
  1474. @param msg: Exception string's description.
  1475. @type msg: string
  1476. @param wmd: This dictionary contains the wd assigned to paths of the
  1477. same call for which watches were successfully added.
  1478. @type wmd: dict
  1479. """
  1480. self.wmd = wmd
  1481. Exception.__init__(self, msg)
  1482. class WatchManager:
  1483. """
  1484. Provide operations for watching files and directories. Its internal
  1485. dictionary is used to reference watched items. When used inside
  1486. threaded code, one must instanciate as many WatchManager instances as
  1487. there are ThreadedNotifier instances.
  1488. """
  1489. def __init__(self, exclude_filter=lambda path: False):
  1490. """
  1491. Initialization: init inotify, init watch manager dictionary.
  1492. Raise OSError if initialization fails, raise InotifyBindingNotFoundError
  1493. if no inotify binding was found (through ctypes or from direct access to
  1494. syscalls).
  1495. @param exclude_filter: boolean function, returns True if current
  1496. path must be excluded from being watched.
  1497. Convenient for providing a common exclusion
  1498. filter for every call to add_watch.
  1499. @type exclude_filter: callable object
  1500. """
  1501. self._ignore_events = False
  1502. self._exclude_filter = exclude_filter
  1503. self._wmd = {} # watch dict key: watch descriptor, value: watch
  1504. self._inotify_wrapper = INotifyWrapper.create()
  1505. if self._inotify_wrapper is None:
  1506. raise InotifyBindingNotFoundError()
  1507. self._fd = self._inotify_wrapper.inotify_init() # file descriptor
  1508. if self._fd < 0:
  1509. err = 'Cannot initialize new instance of inotify, %s'
  1510. raise OSError(err % self._inotify_wrapper.str_errno())
  1511. def close(self):
  1512. """
  1513. Close inotify's file descriptor, this action will also automatically
  1514. remove (i.e. stop watching) all its associated watch descriptors.
  1515. After a call to this method the WatchManager's instance become useless
  1516. and cannot be reused, a new instance must then be instanciated. It
  1517. makes sense to call this method in few situations for instance if
  1518. several independant WatchManager must be instanciated or if all watches
  1519. must be removed and no other watches need to be added.
  1520. """
  1521. os.close(self._fd)
  1522. def get_fd(self):
  1523. """
  1524. Return assigned inotify's file descriptor.
  1525. @return: File descriptor.
  1526. @rtype: int
  1527. """
  1528. return self._fd
  1529. def get_watch(self, wd):
  1530. """
  1531. Get watch from provided watch descriptor wd.
  1532. @param wd: Watch descriptor.
  1533. @type wd: int
  1534. """
  1535. return self._wmd.get(wd)
  1536. def del_watch(self, wd):
  1537. """
  1538. Remove watch entry associated to watch descriptor wd.
  1539. @param wd: Watch descriptor.
  1540. @type wd: int
  1541. """
  1542. try:
  1543. del self._wmd[wd]
  1544. except KeyError as err:
  1545. log.error('Cannot delete unknown watch descriptor %s' % str(err))
  1546. @property
  1547. def watches(self):
  1548. """
  1549. Get a reference on the internal watch manager dictionary.
  1550. @return: Internal watch manager dictionary.
  1551. @rtype: dict
  1552. """
  1553. return self._wmd
  1554. def __format_path(self, path):
  1555. """
  1556. Format path to its internal (stored in watch manager) representation.
  1557. """
  1558. # path must be a unicode string (str) and is just normalized.
  1559. return os.path.normpath(path)
  1560. def __add_watch(self, path, mask, proc_fun, auto_add, exclude_filter):
  1561. """
  1562. Add a watch on path, build a Watch object and insert it in the
  1563. watch manager dictionary. Return the wd value.
  1564. """
  1565. path = self.__format_path(path)
  1566. if auto_add and not mask & IN_CREATE:
  1567. mask |= IN_CREATE
  1568. wd = self._inotify_wrapper.inotify_add_watch(self._fd, path, mask)
  1569. if wd < 0:
  1570. return wd
  1571. watch = Watch(wd=wd, path=path, mask=mask, proc_fun=proc_fun,
  1572. auto_add=auto_add, exclude_filter=exclude_filter)
  1573. # wd are _always_ indexed with their original unicode paths in wmd.
  1574. self._wmd[wd] = watch
  1575. log.debug('New %s', watch)
  1576. return wd
  1577. def __glob(self, path, do_glob):
  1578. if do_glob:
  1579. return glob.iglob(path)
  1580. else:
  1581. return [path]
  1582. def add_watch(self, path, mask, proc_fun=None, rec=False,
  1583. auto_add=False, do_glob=False, quiet=True,
  1584. exclude_filter=None):
  1585. """
  1586. Add watch(s) on the provided |path|(s) with associated |mask| flag
  1587. value and optionally with a processing |proc_fun| function and
  1588. recursive flag |rec| set to True.
  1589. All |path| components _must_ be str (i.e. unicode) objects.
  1590. If |path| is already watched it is ignored, but if it is called with
  1591. option rec=True a watch is put on each one of its not-watched
  1592. subdirectory.
  1593. @param path: Path to watch, the path can either be a file or a
  1594. directory. Also accepts a sequence (list) of paths.
  1595. @type path: string or list of strings
  1596. @param mask: Bitmask of events.
  1597. @type mask: int
  1598. @param proc_fun: Processing object.
  1599. @type proc_fun: function or ProcessEvent instance or instance of
  1600. one of its subclasses or callable object.
  1601. @param rec: Recursively add watches from path on all its
  1602. subdirectories, set to False by default (doesn't
  1603. follows symlinks in any case).
  1604. @type rec: bool
  1605. @param auto_add: Automatically add watches on newly created
  1606. directories in watched parent |path| directory.
  1607. If |auto_add| is True, IN_CREATE is ored with |mask|
  1608. when the watch is added.
  1609. @type auto_add: bool
  1610. @param do_glob: Do globbing on pathname (see standard globbing
  1611. module for more informations).
  1612. @type do_glob: bool
  1613. @param quiet: if False raises a WatchManagerError exception on
  1614. error. See example not_quiet.py.
  1615. @type quiet: bool
  1616. @param exclude_filter: predicate (boolean function), which returns
  1617. True if the current path must be excluded
  1618. from being watched. This argument has
  1619. precedence over exclude_filter passed to
  1620. the class' constructor.
  1621. @type exclude_filter: callable object
  1622. @return: dict of paths associated to watch descriptors. A wd value
  1623. is positive if the watch was added sucessfully, otherwise
  1624. the value is negative. If the path was invalid or was already
  1625. watched it is not included into this returned dictionary.
  1626. @rtype: dict of {str: int}
  1627. """
  1628. ret_ = {} # return {path: wd, ...}
  1629. if exclude_filter is None:
  1630. exclude_filter = self._exclude_filter
  1631. # normalize args as list elements
  1632. for npath in self.__format_param(path):
  1633. # Require that path be a unicode string
  1634. if not isinstance(npath, str):
  1635. ret_[path] = -3
  1636. continue
  1637. # unix pathname pattern expansion
  1638. for apath in self.__glob(npath, do_glob):
  1639. # recursively list subdirs according to rec param
  1640. for rpath in self.__walk_rec(apath, rec):
  1641. if not exclude_filter(rpath):
  1642. wd = ret_[rpath] = self.__add_watch(rpath, mask,
  1643. proc_fun,
  1644. auto_add,
  1645. exclude_filter)
  1646. if wd < 0:
  1647. err = ('add_watch: cannot watch %s WD=%d, %s' % \
  1648. (rpath, wd,
  1649. self._inotify_wrapper.str_errno()))
  1650. if quiet:
  1651. log.error(err)
  1652. else:
  1653. raise WatchManagerError(err, ret_)
  1654. else:
  1655. # Let's say -2 means 'explicitely excluded
  1656. # from watching'.
  1657. ret_[rpath] = -2
  1658. return ret_
  1659. def __get_sub_rec(self, lpath):
  1660. """
  1661. Get every wd from self._wmd if its path is under the path of
  1662. one (at least) of those in lpath. Doesn't follow symlinks.
  1663. @param lpath: list of watch descriptor
  1664. @type lpath: list of int
  1665. @return: list of watch descriptor
  1666. @rtype: list of int
  1667. """
  1668. for d in lpath:
  1669. root = self.get_path(d)
  1670. if root is not None:
  1671. # always keep root
  1672. yield d
  1673. else:
  1674. # if invalid
  1675. continue
  1676. # nothing else to expect
  1677. if not os.path.isdir(root):
  1678. continue
  1679. # normalization
  1680. root = os.path.normpath(root)
  1681. # recursion
  1682. lend = len(root)
  1683. for iwd in self._wmd.items():
  1684. cur = iwd[1].path
  1685. pref = os.path.commonprefix([root, cur])
  1686. if root == os.sep or (len(pref) == lend and \
  1687. len(cur) > lend and \
  1688. cur[lend] == os.sep):
  1689. yield iwd[1].wd
  1690. def update_watch(self, wd, mask=None, proc_fun=None, rec=False,
  1691. auto_add=False, quiet=True):
  1692. """
  1693. Update existing watch descriptors |wd|. The |mask| value, the
  1694. processing object |proc_fun|, the recursive param |rec| and the
  1695. |auto_add| and |quiet| flags can all be updated.
  1696. @param wd: Watch Descriptor to update. Also accepts a list of
  1697. watch descriptors.
  1698. @type wd: int or list of int
  1699. @param mask: Optional new bitmask of events.
  1700. @type mask: int
  1701. @param proc_fun: Optional new processing function.
  1702. @type proc_fun: function or ProcessEvent instance or instance of
  1703. one of its subclasses or callable object.
  1704. @param rec: Optionally adds watches recursively on all
  1705. subdirectories contained into |wd| directory.
  1706. @type rec: bool
  1707. @param auto_add: Automatically adds watches on newly created
  1708. directories in the watch's path corresponding to |wd|.
  1709. If |auto_add| is True, IN_CREATE is ored with |mask|
  1710. when the watch is updated.
  1711. @type auto_add: bool
  1712. @param quiet: If False raises a WatchManagerError exception on
  1713. error. See example not_quiet.py
  1714. @type quiet: bool
  1715. @return: dict of watch descriptors associated to booleans values.
  1716. True if the corresponding wd has been successfully
  1717. updated, False otherwise.
  1718. @rtype: dict of {int: bool}
  1719. """
  1720. lwd = self.__format_param(wd)
  1721. if rec:
  1722. lwd = self.__get_sub_rec(lwd)
  1723. ret_ = {} # return {wd: bool, ...}
  1724. for awd in lwd:
  1725. apath = self.get_path(awd)
  1726. if not apath or awd < 0:
  1727. err = 'update_watch: invalid WD=%d' % awd
  1728. if quiet:
  1729. log.error(err)
  1730. continue
  1731. raise WatchManagerError(err, ret_)
  1732. if mask:
  1733. wd_ = self._inotify_wrapper.inotify_add_watch(self._fd, apath,
  1734. mask)
  1735. if wd_ < 0:
  1736. ret_[awd] = False
  1737. err = ('update_watch: cannot update %s WD=%d, %s' % \
  1738. (apath, wd_, self._inotify_wrapper.str_errno()))
  1739. if quiet:
  1740. log.error(err)
  1741. continue
  1742. raise WatchManagerError(err, ret_)
  1743. assert(awd == wd_)
  1744. if proc_fun or auto_add:
  1745. watch_ = self._wmd[awd]
  1746. if proc_fun:
  1747. watch_.proc_fun = proc_fun
  1748. if auto_add:
  1749. watch_.auto_add = auto_add
  1750. ret_[awd] = True
  1751. log.debug('Updated watch - %s', self._wmd[awd])
  1752. return ret_
  1753. def __format_param(self, param):
  1754. """
  1755. @param param: Parameter.
  1756. @type param: string or int
  1757. @return: wrap param.
  1758. @rtype: list of type(param)
  1759. """
  1760. if isinstance(param, list):
  1761. for p_ in param:
  1762. yield p_
  1763. else:
  1764. yield param
  1765. def get_wd(self, path):
  1766. """
  1767. Returns the watch descriptor associated to path. This method
  1768. presents a prohibitive cost, always prefer to keep the WD
  1769. returned by add_watch(). If the path is unknown it returns None.
  1770. @param path: Path.
  1771. @type path: str
  1772. @return: WD or None.
  1773. @rtype: int or None
  1774. """
  1775. path = self.__format_path(path)
  1776. for iwd in self._wmd.items():
  1777. if iwd[1].path == path:
  1778. return iwd[0]
  1779. def get_path(self, wd):
  1780. """
  1781. Returns the path associated to WD, if WD is unknown it returns None.
  1782. @param wd: Watch descriptor.
  1783. @type wd: int
  1784. @return: Path or None.
  1785. @rtype: string or None
  1786. """
  1787. watch_ = self._wmd.get(wd)
  1788. if watch_ is not None:
  1789. return watch_.path
  1790. def __walk_rec(self, top, rec):
  1791. """
  1792. Yields each subdirectories of top, doesn't follow symlinks.
  1793. If rec is false, only yield top.
  1794. @param top: root directory.
  1795. @type top: string
  1796. @param rec: recursive flag.
  1797. @type rec: bool
  1798. @return: path of one subdirectory.
  1799. @rtype: string
  1800. """
  1801. if not rec or os.path.islink(top) or not os.path.isdir(top):
  1802. yield top
  1803. else:
  1804. for root, dirs, files in os.walk(top):
  1805. yield root
  1806. def rm_watch(self, wd, rec=False, quiet=True):
  1807. """
  1808. Removes watch(s).
  1809. @param wd: Watch Descriptor of the file or directory to unwatch.
  1810. Also accepts a list of WDs.
  1811. @type wd: int or list of int.
  1812. @param rec: Recursively removes watches on every already watched
  1813. subdirectories and subfiles.
  1814. @type rec: bool
  1815. @param quiet: If False raises a WatchManagerError exception on
  1816. error. See example not_quiet.py
  1817. @type quiet: bool
  1818. @return: dict of watch descriptors associated to booleans values.
  1819. True if the corresponding wd has been successfully
  1820. removed, False otherwise.
  1821. @rtype: dict of {int: bool}
  1822. """
  1823. lwd = self.__format_param(wd)
  1824. if rec:
  1825. lwd = self.__get_sub_rec(lwd)
  1826. ret_ = {} # return {wd: bool, ...}
  1827. for awd in lwd:
  1828. # remove watch
  1829. wd_ = self._inotify_wrapper.inotify_rm_watch(self._fd, awd)
  1830. if wd_ < 0:
  1831. ret_[awd] = False
  1832. err = ('rm_watch: cannot remove WD=%d, %s' % \
  1833. (awd, self._inotify_wrapper.str_errno()))
  1834. if quiet:
  1835. log.error(err)
  1836. continue
  1837. raise WatchManagerError(err, ret_)
  1838. # Remove watch from our dictionary
  1839. if awd in self._wmd:
  1840. del self._wmd[awd]
  1841. ret_[awd] = True
  1842. log.debug('Watch WD=%d (%s) removed', awd, self.get_path(awd))
  1843. return ret_
  1844. def watch_transient_file(self, filename, mask, proc_class):
  1845. """
  1846. Watch a transient file, which will be created and deleted frequently
  1847. over time (e.g. pid file).
  1848. @attention: Currently under the call to this function it is not
  1849. possible to correctly watch the events triggered into the same
  1850. base directory than the directory where is located this watched
  1851. transient file. For instance it would be wrong to make these
  1852. two successive calls: wm.watch_transient_file('/var/run/foo.pid', ...)
  1853. and wm.add_watch('/var/run/', ...)
  1854. @param filename: Filename.
  1855. @type filename: string
  1856. @param mask: Bitmask of events, should contain IN_CREATE and IN_DELETE.
  1857. @type mask: int
  1858. @param proc_class: ProcessEvent (or of one of its subclass), beware of
  1859. accepting a ProcessEvent's instance as argument into
  1860. __init__, see transient_file.py example for more
  1861. details.
  1862. @type proc_class: ProcessEvent's instance or of one of its subclasses.
  1863. @return: Same as add_watch().
  1864. @rtype: Same as add_watch().
  1865. """
  1866. dirname = os.path.dirname(filename)
  1867. if dirname == '':
  1868. return {} # Maintains coherence with add_watch()
  1869. basename = os.path.basename(filename)
  1870. # Assuming we are watching at least for IN_CREATE and IN_DELETE
  1871. mask |= IN_CREATE | IN_DELETE
  1872. def cmp_name(event):
  1873. if getattr(event, 'name') is None:
  1874. return False
  1875. return basename == event.name
  1876. return self.add_watch(dirname, mask,
  1877. proc_fun=proc_class(ChainIfTrue(func=cmp_name)),
  1878. rec=False,
  1879. auto_add=False, do_glob=False,
  1880. exclude_filter=lambda path: False)
  1881. def get_ignore_events(self):
  1882. return self._ignore_events
  1883. def set_ignore_events(self, nval):
  1884. self._ignore_events = nval
  1885. ignore_events = property(get_ignore_events, set_ignore_events,
  1886. "Make watch manager ignoring new events.")
  1887. class RawOutputFormat:
  1888. """
  1889. Format string representations.
  1890. """
  1891. def __init__(self, format=None):
  1892. self.format = format or {}
  1893. def simple(self, s, attribute):
  1894. if not isinstance(s, str):
  1895. s = str(s)
  1896. return (self.format.get(attribute, '') + s +
  1897. self.format.get('normal', ''))
  1898. def punctuation(self, s):
  1899. """Punctuation color."""
  1900. return self.simple(s, 'normal')
  1901. def field_value(self, s):
  1902. """Field value color."""
  1903. return self.simple(s, 'purple')
  1904. def field_name(self, s):
  1905. """Field name color."""
  1906. return self.simple(s, 'blue')
  1907. def class_name(self, s):
  1908. """Class name color."""
  1909. return self.format.get('red', '') + self.simple(s, 'bold')
  1910. output_format = RawOutputFormat()
  1911. class ColoredOutputFormat(RawOutputFormat):
  1912. """
  1913. Format colored string representations.
  1914. """
  1915. def __init__(self):
  1916. f = {'normal': '\033[0m',
  1917. 'black': '\033[30m',
  1918. 'red': '\033[31m',
  1919. 'green': '\033[32m',
  1920. 'yellow': '\033[33m',
  1921. 'blue': '\033[34m',
  1922. 'purple': '\033[35m',
  1923. 'cyan': '\033[36m',
  1924. 'bold': '\033[1m',
  1925. 'uline': '\033[4m',
  1926. 'blink': '\033[5m',
  1927. 'invert': '\033[7m'}
  1928. RawOutputFormat.__init__(self, f)
  1929. def compatibility_mode():
  1930. """
  1931. Use this function to turn on the compatibility mode. The compatibility
  1932. mode is used to improve compatibility with Pyinotify 0.7.1 (or older)
  1933. programs. The compatibility mode provides additional variables 'is_dir',
  1934. 'event_name', 'EventsCodes.IN_*' and 'EventsCodes.ALL_EVENTS' as
  1935. Pyinotify 0.7.1 provided. Do not call this function from new programs!!
  1936. Especially if there are developped for Pyinotify >= 0.8.x.
  1937. """
  1938. setattr(EventsCodes, 'ALL_EVENTS', ALL_EVENTS)
  1939. for evname in globals():
  1940. if evname.startswith('IN_'):
  1941. setattr(EventsCodes, evname, globals()[evname])
  1942. global COMPATIBILITY_MODE
  1943. COMPATIBILITY_MODE = True
  1944. def command_line():
  1945. """
  1946. By default the watched path is '/tmp' and all types of events are
  1947. monitored. Events monitoring serves forever, type c^c to stop it.
  1948. """
  1949. from optparse import OptionParser
  1950. usage = "usage: %prog [options] [path1] [path2] [pathn]"
  1951. parser = OptionParser(usage=usage)
  1952. parser.add_option("-v", "--verbose", action="store_true",
  1953. dest="verbose", help="Verbose mode")
  1954. parser.add_option("-r", "--recursive", action="store_true",
  1955. dest="recursive",
  1956. help="Add watches recursively on paths")
  1957. parser.add_option("-a", "--auto_add", action="store_true",
  1958. dest="auto_add",
  1959. help="Automatically add watches on new directories")
  1960. parser.add_option("-g", "--glob", action="store_true",
  1961. dest="glob",
  1962. help="Treat paths as globs")
  1963. parser.add_option("-e", "--events-list", metavar="EVENT[,...]",
  1964. dest="events_list",
  1965. help=("A comma-separated list of events to watch for - "
  1966. "see the documentation for valid options (defaults"
  1967. " to everything)"))
  1968. parser.add_option("-s", "--stats", action="store_true",
  1969. dest="stats",
  1970. help="Display dummy statistics")
  1971. parser.add_option("-V", "--version", action="store_true",
  1972. dest="version", help="Pyinotify version")
  1973. parser.add_option("-f", "--raw-format", action="store_true",
  1974. dest="raw_format",
  1975. help="Disable enhanced output format.")
  1976. parser.add_option("-c", "--command", action="store",
  1977. dest="command",
  1978. help="Shell command to run upon event")
  1979. (options, args) = parser.parse_args()
  1980. if options.verbose:
  1981. log.setLevel(10)
  1982. if options.version:
  1983. print(__version__)
  1984. if not options.raw_format:
  1985. global output_format
  1986. output_format = ColoredOutputFormat()
  1987. if len(args) < 1:
  1988. path = '/tmp' # default watched path
  1989. else:
  1990. path = args
  1991. # watch manager instance
  1992. wm = WatchManager()
  1993. # notifier instance and init
  1994. if options.stats:
  1995. notifier = Notifier(wm, default_proc_fun=Stats(), read_freq=5)
  1996. else:
  1997. notifier = Notifier(wm, default_proc_fun=PrintAllEvents())
  1998. # What mask to apply
  1999. mask = 0
  2000. if options.events_list:
  2001. events_list = options.events_list.split(',')
  2002. for ev in events_list:
  2003. evcode = EventsCodes.ALL_FLAGS.get(ev, 0)
  2004. if evcode:
  2005. mask |= evcode
  2006. else:
  2007. parser.error("The event '%s' specified with option -e"
  2008. " is not valid" % ev)
  2009. else:
  2010. mask = ALL_EVENTS
  2011. # stats
  2012. cb_fun = None
  2013. if options.stats:
  2014. def cb(s):
  2015. sys.stdout.write(repr(s.proc_fun()))
  2016. sys.stdout.write('\n')
  2017. sys.stdout.write(str(s.proc_fun()))
  2018. sys.stdout.write('\n')
  2019. sys.stdout.flush()
  2020. cb_fun = cb
  2021. # External command
  2022. if options.command:
  2023. def cb(s):
  2024. subprocess.Popen(options.command, shell=True)
  2025. cb_fun = cb
  2026. log.debug('Start monitoring %s, (press c^c to halt pyinotify)' % path)
  2027. wm.add_watch(path, mask, rec=options.recursive, auto_add=options.auto_add, do_glob=options.glob)
  2028. # Loop forever (until sigint signal get caught)
  2029. notifier.loop(callback=cb_fun)
  2030. if __name__ == '__main__':
  2031. command_line()