changeset 1152:1c23252958ed

server: iNotify support: a new FileWatcher class allows to check modifications in a directory.
author Goffi <goffi@goffi.org>
date Fri, 22 Feb 2019 16:57:37 +0100
parents 49ff1330c9d0
children 94f9d81a475e
files libervia/server/server.py
diffstat 1 files changed, 29 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/libervia/server/server.py	Fri Feb 22 16:56:58 2019 +0100
+++ b/libervia/server/server.py	Fri Feb 22 16:57:37 2019 +0100
@@ -28,7 +28,7 @@
 import urllib
 import time
 from twisted.application import service
-from twisted.internet import reactor, defer
+from twisted.internet import reactor, defer, inotify
 from twisted.web import server
 from twisted.web import static
 from twisted.web import resource as web_resource
@@ -37,6 +37,7 @@
 from twisted.web import vhost
 from twisted.python.components import registerAdapter
 from twisted.python import failure
+from twisted.python import filepath
 from twisted.words.protocols.jabber import jid
 
 from txjsonrpc.web import jsonrpc
@@ -80,6 +81,32 @@
 # following value are set from twisted.plugins.libervia_server initialise
 # (see the comment there)
 DATA_DIR_DEFAULT = OPT_PARAMETERS_BOTH = OPT_PARAMETERS_CFG = coerceDataDir = None
+DEFAULT_MASK = (inotify.IN_CREATE | inotify.IN_MODIFY | inotify.IN_MOVE_SELF
+                | inotify.IN_MOVED_TO)
+
+
+class FilesWatcher(object):
+    """Class to check files modifications using iNotify"""
+    _notifier = None
+
+    def __init__(self, host):
+        self.host = host
+
+    @property
+    def notifier(self):
+        if self._notifier == None:
+            notifier = self.__class__._notifier = inotify.INotify()
+            notifier.startReading()
+        return self._notifier
+
+    def watchDir(self, dir_path, callback, mask=DEFAULT_MASK, auto_add=False,
+                 recursive=False, **kwargs):
+        log.info(_(u"Watching directory {dir_path}").format(dir_path=dir_path))
+        callbacks = [lambda __, filepath, mask: callback(self.host, filepath,
+                     inotify.humanReadableMask(mask), **kwargs)]
+        self.notifier.watch(
+            filepath.FilePath(dir_path), mask=mask, autoAdd=auto_add, recursive=recursive,
+            callbacks=callbacks)
 
 
 class LiberviaSession(server.Session):
@@ -1708,6 +1735,7 @@
         self.initialised = defer.Deferred()
         self.waiting_profiles = WaitingRequests()  # FIXME: should be removed
         self._main_conf = None
+        self.files_watcher = FilesWatcher(self)
 
         if self.options["base_url_ext"]:
             self.base_url_ext = self.options.pop("base_url_ext")