|
| 1 | +import abc |
| 2 | +from argparse import ArgumentParser |
| 3 | +import asyncio |
| 4 | +from dataclasses import dataclass |
| 5 | +from ipaddress import IPv4Address |
| 6 | +from typing import ClassVar, Generic, Literal, Optional, TypeVar |
| 7 | + |
| 8 | +from ..interfaces import DHCPRangeConfig |
| 9 | + |
| 10 | + |
| 11 | +@dataclass |
| 12 | +class DHCPServerConfig: |
| 13 | + range: DHCPRangeConfig |
| 14 | + interface: str |
| 15 | + lease_time: int = 120 # in seconds |
| 16 | + max_leases: int = 50 |
| 17 | + |
| 18 | +DHCPServerConfigT = TypeVar("DHCPServerConfigT", bound=DHCPServerConfig) |
| 19 | + |
| 20 | +class DHCPServerFixture(abc.ABC, Generic[DHCPServerConfigT]): |
| 21 | + |
| 22 | + BINARY_PATH: ClassVar[Optional[str]] = None |
| 23 | + |
| 24 | + @classmethod |
| 25 | + def get_config_class(cls) -> type[DHCPServerConfigT]: |
| 26 | + return cls.__orig_bases__[0].__args__[0] |
| 27 | + |
| 28 | + def __init__(self, config: DHCPServerConfigT) -> None: |
| 29 | + self.config = config |
| 30 | + self.stdout: list[str] = [] |
| 31 | + self.stderr: list[str] = [] |
| 32 | + self.process: Optional[asyncio.subprocess.Process] = None |
| 33 | + self.output_poller: Optional[asyncio.Task] = None |
| 34 | + |
| 35 | + async def _read_output(self, name: Literal['stdout', 'stderr']): |
| 36 | + '''Read stdout or stderr until the process exits.''' |
| 37 | + stream = getattr(self.process, name) |
| 38 | + output = getattr(self, name) |
| 39 | + while line := await stream.readline(): |
| 40 | + output.append(line.decode().strip()) |
| 41 | + |
| 42 | + async def _read_outputs(self): |
| 43 | + '''Read stdout & stderr until the process exits.''' |
| 44 | + assert self.process |
| 45 | + await asyncio.gather( |
| 46 | + self._read_output('stderr'), self._read_output('stdout') |
| 47 | + ) |
| 48 | + |
| 49 | + |
| 50 | + @abc.abstractmethod |
| 51 | + def get_cmdline_options(self) -> tuple[str]: |
| 52 | + '''All commandline options passed to the server.''' |
| 53 | + |
| 54 | + |
| 55 | + async def __aenter__(self): |
| 56 | + '''Start the server process and start polling its output.''' |
| 57 | + if not self.BINARY_PATH: |
| 58 | + raise RuntimeError(f"server binary is missing for {type(self.__name__)}") |
| 59 | + self.process = await asyncio.create_subprocess_exec( |
| 60 | + self.BINARY_PATH, |
| 61 | + *self.get_cmdline_options(), |
| 62 | + stdout=asyncio.subprocess.PIPE, |
| 63 | + stderr=asyncio.subprocess.PIPE, |
| 64 | + env={'LANG': 'C'}, # usually ensures the output is in english |
| 65 | + ) |
| 66 | + self.output_poller = asyncio.Task(self._read_outputs()) |
| 67 | + return self |
| 68 | + |
| 69 | + async def __aexit__(self, *_): |
| 70 | + if self.process: |
| 71 | + if self.process.returncode is None: |
| 72 | + self.process.terminate() |
| 73 | + await self.process.wait() |
| 74 | + await self.output_poller |
| 75 | + |
| 76 | + |
| 77 | +def get_psr() -> ArgumentParser: |
| 78 | + psr = ArgumentParser() |
| 79 | + psr.add_argument('interface', help='Interface to listen on') |
| 80 | + psr.add_argument( |
| 81 | + '--router', |
| 82 | + type=IPv4Address, |
| 83 | + default=None, |
| 84 | + help='Router IPv4 address.', |
| 85 | + ) |
| 86 | + psr.add_argument( |
| 87 | + '--range-start', |
| 88 | + type=IPv4Address, |
| 89 | + default=IPv4Address('192.168.186.10'), |
| 90 | + help='Start of the DHCP client range.', |
| 91 | + ) |
| 92 | + psr.add_argument( |
| 93 | + '--range-end', |
| 94 | + type=IPv4Address, |
| 95 | + default=IPv4Address('192.168.186.100'), |
| 96 | + help='End of the DHCP client range.', |
| 97 | + ) |
| 98 | + psr.add_argument( |
| 99 | + '--lease-time', |
| 100 | + default=120, |
| 101 | + type=int, |
| 102 | + help='DHCP lease time in seconds (minimum 2 minutes)', |
| 103 | + ) |
| 104 | + psr.add_argument( |
| 105 | + '--netmask', |
| 106 | + type=IPv4Address, |
| 107 | + default=IPv4Address("255.255.255.0"), |
| 108 | + ) |
| 109 | + return psr |
| 110 | + |
| 111 | + |
| 112 | +async def run_fixture_as_main(fixture_cls: type[DHCPServerFixture]): |
| 113 | + config_cls = fixture_cls.get_config_class() |
| 114 | + args = get_psr().parse_args() |
| 115 | + range_config = DHCPRangeConfig( |
| 116 | + start=args.range_start, |
| 117 | + end=args.range_end, |
| 118 | + router=args.router, |
| 119 | + netmask=args.netmask, |
| 120 | + ) |
| 121 | + conf = config_cls( |
| 122 | + range=range_config, |
| 123 | + interface=args.interface, |
| 124 | + lease_time=args.lease_time, |
| 125 | + ) |
| 126 | + read_lines: int = 0 |
| 127 | + async with fixture_cls(conf) as dhcp_server: |
| 128 | + # quick & dirty stderr polling |
| 129 | + while True: |
| 130 | + if len(dhcp_server.stderr) > read_lines: |
| 131 | + read_lines += len(lines := dhcp_server.stderr[read_lines:]) |
| 132 | + print(*lines, sep='\n') |
| 133 | + else: |
| 134 | + await asyncio.sleep(0.2) |
0 commit comments