pyinotify.py 88 KB

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