changeset 1023:8bae81e254a2

core: added a getReady method which can be called by frontends to ensure that backend is fully initialised before doing anything + this ckeck is automatically done in asyncConnect
author Goffi <goffi@goffi.org>
date Thu, 15 May 2014 16:02:16 +0200
parents 002ee8397208
children 7e43ea75cce8
files frontends/src/bridge/DBus.py src/bridge/DBus.py src/bridge/bridge_constructor/bridge_template.ini src/core/sat_main.py src/memory/params.py
diffstat 5 files changed, 85 insertions(+), 65 deletions(-) [+]
line wrap: on
line diff
--- a/frontends/src/bridge/DBus.py	Wed May 14 13:26:23 2014 +0200
+++ b/frontends/src/bridge/DBus.py	Thu May 15 16:02:16 2014 +0200
@@ -180,6 +180,9 @@
     def getProgress(self, id, profile):
         return self.db_core_iface.getProgress(id, profile)
 
+    def getReady(self, , callback=None, errback=None):
+        return self.db_core_iface.getReady(reply_handler=callback, error_handler=lambda err:errback(err._dbus_error_name[len(const_ERROR_PREFIX)+1:]))
+
     def getVersion(self, ):
         return unicode(self.db_core_iface.getVersion())
 
--- a/src/bridge/DBus.py	Wed May 14 13:26:23 2014 +0200
+++ b/src/bridge/DBus.py	Thu May 15 16:02:16 2014 +0200
@@ -356,6 +356,12 @@
         return self._callback("getProgress", unicode(id), unicode(profile))
 
     @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
+                         in_signature='', out_signature='',
+                         async_callbacks=('callback', 'errback'))
+    def getReady(self, callback=None, errback=None):
+        return self._callback("getReady", callback=callback, errback=errback)
+
+    @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
                          in_signature='', out_signature='s',
                          async_callbacks=None)
     def getVersion(self, ):
--- a/src/bridge/bridge_constructor/bridge_template.ini	Wed May 14 13:26:23 2014 +0200
+++ b/src/bridge/bridge_constructor/bridge_template.ini	Thu May 15 16:02:16 2014 +0200
@@ -156,6 +156,14 @@
 
 ;methods
 
+[getReady]
+async=
+type=method
+category=core
+sig_in=
+sig_out=
+doc=Return when backend is initialised
+
 [getVersion]
 type=method
 category=core
--- a/src/core/sat_main.py	Wed May 14 13:26:23 2014 +0200
+++ b/src/core/sat_main.py	Thu May 15 16:02:16 2014 +0200
@@ -93,6 +93,7 @@
         except exceptions.BridgeInitError:
             log.error(u"Bridge can't be initialised, can't start SàT core")
             sys.exit(1)
+        self.bridge.register("getReady", lambda: self.memory.initialized)
         self.bridge.register("getVersion", lambda: C.APP_VERSION)
         self.bridge.register("getProfileName", self.memory.getProfileName)
         self.bridge.register("getProfilesList", self.memory.getProfilesList)
@@ -203,88 +204,90 @@
         """Connect to jabber server with asynchronous reply
         @param profile_key: %(doc_profile)s
         """
-        profile = self.memory.getProfileName(profile_key)
-        if not profile:
-            log.error(_('Trying to connect a non-existant profile'))
-            raise exceptions.ProfileUnknownError(profile_key)
+        def backend_initialized(ignore):
+            profile = self.memory.getProfileName(profile_key)
+            if not profile:
+                log.error(_('Trying to connect a non-existant profile'))
+                raise exceptions.ProfileUnknownError(profile_key)
 
-        if self.isConnected(profile):
-            log.info(_("already connected !"))
-            return defer.succeed("None")
+            if self.isConnected(profile):
+                log.info(_("already connected !"))
+                return defer.succeed("None")
 
-        def afterMemoryInit(ignore):
-            """This part must be called when we have loaded individual parameters from memory"""
-            try:
-                port = int(self.memory.getParamA("Port", "Connection", profile_key=profile))
-            except ValueError:
-                log.error(_("Can't parse port value, using default value"))
-                port = 5222
+            def afterMemoryInit(ignore):
+                """This part must be called when we have loaded individual parameters from memory"""
+                try:
+                    port = int(self.memory.getParamA("Port", "Connection", profile_key=profile))
+                except ValueError:
+                    log.error(_("Can't parse port value, using default value"))
+                    port = 5222
 
-            current = self.profiles[profile] = xmpp.SatXMPPClient(
-                self, profile,
-                jid.JID(self.memory.getParamA("JabberID", "Connection", profile_key=profile), profile),
-                self.memory.getParamA("Password", "Connection", profile_key=profile),
-                self.memory.getParamA("Server", "Connection", profile_key=profile),
-                port)
+                current = self.profiles[profile] = xmpp.SatXMPPClient(
+                    self, profile,
+                    jid.JID(self.memory.getParamA("JabberID", "Connection", profile_key=profile), profile),
+                    self.memory.getParamA("Password", "Connection", profile_key=profile),
+                    self.memory.getParamA("Server", "Connection", profile_key=profile),
+                    port)
 
-            current.messageProt = xmpp.SatMessageProtocol(self)
-            current.messageProt.setHandlerParent(current)
+                current.messageProt = xmpp.SatMessageProtocol(self)
+                current.messageProt.setHandlerParent(current)
 
