示例#1
0
def server(directory, config_path, runner, tool_override):
    loop = asyncio.get_event_loop()

    # EM
    em = EventEmitter(loop)

    config = read_toml_config(config_path, tool_override)

    # TODO: Re-add support for multiple test suites
    suite = TestSuite(config["name"], runner, em, config)
    suites = {config["name"]: suite}

    # Tests
    tests = Tests(suites)

    async def collect_all(request):
        LOGGER.info("Collect ALL")
        tasks = [
            suite.collect_all(directory, em, loop=loop)
            for suite in suites.values()
        ]
        await asyncio.gather(*tasks, loop=loop)
        return "ok"

    async def run_all(request):
        LOGGER.info("Run ALL")
        tasks = [
            suite.launch_all(directory, em, loop=loop)
            for suite in suites.values()
        ]
        await asyncio.gather(*tasks, loop=loop)
        return "ok"

    async def run_selected(request):
        tasks = []
        LOGGER.info("Run selected: %r", request.params)
        for suite_name, suite_tests in request.params.items():
            suite = suites[suite_name]
            tasks.append(suite.launch_tests(directory, em, loop, suite_tests))

        await asyncio.gather(*tasks)
        return "ok"

    rpc = JsonRpc()
    logging.getLogger("aiohttp-json-rpc.server").setLevel(logging.DEBUG)

    async def forward_notifications(message):
        LOGGER.debug("Forwarding to %d clients: %r", len(rpc.clients), message)
        for client in rpc.clients:
            data = {
                "jsonrpc": "2.0",
                "id": None,
                "method": "test",
                "params": message
            }
            r = await client.ws.send_str(json.dumps(data))

    em.register(forward_notifications)
    em.register(process_notification)

    loop = asyncio.get_event_loop()
    rpc.add_methods(("", collect_all), ("", run_selected), ("", run_all))
    rpc.add_topics("test")

    app = Application(loop=loop, debug=True)
    web_interfaces_route = get_static_path()
    app.router.add_static("/interface/",
                          web_interfaces_route,
                          show_index=True,
                          name="static")
    app.router.add_route("*", "/", rpc)

    run_app(app, port=8889)
@asyncio.coroutine
def clock(rpc):
    """
    This task runs forever and notifies all clients subscribed to
    'clock' once a second.
    """

    while True:
        rpc.notify('clock', str(datetime.datetime.now()))

        yield from asyncio.sleep(1)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()

    rpc = JsonRpc()
    rpc.add_topics('clock')

    loop.create_task(clock(rpc))

    app = Application(loop=loop)
    app.router.add_route('*', '/', rpc)

    handler = app.make_handler()

    server = loop.run_until_complete(
        loop.create_server(handler, '0.0.0.0', 8080))

    loop.run_forever()
示例#3
0
@asyncio.coroutine
def clock(rpc):
    """
    This task runs forever and notifies all clients subscribed to
    'clock' once a second.
    """

    while True:
        yield from rpc.notify('clock', str(datetime.datetime.now()))
        yield from asyncio.sleep(1)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()

    rpc = JsonRpc()
    rpc.add_topics('clock')

    loop.create_task(clock(rpc))

    app = Application(loop=loop)
    app.router.add_route('*', '/', rpc)

    handler = app.make_handler()

    server = loop.run_until_complete(
        loop.create_server(handler, '0.0.0.0', 8080))

    loop.run_forever()
示例#4
0
class LaborApi:
    def __init__(self, loop=None, logger=None, state_file=None):
        self.loop = loop or asyncio.get_event_loop()
        self.logger = logger or logging.getLogger('labor-api')

        # setup rpc
        self.rpc = JsonRpc()

        self.rpc.add_topics(('room-state'), )

        self.rpc.add_methods(('', self.set_room_state), )

        # setup cache
        self.state_file = state_file

        self.cache = {
            'state': {
                'since': None,
                'open': None,
            },
            'archive': [],
            'responses': {
                'room': '',
                'room_archive': '',
            },
        }

        if not state_file:
            self.logger.debug('No state file.'
                              'rooms state will be closed by default')

            self._set_room_state(False)

        # setup app
        self.app = Application(loop=self.loop)

        # get room
        self.app.router.add_route('GET', '/api/room/', self.get_room)
        self.app.router.add_route('GET', '/api/room', self.get_room)

        # set room
        self.app.router.add_route('POST', '/api/room/', self.set_room)
        self.app.router.add_route('POST', '/api/room', self.set_room)

        # room archive
        self.app.router.add_route('GET', '/api/room_archive/',
                                  self.get_room_archive)

        self.app.router.add_route('GET', '/api/room_archive',
                                  self.get_room_archive)

        # websockets
        self.app.router.add_route('GET', '/api/rpc/', self.rpc)
        self.app.router.add_route('GET', '/api/rpc', self.rpc)

    def _set_room_state(self, open):
        self.logger.debug('set room state open=%s', open)

        state = {
            'since': int(time.time()),
            'open': bool(open),
        }

        self.cache['state'] = state

        self.cache['archive'].append({
            'lastchange': state['since'],
            'open': open,
        })

        self.cache['responses']['room'] = json.dumps(self.cache['state'])

        self.cache['responses']['room_archive'] = json.dumps(
            self.cache['archive'])

        # notify
        self.rpc.notify('room-state', state)

    def get_bool_from_str(self, str):
        if str.lower().strip() in ('1', 'true'):
            return True

        return False

    # methods
    async def set_room_state(self, request):
        self._set_room_state(request.params['open'])

        return self.cache['state']

    async def get_room(self, request):
        self.logger.debug('LaborApi.get_room(%s)', request)

        response = Response(text=self.cache['responses']['room'],
                            content_type='application/json')

        response.headers['Access-Control-Allow-Origin'] = '*'

        return response

    async def set_room(self, request):
        data = await request.post()

        self.logger.debug('LaborApi.set_room(%s(%s))', request, data)

        open = self.get_bool_from_str(data['open'])
        self._set_room_state(open=open)

        return Response(content_type='application/json',
                        text=json.dumps({
                            'success': True,
                            'status': '',
                        }))

    async def get_room_archive(self, request):
        self.logger.debug('LaborApi.get_room_archive(%s)', request)

        return Response(text=self.cache['responses']['room_archive'],
                        content_type='application/json')