Ejemplo n.º 1
0
    def run(self):
        class RequestHandler(DocXMLRPCRequestHandler):

            rpc_paths = ('/AtlantisRPC', )

            def do_OPTIONS(self):
                self.send_response(200)
                self.end_headers()

            # Add these headers to all responses
            def end_headers(self):
                self.send_header(
                    "Access-Control-Allow-Headers",
                    "Origin, X-Requested-With, Content-Type, Accept")
                self.send_header("Access-Control-Allow-Origin", "*")
                DocXMLRPCRequestHandler.end_headers(self)

        self.server = DocXMLRPCServer(
            (GlobalConfig.xmlrpc_host, GlobalConfig.xmlrpc_port),
            requestHandler=RequestHandler)
        self.server.set_server_title("Atlantis RPCXML server")
        self.server.set_server_name("Atlantis RPCXML server")
        self.server.set_server_documentation(
            "Atlantis RPCXML server documentation")
        self.server.register_introspection_functions()
        self.server.register_function(self.get_status)
        self.server.register_function(self.set_device)
        self.server.register_function(self.turn_on_device)
        self.server.register_function(self.turn_off_device)
        self.server.register_function(self.toggle_device)
        self.server.register_function(self.turn_on_stream)
        self.server.register_function(self.turn_off_stream)
        self.server.register_function(self.toggle_stream)
        self.server.register_function(self.set_leds_color)
        self.server.serve_forever()
Ejemplo n.º 2
0
class APIService(threading.Thread):
    @trace
    def __init__(self, pid, passive, active, debug, port, hostname):
        super(APIService, self).__init__()

        self._stop = threading.Event()
        self.pid = pid
        self.abort = False
        self.aborted = False
        self.port = port
        self.hostname = hostname
        self.api = API(pid, passive, active, port, debug)
        cbdebug("Initializing API Service on " + hostname + ":" + str(port))
        if debug is None:
            self.server = AsyncDocXMLRPCServer((self.hostname, int(self.port)),
                                               allow_none=True)
        else:
            self.server = DocXMLRPCServer((self.hostname, int(self.port)),
                                          allow_none=True)
        self.server.abort = False
        self.server.aborted = False
        self.server.set_server_title("API Service (xmlrpc)")
        self.server.set_server_name("API Service (xmlrpc)")
        #self.server.register_introspection_functions()
        self.api.signatures = {}
        for methodtuple in inspect.getmembers(self.api,
                                              predicate=inspect.ismethod):
            name = methodtuple[0]
            if name in ["__init__", "success", "error", "migrate"]:
                continue
            func = getattr(self.api, name)
            argspec = inspect.getargspec(func)
            spec = argspec[0]
            defaults = [] if argspec[3] is None else argspec[3]
            num_spec = len(spec)
            num_defaults = len(defaults)
            diff = num_spec - num_defaults
            named = diff - 1
            doc = "Usage: "
            for x in range(1, diff):
                doc += spec[x] + ", "
            for x in range(diff, num_spec):
                doc += spec[x] + " = " + str(defaults[x - diff]) + ", "
            doc = doc[:-2]
            self.api.signatures[name] = {"args": spec[1:], "named": named}
            self.server.register_function(unwrap_kwargs(func, doc), name)
#        self.server.register_instance(self.api)
        cbdebug("API Service started")

    @trace
    def run(self):
        cbdebug("API Service waiting for requests...")
        self.server.serve_forever()
        cbdebug("API Service shutting down...")

    @trace
    def stop(self):
        cbdebug("Calling API Service shutdown....")
        self._stop.set()
        self.server.shutdown()
Ejemplo n.º 3
0
	def __init__(self, *args, **kwds):
		kwds['allow_none'] = True
		kwds['logRequests'] = False
		DocXMLRPCServer.__init__(self, *args, **kwds)

		self.set_server_title('Brain XML RPC server')
		self.set_server_name('Brain XML RPC server methods')
		self.set_server_documentation("Keyword arguments should be passed in the last " +
			"parameter to function as a dictionary. If there are no keyword parameters, " +
			"empty dictionary should be passed.")

		# registering multicall function manually, because we should
		# remove keyword argument before calling it
		multicall = _KeywordFunction(self.system_multicall)
		multicall.__doc__ = "XML RPC multicall support"
		self.register_function(multicall, 'system.multicall')
