Example #1
0
class JSONRPCServer(BaseService):

    name = 'jsonrpc'

    def __init__(self, app):
        log.debug('initializing JSONRPCServer')
        BaseService.__init__(self, app)
        self.app = app
        self.dispatcher = RPCDispatcher()
        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

        # start wsgi server as a background-greenlet
        self.wsgi_server = gevent.wsgi.WSGIServer(('127.0.0.1', 5000),
                                                  transport.handle)

        self.rpc_server = RPCServerGreenlets(transport, JSONRPCProtocol(),
                                             self.dispatcher)

    def _run(self):
        log.info('starting JSONRPCServer')
        # in the main greenlet, run our rpc_server
        self.wsgi_thread = gevent.spawn(self.wsgi_server.serve_forever)
        self.rpc_server.serve_forever()

    def add_method(self, func, name=None):
        self.dispatcher.add_method(func, name)

    def stop(self):
        log.info('stopping JSONRPCServer')
        self.wsgi_thread.kill()
Example #2
0
class JSONRPCServer(BaseService):

    name = 'jsonrpc'

    def __init__(self, app):
        log.debug('initializing JSONRPCServer')
        BaseService.__init__(self, app)
        self.app = app
        self.dispatcher = RPCDispatcher()
        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

        # start wsgi server as a background-greenlet
        self.wsgi_server = gevent.wsgi.WSGIServer(('127.0.0.1', 5000), transport.handle)

        self.rpc_server = RPCServerGreenlets(
            transport,
            JSONRPCProtocol(),
            self.dispatcher
        )

    def _run(self):
        log.info('starting JSONRPCServer')
        # in the main greenlet, run our rpc_server
        self.wsgi_thread = gevent.spawn(self.wsgi_server.serve_forever)
        self.rpc_server.serve_forever()

    def add_method(self, func, name=None):
        self.dispatcher.add_method(func, name)

    def stop(self):
        log.info('stopping JSONRPCServer')
        self.wsgi_thread.kill()
Example #3
0
    def __init__(self, app):
        log.debug('initializing JSONRPCServer')
        BaseService.__init__(self, app)
        self.app = app
        self.dispatcher = RPCDispatcher()
        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

        # start wsgi server as a background-greenlet
        self.wsgi_server = gevent.wsgi.WSGIServer(('127.0.0.1', 5000),
                                                  transport.handle)

        self.rpc_server = RPCServerGreenlets(transport, JSONRPCProtocol(),
                                             self.dispatcher)
Example #4
0
 def __init__(self, agent_model=None, agent_channel=None):
     if agent_model:
         self.agent_model = agent_model
     if agent_channel:
         self.agent_channel = agent_channel
     if not self.agent_model:
         raise Exception('Odoo agent model not set!')
     if self.debug == '1':
         logger.setLevel(logging.DEBUG)
     else:
         logger.setLevel(logging.INFO)
     logger.info('Odoo agent UID {} version {} init'.format(
         self.agent_uid, self.version))
     # Init event with disconnected state
     self.odoo_disconnected.set()
     # Init WEB server
     if self.https_enabled:
         logger.debug('Loading HTTPS key from %s', self.https_key_file)
         logger.debug('Loading HTTPS cert from %s', self.https_cert_file)
         self.wsgi_server = WSGIServer(('', self.https_port),
                                       self.wsgi_application,
                                       keyfile=self.https_key_file,
                                       certfile=self.https_cert_file)
     # Hack for slef-signed certificates.
     if not self.odoo_verify_cert:
         # Monkey patch SSL for self signed certificates
         import ssl
         if hasattr(ssl, '_create_unverified_context'):
             ssl._create_default_https_context = ssl._create_unverified_context
         # Supress InsecureRequestWarning on odoo_bus_poll
         import urllib3
         urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
         logging.getLogger("urllib3").setLevel(logging.ERROR)
         # Init RPC
     rpc_dispatcher.register_instance(self)
     self.bus_rpc_server = RPCServerGreenlets(
         AgentCallbackServerTransport(self.receive_bus_rpc_message,
                                      self.send_bus_rpc_reply),
         rpc_protocol, rpc_dispatcher)
     self.https_rpc_server = RPCServerGreenlets(
         AgentCallbackServerTransport(self.receive_https_rpc_message,
                                      self.send_https_rpc_reply),
         rpc_protocol, rpc_dispatcher)
     if self.trace_rpc:
         self.bus_rpc_server.trace = self.trace_rpc_message
         self.https_rpc_server.trace = self.trace_rpc_message