-            current.roster = xmpp.SatRosterProtocol(self)
-            current.roster.setHandlerParent(current)
+                current.roster = xmpp.SatRosterProtocol(self)
+                current.roster.setHandlerParent(current)
 
-            current.presence = xmpp.SatPresenceProtocol(self)
-            current.presence.setHandlerParent(current)
+                current.presence = xmpp.SatPresenceProtocol(self)
+                current.presence.setHandlerParent(current)
 
-            current.fallBack = xmpp.SatFallbackHandler(self)
-            current.fallBack.setHandlerParent(current)
+                current.fallBack = xmpp.SatFallbackHandler(self)
+                current.fallBack.setHandlerParent(current)
 
-            current.versionHandler = xmpp.SatVersionHandler(C.APP_NAME_FULL,
-                                                            C.APP_VERSION)
-            current.versionHandler.setHandlerParent(current)
+                current.versionHandler = xmpp.SatVersionHandler(C.APP_NAME_FULL,
+                                                                C.APP_VERSION)
+                current.versionHandler.setHandlerParent(current)
 
-            current.identityHandler = xmpp.SatIdentityHandler()
-            current.identityHandler.setHandlerParent(current)
+                current.identityHandler = xmpp.SatIdentityHandler()
+                current.identityHandler.setHandlerParent(current)
 
-            log.debug(_("setting plugins parents"))
+                log.debug(_("setting plugins parents"))
 
-            plugin_conn_cb = []
-            for plugin in self.plugins.iteritems():
-                if plugin[1].is_handler:
-                    plugin[1].getHandler(profile).setHandlerParent(current)
-                connected_cb = getattr(plugin[1], "profileConnected", None)
-                if connected_cb:
-                    plugin_conn_cb.append((plugin[0], connected_cb))
+                plugin_conn_cb = []
+                for plugin in self.plugins.iteritems():
+                    if plugin[1].is_handler:
+                        plugin[1].getHandler(profile).setHandlerParent(current)
+                    connected_cb = getattr(plugin[1], "profileConnected", None)
+                    if connected_cb:
+                        plugin_conn_cb.append((plugin[0], connected_cb))
 
-            current.startService()
+                current.startService()
 
-            d = current.getConnectionDeferred()
-            d.addCallback(lambda dummy: current.roster.got_roster)  # we want to be sure that we got the roster
+                d = current.getConnectionDeferred()
+                d.addCallback(lambda dummy: current.roster.got_roster)  # we want to be sure that we got the roster
 
-            def pluginsConnection(dummy):
-                """Call profileConnected callback for all plugins, and print error message if any of them fails"""
-                conn_cb_list = []
-                for dummy, callback in plugin_conn_cb:
-                    conn_cb_list.append(defer.maybeDeferred(callback, profile))
-                list_d = defer.DeferredList(conn_cb_list)
+                def pluginsConnection(dummy):
+                    """Call profileConnected callback for all plugins, and print error message if any of them fails"""
+                    conn_cb_list = []
+                    for dummy, callback in plugin_conn_cb:
+                        conn_cb_list.append(defer.maybeDeferred(callback, profile))
+                    list_d = defer.DeferredList(conn_cb_list)
 
-                def logPluginResults(results):
-                    all_succeed = all([success for success, result in results])
-                    if not all_succeed:
-                        log.error(_("Plugins initialisation error"))
-                        for idx, (success, result) in enumerate(results):
-                            if not success:
-                                log.error("error (plugin %(name)s): %(failure)s" % {'name': plugin_conn_cb[idx][0],
-                                                                                'failure': result})
+                    def logPluginResults(results):
+                        all_succeed = all([success for success, result in results])
+                        if not all_succeed:
+                            log.error(_("Plugins initialisation error"))
+                            for idx, (success, result) in enumerate(results):
+                                if not success:
+                                    log.error("error (plugin %(name)s): %(failure)s" % {'name': plugin_conn_cb[idx][0],
+                                                                                    'failure': result})
 
-                list_d.addCallback(logPluginResults)
-                return list_d
+                    list_d.addCallback(logPluginResults)
+                    return list_d
 
-            d.addCallback(pluginsConnection)
-            return d
+                d.addCallback(pluginsConnection)
+                return d
 
-        self.memory.startProfileSession(profile)
-        return self.memory.loadIndividualParams(profile).addCallback(afterMemoryInit)
+            self.memory.startProfileSession(profile)
+            return self.memory.loadIndividualParams(profile).addCallback(afterMemoryInit)
+        return self.memory.initialized.addCallback(backend_initialized)
 
     def disconnect(self, profile_key):
         """disconnect from jabber server"""
--- a/src/memory/params.py	Wed May 14 13:26:23 2014 +0200
+++ b/src/memory/params.py	Thu May 15 16:02:16 2014 +0200
@@ -187,7 +187,7 @@
         elif return_profile_keys and profile_key in ["@ALL@"]:
             return profile_key # this value must be managed by the caller
         if not self.storage.hasProfile(profile_key):
-            log.info(_('Trying to access an unknown profile'))
+            log.error(_('Trying to access an unknown profile'))
             return "" # FIXME: raise exceptions.ProfileUnknownError here (must be well checked, this method is used in lot of places)
         return profile_key