pyinotify.py 87 KB

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