Example #5
0
def nsRPCBringupServer(ns, path, host, port, maxconn):
    name = os.path.basename(path)
    dev_path = '/dev/rpc/{}'.format(name)
    if nsRPCisServer(ns, path) is not True:
        nsError(ns, "RPC service {} misconfigured".format(name))
        return False
    nsInfo(ns, "Configuring RPC server from {}".format(path))
    nsMkdir(ns, dev_path)
    nsMkdir(ns, "{}/root".format(dev_path))
    _to_root = nsGet(ns, "{}/jail".format(path), [])
    for j in _to_root:
        _n = os.path.basename(j)
        _dst = "{}/root/{}".format(dev_path, _n)
        nsInfo(ns, "RPC.JAIL({}): {}".format(name, j))
        nsLn(ns, j, _dst)
    dispatcher = RPCDispatcher()
    nsSet(ns, "{}/dispatcher".format(dev_path), dispatcher)
    for h in nsLs(ns, "{}/handlers".format(path)):
        nsInfo(ns, "Registering {}->{} ".format(name, h))
        _fun = nsGet(ns, "{}/handlers/{}".format(path, h))
        dispatcher.add_method(partial(_fun, dev_path), h)
    transport = WsgiServerTransport(queue_class=gevent.queue.Queue)
    nsSet(ns, "{}/transport".format(dev_path), transport)
    nsSet(ns, "{}/listen".format(dev_path), host)
    nsSet(ns, "{}/port".format(dev_path), host)
    nsConsole(
        ns, "RPC server {} will be listening on tcp://{}:{}".format(
            name, host, port))
    pool = gevent.pool.Pool(maxconn)
    nsSet(ns, "{}/pool".format(dev_path), pool)
    wsgi_server = gevent.pywsgi.WSGIServer((host, port),
                                           transport.handle,
                                           spawn=pool,
                                           log=None)
    nsSet(ns, "{}/wsgi".format(dev_path), wsgi_server)
    nsDaemon(ns, "{}:WSGI".format(name), wsgi_server.serve_forever, _raw=True)
    rpc_server = RPCServerGreenlets(transport, JSONRPCProtocol(), dispatcher)
    if nsGet(ns, "/config/RPCCatchCalls") is True or nsGet(
            ns, "/etc/flags/rpctrace", False) is True:
        _q = gevent.queue.Queue()
        nsSet(ns, "{}/trace".format(dev_path), _q)
        rpc_server.trace = partial(nsRPCCatcher, ns, dev_path, _q)
    nsSet(ns, "{}/rpc", rpc_server)
    nsDaemon(ns, "{}:RPC".format(name), rpc_server.serve_forever, _raw=True)
    nsInfo(ns, "RPC server {} is up".format(name))
    return True
Example #6
0
    def __init__(self, interface):
        """
        Args:
            interface: Interface to provide.
        """
        self.__dispatcher = RPCLoggingDispatcher()
        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

        self._wsgi_server = gevent.wsgi.WSGIServer(
            ('', configuration.get_rpc_server_port()),
            transport.handle,
            log=None)
        gevent.spawn(self._wsgi_server.serve_forever)

        self.__server = RPCServerGreenlets(transport, JSONRPCProtocol(),
                                           self.__dispatcher)

        # register interface's public functions
        self.__dispatcher.register_instance(interface, "")
Example #7
0
class RPCServer(object):
    """Provides an interface via JSON-RPC.

    This class creates an JSON-RPC server that dispatches calls to @public
    methods of the given interface.
    """
    def __init__(self, interface):
        """
        Args:
            interface: Interface to provide.
        """
        self.__dispatcher = RPCLoggingDispatcher()
        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

        self._wsgi_server = gevent.wsgi.WSGIServer(
            ('', configuration.get_rpc_server_port()),
            transport.handle,
            log=None)
        gevent.spawn(self._wsgi_server.serve_forever)

        self.__server = RPCServerGreenlets(
            transport,
            JSONRPCProtocol(),
            self.__dispatcher
        )

        # register interface's public functions
        self.__dispatcher.register_instance(interface, "")

    def serve_forever(self):
        """Starts the RPC server and serves forever."""
        logger.info("RPC server started listening on 0.0.0.0:{}".format(
            configuration.get_rpc_server_port()))
        try:
            self.__server.serve_forever()
        except gevent.hub.LoopExit:
            # FIXME: Right now this exception seems to be expected in this situation. Maybe have another look...
            pass

    def stop(self):
        """Stops the RPC server."""
        self._wsgi_server.stop()
