|
| 1 | +import contextlib |
| 2 | +import ipaddress |
| 3 | +import os.path |
| 4 | +import socket |
| 5 | +import subprocess |
| 6 | +import time |
| 7 | + |
| 8 | + |
| 9 | +@contextlib.contextmanager |
| 10 | +def serving(argv, sitedir, addr, *, |
| 11 | + pause=None, |
| 12 | + kill=False, |
| 13 | + quiet=True, |
| 14 | + ): |
| 15 | + if os.path.exists(addr): |
| 16 | + sock = addr |
| 17 | + addr = None |
| 18 | + try: |
| 19 | + os.remove(sock) |
| 20 | + except FileNotFoundError: |
| 21 | + pass |
| 22 | + else: |
| 23 | + sock = None |
| 24 | + |
| 25 | + p = subprocess.Popen( |
| 26 | + argv, |
| 27 | + cwd=sitedir, |
| 28 | + stdout=subprocess.DEVNULL if quiet else None, |
| 29 | + stderr=subprocess.STDOUT if quiet else None, |
| 30 | + ) |
| 31 | + try: |
| 32 | + if pause: |
| 33 | + time.sleep(pause) |
| 34 | + if not sock: |
| 35 | + try: |
| 36 | + waitUntilUp(addr) |
| 37 | + except NotImplementedError: |
| 38 | + sock = addr |
| 39 | + addr = None |
| 40 | + if sock: |
| 41 | + while not os.path.exists(sock): |
| 42 | + time.sleep(0.001) |
| 43 | + assert p.poll() is None, p.poll() |
| 44 | + yield |
| 45 | + assert p.poll() is None, p.poll() |
| 46 | + finally: |
| 47 | + p.terminate() |
| 48 | + if kill: |
| 49 | + p.kill() |
| 50 | + p.wait() |
| 51 | + |
| 52 | + |
| 53 | +def waitUntilUp(addr, timeout=10.0): |
| 54 | + end = time.time() + timeout |
| 55 | + addr = parse_socket_addr(addr) |
| 56 | + started = False |
| 57 | + current = time.time() |
| 58 | + while not started or current <= end: |
| 59 | + try: |
| 60 | + with socket.create_connection(addr) as sock: |
| 61 | + return |
| 62 | + except ConnectionRefusedError: |
| 63 | + time.sleep(0.001) |
| 64 | + started = True |
| 65 | + current = time.time() |
| 66 | + raise Exception('Timeout reached when trying to connect') |
| 67 | + |
| 68 | + |
| 69 | +def parse_socket_addr(addr, *, resolve=True): |
| 70 | + if not isinstance(addr, str): |
| 71 | + raise NotImplementedError(addr) |
| 72 | + host, _, port = addr.partition(':') |
| 73 | + |
| 74 | + if not host: |
| 75 | + raise NotImplementedError(addr) |
| 76 | + try: |
| 77 | + host = ipaddress.ip_address(host) |
| 78 | + except ValueError: |
| 79 | + raise NotImplementedError(addr) |
| 80 | + host = str(host) |
| 81 | + |
| 82 | + if not port: |
| 83 | + raise NotImplementedError(addr) |
| 84 | + if not port.isdigit(): |
| 85 | + raise NotImplementedError(addr) |
| 86 | + port = int(port) |
| 87 | + |
| 88 | + return (host, port) |
0 commit comments