-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyinotify.py
2321 lines (2032 loc) · 84.8 KB
/
pyinotify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# pyinotify.py - python interface to inotify
# Copyright (c) 2005-2011 Sebastien Martini <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
pyinotify
@author: Sebastien Martini
@license: MIT License
@contact: [email protected]
"""
class PyinotifyError(Exception):
"""Indicates exceptions raised by a Pyinotify class."""
pass
class UnsupportedPythonVersionError(PyinotifyError):
"""
Raised on unsupported Python versions.
"""
def __init__(self, version):
"""
@param version: Current Python version
@type version: string
"""
err = 'Python %s is unsupported, requires at least Python 2.4'
PyinotifyError.__init__(self, err % version)
# Check Python version
import sys
if sys.version_info < (2, 4):
raise UnsupportedPythonVersionError(sys.version)
# Import directives
import threading
import os
import select
import struct
import fcntl
import errno
import termios
import array
import logging
import atexit
from collections import deque
from datetime import datetime, timedelta
import time
import re
import asyncore
import glob
try:
from functools import reduce
except ImportError:
pass # Will fail on Python 2.4 which has reduce() builtin anyway.
try:
import ctypes
import ctypes.util
except ImportError:
ctypes = None
try:
import inotify_syscalls
except ImportError:
inotify_syscalls = None
__author__ = "[email protected] (Sebastien Martini)"
__version__ = "0.9.1"
__metaclass__ = type # Use new-style classes by default
# Compatibity mode: set to True to improve compatibility with
# Pyinotify 0.7.1. Do not set this variable yourself, call the
# function compatibility_mode() instead.
COMPATIBILITY_MODE = False
class InotifyBindingNotFoundError(PyinotifyError):
"""
Raised when no inotify support couldn't be found.
"""
def __init__(self):
err = "Couldn't find any inotify binding"
PyinotifyError.__init__(self, err)
class INotifyWrapper:
"""
Abstract class wrapping access to inotify's functions. This is an
internal class.
"""
@staticmethod
def create():
# First, try to use ctypes.
if ctypes:
inotify = _CtypesLibcINotifyWrapper()
if inotify.init():
return inotify
# Second, see if C extension is compiled.
if inotify_syscalls:
inotify = _INotifySyscallsWrapper()
if inotify.init():
return inotify
def get_errno(self):
"""
Return None is no errno code is available.
"""
return self._get_errno()
def str_errno(self):
code = self.get_errno()
if code is None:
return 'Errno: no errno support'
return 'Errno=%s (%s)' % (os.strerror(code), errno.errorcode[code])
def inotify_init(self):
return self._inotify_init()
def inotify_add_watch(self, fd, pathname, mask):
# Unicode strings must be encoded to string prior to calling this
# method.
assert isinstance(pathname, str)
return self._inotify_add_watch(fd, pathname, mask)
def inotify_rm_watch(self, fd, wd):
return self._inotify_rm_watch(fd, wd)
class _INotifySyscallsWrapper(INotifyWrapper):
def __init__(self):
# Stores the last errno value.
self._last_errno = None
def init(self):
assert inotify_syscalls
return True
def _get_errno(self):
return self._last_errno
def _inotify_init(self):
try:
fd = inotify_syscalls.inotify_init()
except IOError, err:
self._last_errno = err.errno
return -1
return fd
def _inotify_add_watch(self, fd, pathname, mask):
try:
wd = inotify_syscalls.inotify_add_watch(fd, pathname, mask)
except IOError, err:
self._last_errno = err.errno
return -1
return wd
def _inotify_rm_watch(self, fd, wd):
try:
ret = inotify_syscalls.inotify_rm_watch(fd, wd)
except IOError, err:
self._last_errno = err.errno
return -1
return ret
class _CtypesLibcINotifyWrapper(INotifyWrapper):
def __init__(self):
self._libc = None
self._get_errno_func = None
def init(self):
assert ctypes
libc_name = None
try:
libc_name = ctypes.util.find_library('c')
except (OSError, IOError):
pass # Will attemp to load it with None anyway.
if sys.version_info >= (2, 6):
self._libc = ctypes.CDLL(libc_name, use_errno=True)
self._get_errno_func = ctypes.get_errno
else:
self._libc = ctypes.CDLL(libc_name)
try:
location = self._libc.__errno_location
location.restype = ctypes.POINTER(ctypes.c_int)
self._get_errno_func = lambda: location().contents.value
except AttributeError:
pass
# Eventually check that libc has needed inotify bindings.
if (not hasattr(self._libc, 'inotify_init') or
not hasattr(self._libc, 'inotify_add_watch') or
not hasattr(self._libc, 'inotify_rm_watch')):
return False
return True
def _get_errno(self):
if self._get_errno_func is not None:
return self._get_errno_func()
return None
def _inotify_init(self):
assert self._libc is not None
return self._libc.inotify_init()
def _inotify_add_watch(self, fd, pathname, mask):
assert self._libc is not None
pathname = ctypes.create_string_buffer(pathname)
return self._libc.inotify_add_watch(fd, pathname, mask)
def _inotify_rm_watch(self, fd, wd):
assert self._libc is not None
return self._libc.inotify_rm_watch(fd, wd)
def _sysctl(self, *args):
assert self._libc is not None
return self._libc.sysctl(*args)
class _PyinotifyLogger(logging.Logger):
"""
Pyinotify logger used for logging unicode strings.
"""
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None,
extra=None):
rv = _UnicodeLogRecord(name, level, fn, lno, msg, args, exc_info, func)
if extra is not None:
for key in extra:
if (key in ["message", "asctime"]) or (key in rv.__dict__):
raise KeyError("Attempt to overwrite %r in LogRecord" % key)
rv.__dict__[key] = extra[key]
return rv
class _UnicodeLogRecord(logging.LogRecord):
def __init__(self, name, level, pathname, lineno,
msg, args, exc_info, func=None):
py_version = sys.version_info
# func argument was added in Python 2.5, just ignore it otherwise.
if py_version[0] >= 2 and py_version[1] >= 5:
logging.LogRecord.__init__(self, name, level, pathname, lineno,
msg, args, exc_info, func)
else:
logging.LogRecord.__init__(self, name, level, pathname, lineno,
msg, args, exc_info)
def getMessage(self):
msg = self.msg
if not isinstance(msg, (unicode, str)):
try:
msg = str(self.msg)
except UnicodeError:
pass
if self.args:
if isinstance(self.args, tuple):
def str_to_unicode(s):
"""Return unicode string."""
if not isinstance(s, str):
return s
return unicode(s, sys.getfilesystemencoding())
args = tuple([str_to_unicode(m) for m in self.args])
else:
args = self.args
msg = msg % args
if not isinstance(msg, unicode):
msg = unicode(msg, sys.getfilesystemencoding())
return msg
# Logging
def logger_init():
"""Initialize logger instance."""
logging.setLoggerClass(_PyinotifyLogger)
log = logging.getLogger("pyinotify")
console_handler = logging.StreamHandler()
console_handler.setFormatter(
logging.Formatter("[%(asctime)s %(name)s %(levelname)s] %(message)s"))
log.addHandler(console_handler)
log.setLevel(20)
return log
log = logger_init()
# inotify's variables
class SysCtlINotify:
"""
Access (read, write) inotify's variables through sysctl. Usually it
requires administrator rights to update them.
Examples:
- Read max_queued_events attribute: myvar = max_queued_events.value
- Update max_queued_events attribute: max_queued_events.value = 42
"""
inotify_attrs = {'max_user_instances': 1,
'max_user_watches': 2,
'max_queued_events': 3}
def __init__(self, attrname, inotify_wrapper):
# FIXME: right now only supporting ctypes
assert ctypes
self._attrname = attrname
self._inotify_wrapper = inotify_wrapper
sino = ctypes.c_int * 3
self._attr = sino(5, 20, SysCtlINotify.inotify_attrs[attrname])
@staticmethod
def create(attrname):
"""
Factory method instanciating and returning the right wrapper.
"""
# FIXME: right now only supporting ctypes
if ctypes is None:
return None
inotify_wrapper = _CtypesLibcINotifyWrapper()
if not inotify_wrapper.init():
return None
return SysCtlINotify(attrname, inotify_wrapper)
def get_val(self):
"""
Gets attribute's value.
@return: stored value.
@rtype: int
"""
oldv = ctypes.c_int(0)
size = ctypes.c_int(ctypes.sizeof(oldv))
self._inotify_wrapper._sysctl(self._attr, 3,
ctypes.c_voidp(ctypes.addressof(oldv)),
ctypes.addressof(size),
None, 0)
return oldv.value
def set_val(self, nval):
"""
Sets new attribute's value.
@param nval: replaces current value by nval.
@type nval: int
"""
oldv = ctypes.c_int(0)
sizeo = ctypes.c_int(ctypes.sizeof(oldv))
newv = ctypes.c_int(nval)
sizen = ctypes.c_int(ctypes.sizeof(newv))
self._inotify_wrapper._sysctl(self._attr, 3,
ctypes.c_voidp(ctypes.addressof(oldv)),
ctypes.addressof(sizeo),
ctypes.c_voidp(ctypes.addressof(newv)),
ctypes.addressof(sizen))
value = property(get_val, set_val)
def __repr__(self):
return '<%s=%d>' % (self._attrname, self.get_val())
# Inotify's variables
#
# FIXME: currently these variables are only accessible when ctypes is used,
# otherwise there are set to None.
#
# read: myvar = max_queued_events.value
# update: max_queued_events.value = 42
#
for attrname in ('max_queued_events', 'max_user_instances', 'max_user_watches'):
globals()[attrname] = SysCtlINotify.create(attrname)
class EventsCodes:
"""
Set of codes corresponding to each kind of events.
Some of these flags are used to communicate with inotify, whereas
the others are sent to userspace by inotify notifying some events.
@cvar IN_ACCESS: File was accessed.
@type IN_ACCESS: int
@cvar IN_MODIFY: File was modified.
@type IN_MODIFY: int
@cvar IN_ATTRIB: Metadata changed.
@type IN_ATTRIB: int
@cvar IN_CLOSE_WRITE: Writtable file was closed.
@type IN_CLOSE_WRITE: int
@cvar IN_CLOSE_NOWRITE: Unwrittable file closed.
@type IN_CLOSE_NOWRITE: int
@cvar IN_OPEN: File was opened.
@type IN_OPEN: int
@cvar IN_MOVED_FROM: File was moved from X.
@type IN_MOVED_FROM: int
@cvar IN_MOVED_TO: File was moved to Y.
@type IN_MOVED_TO: int
@cvar IN_CREATE: Subfile was created.
@type IN_CREATE: int
@cvar IN_DELETE: Subfile was deleted.
@type IN_DELETE: int
@cvar IN_DELETE_SELF: Self (watched item itself) was deleted.
@type IN_DELETE_SELF: int
@cvar IN_MOVE_SELF: Self (watched item itself) was moved.
@type IN_MOVE_SELF: int
@cvar IN_UNMOUNT: Backing fs was unmounted.
@type IN_UNMOUNT: int
@cvar IN_Q_OVERFLOW: Event queued overflowed.
@type IN_Q_OVERFLOW: int
@cvar IN_IGNORED: File was ignored.
@type IN_IGNORED: int
@cvar IN_ONLYDIR: only watch the path if it is a directory (new
in kernel 2.6.15).
@type IN_ONLYDIR: int
@cvar IN_DONT_FOLLOW: don't follow a symlink (new in kernel 2.6.15).
IN_ONLYDIR we can make sure that we don't watch
the target of symlinks.
@type IN_DONT_FOLLOW: int
@cvar IN_MASK_ADD: add to the mask of an already existing watch (new
in kernel 2.6.14).
@type IN_MASK_ADD: int
@cvar IN_ISDIR: Event occurred against dir.
@type IN_ISDIR: int
@cvar IN_ONESHOT: Only send event once.
@type IN_ONESHOT: int
@cvar ALL_EVENTS: Alias for considering all of the events.
@type ALL_EVENTS: int
"""
# The idea here is 'configuration-as-code' - this way, we get our nice class
# constants, but we also get nice human-friendly text mappings to do lookups
# against as well, for free:
FLAG_COLLECTIONS = {'OP_FLAGS': {
'IN_ACCESS' : 0x00000001, # File was accessed
'IN_MODIFY' : 0x00000002, # File was modified
'IN_ATTRIB' : 0x00000004, # Metadata changed
'IN_CLOSE_WRITE' : 0x00000008, # Writable file was closed
'IN_CLOSE_NOWRITE' : 0x00000010, # Unwritable file closed
'IN_OPEN' : 0x00000020, # File was opened
'IN_MOVED_FROM' : 0x00000040, # File was moved from X
'IN_MOVED_TO' : 0x00000080, # File was moved to Y
'IN_CREATE' : 0x00000100, # Subfile was created
'IN_DELETE' : 0x00000200, # Subfile was deleted
'IN_DELETE_SELF' : 0x00000400, # Self (watched item itself)
# was deleted
'IN_MOVE_SELF' : 0x00000800, # Self (watched item itself) was moved
},
'EVENT_FLAGS': {
'IN_UNMOUNT' : 0x00002000, # Backing fs was unmounted
'IN_Q_OVERFLOW' : 0x00004000, # Event queued overflowed
'IN_IGNORED' : 0x00008000, # File was ignored
},
'SPECIAL_FLAGS': {
'IN_ONLYDIR' : 0x01000000, # only watch the path if it is a
# directory
'IN_DONT_FOLLOW' : 0x02000000, # don't follow a symlink
'IN_MASK_ADD' : 0x20000000, # add to the mask of an already
# existing watch
'IN_ISDIR' : 0x40000000, # event occurred against dir
'IN_ONESHOT' : 0x80000000, # only send event once
},
}
def maskname(mask):
"""
Returns the event name associated to mask. IN_ISDIR is appended to
the result when appropriate. Note: only one event is returned, because
only one event can be raised at a given time.
@param mask: mask.
@type mask: int
@return: event name.
@rtype: str
"""
ms = mask
name = '%s'
if mask & IN_ISDIR:
ms = mask - IN_ISDIR
name = '%s|IN_ISDIR'
return name % EventsCodes.ALL_VALUES[ms]
maskname = staticmethod(maskname)
# So let's now turn the configuration into code
EventsCodes.ALL_FLAGS = {}
EventsCodes.ALL_VALUES = {}
for flagc, valc in EventsCodes.FLAG_COLLECTIONS.items():
# Make the collections' members directly accessible through the
# class dictionary
setattr(EventsCodes, flagc, valc)
# Collect all the flags under a common umbrella
EventsCodes.ALL_FLAGS.update(valc)
# Make the individual masks accessible as 'constants' at globals() scope
# and masknames accessible by values.
for name, val in valc.items():
globals()[name] = val
EventsCodes.ALL_VALUES[val] = name
# all 'normal' events
ALL_EVENTS = reduce(lambda x, y: x | y, EventsCodes.OP_FLAGS.values())
EventsCodes.ALL_FLAGS['ALL_EVENTS'] = ALL_EVENTS
EventsCodes.ALL_VALUES[ALL_EVENTS] = 'ALL_EVENTS'
class _Event:
"""
Event structure, represent events raised by the system. This
is the base class and should be subclassed.
"""
def __init__(self, dict_):
"""
Attach attributes (contained in dict_) to self.
@param dict_: Set of attributes.
@type dict_: dictionary
"""
for tpl in dict_.items():
setattr(self, *tpl)
def __repr__(self):
"""
@return: Generic event string representation.
@rtype: str
"""
s = ''
for attr, value in sorted(self.__dict__.items(), key=lambda x: x[0]):
if attr.startswith('_'):
continue
if attr == 'mask':
value = hex(getattr(self, attr))
elif isinstance(value, basestring) and not value:
value = "''"
s += ' %s%s%s' % (output_format.field_name(attr),
output_format.punctuation('='),
output_format.field_value(value))
s = '%s%s%s %s' % (output_format.punctuation('<'),
output_format.class_name(self.__class__.__name__),
s,
output_format.punctuation('>'))
return s
def __str__(self):
return repr(self)
class _RawEvent(_Event):
"""
Raw event, it contains only the informations provided by the system.
It doesn't infer anything.
"""
def __init__(self, wd, mask, cookie, name):
"""
@param wd: Watch Descriptor.
@type wd: int
@param mask: Bitmask of events.
@type mask: int
@param cookie: Cookie.
@type cookie: int
@param name: Basename of the file or directory against which the
event was raised in case where the watched directory
is the parent directory. None if the event was raised
on the watched item itself.
@type name: string or None
"""
# Use this variable to cache the result of str(self), this object
# is immutable.
self._str = None
# name: remove trailing '\0'
d = {'wd': wd,
'mask': mask,
'cookie': cookie,
'name': name.rstrip('\0')}
_Event.__init__(self, d)
log.debug(str(self))
def __str__(self):
if self._str is None:
self._str = _Event.__str__(self)
return self._str
class Event(_Event):
"""
This class contains all the useful informations about the observed
event. However, the presence of each field is not guaranteed and
depends on the type of event. In effect, some fields are irrelevant
for some kind of event (for example 'cookie' is meaningless for
IN_CREATE whereas it is mandatory for IN_MOVE_TO).
The possible fields are:
- wd (int): Watch Descriptor.
- mask (int): Mask.
- maskname (str): Readable event name.
- path (str): path of the file or directory being watched.
- name (str): Basename of the file or directory against which the
event was raised in case where the watched directory
is the parent directory. None if the event was raised
on the watched item itself. This field is always provided
even if the string is ''.
- pathname (str): Concatenation of 'path' and 'name'.
- src_pathname (str): Only present for IN_MOVED_TO events and only in
the case where IN_MOVED_FROM events are watched too. Holds the
source pathname from where pathname was moved from.
- cookie (int): Cookie.
- dir (bool): True if the event was raised against a directory.
"""
def __init__(self, raw):
"""
Concretely, this is the raw event plus inferred infos.
"""
_Event.__init__(self, raw)
self.maskname = EventsCodes.maskname(self.mask)
if COMPATIBILITY_MODE:
self.event_name = self.maskname
try:
if self.name:
self.pathname = os.path.abspath(os.path.join(self.path,
self.name))
else:
self.pathname = os.path.abspath(self.path)
except AttributeError, err:
# Usually it is not an error some events are perfectly valids
# despite the lack of these attributes.
log.debug(err)
class ProcessEventError(PyinotifyError):
"""
ProcessEventError Exception. Raised on ProcessEvent error.
"""
def __init__(self, err):
"""
@param err: Exception error description.
@type err: string
"""
PyinotifyError.__init__(self, err)
class _ProcessEvent:
"""
Abstract processing event class.
"""
def __call__(self, event):
"""
To behave like a functor the object must be callable.
This method is a dispatch method. Its lookup order is:
1. process_MASKNAME method
2. process_FAMILY_NAME method
3. otherwise calls process_default
@param event: Event to be processed.
@type event: Event object
@return: By convention when used from the ProcessEvent class:
- Returning False or None (default value) means keep on
executing next chained functors (see chain.py example).
- Returning True instead means do not execute next
processing functions.
@rtype: bool
@raise ProcessEventError: Event object undispatchable,
unknown event.
"""
stripped_mask = event.mask - (event.mask & IN_ISDIR)
maskname = EventsCodes.ALL_VALUES.get(stripped_mask)
if maskname is None:
raise ProcessEventError("Unknown mask 0x%08x" % stripped_mask)
# 1- look for process_MASKNAME
meth = getattr(self, 'process_' + maskname, None)
if meth is not None:
return meth(event)
# 2- look for process_FAMILY_NAME
meth = getattr(self, 'process_IN_' + maskname.split('_')[1], None)
if meth is not None:
return meth(event)
# 3- default call method process_default
return self.process_default(event)
def __repr__(self):
return '<%s>' % self.__class__.__name__
class _SysProcessEvent(_ProcessEvent):
"""
There is three kind of processing according to each event:
1. special handling (deletion from internal container, bug, ...).
2. default treatment: which is applied to the majority of events.
3. IN_ISDIR is never sent alone, he is piggybacked with a standard
event, he is not processed as the others events, instead, its
value is captured and appropriately aggregated to dst event.
"""
def __init__(self, wm, notifier):
"""
@param wm: Watch Manager.
@type wm: WatchManager instance
@param notifier: Notifier.
@type notifier: Notifier instance
"""
self._watch_manager = wm # watch manager
self._notifier = notifier # notifier
self._mv_cookie = {} # {cookie(int): (src_path(str), date), ...}
self._mv = {} # {src_path(str): (dst_path(str), date), ...}
def cleanup(self):
"""
Cleanup (delete) old (>1mn) records contained in self._mv_cookie
and self._mv.
"""
date_cur_ = datetime.now()
for seq in [self._mv_cookie, self._mv]:
for k in seq.keys():
if (date_cur_ - seq[k][1]) > timedelta(minutes=1):
log.debug('Cleanup: deleting entry %s', seq[k][0])
del seq[k]
def process_IN_CREATE(self, raw_event):
"""
If the event affects a directory and the auto_add flag of the
targetted watch is set to True, a new watch is added on this
new directory, with the same attribute values than those of
this watch.
"""
if raw_event.mask & IN_ISDIR:
watch_ = self._watch_manager.get_watch(raw_event.wd)
created_dir = os.path.join(watch_.path, raw_event.name)
if watch_.auto_add and not watch_.exclude_filter(created_dir):
addw = self._watch_manager.add_watch
# The newly monitored directory inherits attributes from its
# parent directory.
addw_ret = addw(created_dir, watch_.mask,
proc_fun=watch_.proc_fun,
rec=False, auto_add=watch_.auto_add,
exclude_filter=watch_.exclude_filter)
# Trick to handle mkdir -p /d1/d2/t3 where d1 is watched and
# d2 and t3 (directory or file) are created.
# Since the directory d2 is new, then everything inside it must
# also be new.
created_dir_wd = addw_ret.get(created_dir)
if (created_dir_wd is not None) and (created_dir_wd > 0):
for name in os.listdir(created_dir):
inner = os.path.join(created_dir, name)
if self._watch_manager.get_wd(inner) is not None:
continue
# Generate (simulate) creation events for sub-
# directories and files.
if os.path.isfile(inner):
# symlinks are handled as files.
flags = IN_CREATE
elif os.path.isdir(inner):
flags = IN_CREATE | IN_ISDIR
else:
# This path should not be taken.
continue
rawevent = _RawEvent(created_dir_wd, flags, 0, name)
self._notifier.append_event(rawevent)
return self.process_default(raw_event)
def process_IN_MOVED_FROM(self, raw_event):
"""
Map the cookie with the source path (+ date for cleaning).
"""
watch_ = self._watch_manager.get_watch(raw_event.wd)
path_ = watch_.path
src_path = os.path.normpath(os.path.join(path_, raw_event.name))
self._mv_cookie[raw_event.cookie] = (src_path, datetime.now())
return self.process_default(raw_event, {'cookie': raw_event.cookie})
def process_IN_MOVED_TO(self, raw_event):
"""
Map the source path with the destination path (+ date for
cleaning).
"""
watch_ = self._watch_manager.get_watch(raw_event.wd)
path_ = watch_.path
dst_path = os.path.normpath(os.path.join(path_, raw_event.name))
mv_ = self._mv_cookie.get(raw_event.cookie)
to_append = {'cookie': raw_event.cookie}
if mv_ is not None:
self._mv[mv_[0]] = (dst_path, datetime.now())
# Let's assume that IN_MOVED_FROM event is always queued before
# that its associated (they share a common cookie) IN_MOVED_TO
# event is queued itself. It is then possible in that scenario
# to provide as additional information to the IN_MOVED_TO event
# the original pathname of the moved file/directory.
to_append['src_pathname'] = mv_[0]
elif (raw_event.mask & IN_ISDIR and watch_.auto_add and
not watch_.exclude_filter(dst_path)):
# We got a diretory that's "moved in" from an unknown source and
# auto_add is enabled. Manually add watches to the inner subtrees.
# The newly monitored directory inherits attributes from its
# parent directory.
self._watch_manager.add_watch(dst_path, watch_.mask,
proc_fun=watch_.proc_fun,
rec=True, auto_add=True,
exclude_filter=watch_.exclude_filter)
return self.process_default(raw_event, to_append)
def process_IN_MOVE_SELF(self, raw_event):
"""
STATUS: the following bug has been fixed in recent kernels (FIXME:
which version ?). Now it raises IN_DELETE_SELF instead.
Old kernels were bugged, this event raised when the watched item
were moved, so we had to update its path, but under some circumstances
it was impossible: if its parent directory and its destination
directory wasn't watched. The kernel (see include/linux/fsnotify.h)
doesn't bring us enough informations like the destination path of
moved items.
"""
watch_ = self._watch_manager.get_watch(raw_event.wd)
src_path = watch_.path
mv_ = self._mv.get(src_path)
if mv_:
dest_path = mv_[0]
watch_.path = dest_path
# add the separator to the source path to avoid overlapping
# path issue when testing with startswith()
src_path += os.path.sep
src_path_len = len(src_path)
# The next loop renames all watches with src_path as base path.
# It seems that IN_MOVE_SELF does not provide IN_ISDIR information
# therefore the next loop is iterated even if raw_event is a file.
for w in self._watch_manager.watches.values():
if w.path.startswith(src_path):
# Note that dest_path is a normalized path.
w.path = os.path.join(dest_path, w.path[src_path_len:])
else:
log.error("The pathname '%s' of this watch %s has probably changed "
"and couldn't be updated, so it cannot be trusted "
"anymore. To fix this error move directories/files only "
"between watched parents directories, in this case e.g. "
"put a watch on '%s'.",
watch_.path, watch_,
os.path.normpath(os.path.join(watch_.path,
os.path.pardir)))
if not watch_.path.endswith('-unknown-path'):
watch_.path += '-unknown-path'
return self.process_default(raw_event)
def process_IN_Q_OVERFLOW(self, raw_event):
"""
Only signal an overflow, most of the common flags are irrelevant
for this event (path, wd, name).
"""
return Event({'mask': raw_event.mask})
def process_IN_IGNORED(self, raw_event):
"""
The watch descriptor raised by this event is now ignored (forever),
it can be safely deleted from the watch manager dictionary.
After this event we can be sure that neither the event queue nor
the system will raise an event associated to this wd again.
"""
event_ = self.process_default(raw_event)
self._watch_manager.del_watch(raw_event.wd)
return event_
def process_default(self, raw_event, to_append=None):
"""
Commons handling for the followings events:
IN_ACCESS, IN_MODIFY, IN_ATTRIB, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE,
IN_OPEN, IN_DELETE, IN_DELETE_SELF, IN_UNMOUNT.
"""
watch_ = self._watch_manager.get_watch(raw_event.wd)
if raw_event.mask & (IN_DELETE_SELF | IN_MOVE_SELF):
# Unfornulately this information is not provided by the kernel
dir_ = watch_.dir
else:
dir_ = bool(raw_event.mask & IN_ISDIR)
dict_ = {'wd': raw_event.wd,
'mask': raw_event.mask,
'path': watch_.path,
'name': raw_event.name,
'dir': dir_}
if COMPATIBILITY_MODE:
dict_['is_dir'] = dir_
if to_append is not None:
dict_.update(to_append)
return Event(dict_)
class ProcessEvent(_ProcessEvent):
"""
Process events objects, can be specialized via subclassing, thus its
behavior can be overriden:
Note: you should not override __init__ in your subclass instead define
a my_init() method, this method will be called automatically from the
constructor of this class with its optionals parameters.
1. Provide specialized individual methods, e.g. process_IN_DELETE for
processing a precise type of event (e.g. IN_DELETE in this case).
2. Or/and provide methods for processing events by 'family', e.g.
process_IN_CLOSE method will process both IN_CLOSE_WRITE and
IN_CLOSE_NOWRITE events (if process_IN_CLOSE_WRITE and
process_IN_CLOSE_NOWRITE aren't defined though).
3. Or/and override process_default for catching and processing all
the remaining types of events.
"""
pevent = None
def __init__(self, pevent=None, **kargs):
"""
Enable chaining of ProcessEvent instances.
@param pevent: Optional callable object, will be called on event
processing (before self).
@type pevent: callable
@param kargs: This constructor is implemented as a template method
delegating its optionals keyworded arguments to the
method my_init().
@type kargs: dict
"""
self.pevent = pevent
self.my_init(**kargs)
def my_init(self, **kargs):
"""
This method is called from ProcessEvent.__init__(). This method is
empty here and must be redefined to be useful. In effect, if you
need to specifically initialize your subclass' instance then you
just have to override this method in your subclass. Then all the
keyworded arguments passed to ProcessEvent.__init__() will be
transmitted as parameters to this method. Beware you MUST pass
keyword arguments though.
@param kargs: optional delegated arguments from __init__().
@type kargs: dict
"""
pass
def __call__(self, event):
stop_chaining = False
if self.pevent is not None:
# By default methods return None so we set as guideline
# that methods asking for stop chaining must explicitely
# return non None or non False values, otherwise the default
# behavior will be to accept chain call to the corresponding
# local method.
stop_chaining = self.pevent(event)
if not stop_chaining:
return _ProcessEvent.__call__(self, event)
def nested_pevent(self):
return self.pevent
def process_IN_Q_OVERFLOW(self, event):
"""
By default this method only reports warning messages, you can overredide
it by subclassing ProcessEvent and implement your own
process_IN_Q_OVERFLOW method. The actions you can take on receiving this
event is either to update the variable max_queued_events in order to
handle more simultaneous events or to modify your code in order to
accomplish a better filtering diminishing the number of raised events.
Because this method is defined, IN_Q_OVERFLOW will never get
transmitted as arguments to process_default calls.
@param event: IN_Q_OVERFLOW event.
@type event: dict
"""
log.warning('Event queue overflowed.')
def process_default(self, event):
"""
Default processing event method. By default does nothing. Subclass
ProcessEvent and redefine this method in order to modify its behavior.
@param event: Event to be processed. Can be of any type of events but