api.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
  5. # Copyright 2012 Google, Inc.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. from __future__ import with_statement
  19. import threading
  20. from watchdog.utils import BaseThread
  21. from watchdog.utils.compat import queue
  22. from watchdog.utils.bricks import SkipRepeatsQueue
  23. DEFAULT_EMITTER_TIMEOUT = 1 # in seconds.
  24. DEFAULT_OBSERVER_TIMEOUT = 1 # in seconds.
  25. # Collection classes
  26. class EventQueue(SkipRepeatsQueue):
  27. """Thread-safe event queue based on a special queue that skips adding
  28. the same event (:class:`FileSystemEvent`) multiple times consecutively.
  29. Thus avoiding dispatching multiple event handling
  30. calls when multiple identical events are produced quicker than an observer
  31. can consume them.
  32. """
  33. class ObservedWatch(object):
  34. """An scheduled watch.
  35. :param path:
  36. Path string.
  37. :param recursive:
  38. ``True`` if watch is recursive; ``False`` otherwise.
  39. """
  40. def __init__(self, path, recursive):
  41. self._path = path
  42. self._is_recursive = recursive
  43. @property
  44. def path(self):
  45. """The path that this watch monitors."""
  46. return self._path
  47. @property
  48. def is_recursive(self):
  49. """Determines whether subdirectories are watched for the path."""
  50. return self._is_recursive
  51. @property
  52. def key(self):
  53. return self.path, self.is_recursive
  54. def __eq__(self, watch):
  55. return self.key == watch.key
  56. def __ne__(self, watch):
  57. return self.key != watch.key
  58. def __hash__(self):
  59. return hash(self.key)
  60. def __repr__(self):
  61. return "<%s: path=%s, is_recursive=%s>" % (
  62. type(self).__name__, self.path, self.is_recursive)
  63. # Observer classes
  64. class EventEmitter(BaseThread):
  65. """
  66. Producer thread base class subclassed by event emitters
  67. that generate events and populate a queue with them.
  68. :param event_queue:
  69. The event queue to populate with generated events.
  70. :type event_queue:
  71. :class:`watchdog.events.EventQueue`
  72. :param watch:
  73. The watch to observe and produce events for.
  74. :type watch:
  75. :class:`ObservedWatch`
  76. :param timeout:
  77. Timeout (in seconds) between successive attempts at reading events.
  78. :type timeout:
  79. ``float``
  80. """
  81. def __init__(self, event_queue, watch, timeout=DEFAULT_EMITTER_TIMEOUT):
  82. BaseThread.__init__(self)
  83. self._event_queue = event_queue
  84. self._watch = watch
  85. self._timeout = timeout
  86. @property
  87. def timeout(self):
  88. """
  89. Blocking timeout for reading events.
  90. """
  91. return self._timeout
  92. @property
  93. def watch(self):
  94. """
  95. The watch associated with this emitter.
  96. """
  97. return self._watch
  98. def queue_event(self, event):
  99. """
  100. Queues a single event.
  101. :param event:
  102. Event to be queued.
  103. :type event:
  104. An instance of :class:`watchdog.events.FileSystemEvent`
  105. or a subclass.
  106. """
  107. self._event_queue.put((event, self.watch))
  108. def queue_events(self, timeout):
  109. """Override this method to populate the event queue with events
  110. per interval period.
  111. :param timeout:
  112. Timeout (in seconds) between successive attempts at
  113. reading events.
  114. :type timeout:
  115. ``float``
  116. """
  117. def run(self):
  118. while self.should_keep_running():
  119. self.queue_events(self.timeout)
  120. class EventDispatcher(BaseThread):
  121. """
  122. Consumer thread base class subclassed by event observer threads
  123. that dispatch events from an event queue to appropriate event handlers.
  124. :param timeout:
  125. Event queue blocking timeout (in seconds).
  126. :type timeout:
  127. ``float``
  128. """
  129. def __init__(self, timeout=DEFAULT_OBSERVER_TIMEOUT):
  130. BaseThread.__init__(self)
  131. self._event_queue = EventQueue()
  132. self._timeout = timeout
  133. @property
  134. def timeout(self):
  135. """Event queue block timeout."""
  136. return self._timeout
  137. @property
  138. def event_queue(self):
  139. """The event queue which is populated with file system events
  140. by emitters and from which events are dispatched by a dispatcher
  141. thread."""
  142. return self._event_queue
  143. def dispatch_events(self, event_queue, timeout):
  144. """Override this method to consume events from an event queue, blocking
  145. on the queue for the specified timeout before raising :class:`queue.Empty`.
  146. :param event_queue:
  147. Event queue to populate with one set of events.
  148. :type event_queue:
  149. :class:`EventQueue`
  150. :param timeout:
  151. Interval period (in seconds) to wait before timing out on the
  152. event queue.
  153. :type timeout:
  154. ``float``
  155. :raises:
  156. :class:`queue.Empty`
  157. """
  158. def run(self):
  159. while self.should_keep_running():
  160. try:
  161. self.dispatch_events(self.event_queue, self.timeout)
  162. except queue.Empty:
  163. continue
  164. class BaseObserver(EventDispatcher):
  165. """Base observer."""
  166. def __init__(self, emitter_class, timeout=DEFAULT_OBSERVER_TIMEOUT):
  167. EventDispatcher.__init__(self, timeout)
  168. self._emitter_class = emitter_class
  169. self._lock = threading.RLock()
  170. self._watches = set()
  171. self._handlers = dict()
  172. self._emitters = set()
  173. self._emitter_for_watch = dict()
  174. def _add_emitter(self, emitter):
  175. self._emitter_for_watch[emitter.watch] = emitter
  176. self._emitters.add(emitter)
  177. def _remove_emitter(self, emitter):
  178. del self._emitter_for_watch[emitter.watch]
  179. self._emitters.remove(emitter)
  180. emitter.stop()
  181. try:
  182. emitter.join()
  183. except RuntimeError:
  184. pass
  185. def _clear_emitters(self):
  186. for emitter in self._emitters:
  187. emitter.stop()
  188. for emitter in self._emitters:
  189. try:
  190. emitter.join()
  191. except RuntimeError:
  192. pass
  193. self._emitters.clear()
  194. self._emitter_for_watch.clear()
  195. def _add_handler_for_watch(self, event_handler, watch):
  196. if watch not in self._handlers:
  197. self._handlers[watch] = set()
  198. self._handlers[watch].add(event_handler)
  199. def _remove_handlers_for_watch(self, watch):
  200. del self._handlers[watch]
  201. @property
  202. def emitters(self):
  203. """Returns event emitter created by this observer."""
  204. return self._emitters
  205. def start(self):
  206. for emitter in self._emitters.copy():
  207. try:
  208. emitter.start()
  209. except Exception:
  210. self._remove_emitter(emitter)
  211. raise
  212. super(BaseObserver, self).start()
  213. def schedule(self, event_handler, path, recursive=False):
  214. """
  215. Schedules watching a path and calls appropriate methods specified
  216. in the given event handler in response to file system events.
  217. :param event_handler:
  218. An event handler instance that has appropriate event handling
  219. methods which will be called by the observer in response to
  220. file system events.
  221. :type event_handler:
  222. :class:`watchdog.events.FileSystemEventHandler` or a subclass
  223. :param path:
  224. Directory path that will be monitored.
  225. :type path:
  226. ``str``
  227. :param recursive:
  228. ``True`` if events will be emitted for sub-directories
  229. traversed recursively; ``False`` otherwise.
  230. :type recursive:
  231. ``bool``
  232. :return:
  233. An :class:`ObservedWatch` object instance representing
  234. a watch.
  235. """
  236. with self._lock:
  237. watch = ObservedWatch(path, recursive)
  238. self._add_handler_for_watch(event_handler, watch)
  239. # If we don't have an emitter for this watch already, create it.
  240. if self._emitter_for_watch.get(watch) is None:
  241. emitter = self._emitter_class(event_queue=self.event_queue,
  242. watch=watch,
  243. timeout=self.timeout)
  244. self._add_emitter(emitter)
  245. if self.is_alive():
  246. emitter.start()
  247. self._watches.add(watch)
  248. return watch
  249. def add_handler_for_watch(self, event_handler, watch):
  250. """Adds a handler for the given watch.
  251. :param event_handler:
  252. An event handler instance that has appropriate event handling
  253. methods which will be called by the observer in response to
  254. file system events.
  255. :type event_handler:
  256. :class:`watchdog.events.FileSystemEventHandler` or a subclass
  257. :param watch:
  258. The watch to add a handler for.
  259. :type watch:
  260. An instance of :class:`ObservedWatch` or a subclass of
  261. :class:`ObservedWatch`
  262. """
  263. with self._lock:
  264. self._add_handler_for_watch(event_handler, watch)
  265. def remove_handler_for_watch(self, event_handler, watch):
  266. """Removes a handler for the given watch.
  267. :param event_handler:
  268. An event handler instance that has appropriate event handling
  269. methods which will be called by the observer in response to
  270. file system events.
  271. :type event_handler:
  272. :class:`watchdog.events.FileSystemEventHandler` or a subclass
  273. :param watch:
  274. The watch to remove a handler for.
  275. :type watch:
  276. An instance of :class:`ObservedWatch` or a subclass of
  277. :class:`ObservedWatch`
  278. """
  279. with self._lock:
  280. self._handlers[watch].remove(event_handler)
  281. def unschedule(self, watch):
  282. """Unschedules a watch.
  283. :param watch:
  284. The watch to unschedule.
  285. :type watch:
  286. An instance of :class:`ObservedWatch` or a subclass of
  287. :class:`ObservedWatch`
  288. """
  289. with self._lock:
  290. emitter = self._emitter_for_watch[watch]
  291. del self._handlers[watch]
  292. self._remove_emitter(emitter)
  293. self._watches.remove(watch)
  294. def unschedule_all(self):
  295. """Unschedules all watches and detaches all associated event
  296. handlers."""
  297. with self._lock:
  298. self._handlers.clear()
  299. self._clear_emitters()
  300. self._watches.clear()
  301. def on_thread_stop(self):
  302. self.unschedule_all()
  303. def dispatch_events(self, event_queue, timeout):
  304. event, watch = event_queue.get(block=True, timeout=timeout)
  305. with self._lock:
  306. # To allow unschedule/stop and safe removal of event handlers
  307. # within event handlers itself, check if the handler is still
  308. # registered after every dispatch.
  309. for handler in list(self._handlers.get(watch, [])):
  310. if handler in self._handlers.get(watch, []):
  311. handler.dispatch(event)
  312. event_queue.task_done()