Exemplo n.º 1
0
    def get_backup_logs(self, number, client, forward=False, deep=False, agent=None):
        """See
        :func:`burpui.misc.backend.interface.BUIbackend.get_backup_logs`
        """
        if not client or not number:
            return {} if number and number != -1 else []

        if number == -1:
            return trio.run(self._async_get_all_backup_logs, client, forward, deep)
        return trio.run(self._async_get_backup_logs, number, client, forward, deep)
Exemplo n.º 2
0
def start(hardware, port=0):
    ctx = zmq_trio.Context.instance()

    async def run():
        adapter = hardware()
        handler = handlers.merge(HardwareHandler(adapter), ProcessHandler(adapter))

        async with trio_asyncio.open_loop(), adapter:
            await HedgehogServer(ctx, 'tcp://*:{}'.format(port), handler).run()

    trio.run(run)
Exemplo n.º 3
0
    def __init__(self, server=None, conf=None):
        """
        :param server: ``Burp-UI`` server instance in order to access logger
                       and/or some global settings
        :type server: :class:`burpui.engines.server.BUIServer`

        :param conf: Configuration to use
        :type conf: :class:`burpui.config.BUIConfig`
        """

        BUIbackend.__init__(self, server, conf)

        self.conf = conf
        self.concurrency = conf.safe_get('concurrency', 'integer', 'Parallel', BUI_DEFAULTS)
        self.init_wait = conf.safe_get('init_wait', 'integer', 'Parallel', BUI_DEFAULTS)

        if os.getenv('BUI_MODE', '') == 'celery':
            # we cap the concurrency level in order not to prevent our main server
            # to talk to the monitor
            self.concurrency = max(1, self.concurrency // 2)

        self.logger.info('burp conf cli: {}'.format(self.burpconfcli))
        self.logger.info('burp conf srv: {}'.format(self.burpconfsrv))
        self.logger.info('command timeout: {}'.format(self.timeout))
        self.logger.info('tmpdir: {}'.format(self.tmpdir))
        self.logger.info('zip64: {}'.format(self.zip64))
        self.logger.info('includes: {}'.format(self.includes))
        self.logger.info('enforce: {}'.format(self.enforce))
        self.logger.info('revoke: {}'.format(self.revoke))
        self.logger.info('concurrency: {}'.format(self.concurrency))
        self.logger.info('init_wait: {}'.format(self.init_wait))

        if self.init_wait:
            exc = None
            for i in range(self.init_wait):
                connector = Connector(conf)
                try:
                    self.logger.warning('monitor not ready, waiting for it... {}/{}'.format(i, self.init_wait))
                    trio.run(connector.conn)
                    if connector.connected:
                        trio.run(connector._send, 'RE')
                        break
                except BUIserverException as eee:
                    exc = eee
                time.sleep(1)
            else:
                self.logger.error('monitor not ready, giving up!')
                raise exc
        stats = self.statistics()
        if 'alive' in stats and stats['alive']:
            self.init_all()
Exemplo n.º 4
0
 def get_server_version(self, agent=None):
     if self._server_version is None:
         try:
             self._server_version = trio.run(self._async_request, 'server_version')
         except BUIserverException:
             return ''
     return self._server_version or ''
Exemplo n.º 5
0
def monitor(options=None):
    import trio
    from burpui.engines.monitor import MonitorPool
    from burpui.utils import lookup_file

    if not options:
        options, _ = parse_args(mode=False, name='bui-agent')

    conf = ['buimonitor.cfg', 'buimonitor.sample.cfg']
    if options.config:
        conf = lookup_file(options.config, guess=False)
    else:
        conf = lookup_file(conf)
    check_config(conf)

    monitor = MonitorPool(conf, options.log, options.logfile)
    trio.run(monitor.run)
Exemplo n.º 6
0
def agent(options=None):
    import trio
    from burpui.engines.agent import BUIAgent as Agent
    from burpui.utils import lookup_file

    if not options:
        options, _ = parse_args(mode=False, name='bui-agent')

    conf = ['buiagent.cfg', 'buiagent.sample.cfg']
    if options.config:
        conf = lookup_file(options.config, guess=False)
    else:
        conf = lookup_file(conf)
    check_config(conf)

    agent = Agent(conf, options.log, options.logfile)
    trio.run(agent.run)
Exemplo n.º 7
0
    def _get_last_backup(self, name):
        """Return the last backup of a given client

        :param name: Name of the client
        :type name: str

        :returns: The last backup
        """
        return trio.run(self._async_get_last_backup, name)
Exemplo n.º 8
0
 def get_all_clients(self, agent=None):
     """See
     :func:`burpui.misc.backend.interface.BUIbackend.get_all_clients`
     """
     # don't need async processing if burp-server < BURP_STATUS_FORMAT_V2
     if not self.deep_inspection or (self.server_version and
                                     self.server_version < BURP_STATUS_FORMAT_V2):
         return Burp2.get_all_clients(self)
     # the deep inspection can take advantage of async processing
     return trio.run(self._async_get_all_clients)
Exemplo n.º 9
0
def _trio_runner(async_fn):
    import trio

    async def loc(coro):
        """
        We need the dummy no-op async def to protect from
        trio's internal. See https://github.com/python-trio/trio/issues/89
        """
        return await coro

    return trio.run(loc, async_fn)
Exemplo n.º 10
0
    def _parse_backup_log(self, number, client):
        """The :func:`burpui.misc.backend.burp2.Burp._parse_backup_log`
        function helps you determine if the backup is protocol 2 or 1 and various
        useful details.

        :param number: Backup number to work on
        :type number: int

        :param client: Client name to work on
        :type client: str

        :returns: a dict with some useful details
        """
        return trio.run(self._async_parse_backup_log, number, client)
Exemplo n.º 11
0
    def _guess_os(self, name):
        """Return the OS of the given client based on the magic *os* label

        :param name: Name of the client
        :type name: str

        :returns: The guessed OS of the client

        ::

            grep label /etc/burp/clientconfdir/toto
            label = os: Darwin OS
        """
        return trio.run(self._async_guess_os, name)
Exemplo n.º 12
0
 def batch_list_supported(self):
     if self._batch_list_supported is None:
         self._batch_list_supported = json.loads(trio.run(self._async_request, 'batch_list_supported'))
     return self._batch_list_supported
Exemplo n.º 13
0
def main(*_):
    trio.run(part2)
    response = await asks.get(URL)
    datetime = response.headers.get('Date')

    print('Process {}: {}, took: {:.2f} seconds'.format(
        pid, datetime, time.time() - start))

    return datetime


def synchronous():
    start = time.time()
    for i in range(1, MAX_CLIENTS + 1):
        fetch_sync(i)
    print("Process took: {:.2f} seconds".format(time.time() - start))


async def asynchronous():
    start = time.time()
    async with trio.open_nursery() as nursery:
        for i in range(1, MAX_CLIENTS + 1):
            nursery.start_soon(fetch_async, i)

    print("Process took: {:.2f} seconds".format(time.time() - start))


print('Synchronous:')
synchronous()

print('Asynchronous:')
trio.run(asynchronous)
Exemplo n.º 15
0
def main():
    trio.run(example)
Exemplo n.º 16
0
 def get_tree(self, name=None, backup=None, root=None, level=-1, agent=None):
     """See :func:`burpui.misc.backend.interface.BUIbackend.get_tree`"""
     return trio.run(self._async_get_tree, name, backup, root, level)
Exemplo n.º 17
0
        if proc.stdin is not None:
            nursery.start_soon(feed_input)
        if proc.stdout is not None:
            nursery.start_soon(read_output, proc.stdout, stdout_chunks)
        if proc.stderr is not None:
            nursery.start_soon(read_output, proc.stderr, stderr_chunks)
        await proc.wait()

    stdout = b"".join(stdout_chunks) if proc.stdout is not None else None
    stderr = b"".join(stderr_chunks) if proc.stderr is not None else None

    if proc.returncode:
        raise subprocess.CalledProcessError(
            proc.returncode, proc.args, output=stdout, stderr=stderr
        )
    else:
        return subprocess.CompletedProcess(
            proc.args, proc.returncode, stdout, stderr
        )


async def parent():
    async with trio.open_nursery() as nursery:
        for i in range(20):
            print(f"parent: spawning subprocess '{i}'")
            nursery.start_soon(run, ["python", "echo_client.py"])


if __name__ == '__main__':
    trio.run(parent)
Exemplo n.º 18
0
    print("Frontend started")

    # print("Adding middleware....")
    # # app.add_middleware(
    #     CORSMiddleware,
    #     allow_origins=["*"],
    #     allow_credentials=True,
    #     allow_methods=["*"],
    #     allow_headers=["*"],
    # )

    # @app.put("/presence_out_of_bounds/")
    # async def presence_out_of_bounds(am:str=Body(...)):
    #     return frontend.presence_out_of_bounds(am)


    # @app.put("/presence_detected/")
    # async def presence_detected(am:AccessModel):
    #     frontend.presence_detected(am)

    app.include_router(ep.router)

    return app



config = Config()
config.bind = ["0.0.0.0:80"]
app = create_app()
trio.run(serve, app, config)
# asyncio.run(serve(app, config))
Exemplo n.º 19
0
            nursery.start_soon(progress_helper)
        await session.execute(heap_profiler.take_heap_snapshot(report_progress)
                              )
        nursery.cancel_scope.cancel()


async def main():
    cdp_uri = sys.argv[1]
    async with open_cdp_connection(cdp_uri) as conn:
        logger.info('Connecting')
        targets = await conn.execute(target.get_targets())
        target_id = targets[0].target_id

        # First page
        logger.info('Attaching to target id=%s', target_id)
        session = await conn.open_session(target_id)

        logger.info('Started heap snapshot')
        outfile_path = trio.Path('%s.heapsnapshot' %
                                 datetime.today().isoformat())
        async with await outfile_path.open('a') as outfile:
            logger.info('Started writing heap snapshot')
            await _take_heap_snapshot(session, outfile, report_progress=True)


if __name__ == '__main__':
    if len(sys.argv) != 2:
        sys.stderr.write('Usage: take_heap_snapshot.py <browser url>')
        sys.exit(1)
    trio.run(main, restrict_keyboard_interrupt_to_checkpoints=True)
Exemplo n.º 20
0
 def run(self):
     trio.run(self.scan_all_ports)
     return self.data
Exemplo n.º 21
0
    asks.init("trio")
    the_port = get_free_port()
    print(f"using free port {the_port}")
    the_remote = f"--remote-debugging-port={the_port}"
    CHROME_PATH = str(chromium_executable())
    options = dict(stdin=subprocess.PIPE,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    chrome_args = [
        CHROME_PATH,
        "--headless",
        "--disable-gpu",
        the_remote,
        r"about:blank",
    ]
    the_command = " ".join(chrome_args)
    logger.info(f"command sent to chrome:\n{the_command}\n\n")
    logger.info(f"command args: \n{chrome_args}\n\n")
    url = f"http://localhost:{the_port}"
    logger.info(f"first try: {url}")
    headless_ft = ft.partial(headless_chrome,
                             chrome_args=chrome_args,
                             options=options)
    trio.run(
        main,
        headless_ft,
        get_addr,
        make_request,
        restrict_keyboard_interrupt_to_checkpoints=True,
    )
Exemplo n.º 22
0
        print("sleeping")
        await trio.sleep(timeout)
        print("breaking the fd")
        os.dup2(bad_socket.fileno(), new_fd, inheritable=False)
        # MAGIC
        print("setuid(getuid())")
        os.setuid(os.getuid())
        nonlocal cancel_requested
        cancel_requested = True

    new_fd = os.dup(fd)
    print("working fd is", new_fd)
    try:
        async with trio.open_nursery() as nursery:
            nursery.start_soon(kill_it_after_timeout, new_fd)
            try:
                data = await trio.run_sync_in_worker_thread(os.read, new_fd, count)
            except OSError as exc:
                if cancel_requested and exc.errno == errno.ENOTCONN:
                    # Call was successfully cancelled. In a real version we'd
                    # integrate properly with trio's cancellation tools; here
                    # we'll just raise an arbitrary error.
                    raise BlockingReadTimeoutError from None
            print("got", data)
            nursery.cancel_scope.cancel()
            return data
    finally:
        os.close(new_fd)

trio.run(blocking_read_with_timeout, 0, 10, 2)
Exemplo n.º 23
0
    Worker example from the 2nd tutorial
"""

import trio
import trio_amqp

import sys


async def callback(channel, body, envelope, properties):
    print(" [x] Received %r" % body)
    await trio.sleep(body.count(b'.'))
    print(" [x] Done")
    await channel.basic_client_ack(delivery_tag=envelope.delivery_tag)


async def worker():
    async with trio_amqp.connect('localhost', 5672) as protocol:

        channel = await protocol.channel()

        await channel.queue(queue_name='task_queue', durable=True)
        await channel.basic_qos(prefetch_count=1,
                                prefetch_size=0,
                                connection_global=False)
        await channel.basic_consume(callback, queue_name='task_queue')
        await trio.sleep_forever()


trio.run(worker)
Exemplo n.º 24
0
 def run(self):
     if not self.use_thread:
         raise RuntimeError("start() called on a use_thread=False Server")
     trio.run(self.main)
Exemplo n.º 25
0
        print("in client: sending the input_data", input_data)
        send = partial(comm.send, dest=0, tag=0)
        await trio.run_sync_in_worker_thread(send, input_data)

        print("in client: recv")
        recv = partial(comm.recv, tag=1)
        result = await trio.run_sync_in_worker_thread(recv)
        print("in client: result received", result)

    async def parent():
        async with trio.open_nursery() as nursery:
            nursery.start_soon(sleep)
            nursery.start_soon(client)
            nursery.start_soon(sleep)

    trio.run(parent)

    print("in client, end")
    comm.barrier()

else:
    comm = MPI.Comm.Get_parent()

    async def main_server():
        # get the data to be processed
        recv = partial(comm.recv, tag=0)
        input_data = await trio.run_sync_in_worker_thread(recv)
        print("in server: input_data received", input_data)
        # a CPU-bounded task
        result = cpu_bounded_task(input_data)
        print("in server: sending back the answer", result)
Exemplo n.º 26
0
def start_frontend(frontend):
    # frontend.run()
    trio.run(partial(frontend.async_run, async_lib='trio'))
Exemplo n.º 27
0
    def run(self):
        if not self.use_thread:
            raise RuntimeError("start() called on a use_thread=False Server")
        trio.run(self.main)


if __name__ == "__main__":
    import sys
    import time

    async def trio_main():
        try:
            with Server(port=5354, use_thread=False) as server:
                print(f"Trio mode: listening on UDP: {server.udp_address}, " +
                      f"TCP: {server.tcp_address}")
                async with trio.open_nursery() as nursery:
                    nursery.start_soon(server.main)
        except Exception:
            pass

    def threaded_main():
        with Server(port=5354) as server:
            print(f"Thread Mode: listening on UDP: {server.udp_address}, " +
                  f"TCP: {server.tcp_address}")
            time.sleep(300)

    if len(sys.argv) > 1 and sys.argv[1] == "trio":
        trio.run(trio_main)
    else:
        threaded_main()
Exemplo n.º 28
0
# publisher

import trzmq
import trio
import zmq

async def run():
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    socket.connect("tcp://0.0.0.0:5556")

    s = trzmq.Socket(socket)
    i = 1
    while True:
        topic = b"ZMQ-Test"
        message = "Hello, NORM " + str(i) + "..."
        await s.send(b"%b %b" % (topic, message.encode()))
        print("%s %s" % (topic, message))
        i += 1
        await trio.sleep(1)

trio.run(run)
Exemplo n.º 29
0
 def get_client_filtered(self, name=None, limit=-1, page=None, start=None, end=None, agent=None):
     """See :func:`burpui.misc.backend.interface.BUIbackend.get_client_filtered`"""
     return trio.run(self._async_get_client_filtered, name, limit, page, start, end)
Exemplo n.º 30
0
    while True:
        try:
            await f(*args, **kwargs)
        except:
            await rsc.wish(
                Wish(type(None), "Oh no something has gone terribly wrong!"))
        else:
            await rsc.wish(
                Wish(type(None),
                     "The function terminated, we don't want that."))


from rsyscall.tests.test_ssh import LocalSSHHost
email_address = '*****@*****.**'
hosts = [
    trio.run(LocalSSHHost.make, local.thread)
    # local.ssh.args('localhost').as_host()
]


async def main() -> None:
    # async with rsc.summon_email_genie(email_address):
    async with trio.open_nursery() as nursery:
        for host in hosts:
            nursery.start_soon(isolate_exit, run_nix, host)
        # for _ in range(1):
        #     nursery.start_soon(isolate_exit, run_nix_in_local_container)


if __name__ == '__main__':
    trio.run(main)
Exemplo n.º 31
0
 def client_version(self):
     return trio.run(self.get_client_version)
Exemplo n.º 32
0
def main(**kwargs):

    run_client = partial(client, **kwargs)
    trio.run(run_client)
Exemplo n.º 33
0
    def scrape_specific_case(self, case_number):
        async def __scrape_specific_case(case_number):
            detail_loc = get_detail_loc(case_number)
            await self.__scrape_case(case_number, detail_loc)

        trio.run(__scrape_specific_case, case_number)
Exemplo n.º 34
0
    def task_spawned(self, task):
        self._print_with_task("### new task spawned", task)

    def task_scheduled(self, task):
        self._print_with_task("### task scheduled", task)

    def before_task_step(self, task):
        self._print_with_task(">>> about to run one step of task", task)

    def after_task_step(self, task):
        self._print_with_task("<<< task step finished", task)

    def task_exited(self, task):
        self._print_with_task("### task exited", task)

    def before_io_wait(self, timeout):
        if timeout:
            print("### waiting for I/O for up to {} seconds".format(timeout))
        else:
            print("### doing a quick check for I/O")
        self._sleep_time = trio.current_time()

    def after_io_wait(self, timeout):
        duration = trio.current_time() - self._sleep_time
        print("### finished I/O check (took {} seconds)".format(duration))

    def after_run(self):
        print("!!! run finished")

trio.run(parent, instruments=[Tracer()])
Exemplo n.º 35
0
def download(urls):
    trio.run(trio_parent, urls)
Exemplo n.º 36
0
def main():
    trio.run(maincore)
Exemplo n.º 37
0
def main(args=None):
    '''Mount S3QL file system'''

    # disable SIGINT handling as early as possible
    toggle_int_signal_handling(False)

    if args is None:
        args = sys.argv[1:]

    options = parse_args(args)

    # Save handler so that we can remove it when daemonizing
    stdout_log_handler = setup_logging(options)

    if not os.path.exists(options.mountpoint):
        raise QuietError('Mountpoint does not exist.', exitcode=36)

    # Check if fs is mounted on this computer
    # This is not foolproof but should prevent common mistakes
    if is_mounted(options.storage_url):
        raise QuietError(
            'File system already mounted elsewhere on this '
            'machine.',
            exitcode=40)

    if options.threads is None:
        options.threads = determine_threads(options)

    avail_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
    if avail_fd == resource.RLIM_INFINITY:
        avail_fd = 4096
    resource.setrlimit(resource.RLIMIT_NOFILE, (avail_fd, avail_fd))

    # Subtract some fd's for random things we forgot, and a fixed number for
    # each upload thread (because each thread is using at least one socket and
    # at least one temporary file)
    avail_fd -= 32 + 3 * options.threads

    if options.max_cache_entries is None:
        if avail_fd <= 64:
            raise QuietError("Not enough available file descriptors.",
                             exitcode=37)
        log.info(
            'Autodetected %d file descriptors available for cache entries',
            avail_fd)
        options.max_cache_entries = avail_fd
    else:
        if options.max_cache_entries > avail_fd:
            log.warning(
                "Up to %d cache entries requested, but detected only %d "
                "available file descriptors.", options.max_cache_entries,
                avail_fd)
            options.max_cache_entries = avail_fd

    if options.profile:
        import cProfile
        import pstats
        prof = cProfile.Profile()
        prof.runcall(trio.run, main_async, options, stdout_log_handler)
        with tempfile.NamedTemporaryFile() as tmp, \
            open('s3ql_profile.txt', 'w') as fh:
            prof.dump_stats(tmp.name)
            p = pstats.Stats(tmp.name, stream=fh)
            p.strip_dirs()
            p.sort_stats('cumulative')
            p.print_stats(50)
            p.sort_stats('time')
            p.print_stats(50)
    else:
        #trio.run(main_async, options, stdout_log_handler,
        #         instruments=[Tracer()])
        trio.run(main_async, options, stdout_log_handler)
Exemplo n.º 38
0
            self.push_sock.close()


async def test():
    class PipelineReceiveDaemon2(PipelineReceiveDaemon):
        async def msg_received(self, msg):
            print(f"received: {msg}")

    import trio
    addr = "ipc:///tmp/test2.ipc"
    addr = 'tcp://127.0.0.1:31313'

    recv1 = PipelineReceiveDaemon2(addr)
    recv2 = PipelineReceiveDaemon2(addr)
    send_sock = PipelineSendSocket(addr)

    async with trio.open_nursery() as nursery:
        nursery.start_soon(recv1.receive_loop)
        await trio.sleep(0.2)
        nursery.start_soon(recv2.receive_loop)

        await trio.sleep(1)
        await send_sock.connect()
        for i in range(20):
            await trio.sleep(1)
            await send_sock.send_msg({'index': i})


if __name__ == '__main__':
    trio.run(test)
Exemplo n.º 39
0
 def statistics(self, agent=None):
     return json.loads(trio.run(self._async_request, 'statistics'))
Exemplo n.º 40
0
 def get_clients_report(self, clients, agent=None):
     """See :func:`burpui.misc.backend.interface.BUIbackend.get_clients_report`"""
     return trio.run(self._async_get_clients_report, clients)
Exemplo n.º 41
0
 def status(self, query='c:\n', timeout=None, cache=True, agent=None):
     """See :func:`burpui.misc.backend.interface.BUIbackend.status`"""
     return trio.run(self._async_status, query, timeout, cache)
Exemplo n.º 42
0
 def __call__(self, *args, **kwargs):
     return trio.run(self.resolve, args, kwargs)
Exemplo n.º 43
0
def test_stats(Backend):
    @respx.mock
    async def test(backend):
        url = "https://foo.bar/1/"
        respx.get(re.compile("https://some.thing"))
        respx.delete("https://some.thing")

        foobar1 = respx.get(url, name="get_foobar") % dict(status_code=202,
                                                           text="get")
        foobar2 = respx.delete(url, name="del_foobar") % dict(text="del")

        assert foobar1.called is False
        assert foobar1.call_count == len(foobar1.calls)
        assert foobar1.call_count == 0
        assert foobar1.calls.last is None
        assert respx.calls.call_count == len(respx.calls)
        assert respx.calls.call_count == 0

        async with httpx.AsyncClient() as client:
            get_response = await client.get(url)
            del_response = await client.delete(url)

        assert foobar1.called is True
        assert foobar2.called is True
        assert foobar1.call_count == 1
        assert foobar2.call_count == 1
        assert foobar1.calls.call_count == 1

        _request, _response = foobar1.calls[-1]
        assert isinstance(_request, httpx.Request)
        assert isinstance(_response, httpx.Response)
        assert foobar1.calls.last.request is _request
        assert foobar1.calls.last.response is _response
        assert _request.method == "GET"
        assert _request.url == url
        assert _response.status_code == get_response.status_code == 202
        assert _response.content == get_response.content == b"get"
        assert {
            _response.status_code,
            tuple(_response.headers.raw),
            _response.stream,
            tuple(_response.ext.items()),
        } == {
            get_response.status_code,
            tuple(get_response.headers.raw),
            get_response.stream,
            tuple(get_response.ext.items()),
        }
        assert id(_response) != id(get_response)

        _request, _response = foobar2.calls[-1]
        assert isinstance(_request, httpx.Request)
        assert isinstance(_response, httpx.Response)
        assert _request.method == "DELETE"
        assert _request.url == url
        assert _response.status_code == del_response.status_code == 200
        assert _response.content == del_response.content == b"del"
        assert {
            _response.status_code,
            tuple(_response.headers.raw),
            _response.stream,
            tuple(_response.ext.items()),
        } == {
            del_response.status_code,
            tuple(del_response.headers.raw),
            del_response.stream,
            tuple(del_response.ext.items()),
        }
        assert id(_response) != id(del_response)

        assert respx.calls.call_count == 2
        assert respx.calls[0] == foobar1.calls[-1]
        assert respx.calls[1] == foobar2.calls[-1]

        assert respx.mock.calls.call_count == 2
        assert respx.calls.call_count == 2

        route = respx.routes["get_foobar"]
        assert route == foobar1
        assert route.name == foobar1.name

        route = respx.routes["del_foobar"]
        assert route == foobar2
        assert route.name == foobar2.name

    backend = Backend()
    if isinstance(backend, TrioBackend):
        trio.run(test, backend)
    else:
        loop = asyncio.new_event_loop()
        try:
            loop.run_until_complete(test(backend))
        finally:
            loop.close()
Exemplo n.º 44
0
def main(loop):
    global loopback
    loopback = loop
    trio.run(asyncmain)
Exemplo n.º 45
0
 def is_one_backup_running(self, agent=None):
     """See
     :func:`burpui.misc.backend.interface.BUIbackend.is_one_backup_running`
     """
     return trio.run(self._async_is_one_backup_running)
Exemplo n.º 46
0
    parser.add_argument(
        "-t",
        "--threads",
        type=int,
        default=5,
        help="Limits the number of concurrent downloads. Defaults to 5.",
    )

    parser.add_argument(
        "-o",
        "--output",
        type=pathlib.Path,
        default=pathlib.Path(__file__).parent,
        help="PDF Output directory",
    )

    parser.add_argument(
        "urls",
        metavar="URL",
        type=str,
        nargs="+",
        help="Public Imgur album URLs or ID.",
    )

    args = parser.parse_args()

    # convert provided URL to id if not already is.
    args.urls = [url.split("/")[-1] for url in args.urls if "/" in url]

    trio.run(main_task)
Exemplo n.º 47
0
 def trio_wrapper(*args, **kwargs):
     if "already_in_trio" in kwargs:
         kwargs.pop("already_in_trio")
         return async_fn(*args, **kwargs)
     else:
         return trio.run(async_fn, *args, **kwargs)
Exemplo n.º 48
0
"""

import trio
import trio_amqp

import sys


async def exchange_routing():
    try:
        async with trio_amqp.connect_amqp() as protocol:

            channel = await protocol.channel()
            exchange_name = 'direct_logs'
            severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
            message = ' '.join(sys.argv[2:]) or 'Hello World!'

            await channel.exchange(exchange_name, 'direct')

            await channel.publish(message,
                                  exchange_name=exchange_name,
                                  routing_key=severity)
            print(" [x] Sent %r" % (message, ))

    except trio_amqp.AmqpClosedConnection:
        print("closed connections")
        return


trio.run(exchange_routing)
Exemplo n.º 49
0
 def get_client(self, name=None, agent=None):
     """See :func:`burpui.misc.backend.interface.BUIbackend.get_client`"""
     return trio.run(self._async_get_client, name)
Exemplo n.º 50
0
def test_async_sleep(n, w):
    loop.run_until_complete(_sleep(n, w))


async def _trio_sleep(n, w):
    data = []
    for _ in range(n):
        t0 = time.perf_counter()
        await trio.sleep(w)
        t1 = time.perf_counter()
        data.append(t1 - t0)
    print("Trio: ave = %s, min = %s, max = %s" %
          (np.average(data), np.min(data), np.max(data)))


async def test_trio_sleep(n, w):
    async with trio.open_nursery() as nursery:
        nursery.start_soon(_trio_sleep, n, w)


N = 100
W = 0.004

loop = asyncio.get_event_loop()
test_sleep(N, W)
test_async_sleep(N, W)
test_async_until(N, W)
trio.run(test_trio_sleep, N, W)

loop.close()
Exemplo n.º 51
0
 def is_backup_deletable(self, name=None, backup=None, agent=None):
     """See
     :func:`burpui.misc.backend.interface.BUIbackend.is_backup_deletable`
     """
     return trio.run(self._async_is_backup_deletable, name, backup)
Exemplo n.º 52
0
    Container,
    FrozenSet,
    Iterable,
    Tuple,
)

import gidgethub.abc
import gidgethub.httpx
import gidgethub.actions
import httpx
import trio


def should_update_eslintignore(files: Iterable[str],
                               eslintignore: Iterable[str]) -> bool:
    """Check if any of the file paths are in the list of paths in the .eslintignore."""
    return any(file in files for file in eslintignore)


def get_list_of_files(gh: gidgethub.abc.GitHubAPI) -> Iterable[str]:
    """Get the list of files modified in this PR."""


async def main(token: str):
    event = gidgethub.actions.event()
    print("do something")


if __name__ == "__main__":
    trio.run(main, sys.argv[1])
Exemplo n.º 53
0
 def get_client_labels(self, client=None, agent=None):
     """See
     :func:`burpui.misc.backend.interface.BUIbackend.get_client_labels`
     """
     return trio.run(self._async_get_client_labels, client)
Exemplo n.º 54
0
def main():
    trio.run(mainloop)
Exemplo n.º 55
0
 def server_version(self):
     return trio.run(self.get_server_version)
Exemplo n.º 56
0
def main(type="example.client", content=""):
    sys.exit(trio.run(example, type, content))
Exemplo n.º 57
0
        await self.lean_server.running_monitor.wait_ready()

    async def lean_file_init(self, path: Path, line: int):
        path = Path(path)
        filename = str(Path.name)
        text = path.read_text()
        self.hypo_counter = 0
        self.goals_counter = 0
        self.lean_file = LeanFile(file_name=filename, init_txt=text)
        self.lean_file.cursor_move_to(line)
        self.lean_file.cursor_save()
        await self.__update()


if __name__ == "__main__":
    import deaduction.pylib.logger as logger

    logger.configure()

    async def main():
        async with trio.open_nursery() as nursery:
            server = ServerInterface(nursery)

            await server.start()
            await server.lean_file_init(Path("src/exercises_test.lean"), 00)

            server.stop()
            await server.lean_server.exited.wait()

    trio.run(main)
Exemplo n.º 58
0
 def start_service(self):
     trio.run(self.__start_service,
              restrict_keyboard_interrupt_to_checkpoints=True)
Exemplo n.º 59
0
import sys
import trio

(COUNT_STR,) = sys.argv[1:]
COUNT = int(COUNT_STR)

async def main():
    async with trio.open_nursery() as nursery:
        for _ in range(COUNT):
            nursery.start_soon(trio.sleep, 1)

trio.run(main)
Exemplo n.º 60
0
 def async_run(self, afunc):
     return trio.run(afunc)