comparison src/bridge/bridge_constructor/constructors/dbus/dbus_frontend_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_frontend_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 communication bridge
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 from bridge_frontend import BridgeFrontend, BridgeException
22 import dbus
23 from sat.core.log import getLogger
24 log = getLogger(__name__)
25 from sat.core.exceptions import BridgeExceptionNoService, BridgeInitError
26
27 from dbus.mainloop.glib import DBusGMainLoop
28 DBusGMainLoop(set_as_default=True)
29
30 import ast
31
32 const_INT_PREFIX = "org.goffi.SAT" # Interface prefix
33 const_ERROR_PREFIX = const_INT_PREFIX + ".error"
34 const_OBJ_PATH = '/org/goffi/SAT/bridge'
35 const_CORE_SUFFIX = ".core"
36 const_PLUGIN_SUFFIX = ".plugin"
37 const_TIMEOUT = 120
38
39
40 def dbus_to_bridge_exception(dbus_e):
41 """Convert a DBusException to a BridgeException.
42
43 @param dbus_e (DBusException)
44 @return: BridgeException
45 """
46 full_name = dbus_e.get_dbus_name()
47 if full_name.startswith(const_ERROR_PREFIX):
48 name = dbus_e.get_dbus_name()[len(const_ERROR_PREFIX) + 1:]
49 else:
50 name = full_name
51 # XXX: dbus_e.args doesn't contain the original DBusException args, but we
52 # receive its serialized form in dbus_e.args[0]. From that we can rebuild
53 # the original arguments list thanks to ast.literal_eval (secure eval).
54 message = dbus_e.get_dbus_message() # similar to dbus_e.args[0]
55 try:
56 message, condition = ast.literal_eval(message)
57 except (SyntaxError, ValueError, TypeError):
58 condition = ''
59 return BridgeException(name, message, condition)
60
61
62 class DBusBridgeFrontend(BridgeFrontend):
63 def __init__(self):
64 try:
65 self.sessions_bus = dbus.SessionBus()
66 self.db_object = self.sessions_bus.get_object(const_INT_PREFIX,
67 const_OBJ_PATH)
68 self.db_core_iface = dbus.Interface(self.db_object,
69 dbus_interface=const_INT_PREFIX + const_CORE_SUFFIX)
70 self.db_plugin_iface = dbus.Interface(self.db_object,
71 dbus_interface=const_INT_PREFIX + const_PLUGIN_SUFFIX)
72 except dbus.exceptions.DBusException, e:
73 if e._dbus_error_name in ('org.freedesktop.DBus.Error.ServiceUnknown',
74 'org.freedesktop.DBus.Error.Spawn.ExecFailed'):
75 raise BridgeExceptionNoService
76 elif e._dbus_error_name == 'org.freedesktop.DBus.Error.NotSupported':
77 log.error(_(u"D-Bus is not launched, please see README to see instructions on how to launch it"))
78 raise BridgeInitError
79 else:
80 raise e
81 #props = self.db_core_iface.getProperties()
82
83 def register(self, functionName, handler, iface="core"):
84 if iface == "core":
85 self.db_core_iface.connect_to_signal(functionName, handler)
86 elif iface == "plugin":
87 self.db_plugin_iface.connect_to_signal(functionName, handler)
88 else:
89 log.error(_('Unknown interface'))
90
91 def __getattribute__(self, name):
92 """ usual __getattribute__ if the method exists, else try to find a plugin method """
93 try:
94 return object.__getattribute__(self, name)
95 except AttributeError:
96 # The attribute is not found, we try the plugin proxy to find the requested method
97
98 def getPluginMethod(*args, **kwargs):
99 # We first check if we have an async call. We detect this in two ways:
100 # - if we have the 'callback' and 'errback' keyword arguments
101 # - or if the last two arguments are callable
102
103 async = False
104 args = list(args)
105
106 if kwargs:
107 if 'callback' in kwargs:
108 async = True
109 _callback = kwargs.pop('callback')
110 _errback = kwargs.pop('errback', lambda failure: log.error(unicode(failure)))
111 try:
112 args.append(kwargs.pop('profile'))
113 except KeyError:
114 try:
115 args.append(kwargs.pop('profile_key'))
116 except KeyError:
117 pass
118 # at this point, kwargs should be empty
119 if kwargs:
120 log.warnings(u"unexpected keyword arguments, they will be ignored: {}".format(kwargs))
121 elif len(args) >= 2 and callable(args[-1]) and callable(args[-2]):
122 async = True
123 _errback = args.pop()
124 _callback = args.pop()
125
126 method = getattr(self.db_plugin_iface, name)
127
128 if async:
129 kwargs['timeout'] = const_TIMEOUT
130 kwargs['reply_handler'] = _callback
131 kwargs['error_handler'] = lambda err: _errback(dbus_to_bridge_exception(err))
132
133 return method(*args, **kwargs)
134
135 return getPluginMethod
136
137 ##METHODS_PART##