Example #8
0
    def __init__(self, rest_url=None):

        self.dispatcher = RESTDispatcher(rest_url)

        # TinyRPC WSGI App
        self.transport = WsgiServerTransport(queue_class=gevent.queue.Queue)
        self.wsgi_app = self.transport.handle

        # TinyRPC RPC Server
        self.rpc_server = RPCServerGreenlets(self.transport, JSONRPCProtocol(),
                                             self.dispatcher)
        gevent.spawn(self.rpc_server.serve_forever)
Example #9
0
    def __init__(self, app):
        log.debug('initializing JSONRPCServer')
        BaseService.__init__(self, app)
        self.app = app

        self.dispatcher = LoggingDispatcher()
        # register sub dispatchers
        for subdispatcher in self.subdispatcher_classes():
            subdispatcher.register(self)

        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)
        # start wsgi server as a background-greenlet
        self.listen_port = app.config['jsonrpc']['listen_port']
        self.listen_host = app.config['jsonrpc']['listen_host']
        self.wsgi_server = gevent.wsgi.WSGIServer(
            (self.listen_host, self.listen_port),
            transport.handle,
            log=WSGIServerLogger)
        self.rpc_server = RPCServerGreenlets(transport, JSONRPCProtocol(),
                                             self.dispatcher)
        self.default_block = 'latest'
Example #10
0
class RPCServer(object):
    """Provides an interface via JSON-RPC.

    This class creates an JSON-RPC server that dispatches calls to @public
    methods of the given interface.
    """
    def __init__(self, interface):
        """
        Args:
            interface: Interface to provide.
        """
        self.__dispatcher = RPCLoggingDispatcher()
        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

        self._wsgi_server = gevent.wsgi.WSGIServer(
            ('', configuration.get_rpc_server_port()),
            transport.handle,
            log=None)
        gevent.spawn(self._wsgi_server.serve_forever)

        self.__server = RPCServerGreenlets(transport, JSONRPCProtocol(),
                                           self.__dispatcher)

        # register interface's public functions
        self.__dispatcher.register_instance(interface, "")

    def serve_forever(self):
        """Starts the RPC server and serves forever."""
        logger.info("RPC server started listening on 0.0.0.0:{}".format(
            configuration.get_rpc_server_port()))
        try:
            self.__server.serve_forever()
        except gevent.hub.LoopExit:
            # FIXME: Right now this exception seems to be expected in this situation. Maybe have another look...
            pass

    def stop(self):
        """Stops the RPC server."""
        self._wsgi_server.stop()
Example #11
0
def main(*args, **kwargs):
    parser = argparse.ArgumentParser(description="json-rpc server for coils")
    parser.add_argument('--hostname', default='0.0.0.0')
    parser.add_argument('--port', type=int, default=8080)
    # parser.add_argument('--kernel-hostname', default='127.0.0.1')
    # parser.add_argument('--kernel-key')
    # parser.add_argument('--shell-port', type=int)
    # parser.add_argument('--iopub-port', type=int)
    # parser.add_argument('--stdin-port', type=int)
    # parser.add_argument('--control-port', type=int)
    args = parser.parse_args()

    transport = WsgiServerTransport(queue_class=gevent.queue.Queue)
    wsgi_server = gevent.wsgi.WSGIServer((args.hostname, args.port), transport.handle)
    gevent.spawn(wsgi_server.serve_forever)

    server = RPCServerGreenlets(
        transport,
        JSONRPCProtocol(),
        dispatcher)

    print "[*] running"
    server.serve_forever()
Example #12
0
    def __init__(self, app):
        log.debug('initializing JSONRPCServer')
        BaseService.__init__(self, app)
        self.app = app
        self.dispatcher = RPCDispatcher()
        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

        # start wsgi server as a background-greenlet
        self.wsgi_server = gevent.wsgi.WSGIServer(('127.0.0.1', 5000), transport.handle)

        self.rpc_server = RPCServerGreenlets(
            transport,
            JSONRPCProtocol(),
            self.dispatcher
        )
Example #13
0
    def __init__(self, app):
        log.debug('initializing JSONRPCServer')
        BaseService.__init__(self, app)
        self.app = app

        self.dispatcher = LoggingDispatcher()
        # register sub dispatchers
        for subdispatcher in self.subdispatcher_classes():
            subdispatcher.register(self)

        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)
        # start wsgi server as a background-greenlet
        self.listen_port = app.config['jsonrpc']['listen_port']
        self.listen_host = app.config['jsonrpc']['listen_host']
        self.wsgi_server = gevent.wsgi.WSGIServer((self.listen_host, self.listen_port),
                                                  transport.handle, log=WSGIServerLogger)
        self.rpc_server = RPCServerGreenlets(
            transport,
            JSONRPCProtocol(),
            self.dispatcher
        )
        self.default_block = 'latest'