Ejemplo n.º 4
0
class XMLRPC_Server(threading.Thread):
    def __init__(self, relays, stream, sensors, leds):
        self.relays = relays
        self.stream = stream
        self.sensors = sensors
        self.leds = leds
        threading.Thread.__init__(self)
        self.start()

    def stop(self):
        self.server.shutdown()
        self.server.server_close()

    def run(self):
        class RequestHandler(DocXMLRPCRequestHandler):

            rpc_paths = ('/AtlantisRPC', )

            def do_OPTIONS(self):
                self.send_response(200)
                self.end_headers()

            # Add these headers to all responses
            def end_headers(self):
                self.send_header(
                    "Access-Control-Allow-Headers",
                    "Origin, X-Requested-With, Content-Type, Accept")
                self.send_header("Access-Control-Allow-Origin", "*")
                DocXMLRPCRequestHandler.end_headers(self)

        self.server = DocXMLRPCServer(
            (GlobalConfig.xmlrpc_host, GlobalConfig.xmlrpc_port),
            requestHandler=RequestHandler)
        self.server.set_server_title("Atlantis RPCXML server")
        self.server.set_server_name("Atlantis RPCXML server")
        self.server.set_server_documentation(
            "Atlantis RPCXML server documentation")
        self.server.register_introspection_functions()
        self.server.register_function(self.get_status)
        self.server.register_function(self.set_device)
        self.server.register_function(self.turn_on_device)
        self.server.register_function(self.turn_off_device)
        self.server.register_function(self.toggle_device)
        self.server.register_function(self.turn_on_stream)
        self.server.register_function(self.turn_off_stream)
        self.server.register_function(self.toggle_stream)
        self.server.register_function(self.set_leds_color)
        self.server.serve_forever()

    # XMLRPC methods

    def get_status(self):
        status = {
            "sensors": self.sensors.getSensorsJSON(),
            "leds": [{
                "mode": "static",
                "r": 1.0,
                "g": 1.0,
                "b": 1.0
            }],
            "relays": {},
            "streaming": self.stream.isOn()
        }
        # Insert relay status
        for r in self.relays.devices:
            status["relays"][r] = self.relays.getDeviceState(r)
        return status

    def set_device(self, id, value):
        if value:
            self.relays.turnOnDevice(id)
        else:
            self.relays.turnOffDevice(id)
        return self.get_status()

    def turn_on_device(self, id):
        self.relays.turnOnDevice(id)
        return self.get_status()

    def turn_off_device(self, id):
        self.relays.turnOffDevice(id)
        return self.get_status()

    def toggle_device(self, id):
        self.relays.toggleDevice(id)
        return self.get_status()

    def turn_on_stream(self):
        self.stream.start()

    def turn_off_stream(self):
        self.stream.stop()

    def toggle_stream(self):
        if self.stream.isOn():
            self.stream.stop()
        else:
            self.stream.start()

    def set_leds_color(self, id, color):
        print("Setting LEDS color ", color)
        self.leds.setColor(color)
Ejemplo n.º 5
0
def server(evt, numrequests):
    serv = DocXMLRPCServer(("localhost", 0), logRequests=False)

    try:
        global PORT
        PORT = serv.socket.getsockname()[1]

        # Add some documentation
        serv.set_server_title("DocXMLRPCServer Test Documentation")
        serv.set_server_name("DocXMLRPCServer Test Docs")
        serv.set_server_documentation(
            """This is an XML-RPC server's documentation, but the server can be used by
POSTing to /RPC2. Try self.add, too.""")

        # Create and register classes and functions
        class TestClass(object):
            def test_method(self, arg):
                """Test method's docs. This method truly does very little."""
                self.arg = arg

        serv.register_introspection_functions()
        serv.register_instance(TestClass())

        def add(x, y):
            """Add two instances together. This follows PEP008, but has nothing
            to do with RFC1952. Case should matter: pEp008 and rFC1952.  Things
            that start with http and ftp should be auto-linked, too:
            http://google.com.
            """
            return x + y

        serv.register_function(add)
        serv.register_function(lambda x, y: x - y)

        while numrequests > 0:
            serv.handle_request()
            numrequests -= 1
    except socket.timeout:
        pass
    finally:
        serv.server_close()
        PORT = None
        evt.set()
