git-editlog 1.0.1__py3-none-any.whl

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