pyinotify.py 86 KB

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