def make_server():
    serv = DocXMLRPCServer(("localhost", 0), logRequests=False)

    try:
        # Add some documentation
        serv.set_server_title("DocXMLRPCServer Test Documentation")
        serv.set_server_name("DocXMLRPCServer Test Docs")
        serv.set_server_documentation(
            "This is an XML-RPC server's documentation, but the server "
            "can be used by POSTing to /RPC2. Try self.add, too.")

        # Create and register classes and functions
        class TestClass(object):
            def test_method(self, arg):
                """Test method's docs. This method truly does very little."""
                self.arg = arg

        serv.register_introspection_functions()
        serv.register_instance(TestClass())

        def add(x, y):
            """Add two instances together. This follows PEP008, but has nothing
            to do with RFC1952. Case should matter: pEp008 and rFC1952.  Things
            that start with http and ftp should be auto-linked, too:
            http://google.com.
            """
            return x + y

        def annotation(x: int):
            """ Use function annotations. """
            return x

        class ClassWithAnnotation:
            def method_annotation(self, x: bytes):
                return x.decode()

        serv.register_function(add)
        serv.register_function(lambda x, y: x - y)
        serv.register_function(annotation)
        serv.register_instance(ClassWithAnnotation())
        return serv
    except:
        serv.server_close()
        raise
Ejemplo n.º 7
0
def serve():
    logger.info("Started serving.")

    from xmlrpc.server import DocXMLRPCServer
    from xmlrpc.server import DocXMLRPCRequestHandler
    from . import config

    # A request handler that responds appropriately for CORS and preflight
    class CORSRequestHandler(DocXMLRPCRequestHandler):
        def do_OPTIONS(self):
            self.send_response(200)
            self.end_headers()

        # Add these headers to all responses
        def end_headers(self):
            self.send_header(
                "Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept",
            )
            self.send_header("Access-Control-Allow-Origin", "*")
            super().end_headers()

    net_address = config.get_config_for_key("Scheduler Address")
    server = DocXMLRPCServer(
        ("0.0.0.0", net_address.get("Port")), requestHandler=CORSRequestHandler
    )
    server.set_server_title("Scheduler Docs")
    server.set_server_name("CTMO Scheduler Service")
    server.set_server_documentation(
        "The scheduler module exports only the front_desk method through the XML-RPC protocol."
    )
    server.register_function(front_desk)
    server.serve_forever()
Ejemplo n.º 8
0
def server(evt, numrequests):
    serv = DocXMLRPCServer(("localhost", 0), logRequests=False)

    try:
        global PORT
        PORT = serv.socket.getsockname()[1]

        # Add some documentation
        serv.set_server_title("DocXMLRPCServer Test Documentation")
        serv.set_server_name("DocXMLRPCServer Test Docs")
        serv.set_server_documentation(
            "This is an XML-RPC server's documentation, but the server "
            "can be used by POSTing to /RPC2. Try self.add, too.")

        # Create and register classes and functions
        class TestClass(object):
            def test_method(self, arg):
                """Test method's docs. This method truly does very little."""
                self.arg = arg

        serv.register_introspection_functions()
        serv.register_instance(TestClass())

        def add(x, y):
            """Add two instances together. This follows PEP008, but has nothing
            to do with RFC1952. Case should matter: pEp008 and rFC1952.  Things
            that start with http and ftp should be auto-linked, too:
            http://google.com.
            """
            return x + y

        def annotation(x: int):
            """ Use function annotations. """
            return x

        class ClassWithAnnotation:
            def method_annotation(self, x: bytes):
                return x.decode()

        serv.register_function(add)
        serv.register_function(lambda x, y: x-y)
        serv.register_function(annotation)
        serv.register_instance(ClassWithAnnotation())

        while numrequests > 0:
            serv.handle_request()
            numrequests -= 1
    except socket.timeout:
        pass
    finally:
        serv.server_close()
        PORT = None
        evt.set()