Example #14
0
    def __init__(self, interface):
        """
        Args:
            interface: Interface to provide.
        """
        self.__dispatcher = RPCLoggingDispatcher()
        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

        self._wsgi_server = gevent.wsgi.WSGIServer(
            ('', configuration.get_rpc_server_port()),
            transport.handle,
            log=None)
        gevent.spawn(self._wsgi_server.serve_forever)

        self.__server = RPCServerGreenlets(
            transport,
            JSONRPCProtocol(),
            self.__dispatcher
        )

        # register interface's public functions
        self.__dispatcher.register_instance(interface, "")
Example #15
0
class JSONRPCServer(BaseService):

    """Service providing an HTTP server with JSON RPC interface.

    Other services can extend the JSON RPC interface by creating a
    :class:`Subdispatcher` and registering it via
    `Subdispatcher.register(self.app.services.json_rpc_server)`.

    Alternatively :attr:`dispatcher` can be extended directly (see
    https://tinyrpc.readthedocs.org/en/latest/dispatch.html).
    """

    name = 'jsonrpc'
    default_config = dict(jsonrpc=dict(listen_port=4000, listen_host='127.0.0.1'))

    @classmethod
    def subdispatcher_classes(cls):
        return (Web3, Net, Compilers, DB, Chain, Miner, FilterManager)

    def __init__(self, app):
        log.debug('initializing JSONRPCServer')
        BaseService.__init__(self, app)
        self.app = app

        self.dispatcher = LoggingDispatcher()
        # register sub dispatchers
        for subdispatcher in self.subdispatcher_classes():
            subdispatcher.register(self)

        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)
        # start wsgi server as a background-greenlet
        self.listen_port = app.config['jsonrpc']['listen_port']
        self.listen_host = app.config['jsonrpc']['listen_host']
        self.wsgi_server = gevent.wsgi.WSGIServer((self.listen_host, self.listen_port),
                                                  transport.handle, log=WSGIServerLogger)
        self.rpc_server = RPCServerGreenlets(
            transport,
            JSONRPCProtocol(),
            self.dispatcher
        )
        self.default_block = 'latest'

    def _run(self):
        log.info('starting JSONRPCServer', port=self.listen_port)
        # in the main greenlet, run our rpc_server
        self.wsgi_thread = gevent.spawn(self.wsgi_server.serve_forever)
        self.rpc_server.serve_forever()

    def stop(self):
        log.info('stopping JSONRPCServer')
        self.wsgi_thread.kill()

    def get_block(self, block_id=None):
        """Return the block identified by `block_id`.

        This method also sets :attr:`default_block` to the value of `block_id`
        which will be returned if, at later calls, `block_id` is not provided.

        Subdispatchers using this function have to ensure sure that a
        chainmanager is registered via :attr:`required_services`.

        :param block_id: either the block number as integer or 'pending',
                        'earliest' or 'latest', or `None` for the default
                        block
        :returns: the requested block
        :raises: :exc:`KeyError` if the block does not exist
        """
        assert 'chain' in self.app.services
        chain = self.app.services.chain.chain
        if block_id is None:
            block_id = self.default_block
        else:
            self.default_block = block_id
        if block_id == 'pending':
            return self.app.services.chain.chain.head_candidate
        if block_id == 'latest':
            return chain.head
        if block_id == 'earliest':
            block_id = 0
        if is_numeric(block_id):
            # by number
            hash_ = chain.index.get_block_by_number(block_id)
        elif block_id == chain.head_candidate.hash:
            return chain.head_candidate
        else:
            # by hash
            assert is_string(block_id)
            hash_ = block_id
        return chain.get(hash_)
