bridbe(pb): Perspective Broker bridge, first draft
This commit is contained in:
parent
34cec8fe14
commit
90440303ea
4 changed files with 284 additions and 0 deletions
56
src/bridge/bridge_constructor/constructors/pb/constructor.py
Normal file
56
src/bridge/bridge_constructor/constructors/pb/constructor.py
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
#!/usr/bin/env python2
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# SàT: a XMPP client
|
||||
# Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from sat.bridge.bridge_constructor import base_constructor
|
||||
|
||||
|
||||
class pbConstructor(base_constructor.Constructor):
|
||||
NAME = "pb"
|
||||
CORE_TEMPLATE = "pb_core_template.py"
|
||||
CORE_DEST = "pb.py"
|
||||
CORE_FORMATS = {
|
||||
'signals': """\
|
||||
def {name}(self, {args}):
|
||||
{debug}self.sendSignal("{name}", {args_no_def})\n""",
|
||||
}
|
||||
|
||||
FRONTEND_TEMPLATE = "pb_frontend_template.py"
|
||||
FRONTEND_DEST = CORE_DEST
|
||||
FRONTEND_FORMATS = {
|
||||
'methods': """\
|
||||
def {name}(self{args_comma}{args}, callback=None, errback=None):
|
||||
{debug}d = self.root.callRemote("{name}"{args_comma}{args_no_def})
|
||||
if callback is not None:
|
||||
d.addCallback({callback})
|
||||
if errback is None:
|
||||
errback = self._generic_errback
|
||||
d.addErrback(errback)\n""",
|
||||
}
|
||||
|
||||
def core_completion_signal(self, completion, function, default, arg_doc, async_):
|
||||
completion['args_no_def'] = self.getArguments(function['sig_in'], name=arg_doc)
|
||||
completion['debug'] = "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' ')
|
||||
|
||||
def frontend_completion_method(self, completion, function, default, arg_doc, async_):
|
||||
completion.update({
|
||||
'args_comma': ', ' if function['sig_in'] else '',
|
||||
'args_no_def': self.getArguments(function['sig_in'], name=arg_doc),
|
||||
'callback': 'callback' if function['sig_out'] else 'lambda dummy: callback()',
|
||||
'debug': "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' '),
|
||||
})
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
#!/usr/bin/env python2
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
from sat.core.log import getLogger
|
||||
log = getLogger(__name__)
|
||||
from twisted.spread import jelly, pb
|
||||
from twisted.internet import reactor
|
||||
|
||||
|
||||
## jelly hack
|
||||
# we monkey patch jelly to handle namedtuple
|
||||
ori_jelly = jelly._Jellier.jelly
|
||||
|
||||
def fixed_jelly(self, obj):
|
||||
"""this method fix handling of namedtuple"""
|
||||
if isinstance(obj, tuple) and not obj is tuple:
|
||||
obj = tuple(obj)
|
||||
return ori_jelly(self, obj)
|
||||
|
||||
jelly._Jellier.jelly = fixed_jelly
|
||||
|
||||
|
||||
class PBRoot(pb.Root):
|
||||
|
||||
def __init__(self):
|
||||
self.signals_handlers = []
|
||||
|
||||
def remote_initBridge(self, signals_handler):
|
||||
self.signals_handlers.append(signals_handler)
|
||||
log.info(u"registered signal handler")
|
||||
|
||||
def sendSignalEb(self, failure, signal_name):
|
||||
log.error(u"Error while sending signal {name}: {msg}".format(
|
||||
name = signal_name,
|
||||
msg = failure,
|
||||
))
|
||||
|
||||
def sendSignal(self, name, args, kwargs):
|
||||
to_remove = []
|
||||
for handler in self.signals_handlers:
|
||||
try:
|
||||
d = handler.callRemote(name, *args, **kwargs)
|
||||
except pb.DeadReferenceError:
|
||||
to_remove.append(handler)
|
||||
else:
|
||||
d.addErrback(self.sendSignalEb, name)
|
||||
if to_remove:
|
||||
for handler in to_remove:
|
||||
log.debug(u"Removing signal handler for dead frontend")
|
||||
self.signals_handlers.remove(handler)
|
||||
|
||||
##METHODS_PART##
|
||||
|
||||
|
||||
class Bridge(object):
|
||||
|
||||
def __init__(self):
|
||||
log.info("Init Perspective Broker...")
|
||||
self.root = PBRoot()
|
||||
reactor.listenTCP(8789, pb.PBServerFactory(self.root))
|
||||
|
||||
def sendSignal(self, name, *args, **kwargs):
|
||||
self.root.sendSignal(name, args, kwargs)
|
||||
|
||||
def remote_initBridge(self, signals_handler):
|
||||
self.signals_handlers.append(signals_handler)
|
||||
log.info(u"registered signal handler")
|
||||
|
||||
def register_method(self, name, callback):
|
||||
log.debug("registering PB bridge method [%s]" % name)
|
||||
setattr(self.root, "remote_"+name, callback)
|
||||
# self.root.register_method(name, callback)
|
||||
|
||||
def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False, doc={}):
|
||||
"""Dynamically add a method to PB Bridge"""
|
||||
#FIXME: doc parameter is kept only temporary, the time to remove it from calls
|
||||
log.debug("Adding method {name} to PB bridge".format(name=name))
|
||||
self.register_method(name, method)
|
||||
|
||||
def addSignal(self, name, int_suffix, signature, doc={}):
|
||||
log.debug("Adding signal {name} to PB bridge".format(name=name))
|
||||
setattr(self, name, lambda *args, **kwargs: self.sendSignal(name, *args, **kwargs))
|
||||
|
||||
##SIGNALS_PART##
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
#!/usr/bin/env python2
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# SAT communication bridge
|
||||
# Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from sat.core.log import getLogger
|
||||
log = getLogger(__name__)
|
||||
from sat.core import exceptions
|
||||
from twisted.spread import pb
|
||||
from twisted.internet import reactor
|
||||
|
||||
|
||||
class SignalsHandler(pb.Referenceable):
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name.startswith("remote_"):
|
||||
log.debug(u"calling an unregistered signal: {name}".format(
|
||||
name = name[7:]))
|
||||
return lambda *args, **kwargs: None
|
||||
|
||||
else:
|
||||
raise AttributeError(name)
|
||||
|
||||
def register_signal(self, name, handler, iface="core"):
|
||||
log.debug("registering signal {name}".format(name=name))
|
||||
method_name = "remote_" + name
|
||||
try:
|
||||
self.__getattribute__(self, method_name)
|
||||
except AttributeError:
|
||||
pass
|
||||
else:
|
||||
raise exceptions.InternalError(u"{name} signal handler has been registered twice".format(
|
||||
name = method_name))
|
||||
setattr(self, method_name, handler)
|
||||
|
||||
|
||||
class Bridge(object):
|
||||
|
||||
def __init__(self):
|
||||
self.signals_handler = SignalsHandler()
|
||||
|
||||
def __getattr__(self, name):
|
||||
return lambda *args, **kwargs: self.call(name, args, kwargs)
|
||||
|
||||
def remoteCallback(self, result, callback):
|
||||
"""call callback with argument or None
|
||||
|
||||
if result is not None not argument is used,
|
||||
else result is used as argument
|
||||
@param result: remote call result
|
||||
@param callback(callable): method to call on result
|
||||
"""
|
||||
if result is None:
|
||||
callback()
|
||||
else:
|
||||
callback(result)
|
||||
|
||||
def call(self, name, args, kwargs):
|
||||
"""call a remote method
|
||||
|
||||
@param name(str): name of the bridge method
|
||||
@param args(list): arguments
|
||||
may contain callback and errback as last 2 items
|
||||
@param kwargs(dict): keyword arguments
|
||||
may contain callback and errback
|
||||
"""
|
||||
callback = errback = None
|
||||
if kwargs:
|
||||
try:
|
||||
callback = kwargs.pop('callback')
|
||||
except KeyError:
|
||||
pass
|
||||
try:
|
||||
errback = kwargs.pop('errback')
|
||||
except KeyError:
|
||||
pass
|
||||
elif len(args) >= 2 and callable(args[-1]) and callable(args[-2]):
|
||||
errback = args.pop()
|
||||
callback = args.pop()
|
||||
d = self.root.callRemote(name, *args, **kwargs)
|
||||
if callback is not None:
|
||||
d.addCallback(self.remoteCallback, callback)
|
||||
if errback is not None:
|
||||
d.addErrback(errback)
|
||||
|
||||
def _initBridgeEb(self, failure):
|
||||
log.error(u"Can't init bridge: {msg}".format(msg=failure))
|
||||
|
||||
def _set_root(self, root):
|
||||
"""set remote root object
|
||||
|
||||
bridge will then be initialised
|
||||
"""
|
||||
self.root = root
|
||||
d = root.callRemote("initBridge", self.signals_handler)
|
||||
d.addErrback(self._initBridgeEb)
|
||||
return d
|
||||
|
||||
def _generic_errback(self, failure):
|
||||
log.error(u"bridge failure: {}".format(failure))
|
||||
|
||||
def bridgeConnect(self, callback, errback):
|
||||
factory = pb.PBClientFactory()
|
||||
reactor.connectTCP("localhost", 8789, factory)
|
||||
d = factory.getRootObject()
|
||||
d.addCallback(self._set_root)
|
||||
d.addCallback(lambda dummy: callback())
|
||||
d.addErrback(errback)
|
||||
|
||||
def register_signal(self, functionName, handler, iface="core"):
|
||||
self.signals_handler.register_signal(functionName, handler, iface)
|
||||
|
||||
##METHODS_PART##
|
||||
Loading…
Reference in a new issue