Ejemplo n.º 9
0
	def register_instance(self, inst):
		DocXMLRPCServer.register_instance(self, _KeywordInstance(inst))
Ejemplo n.º 10
0
        if name in cmds:
            lqs = 'last_{:s}_query'.format(name)
            lqd = 'last_{:s}_retval'.format(name)
            lastq = store.get(lqs, 0)

            if time() - lastq > config.rpyc_cmd_retry_interval:
                retval = cmds.get(name).exec(**kwargs)
                store[lqs] = time()
                store[lqd] = retval
            else:
                retval = store[lqd]

            return retval


if __name__ == "__main__":
    rm = ResourceMonitor()
    rm.start()

    with DocXMLRPCServer(('', 8001)) as server_:
        from disco import DiscoClient
        from apparatus import get_my_ip

        dc = DiscoClient()
        dc.announce('SmartieSlave',
                    'http://{:s}:{:d}'.format(get_my_ip(), 8001))

        server_.register_instance(SmartieSlave())
        os.system('systemd-notify --ready')
        server_.serve_forever()
Ejemplo n.º 11
0
#!/usr/bin/python3

# Implements a simple XMLRPC server for test purposes
# 26.03.2010 Bram

from xmlrpc.server import DocXMLRPCServer
from xmlrpc.server import DocXMLRPCRequestHandler


class RequestHandler(DocXMLRPCRequestHandler):
    rpc_paths = ('/RPC2', )


server = DocXMLRPCServer(("0.0.0.0", 2720), requestHandler=RequestHandler)

# gives access to system.listMethods, system.methodHelp and system.methodSignature
server.register_introspection_functions()


def reverse(x):
    return "".join(list(reversed(x)))


def get():
    return ["Power", "Energy", "Force", "Distance", "Current", "Apple pies"]


print("Registering functions")
server.register_function(reverse, 'reverse')
server.register_function(get, 'get')
Ejemplo n.º 12
0
def simple_server():
    def is_even(n):
        """
        偶数判断
        """
        return n % 2 == 0

    server = DocXMLRPCServer(("localhost", 8000))
    server.register_function(pow)
    server.register_function(lambda x, y: x + y, 'add')
    server.register_function(is_even, "is_even")
    server.register_introspection_functions()
    server.serve_forever()
Ejemplo n.º 13
0
def docxmlrpcserver(title, name, documentation):
    p = int(os.environ['INITIAL_PORT']
            )  # avoid starting the server on the same port by PyExZ3
    serv = DocXMLRPCServer(("localhost", p), logRequests=False)
    serv.set_server_title(title)  #"DocXMLRPCServer Test Documentation")
    serv.set_server_name(name)  #"DocXMLRPCServer Test Docs")
    serv.set_server_documentation(
        documentation)  #"This is an XML-RPC server's documentation")
    serv.register_introspection_functions()
    serv.register_multicall_functions()
    serv.register_function(lambda x, y: x + y)
    serv.register_instance(DocXMLRPCServer(("localhost", p + 1)))
    generated = serv.generate_html_documentation()
    os.environ["INITIAL_PORT"] = str(p + 2)
    if '<script>' in generated:
        return 'dangerous'
    else:
        return 'safe'
Ejemplo n.º 14
0
if __name__ == '__main__':
    from xmlrpc.server import DocXMLRPCServer
    import os
    from disco import DiscoServer

    redis_url = os.environ.get('REDIS_URL', 'redis://localhost')

    instance = DiscoServer(redis_url)

    with DocXMLRPCServer(('', 8888), allow_none=True) as server:
        server.register_instance(instance)
        os.system('systemd-notify --ready')
        server.serve_forever()