Mercurial > libervia-backend
comparison src/bridge/bridge_constructor/constructors/dbus/dbus_core_template.py @ 2085:da4097de5a95
bridge (constructor): refactoring:
- constructors are now in separate modules
- constructors are discovered dynamically
- factorised generation code from D-Bus in base Constructor.
- A generic generation method is now available in base Constructor, using python formatting.
- removed bridge/bridge.py in core as it was useless, may come back in the future if needed
author | Goffi <goffi@goffi.org> |
---|---|
date | Sun, 02 Oct 2016 22:44:33 +0200 |
parents | src/bridge/bridge_constructor/dbus_core_template.py@2daf7b4c6756 |
children | 4633cfcbcccb |
comparison
equal
deleted
inserted
replaced
2084:e1015a5df6f5 | 2085:da4097de5a95 |
---|---|
1 #!/usr/bin/env python2 | |
2 #-*- coding: utf-8 -*- | |
3 | |
4 # SAT: a jabber client | |
5 # Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org) | |
6 | |
7 # This program is free software: you can redistribute it and/or modify | |
8 # it under the terms of the GNU Affero General Public License as published by | |
9 # the Free Software Foundation, either version 3 of the License, or | |
10 # (at your option) any later version. | |
11 | |
12 # This program is distributed in the hope that it will be useful, | |
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 # GNU Affero General Public License for more details. | |
16 | |
17 # You should have received a copy of the GNU Affero General Public License | |
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
19 | |
20 from sat.core.i18n import _ | |
21 import dbus | |
22 import dbus.service | |
23 import dbus.mainloop.glib | |
24 import inspect | |
25 from sat.core.log import getLogger | |
26 log = getLogger(__name__) | |
27 from twisted.internet.defer import Deferred | |
28 from sat.core.exceptions import BridgeInitError | |
29 | |
30 const_INT_PREFIX = "org.goffi.SAT" # Interface prefix | |
31 const_ERROR_PREFIX = const_INT_PREFIX + ".error" | |
32 const_OBJ_PATH = '/org/goffi/SAT/bridge' | |
33 const_CORE_SUFFIX = ".core" | |
34 const_PLUGIN_SUFFIX = ".plugin" | |
35 | |
36 | |
37 class ParseError(Exception): | |
38 pass | |
39 | |
40 | |
41 class MethodNotRegistered(dbus.DBusException): | |
42 _dbus_error_name = const_ERROR_PREFIX + ".MethodNotRegistered" | |
43 | |
44 | |
45 class InternalError(dbus.DBusException): | |
46 _dbus_error_name = const_ERROR_PREFIX + ".InternalError" | |
47 | |
48 | |
49 class AsyncNotDeferred(dbus.DBusException): | |
50 _dbus_error_name = const_ERROR_PREFIX + ".AsyncNotDeferred" | |
51 | |
52 | |
53 class DeferredNotAsync(dbus.DBusException): | |
54 _dbus_error_name = const_ERROR_PREFIX + ".DeferredNotAsync" | |
55 | |
56 | |
57 class GenericException(dbus.DBusException): | |
58 def __init__(self, twisted_error): | |
59 """ | |
60 | |
61 @param twisted_error (Failure): instance of twisted Failure | |
62 @return: DBusException | |
63 """ | |
64 super(GenericException, self).__init__() | |
65 try: | |
66 # twisted_error.value is a class | |
67 class_ = twisted_error.value().__class__ | |
68 except TypeError: | |
69 # twisted_error.value is an instance | |
70 class_ = twisted_error.value.__class__ | |
71 message = twisted_error.getErrorMessage() | |
72 try: | |
73 self.args = (message, twisted_error.value.condition) | |
74 except AttributeError: | |
75 self.args = (message,) | |
76 self._dbus_error_name = '.'.join([const_ERROR_PREFIX, class_.__module__, class_.__name__]) | |
77 | |
78 | |
79 class DbusObject(dbus.service.Object): | |
80 | |
81 def __init__(self, bus, path): | |
82 dbus.service.Object.__init__(self, bus, path) | |
83 log.debug("Init DbusObject...") | |
84 self.cb = {} | |
85 | |
86 def register(self, name, cb): | |
87 self.cb[name] = cb | |
88 | |
89 def _callback(self, name, *args, **kwargs): | |
90 """call the callback if it exists, raise an exception else | |
91 if the callback return a deferred, use async methods""" | |
92 if not name in self.cb: | |
93 raise MethodNotRegistered | |
94 | |
95 if "callback" in kwargs: | |
96 #we must have errback too | |
97 if not "errback" in kwargs: | |
98 log.error("errback is missing in method call [%s]" % name) | |
99 raise InternalError | |
100 callback = kwargs.pop("callback") | |
101 errback = kwargs.pop("errback") | |
102 async = True | |
103 else: | |
104 async = False | |
105 result = self.cb[name](*args, **kwargs) | |
106 if async: | |
107 if not isinstance(result, Deferred): | |
108 log.error("Asynchronous method [%s] does not return a Deferred." % name) | |
109 raise AsyncNotDeferred | |
110 result.addCallback(lambda result: callback() if result is None else callback(result)) | |
111 result.addErrback(lambda err: errback(GenericException(err))) | |
112 else: | |
113 if isinstance(result, Deferred): | |
114 log.error("Synchronous method [%s] return a Deferred." % name) | |
115 raise DeferredNotAsync | |
116 return result | |
117 ### signals ### | |
118 | |
119 @dbus.service.signal(const_INT_PREFIX + const_PLUGIN_SUFFIX, | |
120 signature='') | |
121 def dummySignal(self): | |
122 #FIXME: workaround for addSignal (doesn't work if one method doensn't | |
123 # already exist for plugins), probably missing some initialisation, need | |
124 # further investigations | |
125 pass | |
126 | |
127 ##SIGNALS_PART## | |
128 ### methods ### | |
129 | |
130 ##METHODS_PART## | |
131 def __attributes(self, in_sign): | |
132 """Return arguments to user given a in_sign | |
133 @param in_sign: in_sign in the short form (using s,a,i,b etc) | |
134 @return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")""" | |
135 i = 0 | |
136 idx = 0 | |
137 attr = [] | |
138 while i < len(in_sign): | |
139 if in_sign[i] not in ['b', 'y', 'n', 'i', 'x', 'q', 'u', 't', 'd', 's', 'a']: | |
140 raise ParseError("Unmanaged attribute type [%c]" % in_sign[i]) | |
141 | |
142 attr.append("arg_%i" % idx) | |
143 idx += 1 | |
144 | |
145 if in_sign[i] == 'a': | |
146 i += 1 | |
147 if in_sign[i] != '{' and in_sign[i] != '(': # FIXME: must manage tuples out of arrays | |
148 i += 1 | |
149 continue # we have a simple type for the array | |
150 opening_car = in_sign[i] | |
151 assert(opening_car in ['{', '(']) | |
152 closing_car = '}' if opening_car == '{' else ')' | |
153 opening_count = 1 | |
154 while (True): # we have a dict or a list of tuples | |
155 i += 1 | |
156 if i >= len(in_sign): | |
157 raise ParseError("missing }") | |
158 if in_sign[i] == opening_car: | |
159 opening_count += 1 | |
160 if in_sign[i] == closing_car: | |
161 opening_count -= 1 | |
162 if opening_count == 0: | |
163 break | |
164 i += 1 | |
165 return attr | |
166 | |
167 def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False): | |
168 """Dynamically add a method to Dbus Bridge""" | |
169 inspect_args = inspect.getargspec(method) | |
170 | |
171 _arguments = inspect_args.args | |
172 _defaults = list(inspect_args.defaults or []) | |
173 | |
174 if inspect.ismethod(method): | |
175 #if we have a method, we don't want the first argument (usually 'self') | |
176 del(_arguments[0]) | |
177 | |
178 #first arguments are for the _callback method | |
179 arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback', 'errback=errback']) if async else _arguments)) | |
180 | |
181 if async: | |
182 _arguments.extend(['callback', 'errback']) | |
183 _defaults.extend([None, None]) | |
184 | |
185 #now we create a second list with default values | |
186 for i in range(1, len(_defaults) + 1): | |
187 _arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i])) | |
188 | |
189 arguments_defaults = ', '.join(_arguments) | |
190 | |
191 code = compile('def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)' % | |
192 {'name': name, 'arguments_defaults': arguments_defaults, 'arguments_callback': arguments_callback}, '<DBus bridge>', 'exec') | |
193 exec (code) # FIXME: to the same thing in a cleaner way, without compile/exec | |
194 method = locals()[name] | |
195 async_callbacks = ('callback', 'errback') if async else None | |
196 setattr(DbusObject, name, dbus.service.method( | |
197 const_INT_PREFIX + int_suffix, in_signature=in_sign, out_signature=out_sign, | |
198 async_callbacks=async_callbacks)(method)) | |
199 function = getattr(self, name) | |
200 func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface] | |
201 func_table[function.__name__] = function # Needed for introspection | |
202 | |
203 def addSignal(self, name, int_suffix, signature, doc={}): | |
204 """Dynamically add a signal to Dbus Bridge""" | |
205 attributes = ', '.join(self.__attributes(signature)) | |
206 #TODO: use doc parameter to name attributes | |
207 | |
208 #code = compile ('def '+name+' (self,'+attributes+'): log.debug ("'+name+' signal")', '<DBus bridge>','exec') #XXX: the log.debug is too annoying with xmllog | |
209 code = compile('def ' + name + ' (self,' + attributes + '): pass', '<DBus bridge>', 'exec') | |
210 exec (code) | |
211 signal = locals()[name] | |
212 setattr(DbusObject, name, dbus.service.signal( | |
213 const_INT_PREFIX + int_suffix, signature=signature)(signal)) | |
214 function = getattr(self, name) | |
215 func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface] | |
216 func_table[function.__name__] = function # Needed for introspection | |
217 | |
218 | |
219 class DBusBridge(object): | |
220 def __init__(self): | |
221 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) | |
222 log.info("Init DBus...") | |
223 try: | |
224 self.session_bus = dbus.SessionBus() | |
225 except dbus.DBusException as e: | |
226 if e._dbus_error_name == 'org.freedesktop.DBus.Error.NotSupported': | |
227 log.error(_(u"D-Bus is not launched, please see README to see instructions on how to launch it")) | |
228 raise BridgeInitError | |
229 self.dbus_name = dbus.service.BusName(const_INT_PREFIX, self.session_bus) | |
230 self.dbus_bridge = DbusObject(self.session_bus, const_OBJ_PATH) | |
231 | |
232 ##SIGNAL_DIRECT_CALLS_PART## | |
233 def register(self, name, callback): | |
234 log.debug("registering DBus bridge method [%s]" % name) | |
235 self.dbus_bridge.register(name, callback) | |
236 | |
237 def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False, doc={}): | |
238 """Dynamically add a method to Dbus Bridge""" | |
239 #FIXME: doc parameter is kept only temporary, the time to remove it from calls | |
240 log.debug("Adding method [%s] to DBus bridge" % name) | |
241 self.dbus_bridge.addMethod(name, int_suffix, in_sign, out_sign, method, async) | |
242 self.register(name, method) | |
243 | |
244 def addSignal(self, name, int_suffix, signature, doc={}): | |
245 self.dbus_bridge.addSignal(name, int_suffix, signature, doc) | |
246 setattr(DBusBridge, name, getattr(self.dbus_bridge, name)) |