inotify_buffer.py 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright 2014 Thomas Amland <thomas.amland@gmail.com>
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from watchdog.utils import BaseThread
  18. from watchdog.utils.delayed_queue import DelayedQueue
  19. from watchdog.observers.inotify_c import Inotify
  20. logger = logging.getLogger(__name__)
  21. class InotifyBuffer(BaseThread):
  22. """A wrapper for `Inotify` that holds events for `delay` seconds. During
  23. this time, IN_MOVED_FROM and IN_MOVED_TO events are paired.
  24. """
  25. delay = 0.5
  26. def __init__(self, path, recursive=False):
  27. BaseThread.__init__(self)
  28. self._queue = DelayedQueue(self.delay)
  29. self._inotify = Inotify(path, recursive)
  30. self.start()
  31. def read_event(self):
  32. """Returns a single event or a tuple of from/to events in case of a
  33. paired move event. If this buffer has been closed, immediately return
  34. None.
  35. """
  36. return self._queue.get()
  37. def on_thread_stop(self):
  38. self._inotify.close()
  39. self._queue.close()
  40. def close(self):
  41. self.stop()
  42. self.join()
  43. def _group_events(self, event_list):
  44. """Group any matching move events"""
  45. grouped = []
  46. for inotify_event in event_list:
  47. logger.debug("in-event %s", inotify_event)
  48. def matching_from_event(event):
  49. return (not isinstance(event, tuple) and event.is_moved_from
  50. and event.cookie == inotify_event.cookie)
  51. if inotify_event.is_moved_to:
  52. # Check if move_from is already in the buffer
  53. for index, event in enumerate(grouped):
  54. if matching_from_event(event):
  55. grouped[index] = (event, inotify_event)
  56. break
  57. else:
  58. # Check if move_from is in delayqueue already
  59. from_event = self._queue.remove(matching_from_event)
  60. if from_event is not None:
  61. grouped.append((from_event, inotify_event))
  62. else:
  63. logger.debug("could not find matching move_from event")
  64. grouped.append(inotify_event)
  65. else:
  66. grouped.append(inotify_event)
  67. return grouped
  68. def run(self):
  69. """Read event from `inotify` and add them to `queue`. When reading a
  70. IN_MOVE_TO event, remove the previous added matching IN_MOVE_FROM event
  71. and add them back to the queue as a tuple.
  72. """
  73. deleted_self = False
  74. while self.should_keep_running() and not deleted_self:
  75. inotify_events = self._inotify.read_events()
  76. grouped_events = self._group_events(inotify_events)
  77. for inotify_event in grouped_events:
  78. # Only add delay for unmatched move_from events
  79. delay = not isinstance(inotify_event, tuple) and inotify_event.is_moved_from
  80. self._queue.put(inotify_event, delay)
  81. if not isinstance(inotify_event, tuple) and inotify_event.is_delete_self and \
  82. inotify_event.src_path == self._inotify.path:
  83. # Deleted the watched directory, stop watching for events
  84. deleted_self = True