Example #16
0
class JSONRPCServer(BaseService):
    """Service providing an HTTP server with JSON RPC interface.

    Other services can extend the JSON RPC interface by creating a
    :class:`Subdispatcher` and registering it via
    `Subdispatcher.register(self.app.services.json_rpc_server)`.

    Alternatively :attr:`dispatcher` can be extended directly (see
    https://tinyrpc.readthedocs.org/en/latest/dispatch.html).
    """

    name = 'jsonrpc'
    default_config = dict(
        jsonrpc=dict(listen_port=4000, listen_host='127.0.0.1'))

    @classmethod
    def subdispatcher_classes(cls):
        return (Web3, Net, Compilers, DB, Chain, Miner, FilterManager)

    def __init__(self, app):
        log.debug('initializing JSONRPCServer')
        BaseService.__init__(self, app)
        self.app = app

        self.dispatcher = LoggingDispatcher()
        # register sub dispatchers
        for subdispatcher in self.subdispatcher_classes():
            subdispatcher.register(self)

        transport = WsgiServerTransport(queue_class=gevent.queue.Queue)
        # start wsgi server as a background-greenlet
        self.listen_port = app.config['jsonrpc']['listen_port']
        self.listen_host = app.config['jsonrpc']['listen_host']
        self.wsgi_server = gevent.wsgi.WSGIServer(
            (self.listen_host, self.listen_port),
            transport.handle,
            log=WSGIServerLogger)
        self.rpc_server = RPCServerGreenlets(transport, JSONRPCProtocol(),
                                             self.dispatcher)
        self.default_block = 'latest'

    def _run(self):
        log.info('starting JSONRPCServer', port=self.listen_port)
        # in the main greenlet, run our rpc_server
        self.wsgi_thread = gevent.spawn(self.wsgi_server.serve_forever)
        self.rpc_server.serve_forever()

    def stop(self):
        log.info('stopping JSONRPCServer')
        self.wsgi_thread.kill()

    def get_block(self, block_id=None):
        """Return the block identified by `block_id`.

        This method also sets :attr:`default_block` to the value of `block_id`
        which will be returned if, at later calls, `block_id` is not provided.

        Subdispatchers using this function have to ensure sure that a
        chainmanager is registered via :attr:`required_services`.

        :param block_id: either the block number as integer or 'pending',
                        'earliest' or 'latest', or `None` for the default
                        block
        :returns: the requested block
        :raises: :exc:`KeyError` if the block does not exist
        """
        assert 'chain' in self.app.services
        chain = self.app.services.chain.chain
        if block_id is None:
            block_id = self.default_block
        else:
            self.default_block = block_id
        if block_id == 'pending':
            return self.app.services.chain.chain.head_candidate
        if block_id == 'latest':
            return chain.head
        if block_id == 'earliest':
            block_id = 0
        if is_numeric(block_id):
            # by number
            hash_ = chain.index.get_block_by_number(block_id)
        else:
            # by hash
            assert is_string(block_id)
            hash_ = block_id
        return chain.get(hash_)
Example #17
0
from tinyrpc.dispatch import RPCDispatcher
import subprocess
import json
import radio_data_rate
import time
import re

dispatcher = RPCDispatcher()
transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

# start wsgi server as a background-greenlet
wsgi_server = gevent.pywsgi.WSGIServer(('192.168.1.100', 8080),
                                       transport.handle)
gevent.spawn(wsgi_server.serve_forever)

rpc_server = RPCServerGreenlets(transport, JSONRPCProtocol(), dispatcher)

current_radio_rate_r1 = {'vhf': 9600, 'uhf': 240, 'sat_comm': 512}


def set_vhf_data_rate(interface=None, rate=None, parent=None, classid=None):
    if None not in (interface, rate, parent, classid):
        if rate == 9600:
            rate_in_kbps = '9.6kbps'
        elif rate == 4800:
            rate_in_kbps = '4.8kbps'
        elif rate == 2400:
            rate_in_kbps = '2.4kbps'
        elif rate == 1200:
            rate_in_kbps = '1.2kbps'
        else:
Example #18
0
import gevent.queue
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.wsgi import WsgiServerTransport
from tinyrpc.server.gevent import RPCServerGreenlets
from tinyrpc.dispatch import RPCDispatcher

dispatcher = RPCDispatcher()
transport = WsgiServerTransport(queue_class=gevent.queue.Queue)

# start wsgi server as a background-greenlet
wsgi_server = gevent.wsgi.WSGIServer(('0.0.0.0', 5050), transport.handle)
gevent.spawn(wsgi_server.serve_forever)

rpc_server = RPCServerGreenlets(
    transport,
    JSONRPCProtocol(),
    dispatcher
)

def getROSActionCores(action_cores_RPC):
  action_cores_ROS = []
  for action_core_RPC in action_cores_RPC:
    action_core_ROS = ActionCore()
    action_core_ROS.action_core_name = action_core_RPC['action_core_name']
    action_core_ROS.action_roles = []
    for role_RPC in action_core_RPC['action_roles']:
      role_ROS = ActionRole(role_name=role_RPC['role_name'], role_value=role_RPC['role_value'])
      action_core_ROS.action_roles.append(role_ROS)
    action_cores_ROS.append(action_core_ROS)